leejunyoung5819 handmade-dataset-creator
공개고품질 LLM 데이터셋 수제작을 위한 생산성 도구
| 1 | //! 본문 서식 표기 규칙. |
| 2 | //! |
| 3 | //! | 서식 | 표기 | |
| 4 | //! |---|---| |
| 5 | //! | 굵게 | `**텍스트**` | |
| 6 | //! | 취소선 | `~~텍스트~~` | |
| 7 | //! | 밑줄 | `<u>텍스트</u>` | |
| 8 | //! | 그 밖의 시각적 강조(박스·음영·형광펜 등) | `<mark>텍스트</mark>` (속성 허용: `<mark type="box">`) | |
| 9 | //! |
| 10 | //! 저장되는 것은 이 표기가 들어간 평범한 텍스트이고, 편집기는 감싸기 단축키와 목록 미리보기만 제공한다. |
| 11 | |
| 12 | use std::ops::Range; |
| 13 | |
| 14 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 15 | pub enum Fmt { |
| 16 | Bold, |
| 17 | Strike, |
| 18 | Underline, |
| 19 | Mark, |
| 20 | } |
| 21 | |
| 22 | impl Fmt { |
| 23 | pub fn open(self) -> &'static str { |
| 24 | match self { |
| 25 | Fmt::Bold => "**", |
| 26 | Fmt::Strike => "~~", |
| 27 | Fmt::Underline => "<u>", |
| 28 | Fmt::Mark => "<mark>", |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | pub fn close(self) -> &'static str { |
| 33 | match self { |
| 34 | Fmt::Bold => "**", |
| 35 | Fmt::Strike => "~~", |
| 36 | Fmt::Underline => "</u>", |
| 37 | Fmt::Mark => "</mark>", |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | fn byte_of(text: &str, char_idx: usize) -> usize { |
| 43 | text.char_indices().nth(char_idx).map(|(b, _)| b).unwrap_or(text.len()) |
| 44 | } |
| 45 | |
| 46 | fn chars(s: &str) -> usize { |
| 47 | s.chars().count() |
| 48 | } |
| 49 | |
| 50 | /// 선택 영역(문자 인덱스)에 서식을 토글한다. 새 텍스트와 새 선택 영역(문자 인덱스)을 돌려준다. |
| 51 | /// - 선택한 텍스트가 이미 표기로 감싸져 있거나, 선택 영역 바로 바깥에 표기가 있으면 표기를 벗긴다. |
| 52 | /// - 아니면 감싼다. 선택이 없으면 빈 표기를 넣고 커서를 그 사이에 둔다. |
| 53 | pub fn toggle(text: &str, sel: Range<usize>, fmt: Fmt) -> (String, Range<usize>) { |
| 54 | let (open, close) = (fmt.open(), fmt.close()); |
| 55 | let (oc, cc) = (chars(open), chars(close)); |
| 56 | let (a, b) = (sel.start.min(sel.end), sel.start.max(sel.end)); |
| 57 | let (ab, bb) = (byte_of(text, a), byte_of(text, b)); |
| 58 | let selected = &text[ab..bb]; |
| 59 | |
| 60 | // 1) 선택 안쪽 양 끝이 표기 |
| 61 | if selected.len() >= open.len() + close.len() && selected.starts_with(open) && selected.ends_with(close) { |
| 62 | let inner = &selected[open.len()..selected.len() - close.len()]; |
| 63 | let out = format!("{}{}{}", &text[..ab], inner, &text[bb..]); |
| 64 | return (out, a..b - oc - cc); |
| 65 | } |
| 66 | // 2) 선택 바로 바깥이 표기 |
| 67 | if text[..ab].ends_with(open) && text[bb..].starts_with(close) { |
| 68 | let out = format!("{}{}{}", &text[..ab - open.len()], selected, &text[bb + close.len()..]); |
| 69 | return (out, a - oc..b - oc); |
| 70 | } |
| 71 | // 3) 감싸기 |
| 72 | let out = format!("{}{open}{selected}{close}{}", &text[..ab], &text[bb..]); |
| 73 | (out, a + oc..b + oc) |
| 74 | } |
| 75 | |
| 76 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 77 | pub struct Style { |
| 78 | pub bold: bool, |
| 79 | pub strike: bool, |
| 80 | pub underline: bool, |
| 81 | pub mark: bool, |
| 82 | } |
| 83 | |
| 84 | /// 미리보기용 조각. `marker`가 true면 표기 자체(`**`, `<u>` 등)이다. |
| 85 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 86 | pub struct Span { |
| 87 | pub text: String, |
| 88 | pub style: Style, |
| 89 | pub marker: bool, |
| 90 | } |
| 91 | |
| 92 | /// 표기를 해석해 조각으로 나눈다. 표기 문자도 조각으로 남기므로 이어 붙이면 원문과 같다. |
| 93 | /// 닫히지 않은 표기는 끝까지 적용된다(미리보기에서 실수가 눈에 띄도록). |
| 94 | pub fn parse(text: &str) -> Vec<Span> { |
| 95 | let mut out: Vec<Span> = Vec::new(); |
| 96 | let mut style = Style::default(); |
| 97 | let mut buf = String::new(); |
| 98 | let mut i = 0; |
| 99 | let flush = |buf: &mut String, out: &mut Vec<Span>, style: Style| { |
| 100 | if !buf.is_empty() { |
| 101 | out.push(Span { text: std::mem::take(buf), style, marker: false }); |
| 102 | } |
| 103 | }; |
| 104 | while i < text.len() { |
| 105 | let rest = &text[i..]; |
| 106 | let marker_len = if rest.starts_with("**") { |
| 107 | flush(&mut buf, &mut out, style); |
| 108 | style.bold = !style.bold; |
| 109 | Some(2) |
| 110 | } else if rest.starts_with("~~") { |
| 111 | flush(&mut buf, &mut out, style); |
| 112 | style.strike = !style.strike; |
| 113 | Some(2) |
| 114 | } else if rest.starts_with("<u>") { |
| 115 | flush(&mut buf, &mut out, style); |
| 116 | style.underline = true; |
| 117 | Some(3) |
| 118 | } else if rest.starts_with("</u>") { |
| 119 | flush(&mut buf, &mut out, style); |
| 120 | style.underline = false; |
| 121 | Some(4) |
| 122 | } else if rest.starts_with("</mark>") { |
| 123 | flush(&mut buf, &mut out, style); |
| 124 | style.mark = false; |
| 125 | Some(7) |
| 126 | } else if rest.starts_with("<mark") |
| 127 | && let Some(end) = rest.find('>') |
| 128 | && (end == 5 || rest.as_bytes()[5] == b' ') |
| 129 | && !rest[..end].contains('\n') |
| 130 | { |
| 131 | flush(&mut buf, &mut out, style); |
| 132 | style.mark = true; |
| 133 | Some(end + 1) |
| 134 | } else { |
| 135 | None |
| 136 | }; |
| 137 | match marker_len { |
| 138 | Some(n) => { |
| 139 | // 여는 표기는 바뀐 뒤 스타일, 닫는 표기는 바뀌기 전 스타일로 보이면 어색하므로 표기에는 스타일을 주지 않는다. |
| 140 | out.push(Span { text: rest[..n].to_string(), style: Style::default(), marker: true }); |
| 141 | i += n; |
| 142 | } |
| 143 | None => { |
| 144 | let ch = rest.chars().next().unwrap(); |
| 145 | buf.push(ch); |
| 146 | i += ch.len_utf8(); |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | flush(&mut buf, &mut out, style); |
| 151 | out |
| 152 | } |
| 153 | |
| 154 | /// 미리보기에서 실제 서식이 하나라도 있는지 (없으면 일반 라벨로 그리면 된다). |
| 155 | pub fn has_markup(text: &str) -> bool { |
| 156 | text.contains("**") || text.contains("~~") || text.contains("<u>") || text.contains("<mark") |
| 157 | } |