feat(chat): code blocks open on ```, show Copy in Teams, confirm Copy (#145)
@@ -63,6 +63,33 @@ pub struct Outgoing {
63
63
pub banner: Option<AnnouncementBanner>,
64
64
}
65
65
66
/// Teams shows a code block's language and Copy button only when a marker paragraph links to it.
67
/// The server adds the `x_` that Teams' own messages show on the marker's id.
68
fn link_code_blocks(html: &str) -> String {
69
let mut linked = String::with_capacity(html.len());
70
for (index, part) in html.split("<pre ").enumerate() {
71
if index > 0 {
72
// Derived from the body, so every html() of one message gives the same text.
73
let id = code_block_id(html, index);
74
linked.push_str(&format!(
75
"<p itemtype=\"{}\" id=\"codeBlockEditor-{id}\"> </p><pre itemid=\"codeBlockEditor-{id}\" ",
76
teams_core::CODE_BLOCK_ITEMTYPE
77
));
78
}
79
linked.push_str(part);
80
}
81
linked
82
}
83
84
fn code_block_id(html: &str, index: usize) -> uuid::Uuid {
85
use std::hash::{Hash, Hasher};
86
let mut hasher = std::hash::DefaultHasher::new();
87
(html, index).hash(&mut hasher);
88
let high = hasher.finish();
89
high.hash(&mut hasher);
90
uuid::Uuid::from_u64_pair(high, hasher.finish())
91
}
92
66
93
impl Outgoing {
67
94
/// Without list and quote markers, for previews.
68
95
pub fn text(&self) -> String {
@@ -90,7 +117,10 @@ impl Outgoing {
90
117
None => {}
91
118
}
92
119
}
93
teams_core::emoticon_tags(&html, crate::emoticons::send_tag)
120
link_code_blocks(&teams_core::emoticon_tags(
121
&html,
122
crate::emoticons::send_tag,
123
))
94
124
}
95
125
96
126
pub fn has_attachments(&self) -> bool {
@@ -120,3 +150,30 @@ impl Outgoing {
120
150
}
121
151
}
122
152
}
153
154
#[cfg(test)]
155
mod tests {
156
use super::*;
157
158
#[test]
159
fn each_code_block_gets_its_own_teams_marker() {
160
let html = "<p>a</p><pre class=\"language-rs\"><code>x</code></pre><pre class=\"language-py\"><code><pre y</code></pre>";
161
let linked = link_code_blocks(html);
162
let ids: Vec<&str> = linked
163
.split("itemid=\"codeBlockEditor-")
164
.skip(1)
165
.map(|rest| &rest[..36])
166
.collect();
167
assert_eq!(ids.len(), 2);
168
assert_ne!(ids[0], ids[1]);
169
for id in &ids {
170
assert!(linked.contains(&format!(
171
"<p itemtype=\"{}\" id=\"codeBlockEditor-{id}\"> </p><pre itemid=\"codeBlockEditor-{id}\" class=",
172
teams_core::CODE_BLOCK_ITEMTYPE
173
)));
174
}
175
assert!(linked.contains("<pre y"));
176
assert_eq!(link_code_blocks(html), linked);
177
assert_eq!(link_code_blocks("<p>no code</p>"), "<p>no code</p>");
178
}
179
}
@@ -63,6 +63,33 @@ pub struct Outgoing {63
pub banner: Option<AnnouncementBanner>,63
pub banner: Option<AnnouncementBanner>,64
}64
}65
65
66
/// Teams shows a code block's language and Copy button only when a marker paragraph links to it.67
/// The server adds the `x_` that Teams' own messages show on the marker's id.68
fn link_code_blocks(html: &str) -> String {69
let mut linked = String::with_capacity(html.len());70
for (index, part) in html.split("<pre ").enumerate() {71
if index > 0 {72
// Derived from the body, so every html() of one message gives the same text.73
let id = code_block_id(html, index);74
linked.push_str(&format!(75
"<p itemtype=\"{}\" id=\"codeBlockEditor-{id}\"> </p><pre itemid=\"codeBlockEditor-{id}\" ",76
teams_core::CODE_BLOCK_ITEMTYPE77
));78
}79
linked.push_str(part);80
}81
linked82
}83
84
fn code_block_id(html: &str, index: usize) -> uuid::Uuid {85
use std::hash::{Hash, Hasher};86
let mut hasher = std::hash::DefaultHasher::new();87
(html, index).hash(&mut hasher);88
let high = hasher.finish();89
high.hash(&mut hasher);90
uuid::Uuid::from_u64_pair(high, hasher.finish())91
}92
66
impl Outgoing {93
impl Outgoing {67
/// Without list and quote markers, for previews.94
/// Without list and quote markers, for previews.68
pub fn text(&self) -> String {95
pub fn text(&self) -> String {@@ -90,7 +117,10 @@ impl Outgoing {90
None => {}117
None => {}91
}118
}92
}119
}93
teams_core::emoticon_tags(&html, crate::emoticons::send_tag)120
link_code_blocks(&teams_core::emoticon_tags(121
&html,122
crate::emoticons::send_tag,123
))94
}124
}95
125
96
pub fn has_attachments(&self) -> bool {126
pub fn has_attachments(&self) -> bool {@@ -120,3 +150,30 @@ impl Outgoing {120
}150
}121
}151
}122
}152
}153
154
#[cfg(test)]155
mod tests {156
use super::*;157
158
#[test]159
fn each_code_block_gets_its_own_teams_marker() {160
let html = "<p>a</p><pre class=\"language-rs\"><code>x</code></pre><pre class=\"language-py\"><code><pre y</code></pre>";161
let linked = link_code_blocks(html);162
let ids: Vec<&str> = linked163
.split("itemid=\"codeBlockEditor-")164
.skip(1)165
.map(|rest| &rest[..36])166
.collect();167
assert_eq!(ids.len(), 2);168
assert_ne!(ids[0], ids[1]);169
for id in &ids {170
assert!(linked.contains(&format!(171
"<p itemtype=\"{}\" id=\"codeBlockEditor-{id}\"> </p><pre itemid=\"codeBlockEditor-{id}\" class=",172
teams_core::CODE_BLOCK_ITEMTYPE173
)));174
}175
assert!(linked.contains("<pre y"));176
assert_eq!(link_code_blocks(html), linked);177
assert_eq!(link_code_blocks("<p>no code</p>"), "<p>no code</p>");178
}179
}@@ -5,14 +5,16 @@ use gpui_kit::*;
5
5
use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};
6
6
7
7
use crate::render::blocks::{Script, StyleFlags};
8
use crate::render::elements::{highlight_fill, readable_on};
8
use crate::render::elements::{highlight_fill, readable_on, token_style};
9
use crate::render::syntax;
9
10
use app_base::theme;
10
11
11
12
const CODE_PILL_RADIUS: f32 = 4.;
12
13
const CODE_BLOCK_RADIUS: f32 = 6.;
13
14
const QUOTE_BAR_WIDTH: f32 = 3.;
14
15
const QUOTE_INDENT: f32 = 12.;
15
const CODE_INDENT: f32 = 10.;
16
/// Room before code lines: the line numbers sit in it.
17
pub const CODE_INDENT: f32 = 36.;
16
18
const LIST_LEVEL_INDENT: f32 = 18.;
17
19
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];
18
20
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;
@@ -24,6 +26,8 @@ pub struct DraftStyle {
24
26
pub ranges: Vec<RangeDecoration>,
25
27
pub markers: Vec<Range<usize>>,
26
28
pub indents: Vec<(usize, Pixels)>,
29
/// Code line numbers, each before the start of its line's content.
30
pub labels: Vec<(usize, SharedString)>,
27
31
}
28
32
29
33
fn line_indent(kind: &LineKind) -> f32 {
@@ -111,6 +115,34 @@ fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {
111
115
line_ranges[lines.start].start..line_ranges[lines.end - 1].end
112
116
}
113
117
118
/// A code line cut where its tokens start and end, so no two decorations overlap: the
119
/// input does not say which of two overlapping ones in a collection wins.
120
fn code_pieces(
121
line: Range<usize>,
122
tokens: &[(Range<usize>, HighlightStyle)],
123
) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
124
let plain = color(theme::text_strong());
125
let mut pieces = Vec::new();
126
let mut at = line.start;
127
for (range, style) in tokens {
128
let range = range.start.max(line.start)..range.end.min(line.end);
129
if range.start >= range.end || range.start < at {
130
continue;
131
}
132
if at < range.start {
133
pieces.push((at..range.start, plain));
134
}
135
let mut style = *style;
136
style.color = style.color.or(plain.color);
137
pieces.push((range.clone(), style));
138
at = range.end;
139
}
140
if at < line.end {
141
pieces.push((at..line.end, plain));
142
}
143
pieces.into_iter()
144
}
145
114
146
pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
115
147
let mut text = Vec::new();
116
148
let mut ranges = Vec::new();
@@ -152,6 +184,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
152
184
text.push(decoration);
153
185
}
154
186
}
187
let mut labels = Vec::new();
155
188
let kinds = draft.lines();
156
189
let mut index = 0;
157
190
while index < kinds.len() {
@@ -161,10 +194,32 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
161
194
.iter()
162
195
.take_while(|other| *other == kind)
163
196
.count();
197
// From after the header mark, so line one reads as a line start.
198
let tokens: Vec<(Range<usize>, HighlightStyle)> = match kind {
199
LineKind::Code(Some(language)) => {
200
let block =
201
draft.content_range(index).start..block_range(draft, index..run_end).end;
202
syntax::highlight(&draft.text()[block.clone()], language)
203
.unwrap_or_default()
204
.into_iter()
205
.map(|(range, token)| {
206
(
207
block.start + range.start..block.start + range.end,
208
token_style(token),
209
)
210
})
211
.collect()
212
}
213
_ => Vec::new(),
214
};
164
215
for line in index..run_end {
165
216
let marker = draft.marker_range(line);
166
217
let content = draft.content_range(line);
167
if !marker.is_empty() {
218
if matches!(kind, LineKind::Code(_)) {
219
labels.push((content.start, (line - index + 1).to_string().into()));
220
}
221
// A code block's header sits on its own row, so it hangs nothing.
222
if !marker.is_empty() && !matches!(kind, LineKind::Code(_)) {
168
223
markers.push(marker.clone());
169
224
if kind.is_list() {
170
225
text.push(TextDecoration::new(marker, color(theme::text_soft())));
@@ -177,10 +232,11 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
177
232
LineKind::Quote => {
178
233
text.push(TextDecoration::new(content, color(theme::text_soft())))
179
234
}
180
LineKind::Code(_) => text.push(
181
TextDecoration::new(content, color(theme::text_strong()))
182
.with_font_family(mono.clone()),
183
),
235
LineKind::Code(_) => {
236
text.extend(code_pieces(content, &tokens).map(|(range, style)| {
237
TextDecoration::new(range, style).with_font_family(mono.clone())
238
}))
239
}
184
240
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),
185
241
_ => {}
186
242
}
@@ -190,6 +246,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
190
246
RangeDecoration::new(block_range(draft, index..run_end))
191
247
.with_style(RangeDecorationStyle::Block)
192
248
.with_color(theme::code_surface())
249
.with_border(theme::code_frame())
193
250
.with_radius(px(CODE_BLOCK_RADIUS)),
194
251
),
195
252
LineKind::Quote => Some(
@@ -208,6 +265,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
208
265
ranges,
209
266
markers,
210
267
indents,
268
labels,
211
269
}
212
270
}
213
271
@@ -252,7 +310,7 @@ mod tests {
252
310
[
253
311
(starts[1].start, gpui_kit::px(18.)),
254
312
(starts[2].start, gpui_kit::px(12.)),
255
(starts[3].start, gpui_kit::px(10.)),
313
(starts[3].start, gpui_kit::px(36.)),
256
314
]
257
315
);
258
316
assert!(!draft.text().contains('\u{2003}'));
@@ -271,6 +329,58 @@ mod tests {
271
329
assert!(block.end < draft.line_ranges()[2].start);
272
330
}
273
331
332
#[test]
333
fn code_with_a_language_is_highlighted_while_typing() {
334
let draft = Draft::from_lines(&[
335
line(LineKind::Code(Some("go".into())), "x // y"),
336
line(LineKind::Code(Some("go".into())), "z"),
337
]);
338
let style = draft_style(&draft, "Mono".into());
339
let ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect();
340
// "x " plain, the comment, then "z": all after the 3-byte header mark.
341
assert_eq!(ranges[..2], [3..5, 5..9]);
342
assert_eq!(
343
draft_style(
344
&Draft::from_lines(&[line(LineKind::Code(None), "x // y")]),
345
"Mono".into()
346
)
347
.text
348
.len(),
349
1
350
);
351
}
352
353
#[test]
354
fn the_first_code_line_starts_a_line_for_the_highlighter() {
355
let draft = Draft::from_lines(&[line(LineKind::Code(Some("markdown".into())), "# h")]);
356
let style = draft_style(&draft, "Mono".into());
357
assert_eq!(&draft.text()[style.text[0].range.clone()], "# h");
358
}
359
360
#[test]
361
fn python_keywords_are_highlighted_in_the_composer() {
362
let draft = Draft::from_lines(&[
363
line(LineKind::Code(Some("python".into())), "def f():"),
364
line(LineKind::Code(Some("python".into())), "class A:"),
365
]);
366
let style = draft_style(&draft, "Mono".into());
367
let words: Vec<_> = style
368
.text
369
.iter()
370
.map(|d| &draft.text()[d.range.clone()])
371
.collect();
372
assert!(
373
words.contains(&"def") && words.contains(&"class"),
374
"{words:?}"
375
);
376
let mut ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect();
377
ranges.sort_by_key(|range| range.start);
378
assert!(
379
ranges.windows(2).all(|pair| pair[0].end <= pair[1].start),
380
"{ranges:?}"
381
);
382
}
383
274
384
#[test]
275
385
fn a_lone_code_line_still_gets_a_block() {
276
386
let draft = Draft::from_lines(&[line(LineKind::Code(None), "")]);
@@ -5,14 +5,16 @@ use gpui_kit::*;5
use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};5
use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};6
6
7
use crate::render::blocks::{Script, StyleFlags};7
use crate::render::blocks::{Script, StyleFlags};8
use crate::render::elements::{highlight_fill, readable_on};8
use crate::render::elements::{highlight_fill, readable_on, token_style};9
use crate::render::syntax;9
use app_base::theme;10
use app_base::theme;10
11
11
const CODE_PILL_RADIUS: f32 = 4.;12
const CODE_PILL_RADIUS: f32 = 4.;12
const CODE_BLOCK_RADIUS: f32 = 6.;13
const CODE_BLOCK_RADIUS: f32 = 6.;13
const QUOTE_BAR_WIDTH: f32 = 3.;14
const QUOTE_BAR_WIDTH: f32 = 3.;14
const QUOTE_INDENT: f32 = 12.;15
const QUOTE_INDENT: f32 = 12.;15
const CODE_INDENT: f32 = 10.;16
/// Room before code lines: the line numbers sit in it.17
pub const CODE_INDENT: f32 = 36.;16
const LIST_LEVEL_INDENT: f32 = 18.;18
const LIST_LEVEL_INDENT: f32 = 18.;17
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];19
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];18
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;20
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;@@ -24,6 +26,8 @@ pub struct DraftStyle {24
pub ranges: Vec<RangeDecoration>,26
pub ranges: Vec<RangeDecoration>,25
pub markers: Vec<Range<usize>>,27
pub markers: Vec<Range<usize>>,26
pub indents: Vec<(usize, Pixels)>,28
pub indents: Vec<(usize, Pixels)>,29
/// Code line numbers, each before the start of its line's content.30
pub labels: Vec<(usize, SharedString)>,27
}31
}28
32
29
fn line_indent(kind: &LineKind) -> f32 {33
fn line_indent(kind: &LineKind) -> f32 {@@ -111,6 +115,34 @@ fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {111
line_ranges[lines.start].start..line_ranges[lines.end - 1].end115
line_ranges[lines.start].start..line_ranges[lines.end - 1].end112
}116
}113
117
118
/// A code line cut where its tokens start and end, so no two decorations overlap: the119
/// input does not say which of two overlapping ones in a collection wins.120
fn code_pieces(121
line: Range<usize>,122
tokens: &[(Range<usize>, HighlightStyle)],123
) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {124
let plain = color(theme::text_strong());125
let mut pieces = Vec::new();126
let mut at = line.start;127
for (range, style) in tokens {128
let range = range.start.max(line.start)..range.end.min(line.end);129
if range.start >= range.end || range.start < at {130
continue;131
}132
if at < range.start {133
pieces.push((at..range.start, plain));134
}135
let mut style = *style;136
style.color = style.color.or(plain.color);137
pieces.push((range.clone(), style));138
at = range.end;139
}140
if at < line.end {141
pieces.push((at..line.end, plain));142
}143
pieces.into_iter()144
}145
114
pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {146
pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {115
let mut text = Vec::new();147
let mut text = Vec::new();116
let mut ranges = Vec::new();148
let mut ranges = Vec::new();@@ -152,6 +184,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {152
text.push(decoration);184
text.push(decoration);153
}185
}154
}186
}187
let mut labels = Vec::new();155
let kinds = draft.lines();188
let kinds = draft.lines();156
let mut index = 0;189
let mut index = 0;157
while index < kinds.len() {190
while index < kinds.len() {@@ -161,10 +194,32 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {161
.iter()194
.iter()162
.take_while(|other| *other == kind)195
.take_while(|other| *other == kind)163
.count();196
.count();197
// From after the header mark, so line one reads as a line start.198
let tokens: Vec<(Range<usize>, HighlightStyle)> = match kind {199
LineKind::Code(Some(language)) => {200
let block =201
draft.content_range(index).start..block_range(draft, index..run_end).end;202
syntax::highlight(&draft.text()[block.clone()], language)203
.unwrap_or_default()204
.into_iter()205
.map(|(range, token)| {206
(207
block.start + range.start..block.start + range.end,208
token_style(token),209
)210
})211
.collect()212
}213
_ => Vec::new(),214
};164
for line in index..run_end {215
for line in index..run_end {165
let marker = draft.marker_range(line);216
let marker = draft.marker_range(line);166
let content = draft.content_range(line);217
let content = draft.content_range(line);167
if !marker.is_empty() {218
if matches!(kind, LineKind::Code(_)) {219
labels.push((content.start, (line - index + 1).to_string().into()));220
}221
// A code block's header sits on its own row, so it hangs nothing.222
if !marker.is_empty() && !matches!(kind, LineKind::Code(_)) {168
markers.push(marker.clone());223
markers.push(marker.clone());169
if kind.is_list() {224
if kind.is_list() {170
text.push(TextDecoration::new(marker, color(theme::text_soft())));225
text.push(TextDecoration::new(marker, color(theme::text_soft())));@@ -177,10 +232,11 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {177
LineKind::Quote => {232
LineKind::Quote => {178
text.push(TextDecoration::new(content, color(theme::text_soft())))233
text.push(TextDecoration::new(content, color(theme::text_soft())))179
}234
}180
LineKind::Code(_) => text.push(235
LineKind::Code(_) => {181
TextDecoration::new(content, color(theme::text_strong()))236
text.extend(code_pieces(content, &tokens).map(|(range, style)| {182
.with_font_family(mono.clone()),237
TextDecoration::new(range, style).with_font_family(mono.clone())183
),238
}))239
}184
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),240
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),185
_ => {}241
_ => {}186
}242
}@@ -190,6 +246,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {190
RangeDecoration::new(block_range(draft, index..run_end))246
RangeDecoration::new(block_range(draft, index..run_end))191
.with_style(RangeDecorationStyle::Block)247
.with_style(RangeDecorationStyle::Block)192
.with_color(theme::code_surface())248
.with_color(theme::code_surface())249
.with_border(theme::code_frame())193
.with_radius(px(CODE_BLOCK_RADIUS)),250
.with_radius(px(CODE_BLOCK_RADIUS)),194
),251
),195
LineKind::Quote => Some(252
LineKind::Quote => Some(@@ -208,6 +265,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {208
ranges,265
ranges,209
markers,266
markers,210
indents,267
indents,268
labels,211
}269
}212
}270
}213
271
@@ -252,7 +310,7 @@ mod tests {252
[310
[253
(starts[1].start, gpui_kit::px(18.)),311
(starts[1].start, gpui_kit::px(18.)),254
(starts[2].start, gpui_kit::px(12.)),312
(starts[2].start, gpui_kit::px(12.)),255
(starts[3].start, gpui_kit::px(10.)),313
(starts[3].start, gpui_kit::px(36.)),256
]314
]257
);315
);258
assert!(!draft.text().contains('\u{2003}'));316
assert!(!draft.text().contains('\u{2003}'));@@ -271,6 +329,58 @@ mod tests {271
assert!(block.end < draft.line_ranges()[2].start);329
assert!(block.end < draft.line_ranges()[2].start);272
}330
}273
331
332
#[test]333
fn code_with_a_language_is_highlighted_while_typing() {334
let draft = Draft::from_lines(&[335
line(LineKind::Code(Some("go".into())), "x // y"),336
line(LineKind::Code(Some("go".into())), "z"),337
]);338
let style = draft_style(&draft, "Mono".into());339
let ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect();340
// "x " plain, the comment, then "z": all after the 3-byte header mark.341
assert_eq!(ranges[..2], [3..5, 5..9]);342
assert_eq!(343
draft_style(344
&Draft::from_lines(&[line(LineKind::Code(None), "x // y")]),345
"Mono".into()346
)347
.text348
.len(),349
1350
);351
}352
353
#[test]354
fn the_first_code_line_starts_a_line_for_the_highlighter() {355
let draft = Draft::from_lines(&[line(LineKind::Code(Some("markdown".into())), "# h")]);356
let style = draft_style(&draft, "Mono".into());357
assert_eq!(&draft.text()[style.text[0].range.clone()], "# h");358
}359
360
#[test]361
fn python_keywords_are_highlighted_in_the_composer() {362
let draft = Draft::from_lines(&[363
line(LineKind::Code(Some("python".into())), "def f():"),364
line(LineKind::Code(Some("python".into())), "class A:"),365
]);366
let style = draft_style(&draft, "Mono".into());367
let words: Vec<_> = style368
.text369
.iter()370
.map(|d| &draft.text()[d.range.clone()])371
.collect();372
assert!(373
words.contains(&"def") && words.contains(&"class"),374
"{words:?}"375
);376
let mut ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect();377
ranges.sort_by_key(|range| range.start);378
assert!(379
ranges.windows(2).all(|pair| pair[0].end <= pair[1].start),380
"{ranges:?}"381
);382
}383
274
#[test]384
#[test]275
fn a_lone_code_line_still_gets_a_block() {385
fn a_lone_code_line_still_gets_a_block() {276
let draft = Draft::from_lines(&[line(LineKind::Code(None), "")]);386
let draft = Draft::from_lines(&[line(LineKind::Code(None), "")]);@@ -1,3 +1,4 @@
1
use gpui_kit::component::tooltip::Tooltip;
1
2
use gpui_kit::component::{h_flex, v_flex};
2
3
use gpui_kit::prelude::FluentBuilder as _;
3
4
use gpui_kit::*;
@@ -15,13 +16,17 @@ const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;
15
16
const MARKER_WIDTH: f32 = 18.;
16
17
const WIDE_MARKER_WIDTH: f32 = 26.;
17
18
const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];
18
const CODE_HEADER_MIN_LINES: usize = 3;
19
const PLAIN_LANGUAGE: &str = "text";
20
19
const MIN_CONTRAST: f32 = 4.5;
21
20
const HIGHLIGHT_ALPHA: f32 = 0.3;
22
21
const CODE_LINE_PADDING_X: f32 = 6.;
23
22
const CODE_LINE_PADDING_Y: f32 = 4.;
24
23
const CODE_LINE_RADIUS: f32 = 4.;
24
const COPIED_SHOWN: std::time::Duration = std::time::Duration::from_millis(1500);
25
26
// shortcut: one "Copied" at a time app-wide, which is all a click can produce.
27
// The click number lets a later click on the same block keep "Copied" for its full time.
28
static COPIED_BLOCK: std::sync::Mutex<Option<(String, u64)>> = std::sync::Mutex::new(None);
29
static COPY_CLICKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
25
30
pub const CODE_LINE_TAG: &str = "message/code-line";
26
31
pub const CODE_BLOCK_TAG: &str = "message/code-block";
27
32
@@ -126,16 +131,38 @@ fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &A
126
131
.into_iter()
127
132
.map(|(range, token)| (range, token_style(token)))
128
133
.collect();
129
let body = div()
134
let numbers = (1..=code.split('\n').count())
135
.map(|number| number.to_string())
136
.collect::<Vec<_>>()
137
.join("\n");
138
// Lines do not wrap, so the numbers stay beside their lines; a long line scrolls.
139
let body = h_flex()
130
140
.w_full()
131
.px(px(10.))
141
.items_start()
132
142
.py(px(8.))
133
.child(SelectableRichText::new(
134
ElementId::Name(id.clone().into()),
135
code.to_owned(),
136
highlights,
137
));
138
let show_header = language.is_some() || code.lines().count() >= CODE_HEADER_MIN_LINES;
143
.child(
144
div()
145
.flex_none()
146
.pl(px(10.))
147
.pr(px(10.))
148
.text_right()
149
.text_color(code_meta(own))
150
.child(numbers),
151
)
152
.child(
153
div()
154
.id(ElementId::Name(format!("{id}-lines").into()))
155
.flex_1()
156
.min_w_0()
157
.pr(px(10.))
158
.overflow_x_scroll()
159
.whitespace_nowrap()
160
.child(SelectableRichText::new(
161
ElementId::Name(id.clone().into()),
162
code.to_owned(),
163
highlights,
164
)),
165
);
139
166
v_flex()
140
167
.debug_selector(|| CODE_BLOCK_TAG.into())
141
168
.w_full()
@@ -148,14 +175,15 @@ fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &A
148
175
.font_family(code_font(cx))
149
176
.text_size(px(12.5))
150
177
.line_height(relative(1.5))
151
.when(show_header, |container| {
152
container.child(code_header(
153
language.unwrap_or(PLAIN_LANGUAGE),
154
code,
155
&id,
156
own,
157
))
158
})
178
.child(code_header(
179
{
180
let id = language.unwrap_or(teams_core::PLAIN_LANGUAGE);
181
teams_core::code_language(id).map_or(id, |language| language.name)
182
},
183
code,
184
&id,
185
own,
186
))
159
187
.child(body)
160
188
.into_any_element()
161
189
}
@@ -194,18 +222,28 @@ fn code_text(own: bool) -> Hsla {
194
222
}
195
223
}
196
224
197
fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
198
let muted = if own {
225
fn code_meta(own: bool) -> Hsla {
226
if own {
199
227
theme::own_meta()
200
228
} else {
201
229
theme::text_muted()
202
};
230
}
231
}
232
233
fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
234
let muted = code_meta(own);
203
235
let code = code.to_owned();
236
let copy_id = format!("{id}-copy");
237
let copied = COPIED_BLOCK
238
.lock()
239
.is_ok_and(|block| block.as_ref().is_some_and(|(shown, _)| *shown == copy_id));
204
240
h_flex()
205
241
.w_full()
206
242
.h(px(26.))
207
243
.pl(px(10.))
208
.pr(px(6.))
244
.pr(px(4.))
245
.border_b_1()
246
.border_color(theme::code_frame())
209
247
.justify_between()
210
248
.items_center()
211
249
.font_family(theme::font_family())
@@ -214,23 +252,47 @@ fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
214
252
.child(language.to_owned())
215
253
.child(
216
254
h_flex()
217
.id(ElementId::Name(format!("{id}-copy").into()))
218
.h(px(20.))
219
.px(px(6.))
220
.gap(px(4.))
255
.id(ElementId::Name(copy_id.clone().into()))
256
.size(px(20.))
257
.justify_center()
221
258
.items_center()
222
259
.rounded(px(4.))
223
260
.cursor_pointer()
224
261
.hover(|button| button.bg(theme::inline_code_fill(false)))
262
.tooltip(move |window, cx| {
263
Tooltip::new(if copied { "Copied" } else { "Copy" }).build(window, cx)
264
})
225
265
.on_click(move |_, _, cx| {
226
cx.write_to_clipboard(ClipboardItem::new_string(code.clone()))
266
cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
267
show_copied(copy_id.clone(), cx);
227
268
})
228
.child(symbol("content_copy", 13., muted))
229
.child("Copy"),
269
.child(symbol(
270
if copied { "check" } else { "content_copy" },
271
13.,
272
muted,
273
)),
230
274
)
231
275
}
232
276
233
fn token_style(token: Token) -> HighlightStyle {
277
fn show_copied(copy_id: String, cx: &mut App) {
278
let click = COPY_CLICKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
279
if let Ok(mut block) = COPIED_BLOCK.lock() {
280
*block = Some((copy_id.clone(), click));
281
}
282
cx.refresh_windows();
283
cx.spawn(async move |cx| {
284
cx.background_executor().timer(COPIED_SHOWN).await;
285
let ended = COPIED_BLOCK
286
.lock()
287
.is_ok_and(|mut block| block.take_if(|shown| shown.1 == click).is_some());
288
if ended {
289
cx.update(|cx| cx.refresh_windows());
290
}
291
})
292
.detach();
293
}
294
295
pub(crate) fn token_style(token: Token) -> HighlightStyle {
234
296
match token {
235
297
Token::Keyword => HighlightStyle {
236
298
color: Some(theme::accent_text()),
@@ -245,6 +307,44 @@ fn token_style(token: Token) -> HighlightStyle {
245
307
font_style: Some(FontStyle::Italic),
246
308
..Default::default()
247
309
},
310
Token::Type => HighlightStyle {
311
color: Some(theme::green()),
312
..Default::default()
313
},
314
Token::Title => HighlightStyle {
315
color: Some(theme::amber()),
316
..Default::default()
317
},
318
Token::Tag => HighlightStyle {
319
color: Some(theme::accent_text()),
320
..Default::default()
321
},
322
Token::Attribute => HighlightStyle {
323
color: Some(theme::amber()),
324
..Default::default()
325
},
326
Token::Heading => HighlightStyle {
327
color: Some(theme::accent_text()),
328
font_weight: Some(FontWeight::BOLD),
329
..Default::default()
330
},
331
Token::Strong => HighlightStyle {
332
font_weight: Some(FontWeight::BOLD),
333
..Default::default()
334
},
335
Token::Emphasis => HighlightStyle {
336
font_style: Some(FontStyle::Italic),
337
..Default::default()
338
},
339
Token::Link => HighlightStyle {
340
color: Some(theme::accent_soft()),
341
underline: Some(UnderlineStyle {
342
thickness: px(1.),
343
color: Some(theme::accent_soft()),
344
wavy: false,
345
}),
346
..Default::default()
347
},
248
348
}
249
349
}
250
350
@@ -1,3 +1,4 @@1
use gpui_kit::component::tooltip::Tooltip;1
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::*;4
use gpui_kit::*;@@ -15,13 +16,17 @@ const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;15
const MARKER_WIDTH: f32 = 18.;16
const MARKER_WIDTH: f32 = 18.;16
const WIDE_MARKER_WIDTH: f32 = 26.;17
const WIDE_MARKER_WIDTH: f32 = 26.;17
const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];18
const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];18
const CODE_HEADER_MIN_LINES: usize = 3;19
const PLAIN_LANGUAGE: &str = "text";20
const MIN_CONTRAST: f32 = 4.5;19
const MIN_CONTRAST: f32 = 4.5;21
const HIGHLIGHT_ALPHA: f32 = 0.3;20
const HIGHLIGHT_ALPHA: f32 = 0.3;22
const CODE_LINE_PADDING_X: f32 = 6.;21
const CODE_LINE_PADDING_X: f32 = 6.;23
const CODE_LINE_PADDING_Y: f32 = 4.;22
const CODE_LINE_PADDING_Y: f32 = 4.;24
const CODE_LINE_RADIUS: f32 = 4.;23
const CODE_LINE_RADIUS: f32 = 4.;24
const COPIED_SHOWN: std::time::Duration = std::time::Duration::from_millis(1500);25
26
// shortcut: one "Copied" at a time app-wide, which is all a click can produce.27
// The click number lets a later click on the same block keep "Copied" for its full time.28
static COPIED_BLOCK: std::sync::Mutex<Option<(String, u64)>> = std::sync::Mutex::new(None);29
static COPY_CLICKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);25
pub const CODE_LINE_TAG: &str = "message/code-line";30
pub const CODE_LINE_TAG: &str = "message/code-line";26
pub const CODE_BLOCK_TAG: &str = "message/code-block";31
pub const CODE_BLOCK_TAG: &str = "message/code-block";27
32
@@ -126,16 +131,38 @@ fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &A126
.into_iter()131
.into_iter()127
.map(|(range, token)| (range, token_style(token)))132
.map(|(range, token)| (range, token_style(token)))128
.collect();133
.collect();129
let body = div()134
let numbers = (1..=code.split('\n').count())135
.map(|number| number.to_string())136
.collect::<Vec<_>>()137
.join("\n");138
// Lines do not wrap, so the numbers stay beside their lines; a long line scrolls.139
let body = h_flex()130
.w_full()140
.w_full()131
.px(px(10.))141
.items_start()132
.py(px(8.))142
.py(px(8.))133
.child(SelectableRichText::new(143
.child(134
ElementId::Name(id.clone().into()),144
div()135
code.to_owned(),145
.flex_none()136
highlights,146
.pl(px(10.))137
));147
.pr(px(10.))138
let show_header = language.is_some() || code.lines().count() >= CODE_HEADER_MIN_LINES;148
.text_right()149
.text_color(code_meta(own))150
.child(numbers),151
)152
.child(153
div()154
.id(ElementId::Name(format!("{id}-lines").into()))155
.flex_1()156
.min_w_0()157
.pr(px(10.))158
.overflow_x_scroll()159
.whitespace_nowrap()160
.child(SelectableRichText::new(161
ElementId::Name(id.clone().into()),162
code.to_owned(),163
highlights,164
)),165
);139
v_flex()166
v_flex()140
.debug_selector(|| CODE_BLOCK_TAG.into())167
.debug_selector(|| CODE_BLOCK_TAG.into())141
.w_full()168
.w_full()@@ -148,14 +175,15 @@ fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &A148
.font_family(code_font(cx))175
.font_family(code_font(cx))149
.text_size(px(12.5))176
.text_size(px(12.5))150
.line_height(relative(1.5))177
.line_height(relative(1.5))151
.when(show_header, |container| {178
.child(code_header(152
container.child(code_header(179
{153
language.unwrap_or(PLAIN_LANGUAGE),180
let id = language.unwrap_or(teams_core::PLAIN_LANGUAGE);154
code,181
teams_core::code_language(id).map_or(id, |language| language.name)155
&id,182
},156
own,183
code,157
))184
&id,158
})185
own,186
))159
.child(body)187
.child(body)160
.into_any_element()188
.into_any_element()161
}189
}@@ -194,18 +222,28 @@ fn code_text(own: bool) -> Hsla {194
}222
}195
}223
}196
224
197
fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {225
fn code_meta(own: bool) -> Hsla {198
let muted = if own {226
if own {199
theme::own_meta()227
theme::own_meta()200
} else {228
} else {201
theme::text_muted()229
theme::text_muted()202
};230
}231
}232
233
fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {234
let muted = code_meta(own);203
let code = code.to_owned();235
let code = code.to_owned();236
let copy_id = format!("{id}-copy");237
let copied = COPIED_BLOCK238
.lock()239
.is_ok_and(|block| block.as_ref().is_some_and(|(shown, _)| *shown == copy_id));204
h_flex()240
h_flex()205
.w_full()241
.w_full()206
.h(px(26.))242
.h(px(26.))207
.pl(px(10.))243
.pl(px(10.))208
.pr(px(6.))244
.pr(px(4.))245
.border_b_1()246
.border_color(theme::code_frame())209
.justify_between()247
.justify_between()210
.items_center()248
.items_center()211
.font_family(theme::font_family())249
.font_family(theme::font_family())@@ -214,23 +252,47 @@ fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {214
.child(language.to_owned())252
.child(language.to_owned())215
.child(253
.child(216
h_flex()254
h_flex()217
.id(ElementId::Name(format!("{id}-copy").into()))255
.id(ElementId::Name(copy_id.clone().into()))218
.h(px(20.))256
.size(px(20.))219
.px(px(6.))257
.justify_center()220
.gap(px(4.))221
.items_center()258
.items_center()222
.rounded(px(4.))259
.rounded(px(4.))223
.cursor_pointer()260
.cursor_pointer()224
.hover(|button| button.bg(theme::inline_code_fill(false)))261
.hover(|button| button.bg(theme::inline_code_fill(false)))262
.tooltip(move |window, cx| {263
Tooltip::new(if copied { "Copied" } else { "Copy" }).build(window, cx)264
})225
.on_click(move |_, _, cx| {265
.on_click(move |_, _, cx| {226
cx.write_to_clipboard(ClipboardItem::new_string(code.clone()))266
cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));267
show_copied(copy_id.clone(), cx);227
})268
})228
.child(symbol("content_copy", 13., muted))269
.child(symbol(229
.child("Copy"),270
if copied { "check" } else { "content_copy" },271
13.,272
muted,273
)),230
)274
)231
}275
}232
276
233
fn token_style(token: Token) -> HighlightStyle {277
fn show_copied(copy_id: String, cx: &mut App) {278
let click = COPY_CLICKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);279
if let Ok(mut block) = COPIED_BLOCK.lock() {280
*block = Some((copy_id.clone(), click));281
}282
cx.refresh_windows();283
cx.spawn(async move |cx| {284
cx.background_executor().timer(COPIED_SHOWN).await;285
let ended = COPIED_BLOCK286
.lock()287
.is_ok_and(|mut block| block.take_if(|shown| shown.1 == click).is_some());288
if ended {289
cx.update(|cx| cx.refresh_windows());290
}291
})292
.detach();293
}294
295
pub(crate) fn token_style(token: Token) -> HighlightStyle {234
match token {296
match token {235
Token::Keyword => HighlightStyle {297
Token::Keyword => HighlightStyle {236
color: Some(theme::accent_text()),298
color: Some(theme::accent_text()),@@ -245,6 +307,44 @@ fn token_style(token: Token) -> HighlightStyle {245
font_style: Some(FontStyle::Italic),307
font_style: Some(FontStyle::Italic),246
..Default::default()308
..Default::default()247
},309
},310
Token::Type => HighlightStyle {311
color: Some(theme::green()),312
..Default::default()313
},314
Token::Title => HighlightStyle {315
color: Some(theme::amber()),316
..Default::default()317
},318
Token::Tag => HighlightStyle {319
color: Some(theme::accent_text()),320
..Default::default()321
},322
Token::Attribute => HighlightStyle {323
color: Some(theme::amber()),324
..Default::default()325
},326
Token::Heading => HighlightStyle {327
color: Some(theme::accent_text()),328
font_weight: Some(FontWeight::BOLD),329
..Default::default()330
},331
Token::Strong => HighlightStyle {332
font_weight: Some(FontWeight::BOLD),333
..Default::default()334
},335
Token::Emphasis => HighlightStyle {336
font_style: Some(FontStyle::Italic),337
..Default::default()338
},339
Token::Link => HighlightStyle {340
color: Some(theme::accent_soft()),341
underline: Some(UnderlineStyle {342
thickness: px(1.),343
color: Some(theme::accent_soft()),344
wavy: false,345
}),346
..Default::default()347
},248
}348
}249
}349
}250
350
@@ -4,7 +4,7 @@ mod flow_text;
4
4
pub mod hooks;
5
5
mod link_tooltip;
6
6
mod selectable;
7
mod syntax;
7
pub(crate) mod syntax;
8
8
9
9
pub use blocks::{
10
10
Block, TableCell, layout_blocks, layout_card_blocks, strip_image_placeholders, table_images,
@@ -4,7 +4,7 @@ mod flow_text;4
pub mod hooks;4
pub mod hooks;5
mod link_tooltip;5
mod link_tooltip;6
mod selectable;6
mod selectable;7
mod syntax;7
pub(crate) mod syntax;8
8
9
pub use blocks::{9
pub use blocks::{10
Block, TableCell, layout_blocks, layout_card_blocks, strip_image_placeholders, table_images,10
Block, TableCell, layout_blocks, layout_card_blocks, strip_image_placeholders, table_images,@@ -6,20 +6,521 @@ pub enum Token {
6
6
String,
7
7
Number,
8
8
Comment,
9
Tag,
10
Attribute,
11
Heading,
12
Strong,
13
Emphasis,
14
Link,
15
/// Built-in types, functions and values: `bool`, `print`, `self`.
16
Type,
17
/// The name a definition gives: `f` in `def f`, `A` in `class A`.
18
Title,
9
19
}
10
20
21
/// A lexer for code: comments, strings, numbers and keywords.
11
22
struct Grammar {
12
23
line_comments: &'static [&'static str],
13
24
block_comment: Option<(&'static str, &'static str)>,
14
25
keywords: &'static [&'static str],
26
/// `'x'` is a character; other single quotes (Rust lifetimes) are left alone.
15
27
char_quotes: bool,
28
case_insensitive: bool,
29
/// Words after this prefix are keywords too, as `\section` in LaTeX.
30
command_prefix: Option<char>,
31
types: &'static [&'static str],
32
/// A word or string right before `:` is a key, as in JSON, YAML and CSS.
33
keys: bool,
34
/// `-` joins words, as in `font-size` and `Get-ChildItem`; such a word is a built-in.
35
dashed_words: bool,
16
36
}
17
37
18
const C_LIKE_KEYWORDS: &[&str] = &[
38
const CODE: Grammar = Grammar {
39
line_comments: &[],
40
block_comment: None,
41
keywords: &[],
42
char_quotes: false,
43
case_insensitive: false,
44
command_prefix: None,
45
types: &[],
46
keys: false,
47
dashed_words: false,
48
};
49
50
const fn c_style(keywords: &'static [&'static str]) -> Grammar {
51
Grammar {
52
line_comments: &["//"],
53
block_comment: Some(("/*", "*/")),
54
keywords,
55
..CODE
56
}
57
}
58
59
const fn hash_style(keywords: &'static [&'static str]) -> Grammar {
60
Grammar {
61
line_comments: &["#"],
62
keywords,
63
..CODE
64
}
65
}
66
67
const C_KEYWORDS: &[&str] = &[
68
"auto",
69
"break",
70
"case",
71
"char",
72
"const",
73
"continue",
74
"default",
75
"do",
76
"double",
77
"else",
78
"enum",
79
"extern",
80
"float",
81
"for",
82
"goto",
83
"if",
84
"inline",
85
"int",
86
"long",
87
"register",
88
"restrict",
89
"return",
90
"short",
91
"signed",
92
"sizeof",
93
"static",
94
"struct",
95
"switch",
96
"typedef",
97
"union",
98
"unsigned",
99
"void",
100
"volatile",
101
"while",
102
"NULL",
103
"true",
104
"false",
105
"bool",
106
"#include",
107
"#define",
108
"@interface",
109
"@implementation",
110
"@end",
111
"@property",
112
"self",
113
"nil",
114
];
115
const CPP_KEYWORDS: &[&str] = &[
116
"auto",
117
"bool",
118
"break",
119
"case",
120
"catch",
121
"char",
122
"class",
123
"const",
124
"constexpr",
125
"continue",
126
"default",
127
"delete",
128
"do",
129
"double",
130
"else",
131
"enum",
132
"explicit",
133
"extern",
134
"false",
135
"float",
136
"for",
137
"friend",
138
"goto",
139
"if",
140
"inline",
141
"int",
142
"long",
143
"namespace",
144
"new",
145
"noexcept",
146
"nullptr",
147
"operator",
148
"override",
149
"private",
150
"protected",
151
"public",
152
"return",
153
"short",
154
"signed",
155
"sizeof",
156
"static",
157
"struct",
158
"switch",
159
"template",
160
"this",
161
"throw",
162
"true",
163
"try",
164
"typedef",
165
"typename",
166
"union",
167
"unsigned",
168
"using",
169
"virtual",
170
"void",
171
"volatile",
172
"while",
173
];
174
const CSHARP_KEYWORDS: &[&str] = &[
175
"abstract",
176
"as",
177
"async",
178
"await",
179
"base",
180
"bool",
181
"break",
182
"case",
183
"catch",
184
"class",
185
"const",
186
"continue",
187
"default",
188
"delegate",
189
"do",
190
"else",
191
"enum",
192
"event",
193
"false",
194
"finally",
195
"for",
196
"foreach",
197
"get",
198
"if",
199
"in",
200
"int",
201
"interface",
202
"internal",
203
"is",
204
"new",
205
"null",
206
"object",
207
"out",
208
"override",
209
"private",
210
"protected",
211
"public",
212
"readonly",
213
"ref",
214
"return",
215
"sealed",
216
"set",
217
"static",
218
"string",
219
"struct",
220
"switch",
221
"this",
222
"throw",
223
"true",
224
"try",
225
"using",
226
"var",
227
"virtual",
228
"void",
229
"while",
230
];
231
const JAVA_KEYWORDS: &[&str] = &[
232
"abstract",
233
"boolean",
234
"break",
235
"case",
236
"catch",
237
"char",
238
"class",
239
"const",
240
"continue",
241
"default",
242
"do",
243
"double",
244
"else",
245
"enum",
246
"extends",
247
"false",
248
"final",
249
"finally",
250
"float",
251
"for",
252
"if",
253
"implements",
254
"import",
255
"instanceof",
256
"int",
257
"interface",
258
"long",
259
"new",
260
"null",
261
"package",
262
"private",
263
"protected",
264
"public",
265
"return",
266
"static",
267
"super",
268
"switch",
269
"this",
270
"throw",
271
"throws",
272
"true",
273
"try",
274
"var",
275
"void",
276
"while",
277
];
278
const JS_KEYWORDS: &[&str] = &[
279
"as",
280
"async",
281
"await",
282
"break",
283
"case",
284
"catch",
285
"class",
286
"const",
287
"continue",
288
"default",
289
"delete",
290
"do",
291
"else",
292
"enum",
293
"export",
294
"extends",
295
"false",
296
"finally",
297
"for",
298
"from",
299
"function",
300
"if",
301
"implements",
302
"import",
303
"in",
304
"instanceof",
305
"interface",
306
"let",
307
"new",
308
"null",
309
"of",
310
"private",
311
"protected",
312
"public",
313
"readonly",
314
"return",
315
"static",
316
"super",
317
"switch",
318
"this",
319
"throw",
320
"true",
321
"try",
322
"type",
323
"typeof",
324
"undefined",
325
"var",
326
"void",
327
"while",
328
"yield",
329
];
330
const DART_KEYWORDS: &[&str] = &[
331
"abstract",
332
"async",
333
"await",
334
"break",
335
"case",
336
"catch",
337
"class",
338
"const",
339
"continue",
340
"default",
341
"do",
342
"else",
343
"enum",
344
"extends",
345
"false",
346
"final",
347
"finally",
348
"for",
349
"if",
350
"implements",
351
"import",
352
"in",
353
"is",
354
"late",
355
"new",
356
"null",
357
"required",
358
"return",
359
"static",
360
"super",
361
"switch",
362
"this",
363
"throw",
364
"true",
365
"try",
366
"var",
367
"void",
368
"while",
369
"with",
370
"yield",
371
];
372
const GO_KEYWORDS: &[&str] = &[
373
"break",
374
"case",
375
"chan",
376
"const",
377
"continue",
378
"default",
379
"defer",
380
"else",
381
"fallthrough",
382
"for",
383
"func",
384
"go",
385
"goto",
386
"if",
387
"import",
388
"interface",
389
"map",
390
"package",
391
"range",
392
"return",
393
"select",
394
"struct",
395
"switch",
396
"type",
397
"var",
398
"true",
399
"false",
400
"nil",
401
"iota",
402
];
403
const KOTLIN_KEYWORDS: &[&str] = &[
404
"as",
405
"break",
406
"class",
407
"continue",
408
"data",
409
"do",
410
"else",
411
"false",
412
"for",
413
"fun",
414
"if",
415
"import",
416
"in",
417
"interface",
418
"is",
419
"null",
420
"object",
421
"override",
422
"package",
423
"private",
424
"return",
425
"super",
426
"this",
427
"throw",
428
"true",
429
"try",
430
"val",
431
"var",
432
"when",
433
"while",
434
];
435
const RUST_KEYWORDS: &[&str] = &[
436
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",
437
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",
438
"ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",
439
"unsafe", "use", "where", "while",
440
];
441
const SCALA_KEYWORDS: &[&str] = &[
442
"abstract",
443
"case",
444
"catch",
445
"class",
446
"def",
447
"do",
448
"else",
449
"extends",
450
"false",
451
"final",
452
"finally",
453
"for",
454
"if",
455
"implicit",
456
"import",
457
"lazy",
458
"match",
459
"new",
460
"null",
461
"object",
462
"override",
463
"package",
464
"private",
465
"protected",
466
"return",
467
"sealed",
468
"super",
469
"this",
470
"throw",
471
"trait",
472
"true",
473
"try",
474
"type",
475
"val",
476
"var",
477
"while",
478
"with",
479
"yield",
480
];
481
const SWIFT_KEYWORDS: &[&str] = &[
482
"as",
483
"break",
484
"case",
485
"catch",
486
"class",
487
"continue",
488
"default",
489
"defer",
490
"do",
491
"else",
492
"enum",
493
"extension",
494
"false",
495
"for",
496
"func",
497
"guard",
498
"if",
499
"import",
500
"in",
501
"init",
502
"let",
503
"nil",
504
"private",
505
"protocol",
506
"public",
507
"return",
508
"self",
509
"static",
510
"struct",
511
"switch",
512
"throw",
513
"throws",
514
"true",
515
"try",
516
"var",
517
"where",
518
"while",
519
];
520
const PHP_KEYWORDS: &[&str] = &[
19
521
"abstract",
522
"array",
20
523
"as",
21
"async",
22
"await",
23
524
"break",
24
525
"case",
25
526
"catch",
@@ -28,129 +529,735 @@ const C_LIKE_KEYWORDS: &[&str] = &[
28
529
"continue",
29
530
"default",
30
531
"do",
532
"echo",
31
533
"else",
32
"enum",
33
"export",
534
"elseif",
34
535
"extends",
35
536
"false",
36
537
"final",
37
538
"finally",
38
"fn",
39
539
"for",
40
"from",
41
"func",
540
"foreach",
42
541
"function",
43
"go",
44
542
"if",
45
"impl",
46
"import",
47
"in",
543
"implements",
544
"include",
48
545
"interface",
49
"let",
50
"loop",
51
"match",
52
"mod",
53
"mut",
54
546
"namespace",
55
547
"new",
56
548
"null",
57
"override",
58
"package",
59
549
"private",
60
550
"protected",
61
"pub",
62
551
"public",
63
"readonly",
552
"require",
64
553
"return",
65
"self",
66
554
"static",
67
"struct",
68
"super",
69
555
"switch",
70
"this",
71
556
"throw",
72
"trait",
73
557
"true",
74
558
"try",
75
"type",
76
"typeof",
77
559
"use",
78
"using",
79
"var",
80
"void",
81
"where",
82
560
"while",
83
"yield",
84
561
];
85
562
const PYTHON_KEYWORDS: &[&str] = &[
86
"and", "as", "async", "await", "break", "class", "continue", "def", "del", "elif", "else",
87
"except", "False", "finally", "for", "from", "if", "import", "in", "is", "lambda", "None",
88
"not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield",
563
"and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif",
564
"else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is",
565
"lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while",
566
"with", "yield",
567
];
568
const RUBY_KEYWORDS: &[&str] = &[
569
"and", "begin", "break", "case", "class", "def", "do", "else", "elsif", "end", "ensure",
570
"false", "for", "if", "in", "module", "next", "nil", "not", "or", "require", "rescue",
571
"return", "self", "super", "then", "true", "unless", "until", "when", "while", "yield",
572
];
573
const PERL_KEYWORDS: &[&str] = &[
574
"else", "elsif", "for", "foreach", "if", "last", "local", "my", "next", "our", "package",
575
"print", "require", "return", "sub", "unless", "until", "use", "while",
576
];
577
const R_KEYWORDS: &[&str] = &[
578
"break", "else", "FALSE", "for", "function", "if", "in", "NA", "next", "NULL", "repeat",
579
"return", "TRUE", "while", "library",
89
580
];
90
581
const SHELL_KEYWORDS: &[&str] = &[
91
"case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in",
92
"local", "return", "then", "while",
582
"case", "do", "done", "echo", "elif", "else", "esac", "exit", "export", "fi", "for",
583
"function", "if", "in", "local", "return", "set", "then", "until", "while",
584
];
585
const POWERSHELL_KEYWORDS: &[&str] = &[
586
"begin", "break", "catch", "class", "continue", "do", "else", "elseif", "end", "exit",
587
"filter", "finally", "for", "foreach", "function", "if", "in", "param", "process", "return",
588
"switch", "throw", "trap", "try", "until", "while", "$true", "$false", "$null",
589
];
590
const DOS_KEYWORDS: &[&str] = &[
591
"call", "cd", "copy", "defined", "del", "do", "echo", "else", "endlocal", "equ", "exist",
592
"exit", "for", "goto", "if", "in", "mkdir", "neq", "not", "pause", "set", "setlocal", "shift",
593
"start",
594
];
595
const DOCKER_KEYWORDS: &[&str] = &[
596
"add",
597
"arg",
598
"as",
599
"cmd",
600
"copy",
601
"entrypoint",
602
"env",
603
"expose",
604
"from",
605
"healthcheck",
606
"label",
607
"onbuild",
608
"run",
609
"shell",
610
"stopsignal",
611
"user",
612
"volume",
613
"workdir",
93
614
];
94
615
const SQL_KEYWORDS: &[&str] = &[
95
"and", "as", "by", "create", "delete", "from", "group", "insert", "into", "join", "left",
96
"not", "null", "on", "or", "order", "select", "set", "table", "update", "values", "where",
616
"alter", "and", "as", "asc", "between", "by", "case", "create", "delete", "desc", "distinct",
617
"drop", "else", "end", "exists", "from", "group", "having", "in", "inner", "insert", "into",
618
"is", "join", "left", "like", "limit", "not", "null", "on", "or", "order", "outer", "right",
619
"select", "set", "table", "then", "union", "update", "values", "when", "where", "with",
620
];
621
const KQL_KEYWORDS: &[&str] = &[
622
"and",
623
"asc",
624
"by",
625
"count",
626
"desc",
627
"distinct",
628
"extend",
629
"join",
630
"let",
631
"limit",
632
"or",
633
"order",
634
"project",
635
"render",
636
"sort",
637
"summarize",
638
"take",
639
"top",
640
"union",
641
"where",
642
];
643
const GRAPHQL_KEYWORDS: &[&str] = &[
644
"enum",
645
"extend",
646
"false",
647
"fragment",
648
"implements",
649
"input",
650
"interface",
651
"mutation",
652
"null",
653
"on",
654
"query",
655
"scalar",
656
"schema",
657
"subscription",
658
"true",
659
"type",
660
"union",
661
];
662
const HTTP_KEYWORDS: &[&str] = &[
663
"CONNECT", "DELETE", "GET", "HEAD", "HTTP", "OPTIONS", "PATCH", "POST", "PUT", "TRACE",
664
];
665
const VB_KEYWORDS: &[&str] = &[
666
"and", "as", "boolean", "byval", "byref", "call", "case", "class", "const", "dim", "do",
667
"each", "else", "elseif", "end", "exit", "false", "for", "function", "if", "imports", "in",
668
"integer", "is", "loop", "module", "new", "next", "not", "nothing", "or", "private", "public",
669
"return", "select", "set", "string", "sub", "then", "to", "true", "while", "with",
670
];
671
const VERILOG_KEYWORDS: &[&str] = &[
672
"always",
673
"assign",
674
"begin",
675
"case",
676
"else",
677
"end",
678
"endcase",
679
"endmodule",
680
"for",
681
"if",
682
"initial",
683
"input",
684
"integer",
685
"module",
686
"negedge",
687
"output",
688
"parameter",
689
"posedge",
690
"reg",
691
"wire",
692
];
693
const VHDL_KEYWORDS: &[&str] = &[
694
"architecture",
695
"begin",
696
"case",
697
"downto",
698
"else",
699
"elsif",
700
"end",
701
"entity",
702
"for",
703
"generic",
704
"if",
705
"in",
706
"is",
707
"library",
708
"loop",
709
"map",
710
"of",
711
"others",
712
"out",
713
"port",
714
"process",
715
"signal",
716
"then",
717
"to",
718
"use",
719
"variable",
720
"when",
721
"while",
722
];
723
const OCTAVE_KEYWORDS: &[&str] = &[
724
"break",
725
"case",
726
"catch",
727
"continue",
728
"else",
729
"elseif",
730
"end",
731
"for",
732
"function",
733
"if",
734
"otherwise",
735
"return",
736
"switch",
737
"try",
738
"while",
739
];
740
const LISP_KEYWORDS: &[&str] = &[
741
"cond",
742
"defmacro",
743
"defparameter",
744
"defun",
745
"defvar",
746
"if",
747
"lambda",
748
"let",
749
"nil",
750
"progn",
751
"quote",
752
"setf",
753
"setq",
754
"t",
755
"unless",
756
"when",
97
757
];
758
const LITERALS: &[&str] = &["true", "false", "null", "yes", "no", "on", "off", "~"];
98
759
99
const C_LIKE: Grammar = Grammar {
100
line_comments: &["//"],
101
block_comment: Some(("/*", "*/")),
102
keywords: C_LIKE_KEYWORDS,
103
char_quotes: false,
760
const C: Grammar = Grammar {
761
types: &[
762
"size_t", "int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t",
763
"uint64_t", "FILE", "printf", "scanf", "malloc", "free", "memcpy", "strlen", "BOOL", "YES",
764
"NO", "id", "NSString", "NSLog",
765
],
766
char_quotes: true,
767
..c_style(C_KEYWORDS)
768
};
769
const CPP: Grammar = Grammar {
770
types: &[
771
"std",
772
"string",
773
"vector",
774
"map",
775
"set",
776
"size_t",
777
"cout",
778
"cin",
779
"endl",
780
"unique_ptr",
781
"shared_ptr",
782
"make_unique",
783
"make_shared",
784
"printf",
785
],
786
char_quotes: true,
787
..c_style(CPP_KEYWORDS)
788
};
789
const CSHARP: Grammar = Grammar {
790
types: &[
791
"byte",
792
"char",
793
"decimal",
794
"double",
795
"float",
796
"long",
797
"Console",
798
"List",
799
"Dictionary",
800
"Task",
801
"DateTime",
802
"Exception",
803
"nameof",
804
],
805
char_quotes: true,
806
..c_style(CSHARP_KEYWORDS)
807
};
808
const JAVA: Grammar = Grammar {
809
types: &[
810
"byte",
811
"short",
812
"String",
813
"Integer",
814
"Long",
815
"Double",
816
"Boolean",
817
"Object",
818
"List",
819
"Map",
820
"ArrayList",
821
"HashMap",
822
"System",
823
"Exception",
824
"Override",
825
],
826
char_quotes: true,
827
..c_style(JAVA_KEYWORDS)
828
};
829
const RUST: Grammar = Grammar {
830
types: &[
831
"i8",
832
"i16",
833
"i32",
834
"i64",
835
"i128",
836
"isize",
837
"u8",
838
"u16",
839
"u32",
840
"u64",
841
"u128",
842
"usize",
843
"f32",
844
"f64",
845
"bool",
846
"char",
847
"str",
848
"String",
849
"Vec",
850
"Option",
851
"Some",
852
"None",
853
"Result",
854
"Ok",
855
"Err",
856
"Box",
857
"Rc",
858
"Arc",
859
"println",
860
"print",
861
"format",
862
"vec",
863
"panic",
864
"assert",
865
"assert_eq",
866
],
867
char_quotes: true,
868
..c_style(RUST_KEYWORDS)
869
};
870
const KOTLIN: Grammar = Grammar {
871
types: &[
872
"Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "println",
873
"listOf", "mapOf", "setOf",
874
],
875
char_quotes: true,
876
..c_style(KOTLIN_KEYWORDS)
104
877
};
105
const CHAR_LIKE: Grammar = Grammar {
878
const SCALA: Grammar = Grammar {
879
types: &[
880
"Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "Option",
881
"Some", "None", "println",
882
],
106
883
char_quotes: true,
107
..C_LIKE
884
..c_style(SCALA_KEYWORDS)
885
};
886
const JS: Grammar = Grammar {
887
types: &[
888
"console", "document", "window", "Promise", "Array", "Object", "JSON", "Math", "Date",
889
"Error", "Map", "Set", "string", "number", "boolean", "any", "unknown", "never", "require",
890
"module",
891
],
892
..c_style(JS_KEYWORDS)
893
};
894
const DART: Grammar = Grammar {
895
types: &[
896
"int", "double", "num", "String", "bool", "List", "Map", "Set", "dynamic", "Future",
897
"Stream", "print",
898
],
899
..c_style(DART_KEYWORDS)
900
};
901
const GO: Grammar = Grammar {
902
types: &[
903
"bool",
904
"byte",
905
"complex64",
906
"complex128",
907
"error",
908
"float32",
909
"float64",
910
"int",
911
"int8",
912
"int16",
913
"int32",
914
"int64",
915
"rune",
916
"string",
917
"uint",
918
"uint8",
919
"uint16",
920
"uint32",
921
"uint64",
922
"uintptr",
923
"any",
924
"append",
925
"cap",
926
"close",
927
"copy",
928
"delete",
929
"len",
930
"make",
931
"new",
932
"panic",
933
"print",
934
"println",
935
"recover",
936
],
937
..c_style(GO_KEYWORDS)
938
};
939
const SWIFT: Grammar = Grammar {
940
types: &[
941
"Int",
942
"Double",
943
"Float",
944
"Bool",
945
"String",
946
"Character",
947
"Array",
948
"Dictionary",
949
"Set",
950
"Optional",
951
"Any",
952
"print",
953
],
954
..c_style(SWIFT_KEYWORDS)
955
};
956
const CSS: Grammar = Grammar {
957
keys: true,
958
dashed_words: true,
959
..c_style(&[])
108
960
};
109
const HASH: Grammar = Grammar {
110
line_comments: &["#"],
961
const JSON: Grammar = Grammar {
962
keys: true,
963
..c_style(LITERALS)
964
};
965
const VERILOG: Grammar = Grammar {
966
types: &["$display", "$finish", "$time", "logic", "bit"],
967
..c_style(VERILOG_KEYWORDS)
968
};
969
const PHP: Grammar = Grammar {
970
types: &[
971
"$this",
972
"array",
973
"count",
974
"isset",
975
"empty",
976
"strlen",
977
"json_encode",
978
"json_decode",
979
"var_dump",
980
"print_r",
981
],
982
line_comments: &["//", "#"],
983
..c_style(PHP_KEYWORDS)
984
};
985
const KQL: Grammar = Grammar {
986
types: &[
987
"ago", "now", "datetime", "bin", "dcount", "tostring", "toint", "strcat", "count", "sum",
988
"avg",
989
],
111
990
block_comment: None,
112
keywords: PYTHON_KEYWORDS,
113
char_quotes: false,
991
case_insensitive: true,
992
..c_style(KQL_KEYWORDS)
993
};
994
const PYTHON: Grammar = Grammar {
995
types: &[
996
"self",
997
"cls",
998
"print",
999
"len",
1000
"range",
1001
"int",
1002
"str",
1003
"float",
1004
"bool",
1005
"bytes",
1006
"list",
1007
"dict",
1008
"set",
1009
"tuple",
1010
"object",
1011
"open",
1012
"super",
1013
"isinstance",
1014
"enumerate",
1015
"zip",
1016
"map",
1017
"filter",
1018
"sorted",
1019
"sum",
1020
"min",
1021
"max",
1022
"abs",
1023
"type",
1024
"Exception",
1025
],
1026
..hash_style(PYTHON_KEYWORDS)
1027
};
1028
const RUBY: Grammar = Grammar {
1029
types: &[
1030
"puts",
1031
"print",
1032
"p",
1033
"attr_accessor",
1034
"attr_reader",
1035
"attr_writer",
1036
"lambda",
1037
"proc",
1038
"raise",
1039
],
1040
..hash_style(RUBY_KEYWORDS)
1041
};
1042
const PERL: Grammar = Grammar {
1043
types: &[
1044
"chomp", "die", "join", "keys", "push", "shift", "split", "values", "open", "close",
1045
],
1046
..hash_style(PERL_KEYWORDS)
1047
};
1048
const R: Grammar = Grammar {
1049
types: &[
1050
"c", "list", "print", "paste", "length", "vector", "matrix", "sum", "mean", "cat",
1051
],
1052
..hash_style(R_KEYWORDS)
114
1053
};
115
1054
const SHELL: Grammar = Grammar {
116
line_comments: &["#"],
117
block_comment: None,
118
keywords: SHELL_KEYWORDS,
119
char_quotes: false,
1055
types: &[
1056
"cd", "ls", "pwd", "grep", "sed", "awk", "cat", "cp", "mv", "rm", "mkdir", "touch",
1057
"chmod", "sudo", "git", "docker", "kubectl", "curl", "wget", "read", "printf", "source",
1058
"test", "true", "false",
1059
],
1060
..hash_style(SHELL_KEYWORDS)
1061
};
1062
const YAML: Grammar = Grammar {
1063
keys: true,
1064
..hash_style(LITERALS)
1065
};
1066
const GRAPHQL: Grammar = Grammar {
1067
types: &["String", "Int", "Float", "Boolean", "ID"],
1068
..hash_style(GRAPHQL_KEYWORDS)
1069
};
1070
const DOCKER: Grammar = Grammar {
1071
case_insensitive: true,
1072
..hash_style(DOCKER_KEYWORDS)
1073
};
1074
const POWERSHELL: Grammar = Grammar {
1075
dashed_words: true,
1076
block_comment: Some(("<#", "#>")),
1077
case_insensitive: true,
1078
..hash_style(POWERSHELL_KEYWORDS)
1079
};
1080
const DOS: Grammar = Grammar {
1081
line_comments: &["::", "rem ", "REM ", "@rem "],
1082
case_insensitive: true,
1083
keywords: DOS_KEYWORDS,
1084
..CODE
120
1085
};
121
1086
const SQL: Grammar = Grammar {
1087
types: &[
1088
"int",
1089
"integer",
1090
"bigint",
1091
"varchar",
1092
"char",
1093
"text",
1094
"date",
1095
"timestamp",
1096
"boolean",
1097
"decimal",
1098
"count",
1099
"sum",
1100
"avg",
1101
"min",
1102
"max",
1103
"coalesce",
1104
"now",
1105
],
122
1106
line_comments: &["--"],
123
1107
block_comment: Some(("/*", "*/")),
124
1108
keywords: SQL_KEYWORDS,
125
char_quotes: false,
1109
case_insensitive: true,
1110
..CODE
126
1111
};
127
const MARKUP: Grammar = Grammar {
128
line_comments: &[],
129
block_comment: Some(("<!--", "-->")),
130
keywords: &[],
131
char_quotes: false,
1112
const VHDL: Grammar = Grammar {
1113
types: &[
1114
"std_logic",
1115
"std_logic_vector",
1116
"integer",
1117
"boolean",
1118
"unsigned",
1119
"signed",
1120
"rising_edge",
1121
],
1122
line_comments: &["--"],
1123
keywords: VHDL_KEYWORDS,
1124
case_insensitive: true,
1125
..CODE
1126
};
1127
const VB: Grammar = Grammar {
1128
line_comments: &["'", "rem ", "REM "],
1129
keywords: VB_KEYWORDS,
1130
case_insensitive: true,
1131
..CODE
1132
};
1133
const OCTAVE: Grammar = Grammar {
1134
types: &[
1135
"disp", "zeros", "ones", "size", "numel", "length", "plot", "printf", "fprintf", "true",
1136
"false",
1137
],
1138
line_comments: &["%", "#"],
1139
block_comment: Some(("%{", "%}")),
1140
keywords: OCTAVE_KEYWORDS,
1141
..CODE
1142
};
1143
const LISP: Grammar = Grammar {
1144
types: &[
1145
"car", "cdr", "cons", "list", "format", "print", "append", "mapcar", "funcall", "apply",
1146
],
1147
line_comments: &[";"],
1148
block_comment: Some(("#|", "|#")),
1149
keywords: LISP_KEYWORDS,
1150
..CODE
1151
};
1152
const HTTP: Grammar = Grammar {
1153
keys: true,
1154
dashed_words: true,
1155
keywords: HTTP_KEYWORDS,
1156
..CODE
1157
};
1158
const LATEX: Grammar = Grammar {
1159
line_comments: &["%"],
1160
command_prefix: Some('\\'),
1161
..CODE
132
1162
};
133
1163
134
fn grammar_for(language: &str) -> Option<&'static Grammar> {
135
match language.to_ascii_lowercase().as_str() {
136
"rust" | "rs" | "c" | "cpp" | "c++" | "csharp" | "cs" | "c#" | "java" | "go" | "kotlin"
137
| "scala" => Some(&CHAR_LIKE),
138
"javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" | "swift" | "php" | "json"
139
| "css" | "scss" | "less" | "dart" => Some(&C_LIKE),
140
"python" | "py" | "ruby" | "rb" | "yaml" | "yml" | "toml" | "r" | "perl" | "dockerfile"
141
| "makefile" => Some(&HASH),
142
"bash" | "sh" | "shell" | "zsh" | "powershell" | "ps1" => Some(&SHELL),
143
"sql" | "tsql" | "plsql" | "lua" => Some(&SQL),
144
"html" | "xml" | "svg" | "markdown" | "md" => Some(&MARKUP),
145
_ => None,
146
}
1164
enum Rules {
1165
Code(&'static Grammar),
1166
Markup,
1167
Markdown,
1168
}
1169
1170
/// The rules for a code block language: one arm per Teams language id (see
1171
/// `teams_core::CODE_LANGUAGES`); a language without an arm stays plain.
1172
fn rules_for(language: &str) -> Option<Rules> {
1173
let id = teams_core::code_language(language).map_or_else(
1174
|| language.to_ascii_lowercase(),
1175
|known| known.id.to_ascii_lowercase(),
1176
);
1177
let grammar = match id.as_str() {
1178
"html" | "xml" | "jsp" => return Some(Rules::Markup),
1179
"markdown" => return Some(Rules::Markdown),
1180
"bash" => &SHELL,
1181
"c" | "objectivec" => &C,
1182
"cpp" => &CPP,
1183
"csharp" => &CSHARP,
1184
"css" | "scss" | "less" => &CSS,
1185
"dart" => &DART,
1186
"dockerfile" => &DOCKER,
1187
"dos" => &DOS,
1188
"go" => &GO,
1189
"graphql" => &GRAPHQL,
1190
"http" => &HTTP,
1191
"java" => &JAVA,
1192
"javascript" | "jsx" | "typescript" => &JS,
1193
"json" => &JSON,
1194
"kotlin" => &KOTLIN,
1195
"kql" => &KQL,
1196
"latex" => &LATEX,
1197
"lisp" => &LISP,
1198
"octave" => &OCTAVE,
1199
"perl" => &PERL,
1200
"php" => &PHP,
1201
"powershell" => &POWERSHELL,
1202
"python" => &PYTHON,
1203
"r" => &R,
1204
"ruby" => &RUBY,
1205
"rust" => &RUST,
1206
"scala" => &SCALA,
1207
"sql" | "tsql" | "plsql" => &SQL,
1208
"swift" => &SWIFT,
1209
"vbnet" | "vbscript" => &VB,
1210
"verilog" => &VERILOG,
1211
"vhdl" => &VHDL,
1212
"yaml" | "toml" => &YAML,
1213
_ => return None,
1214
};
1215
Some(Rules::Code(grammar))
147
1216
}
148
1217
149
1218
pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> {
150
let grammar = grammar_for(language)?;
151
let sql = grammar.keywords == SQL_KEYWORDS;
1219
Some(match rules_for(language)? {
1220
Rules::Code(grammar) => highlight_code(code, grammar),
1221
Rules::Markup => highlight_markup(code),
1222
Rules::Markdown => highlight_markdown(code),
1223
})
1224
}
1225
1226
/// Keywords whose next word is the name being defined.
1227
const DEFINITIONS: &[&str] = &[
1228
"class",
1229
"def",
1230
"enum",
1231
"fn",
1232
"fun",
1233
"func",
1234
"function",
1235
"interface",
1236
"module",
1237
"object",
1238
"protocol",
1239
"struct",
1240
"sub",
1241
"trait",
1242
"type",
1243
];
1244
1245
/// Only spaces, or a YAML list dash, before `at` on its line.
1246
fn starts_line(code: &str, at: usize) -> bool {
1247
let line = &code[code[..at].rfind('\n').map_or(0, |end| end + 1)..at];
1248
matches!(line.trim(), "" | "-")
1249
}
1250
1251
/// Followed by `:` (not `::`) after optional spaces.
1252
fn before_colon(code: &str, end: usize) -> bool {
1253
let rest = code[end..].trim_start_matches([' ', '\t']);
1254
rest.starts_with(':') && !rest.starts_with("::")
1255
}
1256
1257
fn highlight_code(code: &str, grammar: &Grammar) -> Vec<(Range<usize>, Token)> {
152
1258
let mut tokens = Vec::new();
153
1259
let mut index = 0;
1260
let mut defines = false;
154
1261
while index < code.len() {
155
1262
let rest = &code[index..];
156
1263
if let Some((open, close)) = grammar.block_comment
@@ -163,11 +1270,12 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)
163
1270
index = end;
164
1271
continue;
165
1272
}
166
if grammar
167
.line_comments
168
.iter()
169
.any(|marker| rest.starts_with(marker))
170
{
1273
let line_start = index == 0 || code.as_bytes()[index - 1] == b'\n';
1274
if grammar.line_comments.iter().any(|marker| {
1275
rest.starts_with(marker)
1276
// A word comment such as `rem ` only counts at the start of a line.
1277
&& (!marker.ends_with(' ') || line_start || code[..index].ends_with(' '))
1278
}) {
171
1279
let end = rest.find('\n').map_or(code.len(), |offset| index + offset);
172
1280
tokens.push((index..end, Token::Comment));
173
1281
index = end;
@@ -180,7 +1288,11 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)
180
1288
}
181
1289
if matches!(character, '"' | '\'' | '`') {
182
1290
let end = string_end(code, index, character);
183
tokens.push((index..end, Token::String));
1291
let key = grammar.keys && before_colon(code, end);
1292
tokens.push((
1293
index..end,
1294
if key { Token::Attribute } else { Token::String },
1295
));
184
1296
index = end;
185
1297
continue;
186
1298
}
@@ -192,28 +1304,190 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)
192
1304
index += length;
193
1305
continue;
194
1306
}
195
if character.is_alphabetic() || character == '_' {
196
let length = rest
197
.find(|next: char| !(next.is_alphanumeric() || next == '_'))
198
.unwrap_or(rest.len());
1307
let command = grammar.command_prefix == Some(character);
1308
if character.is_alphabetic() || matches!(character, '_' | '$' | '@' | '#') || command {
1309
let dashed = grammar.dashed_words;
1310
let length = character.len_utf8()
1311
+ rest[character.len_utf8()..]
1312
.find(|next: char| {
1313
!(next.is_alphanumeric() || next == '_' || dashed && next == '-')
1314
})
1315
.unwrap_or(rest.len() - character.len_utf8());
1316
let length = rest[..length].trim_end_matches('-').len();
199
1317
let word = &rest[..length];
200
let is_keyword = if sql {
201
grammar
202
.keywords
203
.iter()
204
.any(|keyword| keyword.eq_ignore_ascii_case(word))
1318
let same = |known: &&str| {
1319
if grammar.case_insensitive {
1320
known.eq_ignore_ascii_case(word)
1321
} else {
1322
*known == word
1323
}
1324
};
1325
let end = index + length;
1326
let token = if command && length > 1 || grammar.keywords.iter().any(same) {
1327
Some(Token::Keyword)
1328
} else if grammar.keys && starts_line(code, index) && before_colon(code, end) {
1329
Some(Token::Attribute)
1330
} else if defines {
1331
Some(Token::Title)
1332
} else if grammar.types.iter().any(same) || dashed && word.contains('-') {
1333
Some(Token::Type)
205
1334
} else {
206
grammar.keywords.contains(&word)
1335
None
207
1336
};
208
if is_keyword {
209
tokens.push((index..index + length, Token::Keyword));
210
}
211
index += length;
1337
defines = token == Some(Token::Keyword) && DEFINITIONS.iter().any(same);
1338
tokens.extend(token.map(|token| (index..end, token)));
1339
index = end;
212
1340
continue;
213
1341
}
1342
if !character.is_whitespace() {
1343
defines = false;
1344
}
214
1345
index += character.len_utf8();
215
1346
}
216
Some(tokens)
1347
tokens
1348
}
1349
1350
/// HTML and XML: tag names, attribute names, quoted values and comments.
1351
fn highlight_markup(code: &str) -> Vec<(Range<usize>, Token)> {
1352
let mut tokens = Vec::new();
1353
let mut index = 0;
1354
while let Some(offset) = code[index..].find('<') {
1355
let start = index + offset;
1356
let rest = &code[start..];
1357
if rest.starts_with("<!--") {
1358
let end = rest.find("-->").map_or(code.len(), |at| start + at + 3);
1359
tokens.push((start..end, Token::Comment));
1360
index = end;
1361
continue;
1362
}
1363
let name_start = start + 1 + usize::from(rest[1..].starts_with(['/', '!', '?']));
1364
let name_end = name_start
1365
+ code[name_start..]
1366
.find(|next: char| {
1367
!(next.is_alphanumeric() || matches!(next, '-' | ':' | '_' | '.'))
1368
})
1369
.unwrap_or(code.len() - name_start);
1370
if name_end == name_start {
1371
index = start + 1;
1372
continue;
1373
}
1374
tokens.push((name_start..name_end, Token::Tag));
1375
let close = code[name_end..]
1376
.find('>')
1377
.map_or(code.len(), |at| name_end + at);
1378
let mut at = name_end;
1379
while at < close {
1380
let character = code[at..].chars().next().unwrap_or_default();
1381
if matches!(character, '"' | '\'') {
1382
let end = code[at + 1..close]
1383
.find(character)
1384
.map_or(close, |end| at + 1 + end + 1);
1385
tokens.push((at..end, Token::String));
1386
at = end;
1387
} else if character.is_alphabetic() {
1388
let end = at
1389
+ code[at..close]
1390
.find(|next: char| {
1391
!(next.is_alphanumeric() || matches!(next, '-' | ':' | '_'))
1392
})
1393
.unwrap_or(close - at);
1394
tokens.push((at..end, Token::Attribute));
1395
at = end;
1396
} else {
1397
at += character.len_utf8();
1398
}
1399
}
1400
index = (close + 1).min(code.len());
1401
}
1402
tokens
1403
}
1404
1405
/// Markdown by line: headings, quotes, list markers, fenced code, then inline code, bold,
1406
/// italic and links.
1407
fn highlight_markdown(code: &str) -> Vec<(Range<usize>, Token)> {
1408
let mut tokens = Vec::new();
1409
let mut fenced = false;
1410
let mut start = 0;
1411
for line in code.split('\n') {
1412
let range = start..start + line.len();
1413
start = range.end + 1;
1414
let trimmed = line.trim_start();
1415
let indent = range.start + line.len() - trimmed.len();
1416
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
1417
fenced = !fenced;
1418
tokens.push((range, Token::String));
1419
continue;
1420
}
1421
if fenced {
1422
tokens.push((range, Token::String));
1423
continue;
1424
}
1425
let hashes = trimmed.bytes().take_while(|byte| *byte == b'#').count();
1426
if (1..=6).contains(&hashes) && trimmed[hashes..].starts_with(' ') {
1427
tokens.push((range, Token::Heading));
1428
continue;
1429
}
1430
if trimmed.starts_with('>') {
1431
tokens.push((range, Token::Comment));
1432
continue;
1433
}
1434
let marker = list_marker(trimmed);
1435
if marker > 0 {
1436
tokens.push((indent..indent + marker, Token::Keyword));
1437
}
1438
inline_markdown(code, indent + marker..range.end, &mut tokens);
1439
}
1440
tokens
1441
}
1442
1443
/// Byte length of a `- `, `* `, `+ ` or `1. ` list marker.
1444
fn list_marker(line: &str) -> usize {
1445
if line.starts_with(['-', '*', '+']) && line[1..].starts_with(' ') {
1446
return 1;
1447
}
1448
let digits = line.bytes().take_while(u8::is_ascii_digit).count();
1449
if digits > 0 && line[digits..].starts_with(". ") {
1450
digits + 1
1451
} else {
1452
0
1453
}
1454
}
1455
1456
fn inline_markdown(code: &str, range: Range<usize>, tokens: &mut Vec<(Range<usize>, Token)>) {
1457
let mut index = range.start;
1458
while index < range.end {
1459
let rest = &code[index..range.end];
1460
let span = |open: &str, close: &str| {
1461
rest.strip_prefix(open)?
1462
.find(close)
1463
.filter(|length| *length > 0)
1464
.map(|length| index + open.len() + length + close.len())
1465
};
1466
let found = if rest.starts_with('`') {
1467
span("`", "`").map(|end| (end, Token::String))
1468
} else if rest.starts_with("**") || rest.starts_with("__") {
1469
span(&rest[..2], &rest[..2]).map(|end| (end, Token::Strong))
1470
} else if rest.starts_with(['*', '_']) {
1471
span(&rest[..1], &rest[..1]).map(|end| (end, Token::Emphasis))
1472
} else if rest.starts_with('[') {
1473
rest.find("](")
1474
.and_then(|label| {
1475
rest[label..]
1476
.find(')')
1477
.map(|close| index + label + close + 1)
1478
})
1479
.map(|end| (end, Token::Link))
1480
} else {
1481
None
1482
};
1483
match found {
1484
Some((end, token)) => {
1485
tokens.push((index..end, token));
1486
index = end;
1487
}
1488
None => index += rest.chars().next().map_or(1, char::len_utf8),
1489
}
1490
}
217
1491
}
218
1492
219
1493
fn is_char_literal(rest: &str) -> bool {
@@ -261,6 +1535,7 @@ mod tests {
261
1535
vec![
262
1536
("// x", Token::Comment),
263
1537
("fn", Token::Keyword),
1538
("a", Token::Title),
264
1539
("\"b\"", Token::String),
265
1540
]
266
1541
);
@@ -283,7 +1558,13 @@ mod tests {
283
1558
fn rust_lifetime_is_not_a_string() {
284
1559
assert_eq!(
285
1560
kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"),
286
vec![("fn", Token::Keyword), ("'c'", Token::String),]
1561
vec![
1562
("fn", Token::Keyword),
1563
("a", Token::Title),
1564
("str", Token::Type),
1565
("char", Token::Type),
1566
("'c'", Token::String),
1567
]
287
1568
);
288
1569
assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]);
289
1570
}
@@ -296,6 +1577,7 @@ mod tests {
296
1577
#[test]
297
1578
fn unknown_language_has_no_highlight() {
298
1579
assert!(highlight("x", "brainfuck").is_none());
1580
assert!(highlight("x", "plaintext").is_none());
299
1581
}
300
1582
301
1583
#[test]
@@ -307,4 +1589,102 @@ mod tests {
307
1589
.any(|(text, _)| *text == "1")
308
1590
);
309
1591
}
1592
1593
#[test]
1594
fn every_teams_language_but_plain_text_has_rules() {
1595
let missing: Vec<_> = teams_core::CODE_LANGUAGES
1596
.iter()
1597
.filter(|language| language.id != teams_core::PLAIN_LANGUAGE)
1598
.filter(|language| rules_for(language.id).is_none())
1599
.map(|language| language.id)
1600
.collect();
1601
assert!(missing.is_empty(), "no highlighting for {missing:?}");
1602
}
1603
1604
#[test]
1605
fn markup_colours_tags_attributes_and_values() {
1606
assert_eq!(
1607
kinds("<a href=\"x\">t</a><!-- c -->", "html"),
1608
vec![
1609
("a", Token::Tag),
1610
("href", Token::Attribute),
1611
("\"x\"", Token::String),
1612
("a", Token::Tag),
1613
("<!-- c -->", Token::Comment),
1614
]
1615
);
1616
}
1617
1618
#[test]
1619
fn markdown_colours_its_blocks_and_inline_marks() {
1620
assert_eq!(
1621
kinds(
1622
"# Title\n- **b** and *i* `c` [l](u)\n> q\n```\nx\n```",
1623
"md"
1624
),
1625
vec", Token::Link),
1632
("> q", Token::Comment),
1633
("```", Token::String),
1634
("x", Token::String),
1635
("```", Token::String),
1636
]
1637
);
1638
}
1639
1640
#[test]
1641
fn definitions_types_and_keys() {
1642
assert_eq!(
1643
kinds("def f(self): print(1)", "python"),
1644
vec![
1645
("def", Token::Keyword),
1646
("f", Token::Title),
1647
("self", Token::Type),
1648
("print", Token::Type),
1649
("1", Token::Number),
1650
]
1651
);
1652
assert_eq!(
1653
kinds("func ok() bool", "go"),
1654
vec![
1655
("func", Token::Keyword),
1656
("ok", Token::Title),
1657
("bool", Token::Type)
1658
]
1659
);
1660
assert_eq!(
1661
kinds("{\"a\": \"b\"}", "json"),
1662
vec![("\"a\"", Token::Attribute), ("\"b\"", Token::String)]
1663
);
1664
assert_eq!(
1665
kinds("name: x\nurl: http://y", "yaml"),
1666
vec![("name", Token::Attribute), ("url", Token::Attribute)]
1667
);
1668
assert_eq!(
1669
kinds(" font-size: 2px;", "css")[0],
1670
("font-size", Token::Attribute)
1671
);
1672
assert_eq!(
1673
kinds("Get-ChildItem -Path .", "powershell")[0],
1674
("Get-ChildItem", Token::Type)
1675
);
1676
}
1677
1678
#[test]
1679
fn word_comments_and_latex_commands() {
1680
assert_eq!(
1681
kinds("rem x\necho", "dos"),
1682
vec![("rem x", Token::Comment), ("echo", Token::Keyword)]
1683
);
1684
assert_eq!(
1685
kinds("\\section{a} % c", "latex"),
1686
vec![("\\section", Token::Keyword), ("% c", Token::Comment)]
1687
);
1688
assert_eq!(kinds("FROM x", "dockerFile")[0], ("FROM", Token::Keyword));
1689
}
310
1690
}
@@ -6,20 +6,521 @@ pub enum Token {6
String,6
String,7
Number,7
Number,8
Comment,8
Comment,9
Tag,10
Attribute,11
Heading,12
Strong,13
Emphasis,14
Link,15
/// Built-in types, functions and values: `bool`, `print`, `self`.16
Type,17
/// The name a definition gives: `f` in `def f`, `A` in `class A`.18
Title,9
}19
}10
20
21
/// A lexer for code: comments, strings, numbers and keywords.11
struct Grammar {22
struct Grammar {12
line_comments: &'static [&'static str],23
line_comments: &'static [&'static str],13
block_comment: Option<(&'static str, &'static str)>,24
block_comment: Option<(&'static str, &'static str)>,14
keywords: &'static [&'static str],25
keywords: &'static [&'static str],26
/// `'x'` is a character; other single quotes (Rust lifetimes) are left alone.15
char_quotes: bool,27
char_quotes: bool,28
case_insensitive: bool,29
/// Words after this prefix are keywords too, as `\section` in LaTeX.30
command_prefix: Option<char>,31
types: &'static [&'static str],32
/// A word or string right before `:` is a key, as in JSON, YAML and CSS.33
keys: bool,34
/// `-` joins words, as in `font-size` and `Get-ChildItem`; such a word is a built-in.35
dashed_words: bool,16
}36
}17
37
18
const C_LIKE_KEYWORDS: &[&str] = &[38
const CODE: Grammar = Grammar {39
line_comments: &[],40
block_comment: None,41
keywords: &[],42
char_quotes: false,43
case_insensitive: false,44
command_prefix: None,45
types: &[],46
keys: false,47
dashed_words: false,48
};49
50
const fn c_style(keywords: &'static [&'static str]) -> Grammar {51
Grammar {52
line_comments: &["//"],53
block_comment: Some(("/*", "*/")),54
keywords,55
..CODE56
}57
}58
59
const fn hash_style(keywords: &'static [&'static str]) -> Grammar {60
Grammar {61
line_comments: &["#"],62
keywords,63
..CODE64
}65
}66
67
const C_KEYWORDS: &[&str] = &[68
"auto",69
"break",70
"case",71
"char",72
"const",73
"continue",74
"default",75
"do",76
"double",77
"else",78
"enum",79
"extern",80
"float",81
"for",82
"goto",83
"if",84
"inline",85
"int",86
"long",87
"register",88
"restrict",89
"return",90
"short",91
"signed",92
"sizeof",93
"static",94
"struct",95
"switch",96
"typedef",97
"union",98
"unsigned",99
"void",100
"volatile",101
"while",102
"NULL",103
"true",104
"false",105
"bool",106
"#include",107
"#define",108
"@interface",109
"@implementation",110
"@end",111
"@property",112
"self",113
"nil",114
];115
const CPP_KEYWORDS: &[&str] = &[116
"auto",117
"bool",118
"break",119
"case",120
"catch",121
"char",122
"class",123
"const",124
"constexpr",125
"continue",126
"default",127
"delete",128
"do",129
"double",130
"else",131
"enum",132
"explicit",133
"extern",134
"false",135
"float",136
"for",137
"friend",138
"goto",139
"if",140
"inline",141
"int",142
"long",143
"namespace",144
"new",145
"noexcept",146
"nullptr",147
"operator",148
"override",149
"private",150
"protected",151
"public",152
"return",153
"short",154
"signed",155
"sizeof",156
"static",157
"struct",158
"switch",159
"template",160
"this",161
"throw",162
"true",163
"try",164
"typedef",165
"typename",166
"union",167
"unsigned",168
"using",169
"virtual",170
"void",171
"volatile",172
"while",173
];174
const CSHARP_KEYWORDS: &[&str] = &[175
"abstract",176
"as",177
"async",178
"await",179
"base",180
"bool",181
"break",182
"case",183
"catch",184
"class",185
"const",186
"continue",187
"default",188
"delegate",189
"do",190
"else",191
"enum",192
"event",193
"false",194
"finally",195
"for",196
"foreach",197
"get",198
"if",199
"in",200
"int",201
"interface",202
"internal",203
"is",204
"new",205
"null",206
"object",207
"out",208
"override",209
"private",210
"protected",211
"public",212
"readonly",213
"ref",214
"return",215
"sealed",216
"set",217
"static",218
"string",219
"struct",220
"switch",221
"this",222
"throw",223
"true",224
"try",225
"using",226
"var",227
"virtual",228
"void",229
"while",230
];231
const JAVA_KEYWORDS: &[&str] = &[232
"abstract",233
"boolean",234
"break",235
"case",236
"catch",237
"char",238
"class",239
"const",240
"continue",241
"default",242
"do",243
"double",244
"else",245
"enum",246
"extends",247
"false",248
"final",249
"finally",250
"float",251
"for",252
"if",253
"implements",254
"import",255
"instanceof",256
"int",257
"interface",258
"long",259
"new",260
"null",261
"package",262
"private",263
"protected",264
"public",265
"return",266
"static",267
"super",268
"switch",269
"this",270
"throw",271
"throws",272
"true",273
"try",274
"var",275
"void",276
"while",277
];278
const JS_KEYWORDS: &[&str] = &[279
"as",280
"async",281
"await",282
"break",283
"case",284
"catch",285
"class",286
"const",287
"continue",288
"default",289
"delete",290
"do",291
"else",292
"enum",293
"export",294
"extends",295
"false",296
"finally",297
"for",298
"from",299
"function",300
"if",301
"implements",302
"import",303
"in",304
"instanceof",305
"interface",306
"let",307
"new",308
"null",309
"of",310
"private",311
"protected",312
"public",313
"readonly",314
"return",315
"static",316
"super",317
"switch",318
"this",319
"throw",320
"true",321
"try",322
"type",323
"typeof",324
"undefined",325
"var",326
"void",327
"while",328
"yield",329
];330
const DART_KEYWORDS: &[&str] = &[331
"abstract",332
"async",333
"await",334
"break",335
"case",336
"catch",337
"class",338
"const",339
"continue",340
"default",341
"do",342
"else",343
"enum",344
"extends",345
"false",346
"final",347
"finally",348
"for",349
"if",350
"implements",351
"import",352
"in",353
"is",354
"late",355
"new",356
"null",357
"required",358
"return",359
"static",360
"super",361
"switch",362
"this",363
"throw",364
"true",365
"try",366
"var",367
"void",368
"while",369
"with",370
"yield",371
];372
const GO_KEYWORDS: &[&str] = &[373
"break",374
"case",375
"chan",376
"const",377
"continue",378
"default",379
"defer",380
"else",381
"fallthrough",382
"for",383
"func",384
"go",385
"goto",386
"if",387
"import",388
"interface",389
"map",390
"package",391
"range",392
"return",393
"select",394
"struct",395
"switch",396
"type",397
"var",398
"true",399
"false",400
"nil",401
"iota",402
];403
const KOTLIN_KEYWORDS: &[&str] = &[404
"as",405
"break",406
"class",407
"continue",408
"data",409
"do",410
"else",411
"false",412
"for",413
"fun",414
"if",415
"import",416
"in",417
"interface",418
"is",419
"null",420
"object",421
"override",422
"package",423
"private",424
"return",425
"super",426
"this",427
"throw",428
"true",429
"try",430
"val",431
"var",432
"when",433
"while",434
];435
const RUST_KEYWORDS: &[&str] = &[436
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",437
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",438
"ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",439
"unsafe", "use", "where", "while",440
];441
const SCALA_KEYWORDS: &[&str] = &[442
"abstract",443
"case",444
"catch",445
"class",446
"def",447
"do",448
"else",449
"extends",450
"false",451
"final",452
"finally",453
"for",454
"if",455
"implicit",456
"import",457
"lazy",458
"match",459
"new",460
"null",461
"object",462
"override",463
"package",464
"private",465
"protected",466
"return",467
"sealed",468
"super",469
"this",470
"throw",471
"trait",472
"true",473
"try",474
"type",475
"val",476
"var",477
"while",478
"with",479
"yield",480
];481
const SWIFT_KEYWORDS: &[&str] = &[482
"as",483
"break",484
"case",485
"catch",486
"class",487
"continue",488
"default",489
"defer",490
"do",491
"else",492
"enum",493
"extension",494
"false",495
"for",496
"func",497
"guard",498
"if",499
"import",500
"in",501
"init",502
"let",503
"nil",504
"private",505
"protocol",506
"public",507
"return",508
"self",509
"static",510
"struct",511
"switch",512
"throw",513
"throws",514
"true",515
"try",516
"var",517
"where",518
"while",519
];520
const PHP_KEYWORDS: &[&str] = &[19
"abstract",521
"abstract",522
"array",20
"as",523
"as",21
"async",22
"await",23
"break",524
"break",24
"case",525
"case",25
"catch",526
"catch",@@ -28,129 +529,735 @@ const C_LIKE_KEYWORDS: &[&str] = &[28
"continue",529
"continue",29
"default",530
"default",30
"do",531
"do",532
"echo",31
"else",533
"else",32
"enum",534
"elseif",33
"export",34
"extends",535
"extends",35
"false",536
"false",36
"final",537
"final",37
"finally",538
"finally",38
"fn",39
"for",539
"for",40
"from",540
"foreach",41
"func",42
"function",541
"function",43
"go",44
"if",542
"if",45
"impl",543
"implements",46
"import",544
"include",47
"in",48
"interface",545
"interface",49
"let",50
"loop",51
"match",52
"mod",53
"mut",54
"namespace",546
"namespace",55
"new",547
"new",56
"null",548
"null",57
"override",58
"package",59
"private",549
"private",60
"protected",550
"protected",61
"pub",62
"public",551
"public",63
"readonly",552
"require",64
"return",553
"return",65
"self",66
"static",554
"static",67
"struct",68
"super",69
"switch",555
"switch",70
"this",71
"throw",556
"throw",72
"trait",73
"true",557
"true",74
"try",558
"try",75
"type",76
"typeof",77
"use",559
"use",78
"using",79
"var",80
"void",81
"where",82
"while",560
"while",83
"yield",84
];561
];85
const PYTHON_KEYWORDS: &[&str] = &[562
const PYTHON_KEYWORDS: &[&str] = &[86
"and", "as", "async", "await", "break", "class", "continue", "def", "del", "elif", "else",563
"and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif",87
"except", "False", "finally", "for", "from", "if", "import", "in", "is", "lambda", "None",564
"else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is",88
"not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield",565
"lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while",566
"with", "yield",567
];568
const RUBY_KEYWORDS: &[&str] = &[569
"and", "begin", "break", "case", "class", "def", "do", "else", "elsif", "end", "ensure",570
"false", "for", "if", "in", "module", "next", "nil", "not", "or", "require", "rescue",571
"return", "self", "super", "then", "true", "unless", "until", "when", "while", "yield",572
];573
const PERL_KEYWORDS: &[&str] = &[574
"else", "elsif", "for", "foreach", "if", "last", "local", "my", "next", "our", "package",575
"print", "require", "return", "sub", "unless", "until", "use", "while",576
];577
const R_KEYWORDS: &[&str] = &[578
"break", "else", "FALSE", "for", "function", "if", "in", "NA", "next", "NULL", "repeat",579
"return", "TRUE", "while", "library",89
];580
];90
const SHELL_KEYWORDS: &[&str] = &[581
const SHELL_KEYWORDS: &[&str] = &[91
"case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in",582
"case", "do", "done", "echo", "elif", "else", "esac", "exit", "export", "fi", "for",92
"local", "return", "then", "while",583
"function", "if", "in", "local", "return", "set", "then", "until", "while",584
];585
const POWERSHELL_KEYWORDS: &[&str] = &[586
"begin", "break", "catch", "class", "continue", "do", "else", "elseif", "end", "exit",587
"filter", "finally", "for", "foreach", "function", "if", "in", "param", "process", "return",588
"switch", "throw", "trap", "try", "until", "while", "$true", "$false", "$null",589
];590
const DOS_KEYWORDS: &[&str] = &[591
"call", "cd", "copy", "defined", "del", "do", "echo", "else", "endlocal", "equ", "exist",592
"exit", "for", "goto", "if", "in", "mkdir", "neq", "not", "pause", "set", "setlocal", "shift",593
"start",594
];595
const DOCKER_KEYWORDS: &[&str] = &[596
"add",597
"arg",598
"as",599
"cmd",600
"copy",601
"entrypoint",602
"env",603
"expose",604
"from",605
"healthcheck",606
"label",607
"onbuild",608
"run",609
"shell",610
"stopsignal",611
"user",612
"volume",613
"workdir",93
];614
];94
const SQL_KEYWORDS: &[&str] = &[615
const SQL_KEYWORDS: &[&str] = &[95
"and", "as", "by", "create", "delete", "from", "group", "insert", "into", "join", "left",616
"alter", "and", "as", "asc", "between", "by", "case", "create", "delete", "desc", "distinct",96
"not", "null", "on", "or", "order", "select", "set", "table", "update", "values", "where",617
"drop", "else", "end", "exists", "from", "group", "having", "in", "inner", "insert", "into",618
"is", "join", "left", "like", "limit", "not", "null", "on", "or", "order", "outer", "right",619
"select", "set", "table", "then", "union", "update", "values", "when", "where", "with",620
];621
const KQL_KEYWORDS: &[&str] = &[622
"and",623
"asc",624
"by",625
"count",626
"desc",627
"distinct",628
"extend",629
"join",630
"let",631
"limit",632
"or",633
"order",634
"project",635
"render",636
"sort",637
"summarize",638
"take",639
"top",640
"union",641
"where",642
];643
const GRAPHQL_KEYWORDS: &[&str] = &[644
"enum",645
"extend",646
"false",647
"fragment",648
"implements",649
"input",650
"interface",651
"mutation",652
"null",653
"on",654
"query",655
"scalar",656
"schema",657
"subscription",658
"true",659
"type",660
"union",661
];662
const HTTP_KEYWORDS: &[&str] = &[663
"CONNECT", "DELETE", "GET", "HEAD", "HTTP", "OPTIONS", "PATCH", "POST", "PUT", "TRACE",664
];665
const VB_KEYWORDS: &[&str] = &[666
"and", "as", "boolean", "byval", "byref", "call", "case", "class", "const", "dim", "do",667
"each", "else", "elseif", "end", "exit", "false", "for", "function", "if", "imports", "in",668
"integer", "is", "loop", "module", "new", "next", "not", "nothing", "or", "private", "public",669
"return", "select", "set", "string", "sub", "then", "to", "true", "while", "with",670
];671
const VERILOG_KEYWORDS: &[&str] = &[672
"always",673
"assign",674
"begin",675
"case",676
"else",677
"end",678
"endcase",679
"endmodule",680
"for",681
"if",682
"initial",683
"input",684
"integer",685
"module",686
"negedge",687
"output",688
"parameter",689
"posedge",690
"reg",691
"wire",692
];693
const VHDL_KEYWORDS: &[&str] = &[694
"architecture",695
"begin",696
"case",697
"downto",698
"else",699
"elsif",700
"end",701
"entity",702
"for",703
"generic",704
"if",705
"in",706
"is",707
"library",708
"loop",709
"map",710
"of",711
"others",712
"out",713
"port",714
"process",715
"signal",716
"then",717
"to",718
"use",719
"variable",720
"when",721
"while",722
];723
const OCTAVE_KEYWORDS: &[&str] = &[724
"break",725
"case",726
"catch",727
"continue",728
"else",729
"elseif",730
"end",731
"for",732
"function",733
"if",734
"otherwise",735
"return",736
"switch",737
"try",738
"while",739
];740
const LISP_KEYWORDS: &[&str] = &[741
"cond",742
"defmacro",743
"defparameter",744
"defun",745
"defvar",746
"if",747
"lambda",748
"let",749
"nil",750
"progn",751
"quote",752
"setf",753
"setq",754
"t",755
"unless",756
"when",97
];757
];758
const LITERALS: &[&str] = &["true", "false", "null", "yes", "no", "on", "off", "~"];98
759
99
const C_LIKE: Grammar = Grammar {760
const C: Grammar = Grammar {100
line_comments: &["//"],761
types: &[101
block_comment: Some(("/*", "*/")),762
"size_t", "int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t",102
keywords: C_LIKE_KEYWORDS,763
"uint64_t", "FILE", "printf", "scanf", "malloc", "free", "memcpy", "strlen", "BOOL", "YES",103
char_quotes: false,764
"NO", "id", "NSString", "NSLog",765
],766
char_quotes: true,767
..c_style(C_KEYWORDS)768
};769
const CPP: Grammar = Grammar {770
types: &[771
"std",772
"string",773
"vector",774
"map",775
"set",776
"size_t",777
"cout",778
"cin",779
"endl",780
"unique_ptr",781
"shared_ptr",782
"make_unique",783
"make_shared",784
"printf",785
],786
char_quotes: true,787
..c_style(CPP_KEYWORDS)788
};789
const CSHARP: Grammar = Grammar {790
types: &[791
"byte",792
"char",793
"decimal",794
"double",795
"float",796
"long",797
"Console",798
"List",799
"Dictionary",800
"Task",801
"DateTime",802
"Exception",803
"nameof",804
],805
char_quotes: true,806
..c_style(CSHARP_KEYWORDS)807
};808
const JAVA: Grammar = Grammar {809
types: &[810
"byte",811
"short",812
"String",813
"Integer",814
"Long",815
"Double",816
"Boolean",817
"Object",818
"List",819
"Map",820
"ArrayList",821
"HashMap",822
"System",823
"Exception",824
"Override",825
],826
char_quotes: true,827
..c_style(JAVA_KEYWORDS)828
};829
const RUST: Grammar = Grammar {830
types: &[831
"i8",832
"i16",833
"i32",834
"i64",835
"i128",836
"isize",837
"u8",838
"u16",839
"u32",840
"u64",841
"u128",842
"usize",843
"f32",844
"f64",845
"bool",846
"char",847
"str",848
"String",849
"Vec",850
"Option",851
"Some",852
"None",853
"Result",854
"Ok",855
"Err",856
"Box",857
"Rc",858
"Arc",859
"println",860
"print",861
"format",862
"vec",863
"panic",864
"assert",865
"assert_eq",866
],867
char_quotes: true,868
..c_style(RUST_KEYWORDS)869
};870
const KOTLIN: Grammar = Grammar {871
types: &[872
"Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "println",873
"listOf", "mapOf", "setOf",874
],875
char_quotes: true,876
..c_style(KOTLIN_KEYWORDS)104
};877
};105
const CHAR_LIKE: Grammar = Grammar {878
const SCALA: Grammar = Grammar {879
types: &[880
"Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "Option",881
"Some", "None", "println",882
],106
char_quotes: true,883
char_quotes: true,107
..C_LIKE884
..c_style(SCALA_KEYWORDS)885
};886
const JS: Grammar = Grammar {887
types: &[888
"console", "document", "window", "Promise", "Array", "Object", "JSON", "Math", "Date",889
"Error", "Map", "Set", "string", "number", "boolean", "any", "unknown", "never", "require",890
"module",891
],892
..c_style(JS_KEYWORDS)893
};894
const DART: Grammar = Grammar {895
types: &[896
"int", "double", "num", "String", "bool", "List", "Map", "Set", "dynamic", "Future",897
"Stream", "print",898
],899
..c_style(DART_KEYWORDS)900
};901
const GO: Grammar = Grammar {902
types: &[903
"bool",904
"byte",905
"complex64",906
"complex128",907
"error",908
"float32",909
"float64",910
"int",911
"int8",912
"int16",913
"int32",914
"int64",915
"rune",916
"string",917
"uint",918
"uint8",919
"uint16",920
"uint32",921
"uint64",922
"uintptr",923
"any",924
"append",925
"cap",926
"close",927
"copy",928
"delete",929
"len",930
"make",931
"new",932
"panic",933
"print",934
"println",935
"recover",936
],937
..c_style(GO_KEYWORDS)938
};939
const SWIFT: Grammar = Grammar {940
types: &[941
"Int",942
"Double",943
"Float",944
"Bool",945
"String",946
"Character",947
"Array",948
"Dictionary",949
"Set",950
"Optional",951
"Any",952
"print",953
],954
..c_style(SWIFT_KEYWORDS)955
};956
const CSS: Grammar = Grammar {957
keys: true,958
dashed_words: true,959
..c_style(&[])108
};960
};109
const HASH: Grammar = Grammar {961
const JSON: Grammar = Grammar {110
line_comments: &["#"],962
keys: true,963
..c_style(LITERALS)964
};965
const VERILOG: Grammar = Grammar {966
types: &["$display", "$finish", "$time", "logic", "bit"],967
..c_style(VERILOG_KEYWORDS)968
};969
const PHP: Grammar = Grammar {970
types: &[971
"$this",972
"array",973
"count",974
"isset",975
"empty",976
"strlen",977
"json_encode",978
"json_decode",979
"var_dump",980
"print_r",981
],982
line_comments: &["//", "#"],983
..c_style(PHP_KEYWORDS)984
};985
const KQL: Grammar = Grammar {986
types: &[987
"ago", "now", "datetime", "bin", "dcount", "tostring", "toint", "strcat", "count", "sum",988
"avg",989
],111
block_comment: None,990
block_comment: None,112
keywords: PYTHON_KEYWORDS,991
case_insensitive: true,113
char_quotes: false,992
..c_style(KQL_KEYWORDS)993
};994
const PYTHON: Grammar = Grammar {995
types: &[996
"self",997
"cls",998
"print",999
"len",1000
"range",1001
"int",1002
"str",1003
"float",1004
"bool",1005
"bytes",1006
"list",1007
"dict",1008
"set",1009
"tuple",1010
"object",1011
"open",1012
"super",1013
"isinstance",1014
"enumerate",1015
"zip",1016
"map",1017
"filter",1018
"sorted",1019
"sum",1020
"min",1021
"max",1022
"abs",1023
"type",1024
"Exception",1025
],1026
..hash_style(PYTHON_KEYWORDS)1027
};1028
const RUBY: Grammar = Grammar {1029
types: &[1030
"puts",1031
"print",1032
"p",1033
"attr_accessor",1034
"attr_reader",1035
"attr_writer",1036
"lambda",1037
"proc",1038
"raise",1039
],1040
..hash_style(RUBY_KEYWORDS)1041
};1042
const PERL: Grammar = Grammar {1043
types: &[1044
"chomp", "die", "join", "keys", "push", "shift", "split", "values", "open", "close",1045
],1046
..hash_style(PERL_KEYWORDS)1047
};1048
const R: Grammar = Grammar {1049
types: &[1050
"c", "list", "print", "paste", "length", "vector", "matrix", "sum", "mean", "cat",1051
],1052
..hash_style(R_KEYWORDS)114
};1053
};115
const SHELL: Grammar = Grammar {1054
const SHELL: Grammar = Grammar {116
line_comments: &["#"],1055
types: &[117
block_comment: None,1056
"cd", "ls", "pwd", "grep", "sed", "awk", "cat", "cp", "mv", "rm", "mkdir", "touch",118
keywords: SHELL_KEYWORDS,1057
"chmod", "sudo", "git", "docker", "kubectl", "curl", "wget", "read", "printf", "source",119
char_quotes: false,1058
"test", "true", "false",1059
],1060
..hash_style(SHELL_KEYWORDS)1061
};1062
const YAML: Grammar = Grammar {1063
keys: true,1064
..hash_style(LITERALS)1065
};1066
const GRAPHQL: Grammar = Grammar {1067
types: &["String", "Int", "Float", "Boolean", "ID"],1068
..hash_style(GRAPHQL_KEYWORDS)1069
};1070
const DOCKER: Grammar = Grammar {1071
case_insensitive: true,1072
..hash_style(DOCKER_KEYWORDS)1073
};1074
const POWERSHELL: Grammar = Grammar {1075
dashed_words: true,1076
block_comment: Some(("<#", "#>")),1077
case_insensitive: true,1078
..hash_style(POWERSHELL_KEYWORDS)1079
};1080
const DOS: Grammar = Grammar {1081
line_comments: &["::", "rem ", "REM ", "@rem "],1082
case_insensitive: true,1083
keywords: DOS_KEYWORDS,1084
..CODE120
};1085
};121
const SQL: Grammar = Grammar {1086
const SQL: Grammar = Grammar {1087
types: &[1088
"int",1089
"integer",1090
"bigint",1091
"varchar",1092
"char",1093
"text",1094
"date",1095
"timestamp",1096
"boolean",1097
"decimal",1098
"count",1099
"sum",1100
"avg",1101
"min",1102
"max",1103
"coalesce",1104
"now",1105
],122
line_comments: &["--"],1106
line_comments: &["--"],123
block_comment: Some(("/*", "*/")),1107
block_comment: Some(("/*", "*/")),124
keywords: SQL_KEYWORDS,1108
keywords: SQL_KEYWORDS,125
char_quotes: false,1109
case_insensitive: true,1110
..CODE126
};1111
};127
const MARKUP: Grammar = Grammar {1112
const VHDL: Grammar = Grammar {128
line_comments: &[],1113
types: &[129
block_comment: Some(("<!--", "-->")),1114
"std_logic",130
keywords: &[],1115
"std_logic_vector",131
char_quotes: false,1116
"integer",1117
"boolean",1118
"unsigned",1119
"signed",1120
"rising_edge",1121
],1122
line_comments: &["--"],1123
keywords: VHDL_KEYWORDS,1124
case_insensitive: true,1125
..CODE1126
};1127
const VB: Grammar = Grammar {1128
line_comments: &["'", "rem ", "REM "],1129
keywords: VB_KEYWORDS,1130
case_insensitive: true,1131
..CODE1132
};1133
const OCTAVE: Grammar = Grammar {1134
types: &[1135
"disp", "zeros", "ones", "size", "numel", "length", "plot", "printf", "fprintf", "true",1136
"false",1137
],1138
line_comments: &["%", "#"],1139
block_comment: Some(("%{", "%}")),1140
keywords: OCTAVE_KEYWORDS,1141
..CODE1142
};1143
const LISP: Grammar = Grammar {1144
types: &[1145
"car", "cdr", "cons", "list", "format", "print", "append", "mapcar", "funcall", "apply",1146
],1147
line_comments: &[";"],1148
block_comment: Some(("#|", "|#")),1149
keywords: LISP_KEYWORDS,1150
..CODE1151
};1152
const HTTP: Grammar = Grammar {1153
keys: true,1154
dashed_words: true,1155
keywords: HTTP_KEYWORDS,1156
..CODE1157
};1158
const LATEX: Grammar = Grammar {1159
line_comments: &["%"],1160
command_prefix: Some('\\'),1161
..CODE132
};1162
};133
1163
134
fn grammar_for(language: &str) -> Option<&'static Grammar> {1164
enum Rules {135
match language.to_ascii_lowercase().as_str() {1165
Code(&'static Grammar),136
"rust" | "rs" | "c" | "cpp" | "c++" | "csharp" | "cs" | "c#" | "java" | "go" | "kotlin"1166
Markup,137
| "scala" => Some(&CHAR_LIKE),1167
Markdown,138
"javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" | "swift" | "php" | "json"1168
}139
| "css" | "scss" | "less" | "dart" => Some(&C_LIKE),1169
140
"python" | "py" | "ruby" | "rb" | "yaml" | "yml" | "toml" | "r" | "perl" | "dockerfile"1170
/// The rules for a code block language: one arm per Teams language id (see141
| "makefile" => Some(&HASH),1171
/// `teams_core::CODE_LANGUAGES`); a language without an arm stays plain.142
"bash" | "sh" | "shell" | "zsh" | "powershell" | "ps1" => Some(&SHELL),1172
fn rules_for(language: &str) -> Option<Rules> {143
"sql" | "tsql" | "plsql" | "lua" => Some(&SQL),1173
let id = teams_core::code_language(language).map_or_else(144
"html" | "xml" | "svg" | "markdown" | "md" => Some(&MARKUP),1174
|| language.to_ascii_lowercase(),145
_ => None,1175
|known| known.id.to_ascii_lowercase(),146
}1176
);1177
let grammar = match id.as_str() {1178
"html" | "xml" | "jsp" => return Some(Rules::Markup),1179
"markdown" => return Some(Rules::Markdown),1180
"bash" => &SHELL,1181
"c" | "objectivec" => &C,1182
"cpp" => &CPP,1183
"csharp" => &CSHARP,1184
"css" | "scss" | "less" => &CSS,1185
"dart" => &DART,1186
"dockerfile" => &DOCKER,1187
"dos" => &DOS,1188
"go" => &GO,1189
"graphql" => &GRAPHQL,1190
"http" => &HTTP,1191
"java" => &JAVA,1192
"javascript" | "jsx" | "typescript" => &JS,1193
"json" => &JSON,1194
"kotlin" => &KOTLIN,1195
"kql" => &KQL,1196
"latex" => &LATEX,1197
"lisp" => &LISP,1198
"octave" => &OCTAVE,1199
"perl" => &PERL,1200
"php" => &PHP,1201
"powershell" => &POWERSHELL,1202
"python" => &PYTHON,1203
"r" => &R,1204
"ruby" => &RUBY,1205
"rust" => &RUST,1206
"scala" => &SCALA,1207
"sql" | "tsql" | "plsql" => &SQL,1208
"swift" => &SWIFT,1209
"vbnet" | "vbscript" => &VB,1210
"verilog" => &VERILOG,1211
"vhdl" => &VHDL,1212
"yaml" | "toml" => &YAML,1213
_ => return None,1214
};1215
Some(Rules::Code(grammar))147
}1216
}148
1217
149
pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> {1218
pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> {150
let grammar = grammar_for(language)?;1219
Some(match rules_for(language)? {151
let sql = grammar.keywords == SQL_KEYWORDS;1220
Rules::Code(grammar) => highlight_code(code, grammar),1221
Rules::Markup => highlight_markup(code),1222
Rules::Markdown => highlight_markdown(code),1223
})1224
}1225
1226
/// Keywords whose next word is the name being defined.1227
const DEFINITIONS: &[&str] = &[1228
"class",1229
"def",1230
"enum",1231
"fn",1232
"fun",1233
"func",1234
"function",1235
"interface",1236
"module",1237
"object",1238
"protocol",1239
"struct",1240
"sub",1241
"trait",1242
"type",1243
];1244
1245
/// Only spaces, or a YAML list dash, before `at` on its line.1246
fn starts_line(code: &str, at: usize) -> bool {1247
let line = &code[code[..at].rfind('\n').map_or(0, |end| end + 1)..at];1248
matches!(line.trim(), "" | "-")1249
}1250
1251
/// Followed by `:` (not `::`) after optional spaces.1252
fn before_colon(code: &str, end: usize) -> bool {1253
let rest = code[end..].trim_start_matches([' ', '\t']);1254
rest.starts_with(':') && !rest.starts_with("::")1255
}1256
1257
fn highlight_code(code: &str, grammar: &Grammar) -> Vec<(Range<usize>, Token)> {152
let mut tokens = Vec::new();1258
let mut tokens = Vec::new();153
let mut index = 0;1259
let mut index = 0;1260
let mut defines = false;154
while index < code.len() {1261
while index < code.len() {155
let rest = &code[index..];1262
let rest = &code[index..];156
if let Some((open, close)) = grammar.block_comment1263
if let Some((open, close)) = grammar.block_comment@@ -163,11 +1270,12 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)163
index = end;1270
index = end;164
continue;1271
continue;165
}1272
}166
if grammar1273
let line_start = index == 0 || code.as_bytes()[index - 1] == b'\n';167
.line_comments1274
if grammar.line_comments.iter().any(|marker| {168
.iter()1275
rest.starts_with(marker)169
.any(|marker| rest.starts_with(marker))1276
// A word comment such as `rem ` only counts at the start of a line.170
{1277
&& (!marker.ends_with(' ') || line_start || code[..index].ends_with(' '))1278
}) {171
let end = rest.find('\n').map_or(code.len(), |offset| index + offset);1279
let end = rest.find('\n').map_or(code.len(), |offset| index + offset);172
tokens.push((index..end, Token::Comment));1280
tokens.push((index..end, Token::Comment));173
index = end;1281
index = end;@@ -180,7 +1288,11 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)180
}1288
}181
if matches!(character, '"' | '\'' | '`') {1289
if matches!(character, '"' | '\'' | '`') {182
let end = string_end(code, index, character);1290
let end = string_end(code, index, character);183
tokens.push((index..end, Token::String));1291
let key = grammar.keys && before_colon(code, end);1292
tokens.push((1293
index..end,1294
if key { Token::Attribute } else { Token::String },1295
));184
index = end;1296
index = end;185
continue;1297
continue;186
}1298
}@@ -192,28 +1304,190 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)192
index += length;1304
index += length;193
continue;1305
continue;194
}1306
}195
if character.is_alphabetic() || character == '_' {1307
let command = grammar.command_prefix == Some(character);196
let length = rest1308
if character.is_alphabetic() || matches!(character, '_' | '$' | '@' | '#') || command {197
.find(|next: char| !(next.is_alphanumeric() || next == '_'))1309
let dashed = grammar.dashed_words;198
.unwrap_or(rest.len());1310
let length = character.len_utf8()1311
+ rest[character.len_utf8()..]1312
.find(|next: char| {1313
!(next.is_alphanumeric() || next == '_' || dashed && next == '-')1314
})1315
.unwrap_or(rest.len() - character.len_utf8());1316
let length = rest[..length].trim_end_matches('-').len();199
let word = &rest[..length];1317
let word = &rest[..length];200
let is_keyword = if sql {1318
let same = |known: &&str| {201
grammar1319
if grammar.case_insensitive {202
.keywords1320
known.eq_ignore_ascii_case(word)203
.iter()1321
} else {204
.any(|keyword| keyword.eq_ignore_ascii_case(word))1322
*known == word1323
}1324
};1325
let end = index + length;1326
let token = if command && length > 1 || grammar.keywords.iter().any(same) {1327
Some(Token::Keyword)1328
} else if grammar.keys && starts_line(code, index) && before_colon(code, end) {1329
Some(Token::Attribute)1330
} else if defines {1331
Some(Token::Title)1332
} else if grammar.types.iter().any(same) || dashed && word.contains('-') {1333
Some(Token::Type)205
} else {1334
} else {206
grammar.keywords.contains(&word)1335
None207
};1336
};208
if is_keyword {1337
defines = token == Some(Token::Keyword) && DEFINITIONS.iter().any(same);209
tokens.push((index..index + length, Token::Keyword));1338
tokens.extend(token.map(|token| (index..end, token)));210
}1339
index = end;211
index += length;212
continue;1340
continue;213
}1341
}1342
if !character.is_whitespace() {1343
defines = false;1344
}214
index += character.len_utf8();1345
index += character.len_utf8();215
}1346
}216
Some(tokens)1347
tokens1348
}1349
1350
/// HTML and XML: tag names, attribute names, quoted values and comments.1351
fn highlight_markup(code: &str) -> Vec<(Range<usize>, Token)> {1352
let mut tokens = Vec::new();1353
let mut index = 0;1354
while let Some(offset) = code[index..].find('<') {1355
let start = index + offset;1356
let rest = &code[start..];1357
if rest.starts_with("<!--") {1358
let end = rest.find("-->").map_or(code.len(), |at| start + at + 3);1359
tokens.push((start..end, Token::Comment));1360
index = end;1361
continue;1362
}1363
let name_start = start + 1 + usize::from(rest[1..].starts_with(['/', '!', '?']));1364
let name_end = name_start1365
+ code[name_start..]1366
.find(|next: char| {1367
!(next.is_alphanumeric() || matches!(next, '-' | ':' | '_' | '.'))1368
})1369
.unwrap_or(code.len() - name_start);1370
if name_end == name_start {1371
index = start + 1;1372
continue;1373
}1374
tokens.push((name_start..name_end, Token::Tag));1375
let close = code[name_end..]1376
.find('>')1377
.map_or(code.len(), |at| name_end + at);1378
let mut at = name_end;1379
while at < close {1380
let character = code[at..].chars().next().unwrap_or_default();1381
if matches!(character, '"' | '\'') {1382
let end = code[at + 1..close]1383
.find(character)1384
.map_or(close, |end| at + 1 + end + 1);1385
tokens.push((at..end, Token::String));1386
at = end;1387
} else if character.is_alphabetic() {1388
let end = at1389
+ code[at..close]1390
.find(|next: char| {1391
!(next.is_alphanumeric() || matches!(next, '-' | ':' | '_'))1392
})1393
.unwrap_or(close - at);1394
tokens.push((at..end, Token::Attribute));1395
at = end;1396
} else {1397
at += character.len_utf8();1398
}1399
}1400
index = (close + 1).min(code.len());1401
}1402
tokens1403
}1404
1405
/// Markdown by line: headings, quotes, list markers, fenced code, then inline code, bold,1406
/// italic and links.1407
fn highlight_markdown(code: &str) -> Vec<(Range<usize>, Token)> {1408
let mut tokens = Vec::new();1409
let mut fenced = false;1410
let mut start = 0;1411
for line in code.split('\n') {1412
let range = start..start + line.len();1413
start = range.end + 1;1414
let trimmed = line.trim_start();1415
let indent = range.start + line.len() - trimmed.len();1416
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {1417
fenced = !fenced;1418
tokens.push((range, Token::String));1419
continue;1420
}1421
if fenced {1422
tokens.push((range, Token::String));1423
continue;1424
}1425
let hashes = trimmed.bytes().take_while(|byte| *byte == b'#').count();1426
if (1..=6).contains(&hashes) && trimmed[hashes..].starts_with(' ') {1427
tokens.push((range, Token::Heading));1428
continue;1429
}1430
if trimmed.starts_with('>') {1431
tokens.push((range, Token::Comment));1432
continue;1433
}1434
let marker = list_marker(trimmed);1435
if marker > 0 {1436
tokens.push((indent..indent + marker, Token::Keyword));1437
}1438
inline_markdown(code, indent + marker..range.end, &mut tokens);1439
}1440
tokens1441
}1442
1443
/// Byte length of a `- `, `* `, `+ ` or `1. ` list marker.1444
fn list_marker(line: &str) -> usize {1445
if line.starts_with(['-', '*', '+']) && line[1..].starts_with(' ') {1446
return 1;1447
}1448
let digits = line.bytes().take_while(u8::is_ascii_digit).count();1449
if digits > 0 && line[digits..].starts_with(". ") {1450
digits + 11451
} else {1452
01453
}1454
}1455
1456
fn inline_markdown(code: &str, range: Range<usize>, tokens: &mut Vec<(Range<usize>, Token)>) {1457
let mut index = range.start;1458
while index < range.end {1459
let rest = &code[index..range.end];1460
let span = |open: &str, close: &str| {1461
rest.strip_prefix(open)?1462
.find(close)1463
.filter(|length| *length > 0)1464
.map(|length| index + open.len() + length + close.len())1465
};1466
let found = if rest.starts_with('`') {1467
span("`", "`").map(|end| (end, Token::String))1468
} else if rest.starts_with("**") || rest.starts_with("__") {1469
span(&rest[..2], &rest[..2]).map(|end| (end, Token::Strong))1470
} else if rest.starts_with(['*', '_']) {1471
span(&rest[..1], &rest[..1]).map(|end| (end, Token::Emphasis))1472
} else if rest.starts_with('[') {1473
rest.find("](")1474
.and_then(|label| {1475
rest[label..]1476
.find(')')1477
.map(|close| index + label + close + 1)1478
})1479
.map(|end| (end, Token::Link))1480
} else {1481
None1482
};1483
match found {1484
Some((end, token)) => {1485
tokens.push((index..end, token));1486
index = end;1487
}1488
None => index += rest.chars().next().map_or(1, char::len_utf8),1489
}1490
}217
}1491
}218
1492
219
fn is_char_literal(rest: &str) -> bool {1493
fn is_char_literal(rest: &str) -> bool {@@ -261,6 +1535,7 @@ mod tests {261
vec![1535
vec![262
("// x", Token::Comment),1536
("// x", Token::Comment),263
("fn", Token::Keyword),1537
("fn", Token::Keyword),1538
("a", Token::Title),264
("\"b\"", Token::String),1539
("\"b\"", Token::String),265
]1540
]266
);1541
);@@ -283,7 +1558,13 @@ mod tests {283
fn rust_lifetime_is_not_a_string() {1558
fn rust_lifetime_is_not_a_string() {284
assert_eq!(1559
assert_eq!(285
kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"),1560
kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"),286
vec![("fn", Token::Keyword), ("'c'", Token::String),]1561
vec![1562
("fn", Token::Keyword),1563
("a", Token::Title),1564
("str", Token::Type),1565
("char", Token::Type),1566
("'c'", Token::String),1567
]287
);1568
);288
assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]);1569
assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]);289
}1570
}@@ -296,6 +1577,7 @@ mod tests {296
#[test]1577
#[test]297
fn unknown_language_has_no_highlight() {1578
fn unknown_language_has_no_highlight() {298
assert!(highlight("x", "brainfuck").is_none());1579
assert!(highlight("x", "brainfuck").is_none());1580
assert!(highlight("x", "plaintext").is_none());299
}1581
}300
1582
301
#[test]1583
#[test]@@ -307,4 +1589,102 @@ mod tests {307
.any(|(text, _)| *text == "1")1589
.any(|(text, _)| *text == "1")308
);1590
);309
}1591
}1592
1593
#[test]1594
fn every_teams_language_but_plain_text_has_rules() {1595
let missing: Vec<_> = teams_core::CODE_LANGUAGES1596
.iter()1597
.filter(|language| language.id != teams_core::PLAIN_LANGUAGE)1598
.filter(|language| rules_for(language.id).is_none())1599
.map(|language| language.id)1600
.collect();1601
assert!(missing.is_empty(), "no highlighting for {missing:?}");1602
}1603
1604
#[test]1605
fn markup_colours_tags_attributes_and_values() {1606
assert_eq!(1607
kinds("<a href=\"x\">t</a><!-- c -->", "html"),1608
vec![1609
("a", Token::Tag),1610
("href", Token::Attribute),1611
("\"x\"", Token::String),1612
("a", Token::Tag),1613
("<!-- c -->", Token::Comment),1614
]1615
);1616
}1617
1618
#[test]1619
fn markdown_colours_its_blocks_and_inline_marks() {1620
assert_eq!(1621
kinds(1622
"# Title\n- **b** and *i* `c` [l](u)\n> q\n```\nx\n```",1623
"md"1624
),1625
vec", Token::Link),1632
("> q", Token::Comment),1633
("```", Token::String),1634
("x", Token::String),1635
("```", Token::String),1636
]1637
);1638
}1639
1640
#[test]1641
fn definitions_types_and_keys() {1642
assert_eq!(1643
kinds("def f(self): print(1)", "python"),1644
vec![1645
("def", Token::Keyword),1646
("f", Token::Title),1647
("self", Token::Type),1648
("print", Token::Type),1649
("1", Token::Number),1650
]1651
);1652
assert_eq!(1653
kinds("func ok() bool", "go"),1654
vec![1655
("func", Token::Keyword),1656
("ok", Token::Title),1657
("bool", Token::Type)1658
]1659
);1660
assert_eq!(1661
kinds("{\"a\": \"b\"}", "json"),1662
vec![("\"a\"", Token::Attribute), ("\"b\"", Token::String)]1663
);1664
assert_eq!(1665
kinds("name: x\nurl: http://y", "yaml"),1666
vec![("name", Token::Attribute), ("url", Token::Attribute)]1667
);1668
assert_eq!(1669
kinds(" font-size: 2px;", "css")[0],1670
("font-size", Token::Attribute)1671
);1672
assert_eq!(1673
kinds("Get-ChildItem -Path .", "powershell")[0],1674
("Get-ChildItem", Token::Type)1675
);1676
}1677
1678
#[test]1679
fn word_comments_and_latex_commands() {1680
assert_eq!(1681
kinds("rem x\necho", "dos"),1682
vec![("rem x", Token::Comment), ("echo", Token::Keyword)]1683
);1684
assert_eq!(1685
kinds("\\section{a} % c", "latex"),1686
vec![("\\section", Token::Keyword), ("% c", Token::Comment)]1687
);1688
assert_eq!(kinds("FROM x", "dockerFile")[0], ("FROM", Token::Keyword));1689
}310
}1690
}@@ -25,14 +25,15 @@ use gpui_kit::component::{
25
25
use gpui_kit::prelude::FluentBuilder as _;
26
26
use gpui_kit::*;
27
27
use teams_core::{
28
Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState, LineKind, LinkPreview,
29
MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit,
30
TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown, link_url, map_offset,
31
reverse_edits,
28
CODE_HEADER_MARK, Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState,
29
LineKind, LinkPreview, MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep,
30
TABLE_MARK, TableEdit, TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown,
31
link_url, map_offset, reverse_edits,
32
32
};
33
33
34
34
mod attach_menu;
35
35
mod cloud_picker;
36
mod code_language;
36
37
pub(crate) mod delivery;
37
38
mod drafts;
38
39
mod format_menus;
@@ -78,6 +79,7 @@ use crate::runtime;
78
79
use crate::scheduled_rows::scheduled_label;
79
80
use crate::theme::{self, ElevatedSurface as _};
80
81
use crate::typing::OutgoingTyping;
82
use code_language::is_code_header_token;
81
83
use format_menus::{FormatPopup, paragraph_label};
82
84
use rule::{is_rule_token, render_rule_token};
83
85
use slash::SlashPopup;
@@ -103,6 +105,15 @@ const COMPOSER_BUTTON_SIZE: f32 = 32.;
103
105
const COMPOSER_BUTTON_INSET: f32 = 6.;
104
106
pub const COMPOSER_BOX_TAG: &str = "composer";
105
107
pub const COMPOSER_ACTIONS_TAG: &str = "composer/actions";
108
fn send_divider() -> Div {
109
div()
110
.flex_none()
111
.w(px(1.))
112
.h(px(SEND_DIVIDER_HEIGHT))
113
.ml(px(COMPOSER_BUTTON_INSET))
114
.bg(theme::border())
115
}
116
106
117
pub const COMPOSER_STACKED_ACTIONS_TAG: &str = "composer/stacked-actions";
107
118
const STACKED_ACTIONS_WIDTH: f32 = 400.;
108
119
pub const COMPOSER_INPUT_TAG: &str = "composer/input";
@@ -259,6 +270,8 @@ pub struct Composer {
259
270
table_counter: usize,
260
271
table_picker: Option<TablePicker>,
261
272
table_menu: Option<TableMenu>,
273
/// The first line of the code block whose language menu is open.
274
code_language_menu: Option<usize>,
262
275
format_popup: Option<FormatPopup>,
263
276
format_overflow: bool,
264
277
format_bar: HashSet<String>,
@@ -536,6 +549,7 @@ impl Composer {
536
549
table_counter: 0,
537
550
table_picker: None,
538
551
table_menu: None,
552
code_language_menu: None,
539
553
format_popup: None,
540
554
format_overflow: false,
541
555
format_bar: HashSet::new(),
@@ -635,6 +649,8 @@ impl Composer {
635
649
self.report_typing(!value.trim().is_empty(), cx);
636
650
let previous = std::mem::replace(&mut self.previous_value, value.clone());
637
651
if previous != value {
652
// The menu names its block by line, which an edit can move.
653
self.code_language_menu = None;
638
654
let (start, old_end, new_end) = changed_span(&previous, &value);
639
655
self.shift_anchors(start, old_end, new_end);
640
656
}
@@ -920,6 +936,7 @@ impl Composer {
920
936
ranges.set(style.ranges, cx);
921
937
self.input.update(cx, |state, cx| {
922
938
state.set_line_indents(style.indents, cx);
939
state.set_line_labels(style.labels, theme::text_faint(), cx);
923
940
state.set_hanging_indents(style.markers, cx);
924
941
});
925
942
}
@@ -938,6 +955,7 @@ impl Composer {
938
955
});
939
956
self.previous_value = draft.text().to_owned();
940
957
self.draft = draft;
958
self.code_language_menu = None;
941
959
self.pending_style = None;
942
960
self.conversion = None;
943
961
self.pasted_markdown = None;
@@ -1487,7 +1505,7 @@ impl Composer {
1487
1505
let text = if selected.contains(TABLE_MARK) {
1488
1506
Draft::from_lines(&lines).plain_text()
1489
1507
} else {
1490
selected.replace(OBJECT_MARK, "")
1508
selected.replace([OBJECT_MARK, CODE_HEADER_MARK], "")
1491
1509
};
1492
1510
if text.is_empty() {
1493
1511
return true;
@@ -3103,11 +3121,18 @@ impl Render for Composer {
3103
3121
.children(attach)
3104
3122
.children(self.render_rewrite_button(cx))
3105
3123
.children(self.render_plus_button(cx));
3124
// Teams gives a code block the full width and keeps the actions right, beside Send.
3125
let below_code = self
3126
.draft
3127
.lines()
3128
.iter()
3129
.any(|kind| matches!(kind, LineKind::Code(_)));
3106
3130
let stacked = !post_layout
3107
&& self
3108
.composer_bounds
3109
.get()
3110
.is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH);
3131
&& (below_code
3132
|| self
3133
.composer_bounds
3134
.get()
3135
.is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH));
3111
3136
let mut send = Some(send);
3112
3137
let (row_actions, stacked_actions, post_footer) = if post_layout {
3113
3138
(
@@ -3133,6 +3158,15 @@ impl Render for Composer {
3133
3158
.unwrap_or(false)
3134
3159
})
3135
3160
.token(move |context, _, cx| {
3161
if context.is_block() && is_code_header_token(context.token()) {
3162
let weak = tokens_composer.clone();
3163
let (at, width) = (context.range().start, context.available_width());
3164
if let Ok(header) = tokens_composer
3165
.read_with(cx, |this, _| this.render_code_header(weak, at, width))
3166
{
3167
return header;
3168
}
3169
}
3136
3170
if context.is_block() && is_rule_token(context.token()) {
3137
3171
return render_rule_token(
3138
3172
context.available_width(),
@@ -3515,7 +3549,10 @@ impl Render for Composer {
3515
3549
}
3516
3550
}))
3517
3551
.capture_action(cx.listener(|this, _: &Escape, window, cx| {
3518
if this.table_picker.take().is_some() || this.table_menu.take().is_some() {
3552
if this.table_picker.take().is_some()
3553
|| this.table_menu.take().is_some()
3554
|| this.code_language_menu.take().is_some()
3555
{
3519
3556
cx.notify();
3520
3557
cx.stop_propagation();
3521
3558
return;
@@ -3576,6 +3613,7 @@ impl Render for Composer {
3576
3613
.children(self.render_slash_popup(cx))
3577
3614
.children(self.render_emoji_popup(window, cx))
3578
3615
.children(self.render_toolbar(focused, cx))
3616
.children(self.render_code_language_menu(cx))
3579
3617
.children(self.render_schedule(cx))
3580
3618
.children(self.render_delivery_menu(cx))
3581
3619
.children(self.render_plus_menu(cx))
@@ -3655,15 +3693,7 @@ impl Render for Composer {
3655
3693
)
3656
3694
.children(row_actions)
3657
3695
.when_some(send.filter(|_| !post_layout), |row, send| {
3658
row.child(
3659
div()
3660
.flex_none()
3661
.w(px(1.))
3662
.h(px(SEND_DIVIDER_HEIGHT))
3663
.ml(px(COMPOSER_BUTTON_INSET))
3664
.bg(theme::border()),
3665
)
3666
.child(send)
3696
row.child(send_divider()).child(send)
3667
3697
}),
3668
3698
)
3669
3699
.children(stacked_actions.map(|(actions, send)| {
@@ -3673,8 +3703,12 @@ impl Render for Composer {
3673
3703
.items_center()
3674
3704
.px(px(COMPOSER_BUTTON_INSET))
3675
3705
.pb(px(COMPOSER_BUTTON_INSET))
3706
.when(below_code, |row| row.child(div().flex_1()))
3676
3707
.child(actions)
3677
.child(div().flex_1())
3708
.when(!below_code, |row| row.child(div().flex_1()))
3709
.when(below_code && send.is_some(), |row| {
3710
row.child(send_divider())
3711
})
3678
3712
.children(send)
3679
3713
}))
3680
3714
.children(post_footer),
@@ -4778,16 +4812,132 @@ mod tests {
4778
4812
}
4779
4813
4780
4814
#[gpui_kit::test]
4781
fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
4815
fn backspace_after_a_fence_gives_it_back_for_a_language(cx: &mut TestAppContext) {
4782
4816
let mut typist = typist(cx);
4783
4817
typist.type_text("```");
4818
assert_eq!(typist.draft().lines(), [teams_core::LineKind::Code(None)]);
4819
typist.press("backspace");
4820
assert_eq!(typist.value(), "```");
4821
typist.type_text("py");
4784
4822
typist.press("enter");
4823
assert_eq!(
4824
typist.draft().lines(),
4825
[teams_core::LineKind::Code(Some("python".into()))]
4826
);
4827
}
4828
4829
#[gpui_kit::test]
4830
fn the_language_picker_in_the_header_sets_the_whole_code_block(cx: &mut TestAppContext) {
4831
use gpui_kit::VisualTestContext;
4832
4833
use super::super::code_language::{CODE_LANGUAGE_ROW_TAG, CODE_LANGUAGE_TAG};
4834
4835
let mut typist = typist(cx);
4836
typist.type_text("x");
4837
typist.press("shift-enter");
4838
typist.type_text("```");
4839
typist.type_text("a");
4840
typist.press("enter");
4841
typist.type_text("b");
4842
let composer = typist.composer.clone();
4843
let handle = typist.handle;
4844
let mut visual = VisualTestContext::from_window(handle, typist.cx);
4845
visual.update(|window, cx| window.render_frame(cx));
4846
let header = visual
4847
.debug_bounds(CODE_LANGUAGE_TAG)
4848
.expect("a header on the block");
4849
visual.simulate_click(header.center(), Default::default());
4850
visual.run_until_parked();
4851
assert_eq!(
4852
composer.read_with(&visual, |composer, _| composer.code_language_menu),
4853
Some(1)
4854
);
4855
visual.update(|window, cx| window.render_frame(cx));
4856
let row = visual
4857
.debug_bounds(Box::leak(
4858
format!("{CODE_LANGUAGE_ROW_TAG}dart").into_boxed_str(),
4859
))
4860
.expect("Dart in the open menu");
4861
visual.simulate_click(row.center(), Default::default());
4862
visual.run_until_parked();
4863
let draft = composer.read_with(&visual, |composer, _| composer.draft.clone());
4864
let dart = teams_core::LineKind::Code(Some("dart".into()));
4865
assert_eq!(draft.lines(), [teams_core::LineKind::Text, dart.clone(), dart]);
4866
assert_eq!(
4867
draft.to_html(),
4868
"x<pre class=\"language-dart skipProofing\" spellcheck=\"false\"><code>a<br>b</code></pre>"
4869
);
4870
}
4871
4872
#[gpui_kit::test]
4873
fn code_typed_after_picking_a_language_is_highlighted(cx: &mut TestAppContext) {
4874
let mut typist = typist(cx);
4875
typist.type_text("```");
4876
let composer = typist.composer.clone();
4877
typist.act(|window, cx| {
4878
composer.update(cx, |composer, cx| {
4879
composer.choose_code_language(0, "python", window, cx)
4880
})
4881
});
4882
typist.type_text("def f():");
4883
typist.press("enter");
4884
typist.type_text("class A: pass");
4885
let draft = typist.draft();
4886
assert_eq!(
4887
draft.lines()[1],
4888
teams_core::LineKind::Code(Some("python".into()))
4889
);
4890
let style = super::super::draft_style(&draft, "Mono".into());
4891
let words: Vec<_> = style
4892
.text
4893
.iter()
4894
.map(|decoration| &draft.text()[decoration.range.clone()])
4895
.collect();
4896
for keyword in ["def", "class", "pass"] {
4897
assert!(words.contains(&keyword), "{keyword} in {words:?}");
4898
}
4899
}
4900
4901
#[gpui_kit::test]
4902
fn copied_code_leaves_its_header_behind_and_escape_closes_the_picker(
4903
cx: &mut TestAppContext,
4904
) {
4905
let mut typist = typist(cx);
4906
typist.type_text("x");
4907
typist.press("shift-enter");
4908
typist.type_text("```");
4909
typist.type_text("a");
4910
let composer = typist.composer.clone();
4911
let (input, end) = typist.cx.update(|cx| {
4912
let composer = composer.read(cx);
4913
(composer.input.clone(), composer.draft.text().len())
4914
});
4915
typist.act(|_, cx| {
4916
input.update(cx, |state, cx| state.set_selected_range(0..end, cx));
4917
composer.update(cx, |composer, cx| {
4918
composer.copy_selection(cx);
4919
composer.code_language_menu = Some(1);
4920
})
4921
});
4922
let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());
4923
assert_eq!(copied.as_deref(), Some("x\na"));
4924
typist.press("escape");
4925
assert_eq!(
4926
typist.cx.update(|cx| composer.read(cx).code_language_menu),
4927
None
4928
);
4929
}
4930
4931
#[gpui_kit::test]
4932
fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
4933
let mut typist = typist(cx);
4934
typist.type_text("```");
4785
4935
typist.type_text("a");
4786
4936
typist.press("enter");
4787
4937
typist.type_text("b");
4788
4938
typist.press("up end delete");
4789
4939
assert_eq!(
4790
typist.outgoing().html(),
4940
typist.outgoing().draft.to_html(),
4791
4941
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>"
4792
4942
);
4793
4943
}
@@ -4797,7 +4947,6 @@ mod tests {
4797
4947
fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
4798
4948
let mut typist = typist(cx);
4799
4949
typist.type_text("```");
4800
typist.press("enter");
4801
4950
typist.type_text(" x");
4802
4951
typist.press("ctrl-a ctrl-c");
4803
4952
let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
@@ -4939,7 +5088,6 @@ mod tests {
4939
5088
fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {
4940
5089
let mut typist = typist(cx);
4941
5090
typist.type_text("```");
4942
typist.press("enter");
4943
5091
typist.type_text(":) ");
4944
5092
typist
4945
5093
.cx
@@ -4954,7 +5102,7 @@ mod tests {
4954
5102
);
4955
5103
let outgoing = typist.outgoing();
4956
5104
assert_eq!(
4957
outgoing.html(),
5105
outgoing.draft.to_html(),
4958
5106
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>"
4959
5107
);
4960
5108
}
@@ -25,14 +25,15 @@ use gpui_kit::component::{25
use gpui_kit::prelude::FluentBuilder as _;25
use gpui_kit::prelude::FluentBuilder as _;26
use gpui_kit::*;26
use gpui_kit::*;27
use teams_core::{27
use teams_core::{28
Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState, LineKind, LinkPreview,28
CODE_HEADER_MARK, Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState,29
MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit,29
LineKind, LinkPreview, MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep,30
TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown, link_url, map_offset,30
TABLE_MARK, TableEdit, TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown,31
reverse_edits,31
link_url, map_offset, reverse_edits,32
};32
};33
33
34
mod attach_menu;34
mod attach_menu;35
mod cloud_picker;35
mod cloud_picker;36
mod code_language;36
pub(crate) mod delivery;37
pub(crate) mod delivery;37
mod drafts;38
mod drafts;38
mod format_menus;39
mod format_menus;@@ -78,6 +79,7 @@ use crate::runtime;78
use crate::scheduled_rows::scheduled_label;79
use crate::scheduled_rows::scheduled_label;79
use crate::theme::{self, ElevatedSurface as _};80
use crate::theme::{self, ElevatedSurface as _};80
use crate::typing::OutgoingTyping;81
use crate::typing::OutgoingTyping;82
use code_language::is_code_header_token;81
use format_menus::{FormatPopup, paragraph_label};83
use format_menus::{FormatPopup, paragraph_label};82
use rule::{is_rule_token, render_rule_token};84
use rule::{is_rule_token, render_rule_token};83
use slash::SlashPopup;85
use slash::SlashPopup;@@ -103,6 +105,15 @@ const COMPOSER_BUTTON_SIZE: f32 = 32.;103
const COMPOSER_BUTTON_INSET: f32 = 6.;105
const COMPOSER_BUTTON_INSET: f32 = 6.;104
pub const COMPOSER_BOX_TAG: &str = "composer";106
pub const COMPOSER_BOX_TAG: &str = "composer";105
pub const COMPOSER_ACTIONS_TAG: &str = "composer/actions";107
pub const COMPOSER_ACTIONS_TAG: &str = "composer/actions";108
fn send_divider() -> Div {109
div()110
.flex_none()111
.w(px(1.))112
.h(px(SEND_DIVIDER_HEIGHT))113
.ml(px(COMPOSER_BUTTON_INSET))114
.bg(theme::border())115
}116
106
pub const COMPOSER_STACKED_ACTIONS_TAG: &str = "composer/stacked-actions";117
pub const COMPOSER_STACKED_ACTIONS_TAG: &str = "composer/stacked-actions";107
const STACKED_ACTIONS_WIDTH: f32 = 400.;118
const STACKED_ACTIONS_WIDTH: f32 = 400.;108
pub const COMPOSER_INPUT_TAG: &str = "composer/input";119
pub const COMPOSER_INPUT_TAG: &str = "composer/input";@@ -259,6 +270,8 @@ pub struct Composer {259
table_counter: usize,270
table_counter: usize,260
table_picker: Option<TablePicker>,271
table_picker: Option<TablePicker>,261
table_menu: Option<TableMenu>,272
table_menu: Option<TableMenu>,273
/// The first line of the code block whose language menu is open.274
code_language_menu: Option<usize>,262
format_popup: Option<FormatPopup>,275
format_popup: Option<FormatPopup>,263
format_overflow: bool,276
format_overflow: bool,264
format_bar: HashSet<String>,277
format_bar: HashSet<String>,@@ -536,6 +549,7 @@ impl Composer {536
table_counter: 0,549
table_counter: 0,537
table_picker: None,550
table_picker: None,538
table_menu: None,551
table_menu: None,552
code_language_menu: None,539
format_popup: None,553
format_popup: None,540
format_overflow: false,554
format_overflow: false,541
format_bar: HashSet::new(),555
format_bar: HashSet::new(),@@ -635,6 +649,8 @@ impl Composer {635
self.report_typing(!value.trim().is_empty(), cx);649
self.report_typing(!value.trim().is_empty(), cx);636
let previous = std::mem::replace(&mut self.previous_value, value.clone());650
let previous = std::mem::replace(&mut self.previous_value, value.clone());637
if previous != value {651
if previous != value {652
// The menu names its block by line, which an edit can move.653
self.code_language_menu = None;638
let (start, old_end, new_end) = changed_span(&previous, &value);654
let (start, old_end, new_end) = changed_span(&previous, &value);639
self.shift_anchors(start, old_end, new_end);655
self.shift_anchors(start, old_end, new_end);640
}656
}@@ -920,6 +936,7 @@ impl Composer {920
ranges.set(style.ranges, cx);936
ranges.set(style.ranges, cx);921
self.input.update(cx, |state, cx| {937
self.input.update(cx, |state, cx| {922
state.set_line_indents(style.indents, cx);938
state.set_line_indents(style.indents, cx);939
state.set_line_labels(style.labels, theme::text_faint(), cx);923
state.set_hanging_indents(style.markers, cx);940
state.set_hanging_indents(style.markers, cx);924
});941
});925
}942
}@@ -938,6 +955,7 @@ impl Composer {938
});955
});939
self.previous_value = draft.text().to_owned();956
self.previous_value = draft.text().to_owned();940
self.draft = draft;957
self.draft = draft;958
self.code_language_menu = None;941
self.pending_style = None;959
self.pending_style = None;942
self.conversion = None;960
self.conversion = None;943
self.pasted_markdown = None;961
self.pasted_markdown = None;@@ -1487,7 +1505,7 @@ impl Composer {1487
let text = if selected.contains(TABLE_MARK) {1505
let text = if selected.contains(TABLE_MARK) {1488
Draft::from_lines(&lines).plain_text()1506
Draft::from_lines(&lines).plain_text()1489
} else {1507
} else {1490
selected.replace(OBJECT_MARK, "")1508
selected.replace([OBJECT_MARK, CODE_HEADER_MARK], "")1491
};1509
};1492
if text.is_empty() {1510
if text.is_empty() {1493
return true;1511
return true;@@ -3103,11 +3121,18 @@ impl Render for Composer {3103
.children(attach)3121
.children(attach)3104
.children(self.render_rewrite_button(cx))3122
.children(self.render_rewrite_button(cx))3105
.children(self.render_plus_button(cx));3123
.children(self.render_plus_button(cx));3124
// Teams gives a code block the full width and keeps the actions right, beside Send.3125
let below_code = self3126
.draft3127
.lines()3128
.iter()3129
.any(|kind| matches!(kind, LineKind::Code(_)));3106
let stacked = !post_layout3130
let stacked = !post_layout3107
&& self3131
&& (below_code3108
.composer_bounds3132
|| self3109
.get()3133
.composer_bounds3110
.is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH);3134
.get()3135
.is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH));3111
let mut send = Some(send);3136
let mut send = Some(send);3112
let (row_actions, stacked_actions, post_footer) = if post_layout {3137
let (row_actions, stacked_actions, post_footer) = if post_layout {3113
(3138
(@@ -3133,6 +3158,15 @@ impl Render for Composer {3133
.unwrap_or(false)3158
.unwrap_or(false)3134
})3159
})3135
.token(move |context, _, cx| {3160
.token(move |context, _, cx| {3161
if context.is_block() && is_code_header_token(context.token()) {3162
let weak = tokens_composer.clone();3163
let (at, width) = (context.range().start, context.available_width());3164
if let Ok(header) = tokens_composer3165
.read_with(cx, |this, _| this.render_code_header(weak, at, width))3166
{3167
return header;3168
}3169
}3136
if context.is_block() && is_rule_token(context.token()) {3170
if context.is_block() && is_rule_token(context.token()) {3137
return render_rule_token(3171
return render_rule_token(3138
context.available_width(),3172
context.available_width(),@@ -3515,7 +3549,10 @@ impl Render for Composer {3515
}3549
}3516
}))3550
}))3517
.capture_action(cx.listener(|this, _: &Escape, window, cx| {3551
.capture_action(cx.listener(|this, _: &Escape, window, cx| {3518
if this.table_picker.take().is_some() || this.table_menu.take().is_some() {3552
if this.table_picker.take().is_some()3553
|| this.table_menu.take().is_some()3554
|| this.code_language_menu.take().is_some()3555
{3519
cx.notify();3556
cx.notify();3520
cx.stop_propagation();3557
cx.stop_propagation();3521
return;3558
return;@@ -3576,6 +3613,7 @@ impl Render for Composer {3576
.children(self.render_slash_popup(cx))3613
.children(self.render_slash_popup(cx))3577
.children(self.render_emoji_popup(window, cx))3614
.children(self.render_emoji_popup(window, cx))3578
.children(self.render_toolbar(focused, cx))3615
.children(self.render_toolbar(focused, cx))3616
.children(self.render_code_language_menu(cx))3579
.children(self.render_schedule(cx))3617
.children(self.render_schedule(cx))3580
.children(self.render_delivery_menu(cx))3618
.children(self.render_delivery_menu(cx))3581
.children(self.render_plus_menu(cx))3619
.children(self.render_plus_menu(cx))@@ -3655,15 +3693,7 @@ impl Render for Composer {3655
)3693
)3656
.children(row_actions)3694
.children(row_actions)3657
.when_some(send.filter(|_| !post_layout), |row, send| {3695
.when_some(send.filter(|_| !post_layout), |row, send| {3658
row.child(3696
row.child(send_divider()).child(send)3659
div()3660
.flex_none()3661
.w(px(1.))3662
.h(px(SEND_DIVIDER_HEIGHT))3663
.ml(px(COMPOSER_BUTTON_INSET))3664
.bg(theme::border()),3665
)3666
.child(send)3667
}),3697
}),3668
)3698
)3669
.children(stacked_actions.map(|(actions, send)| {3699
.children(stacked_actions.map(|(actions, send)| {@@ -3673,8 +3703,12 @@ impl Render for Composer {3673
.items_center()3703
.items_center()3674
.px(px(COMPOSER_BUTTON_INSET))3704
.px(px(COMPOSER_BUTTON_INSET))3675
.pb(px(COMPOSER_BUTTON_INSET))3705
.pb(px(COMPOSER_BUTTON_INSET))3706
.when(below_code, |row| row.child(div().flex_1()))3676
.child(actions)3707
.child(actions)3677
.child(div().flex_1())3708
.when(!below_code, |row| row.child(div().flex_1()))3709
.when(below_code && send.is_some(), |row| {3710
row.child(send_divider())3711
})3678
.children(send)3712
.children(send)3679
}))3713
}))3680
.children(post_footer),3714
.children(post_footer),@@ -4778,16 +4812,132 @@ mod tests {4778
}4812
}4779
4813
4780
#[gpui_kit::test]4814
#[gpui_kit::test]4781
fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {4815
fn backspace_after_a_fence_gives_it_back_for_a_language(cx: &mut TestAppContext) {4782
let mut typist = typist(cx);4816
let mut typist = typist(cx);4783
typist.type_text("```");4817
typist.type_text("```");4818
assert_eq!(typist.draft().lines(), [teams_core::LineKind::Code(None)]);4819
typist.press("backspace");4820
assert_eq!(typist.value(), "```");4821
typist.type_text("py");4784
typist.press("enter");4822
typist.press("enter");4823
assert_eq!(4824
typist.draft().lines(),4825
[teams_core::LineKind::Code(Some("python".into()))]4826
);4827
}4828
4829
#[gpui_kit::test]4830
fn the_language_picker_in_the_header_sets_the_whole_code_block(cx: &mut TestAppContext) {4831
use gpui_kit::VisualTestContext;4832
4833
use super::super::code_language::{CODE_LANGUAGE_ROW_TAG, CODE_LANGUAGE_TAG};4834
4835
let mut typist = typist(cx);4836
typist.type_text("x");4837
typist.press("shift-enter");4838
typist.type_text("```");4839
typist.type_text("a");4840
typist.press("enter");4841
typist.type_text("b");4842
let composer = typist.composer.clone();4843
let handle = typist.handle;4844
let mut visual = VisualTestContext::from_window(handle, typist.cx);4845
visual.update(|window, cx| window.render_frame(cx));4846
let header = visual4847
.debug_bounds(CODE_LANGUAGE_TAG)4848
.expect("a header on the block");4849
visual.simulate_click(header.center(), Default::default());4850
visual.run_until_parked();4851
assert_eq!(4852
composer.read_with(&visual, |composer, _| composer.code_language_menu),4853
Some(1)4854
);4855
visual.update(|window, cx| window.render_frame(cx));4856
let row = visual4857
.debug_bounds(Box::leak(4858
format!("{CODE_LANGUAGE_ROW_TAG}dart").into_boxed_str(),4859
))4860
.expect("Dart in the open menu");4861
visual.simulate_click(row.center(), Default::default());4862
visual.run_until_parked();4863
let draft = composer.read_with(&visual, |composer, _| composer.draft.clone());4864
let dart = teams_core::LineKind::Code(Some("dart".into()));4865
assert_eq!(draft.lines(), [teams_core::LineKind::Text, dart.clone(), dart]);4866
assert_eq!(4867
draft.to_html(),4868
"x<pre class=\"language-dart skipProofing\" spellcheck=\"false\"><code>a<br>b</code></pre>"4869
);4870
}4871
4872
#[gpui_kit::test]4873
fn code_typed_after_picking_a_language_is_highlighted(cx: &mut TestAppContext) {4874
let mut typist = typist(cx);4875
typist.type_text("```");4876
let composer = typist.composer.clone();4877
typist.act(|window, cx| {4878
composer.update(cx, |composer, cx| {4879
composer.choose_code_language(0, "python", window, cx)4880
})4881
});4882
typist.type_text("def f():");4883
typist.press("enter");4884
typist.type_text("class A: pass");4885
let draft = typist.draft();4886
assert_eq!(4887
draft.lines()[1],4888
teams_core::LineKind::Code(Some("python".into()))4889
);4890
let style = super::super::draft_style(&draft, "Mono".into());4891
let words: Vec<_> = style4892
.text4893
.iter()4894
.map(|decoration| &draft.text()[decoration.range.clone()])4895
.collect();4896
for keyword in ["def", "class", "pass"] {4897
assert!(words.contains(&keyword), "{keyword} in {words:?}");4898
}4899
}4900
4901
#[gpui_kit::test]4902
fn copied_code_leaves_its_header_behind_and_escape_closes_the_picker(4903
cx: &mut TestAppContext,4904
) {4905
let mut typist = typist(cx);4906
typist.type_text("x");4907
typist.press("shift-enter");4908
typist.type_text("```");4909
typist.type_text("a");4910
let composer = typist.composer.clone();4911
let (input, end) = typist.cx.update(|cx| {4912
let composer = composer.read(cx);4913
(composer.input.clone(), composer.draft.text().len())4914
});4915
typist.act(|_, cx| {4916
input.update(cx, |state, cx| state.set_selected_range(0..end, cx));4917
composer.update(cx, |composer, cx| {4918
composer.copy_selection(cx);4919
composer.code_language_menu = Some(1);4920
})4921
});4922
let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());4923
assert_eq!(copied.as_deref(), Some("x\na"));4924
typist.press("escape");4925
assert_eq!(4926
typist.cx.update(|cx| composer.read(cx).code_language_menu),4927
None4928
);4929
}4930
4931
#[gpui_kit::test]4932
fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {4933
let mut typist = typist(cx);4934
typist.type_text("```");4785
typist.type_text("a");4935
typist.type_text("a");4786
typist.press("enter");4936
typist.press("enter");4787
typist.type_text("b");4937
typist.type_text("b");4788
typist.press("up end delete");4938
typist.press("up end delete");4789
assert_eq!(4939
assert_eq!(4790
typist.outgoing().html(),4940
typist.outgoing().draft.to_html(),4791
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>"4941
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>"4792
);4942
);4793
}4943
}@@ -4797,7 +4947,6 @@ mod tests {4797
fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {4947
fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {4798
let mut typist = typist(cx);4948
let mut typist = typist(cx);4799
typist.type_text("```");4949
typist.type_text("```");4800
typist.press("enter");4801
typist.type_text(" x");4950
typist.type_text(" x");4802
typist.press("ctrl-a ctrl-c");4951
typist.press("ctrl-a ctrl-c");4803
let text = typist.cx.read_from_clipboard().and_then(|item| item.text());4952
let text = typist.cx.read_from_clipboard().and_then(|item| item.text());@@ -4939,7 +5088,6 @@ mod tests {4939
fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {5088
fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {4940
let mut typist = typist(cx);5089
let mut typist = typist(cx);4941
typist.type_text("```");5090
typist.type_text("```");4942
typist.press("enter");4943
typist.type_text(":) ");5091
typist.type_text(":) ");4944
typist5092
typist4945
.cx5093
.cx@@ -4954,7 +5102,7 @@ mod tests {4954
);5102
);4955
let outgoing = typist.outgoing();5103
let outgoing = typist.outgoing();4956
assert_eq!(5104
assert_eq!(4957
outgoing.html(),5105
outgoing.draft.to_html(),4958
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>"5106
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>"4959
);5107
);4960
}5108
}@@ -0,0 +1,204 @@
1
use gpui_kit::component::input::InlineToken;
2
use gpui_kit::component::{h_flex, v_flex};
3
use gpui_kit::prelude::FluentBuilder as _;
4
use gpui_kit::*;
5
use teams_core::{CODE_HEADER_MARK, CODE_LANGUAGES, LineKind, PLAIN_LANGUAGE};
6
7
use super::Composer;
8
use crate::theme::{self, ElevatedSurface as _};
9
use crate::views::draft_style::CODE_INDENT;
10
use crate::views::widgets::symbol;
11
12
const TOKEN_PREFIX: &str = "code-header-";
13
pub(super) const CODE_LANGUAGE_TAG: &str = "composer/code-language";
14
pub(super) const CODE_LANGUAGE_ROW_TAG: &str = "composer/code-language-row-";
15
const HEADER_HEIGHT: f32 = 36.;
16
/// Room between the rule and the first code line.
17
const CODE_TOP_GAP: f32 = 6.;
18
const MENU_WIDTH: f32 = 180.;
19
const MENU_HEIGHT: f32 = 280.;
20
21
pub(super) fn is_code_header_token(token: &InlineToken) -> bool {
22
token.id().starts_with(TOKEN_PREFIX)
23
}
24
25
impl Composer {
26
/// Every code block's first line gets its header token in place of the header mark.
27
pub(super) fn sync_code_headers(&mut self, window: &mut Window, cx: &mut Context<Self>) {
28
if self.input.read(cx).value().as_ref() != self.draft.text() {
29
return;
30
}
31
let tokens: Vec<_> = self
32
.input
33
.read(cx)
34
.tokens()
35
.iter()
36
.filter(|span| is_code_header_token(span.token()))
37
.map(|span| span.range())
38
.collect();
39
let marks: Vec<_> = self
40
.draft
41
.text()
42
.match_indices(CODE_HEADER_MARK)
43
.map(|(at, mark)| at..at + mark.len())
44
.filter(|mark| !tokens.contains(mark))
45
.collect();
46
for mark in marks {
47
self.table_counter += 1;
48
let token = InlineToken::new(
49
format!("{TOKEN_PREFIX}{}", self.table_counter),
50
CODE_HEADER_MARK.to_string(),
51
)
52
.header();
53
self.input.update(cx, |state, cx| {
54
let selection = state.selected_range();
55
if state
56
.replace_range_with_token(mark, token, window, cx)
57
.is_ok()
58
{
59
state.set_selected_range(selection, cx);
60
}
61
});
62
}
63
}
64
65
/// Teams' code block header: the language, which opens its picker, over a rule.
66
pub(super) fn render_code_header(
67
&self,
68
composer: WeakEntity<Composer>,
69
at: usize,
70
width: Pixels,
71
) -> AnyElement {
72
let line = self.draft.line_at(at);
73
let language = match self.draft.lines().get(line) {
74
Some(LineKind::Code(language)) => language.clone(),
75
_ => None,
76
};
77
let chosen = language.unwrap_or_else(|| PLAIN_LANGUAGE.to_owned());
78
let name = teams_core::code_language(&chosen)
79
.map_or(chosen.clone(), |language| language.name.to_owned());
80
let open = self.code_language_menu == Some(line);
81
let toggle = composer.clone();
82
let button = h_flex()
83
.id(ElementId::Name(format!("code-language-{at}").into()))
84
.debug_selector(|| CODE_LANGUAGE_TAG.into())
85
.h(px(24.))
86
.px(px(6.))
87
.gap(px(4.))
88
.items_center()
89
.rounded(px(4.))
90
.text_size(px(13.))
91
.text_color(theme::text())
92
.cursor_pointer()
93
.hover(|button| button.bg(theme::popup_hover()))
94
.on_mouse_down(MouseButton::Left, |_, window, cx| {
95
window.prevent_default();
96
cx.stop_propagation();
97
})
98
.on_click(move |_, _, cx| {
99
toggle
100
.update(cx, |this, cx| {
101
this.code_language_menu = (!open).then_some(line);
102
cx.notify();
103
})
104
.ok();
105
})
106
.child(symbol("code", 14., theme::text_muted()))
107
.child(name)
108
.child(symbol("keyboard_arrow_down", 14., theme::text_muted()));
109
v_flex()
110
.w(width)
111
.pb(px(CODE_TOP_GAP))
112
.child(
113
h_flex()
114
.h(px(HEADER_HEIGHT))
115
.px(px(6.))
116
.items_center()
117
.border_b_1()
118
.border_color(theme::code_frame())
119
.child(button),
120
)
121
.into_any_element()
122
}
123
124
/// The open picker, drawn over the composer: inside the input it could not be clicked
125
/// where it reaches past the input's bounds.
126
pub(super) fn render_code_language_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
127
let line = self.code_language_menu?;
128
let at = self.draft.line_ranges().get(line)?.start;
129
let LineKind::Code(language) = self.draft.lines().get(line)? else {
130
return None;
131
};
132
let chosen = language
133
.as_deref()
134
.and_then(teams_core::code_language)
135
.map_or(PLAIN_LANGUAGE, |language| language.id);
136
let header = self.input.read(cx).range_to_bounds(&(at..at))?;
137
let rows = CODE_LANGUAGES.iter().map(|language| {
138
let (id, name) = (language.id, language.name);
139
div()
140
.id(ElementId::Name(format!("code-language-{id}").into()))
141
.debug_selector(move || format!("{CODE_LANGUAGE_ROW_TAG}{id}"))
142
.px(px(10.))
143
.py(px(5.))
144
.rounded(px(6.))
145
.text_size(px(13.))
146
.text_color(theme::text())
147
.cursor_pointer()
148
.when(id == chosen, |row| row.bg(theme::popup_hover()))
149
.hover(|row| row.bg(theme::popup_hover()))
150
.on_mouse_down(MouseButton::Left, |_, window, cx| {
151
window.prevent_default();
152
cx.stop_propagation();
153
})
154
.on_click(cx.listener(move |this, _, window, cx| {
155
this.choose_code_language(at, id, window, cx)
156
}))
157
.child(name)
158
});
159
// Lined up with the block's edge, left of the line indent where `at` sits.
160
let left = header.left() - px(CODE_INDENT);
161
Some(
162
deferred(
163
// Above the header, as in Teams: the composer sits at the window's bottom.
164
anchored()
165
.position(point(left, header.top()))
166
.anchor(Anchor::BottomLeft)
167
.snap_to_window_with_margin(px(8.))
168
.child(
169
v_flex()
170
.id("code-language-menu")
171
.mb(px(4.))
172
.w(px(MENU_WIDTH))
173
.max_h(px(MENU_HEIGHT))
174
.overflow_y_scroll()
175
.p(px(4.))
176
.rounded(px(10.))
177
.flyout_surface()
178
.occlude()
179
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
180
this.code_language_menu = None;
181
cx.notify();
182
}))
183
.children(rows),
184
),
185
)
186
.with_priority(1)
187
.into_any_element(),
188
)
189
}
190
191
pub(super) fn choose_code_language(
192
&mut self,
193
at: usize,
194
id: &str,
195
window: &mut Window,
196
cx: &mut Context<Self>,
197
) {
198
let language = (id != PLAIN_LANGUAGE).then(|| id.to_owned());
199
self.draft.set_code_language(at, language);
200
self.code_language_menu = None;
201
self.commit(None, window, cx);
202
cx.notify();
203
}
204
}
@@ -0,0 +1,204 @@1
use gpui_kit::component::input::InlineToken;2
use gpui_kit::component::{h_flex, v_flex};3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;5
use teams_core::{CODE_HEADER_MARK, CODE_LANGUAGES, LineKind, PLAIN_LANGUAGE};6
7
use super::Composer;8
use crate::theme::{self, ElevatedSurface as _};9
use crate::views::draft_style::CODE_INDENT;10
use crate::views::widgets::symbol;11
12
const TOKEN_PREFIX: &str = "code-header-";13
pub(super) const CODE_LANGUAGE_TAG: &str = "composer/code-language";14
pub(super) const CODE_LANGUAGE_ROW_TAG: &str = "composer/code-language-row-";15
const HEADER_HEIGHT: f32 = 36.;16
/// Room between the rule and the first code line.17
const CODE_TOP_GAP: f32 = 6.;18
const MENU_WIDTH: f32 = 180.;19
const MENU_HEIGHT: f32 = 280.;20
21
pub(super) fn is_code_header_token(token: &InlineToken) -> bool {22
token.id().starts_with(TOKEN_PREFIX)23
}24
25
impl Composer {26
/// Every code block's first line gets its header token in place of the header mark.27
pub(super) fn sync_code_headers(&mut self, window: &mut Window, cx: &mut Context<Self>) {28
if self.input.read(cx).value().as_ref() != self.draft.text() {29
return;30
}31
let tokens: Vec<_> = self32
.input33
.read(cx)34
.tokens()35
.iter()36
.filter(|span| is_code_header_token(span.token()))37
.map(|span| span.range())38
.collect();39
let marks: Vec<_> = self40
.draft41
.text()42
.match_indices(CODE_HEADER_MARK)43
.map(|(at, mark)| at..at + mark.len())44
.filter(|mark| !tokens.contains(mark))45
.collect();46
for mark in marks {47
self.table_counter += 1;48
let token = InlineToken::new(49
format!("{TOKEN_PREFIX}{}", self.table_counter),50
CODE_HEADER_MARK.to_string(),51
)52
.header();53
self.input.update(cx, |state, cx| {54
let selection = state.selected_range();55
if state56
.replace_range_with_token(mark, token, window, cx)57
.is_ok()58
{59
state.set_selected_range(selection, cx);60
}61
});62
}63
}64
65
/// Teams' code block header: the language, which opens its picker, over a rule.66
pub(super) fn render_code_header(67
&self,68
composer: WeakEntity<Composer>,69
at: usize,70
width: Pixels,71
) -> AnyElement {72
let line = self.draft.line_at(at);73
let language = match self.draft.lines().get(line) {74
Some(LineKind::Code(language)) => language.clone(),75
_ => None,76
};77
let chosen = language.unwrap_or_else(|| PLAIN_LANGUAGE.to_owned());78
let name = teams_core::code_language(&chosen)79
.map_or(chosen.clone(), |language| language.name.to_owned());80
let open = self.code_language_menu == Some(line);81
let toggle = composer.clone();82
let button = h_flex()83
.id(ElementId::Name(format!("code-language-{at}").into()))84
.debug_selector(|| CODE_LANGUAGE_TAG.into())85
.h(px(24.))86
.px(px(6.))87
.gap(px(4.))88
.items_center()89
.rounded(px(4.))90
.text_size(px(13.))91
.text_color(theme::text())92
.cursor_pointer()93
.hover(|button| button.bg(theme::popup_hover()))94
.on_mouse_down(MouseButton::Left, |_, window, cx| {95
window.prevent_default();96
cx.stop_propagation();97
})98
.on_click(move |_, _, cx| {99
toggle100
.update(cx, |this, cx| {101
this.code_language_menu = (!open).then_some(line);102
cx.notify();103
})104
.ok();105
})106
.child(symbol("code", 14., theme::text_muted()))107
.child(name)108
.child(symbol("keyboard_arrow_down", 14., theme::text_muted()));109
v_flex()110
.w(width)111
.pb(px(CODE_TOP_GAP))112
.child(113
h_flex()114
.h(px(HEADER_HEIGHT))115
.px(px(6.))116
.items_center()117
.border_b_1()118
.border_color(theme::code_frame())119
.child(button),120
)121
.into_any_element()122
}123
124
/// The open picker, drawn over the composer: inside the input it could not be clicked125
/// where it reaches past the input's bounds.126
pub(super) fn render_code_language_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {127
let line = self.code_language_menu?;128
let at = self.draft.line_ranges().get(line)?.start;129
let LineKind::Code(language) = self.draft.lines().get(line)? else {130
return None;131
};132
let chosen = language133
.as_deref()134
.and_then(teams_core::code_language)135
.map_or(PLAIN_LANGUAGE, |language| language.id);136
let header = self.input.read(cx).range_to_bounds(&(at..at))?;137
let rows = CODE_LANGUAGES.iter().map(|language| {138
let (id, name) = (language.id, language.name);139
div()140
.id(ElementId::Name(format!("code-language-{id}").into()))141
.debug_selector(move || format!("{CODE_LANGUAGE_ROW_TAG}{id}"))142
.px(px(10.))143
.py(px(5.))144
.rounded(px(6.))145
.text_size(px(13.))146
.text_color(theme::text())147
.cursor_pointer()148
.when(id == chosen, |row| row.bg(theme::popup_hover()))149
.hover(|row| row.bg(theme::popup_hover()))150
.on_mouse_down(MouseButton::Left, |_, window, cx| {151
window.prevent_default();152
cx.stop_propagation();153
})154
.on_click(cx.listener(move |this, _, window, cx| {155
this.choose_code_language(at, id, window, cx)156
}))157
.child(name)158
});159
// Lined up with the block's edge, left of the line indent where `at` sits.160
let left = header.left() - px(CODE_INDENT);161
Some(162
deferred(163
// Above the header, as in Teams: the composer sits at the window's bottom.164
anchored()165
.position(point(left, header.top()))166
.anchor(Anchor::BottomLeft)167
.snap_to_window_with_margin(px(8.))168
.child(169
v_flex()170
.id("code-language-menu")171
.mb(px(4.))172
.w(px(MENU_WIDTH))173
.max_h(px(MENU_HEIGHT))174
.overflow_y_scroll()175
.p(px(4.))176
.rounded(px(10.))177
.flyout_surface()178
.occlude()179
.on_mouse_down_out(cx.listener(|this, _, _, cx| {180
this.code_language_menu = None;181
cx.notify();182
}))183
.children(rows),184
),185
)186
.with_priority(1)187
.into_any_element(),188
)189
}190
191
pub(super) fn choose_code_language(192
&mut self,193
at: usize,194
id: &str,195
window: &mut Window,196
cx: &mut Context<Self>,197
) {198
let language = (id != PLAIN_LANGUAGE).then(|| id.to_owned());199
self.draft.set_code_language(at, language);200
self.code_language_menu = None;201
self.commit(None, window, cx);202
cx.notify();203
}204
}@@ -171,6 +171,7 @@ impl Composer {
171
171
self.sync_table_view(&id, &table, window, cx);
172
172
}
173
173
self.sync_rules(window, cx);
174
self.sync_code_headers(window, cx);
174
175
}
175
176
176
177
fn sync_table_view(
@@ -171,6 +171,7 @@ impl Composer {171
self.sync_table_view(&id, &table, window, cx);171
self.sync_table_view(&id, &table, window, cx);172
}172
}173
self.sync_rules(window, cx);173
self.sync_rules(window, cx);174
self.sync_code_headers(window, cx);174
}175
}175
176
176
fn sync_table_view(177
fn sync_table_view(@@ -0,0 +1,120 @@
1
/// A code block language as Teams offers it: the id its `language-*` class carries and the name shown.
2
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3
pub struct CodeLanguage {
4
pub id: &'static str,
5
pub name: &'static str,
6
}
7
8
pub const PLAIN_LANGUAGE: &str = "plaintext";
9
10
const fn language(id: &'static str, name: &'static str) -> CodeLanguage {
11
CodeLanguage { id, name }
12
}
13
14
/// Teams' code block picker, in its order, from the class map of its code block editor
15
/// (Teams web). Its Shell row sends `language-bash` like Bash, so it is left out here.
16
/// A new language is one row here, and a grammar in the app's highlighter if it gets colours.
17
pub const CODE_LANGUAGES: &[CodeLanguage] = &[
18
language(PLAIN_LANGUAGE, "Plain Text"),
19
language("bash", "Bash"),
20
language("c", "C"),
21
language("cpp", "C++"),
22
language("csharp", "C#"),
23
language("css", "CSS"),
24
language("dart", "Dart"),
25
language("dockerFile", "DockerFile"),
26
language("dos", "DOS"),
27
language("go", "Go"),
28
language("graphql", "GraphQL"),
29
language("html", "HTML"),
30
language("http", "HTTP"),
31
language("java", "Java"),
32
language("javascript", "JavaScript"),
33
language("json", "JSON"),
34
language("jsp", "JSP"),
35
language("jsx", "JSX"),
36
language("kotlin", "Kotlin"),
37
language("kql", "KQL"),
38
language("latex", "LaTeX"),
39
language("lisp", "Lisp"),
40
language("markdown", "Markdown"),
41
language("objectivec", "Objective-C"),
42
language("octave", "Octave"),
43
language("perl", "Perl"),
44
language("php", "PHP"),
45
language("powershell", "PowerShell"),
46
language("python", "Python"),
47
language("r", "R"),
48
language("ruby", "Ruby"),
49
language("rust", "Rust"),
50
language("scala", "Scala"),
51
language("scss", "SCSS"),
52
language("sql", "SQL"),
53
language("swift", "Swift"),
54
language("typescript", "TypeScript"),
55
language("vbnet", "VB.NET"),
56
language("vbscript", "VBScript"),
57
language("verilog", "Verilog"),
58
language("vhdl", "VHDL"),
59
language("xml", "XML"),
60
language("yaml", "YAML"),
61
];
62
63
/// Short names people type after ``` that mean one of Teams' languages.
64
const ALIASES: &[(&str, &str)] = &[
65
("text", PLAIN_LANGUAGE),
66
("txt", PLAIN_LANGUAGE),
67
("sh", "bash"),
68
("shell", "bash"),
69
("zsh", "bash"),
70
("c++", "cpp"),
71
("cs", "csharp"),
72
("c#", "csharp"),
73
("docker", "dockerFile"),
74
("bat", "dos"),
75
("cmd", "dos"),
76
("golang", "go"),
77
("js", "javascript"),
78
("kt", "kotlin"),
79
("tex", "latex"),
80
("md", "markdown"),
81
("objc", "objectivec"),
82
("matlab", "octave"),
83
("ps1", "powershell"),
84
("py", "python"),
85
("rb", "ruby"),
86
("rs", "rust"),
87
("ts", "typescript"),
88
("tsx", "typescript"),
89
("vb", "vbnet"),
90
("svg", "xml"),
91
("yml", "yaml"),
92
];
93
94
/// Teams' language for an id or a common short name, in any case.
95
pub fn code_language(id: &str) -> Option<&'static CodeLanguage> {
96
let id = ALIASES
97
.iter()
98
.find(|(alias, _)| alias.eq_ignore_ascii_case(id))
99
.map_or(id, |(_, target)| target);
100
CODE_LANGUAGES
101
.iter()
102
.find(|language| language.id.eq_ignore_ascii_case(id))
103
}
104
105
#[cfg(test)]
106
mod tests {
107
use super::*;
108
109
#[test]
110
fn ids_names_and_short_names_find_teams_languages() {
111
assert_eq!(
112
code_language("dockerfile").map(|l| l.id),
113
Some("dockerFile")
114
);
115
assert_eq!(code_language("py").map(|l| l.name), Some("Python"));
116
assert_eq!(code_language("SHELL").map(|l| l.name), Some("Bash"));
117
assert_eq!(code_language("brainfuck"), None);
118
assert!(ALIASES.iter().all(|(_, id)| code_language(id).is_some()));
119
}
120
}
@@ -0,0 +1,120 @@1
/// A code block language as Teams offers it: the id its `language-*` class carries and the name shown.2
#[derive(Debug, Clone, Copy, PartialEq, Eq)]3
pub struct CodeLanguage {4
pub id: &'static str,5
pub name: &'static str,6
}7
8
pub const PLAIN_LANGUAGE: &str = "plaintext";9
10
const fn language(id: &'static str, name: &'static str) -> CodeLanguage {11
CodeLanguage { id, name }12
}13
14
/// Teams' code block picker, in its order, from the class map of its code block editor15
/// (Teams web). Its Shell row sends `language-bash` like Bash, so it is left out here.16
/// A new language is one row here, and a grammar in the app's highlighter if it gets colours.17
pub const CODE_LANGUAGES: &[CodeLanguage] = &[18
language(PLAIN_LANGUAGE, "Plain Text"),19
language("bash", "Bash"),20
language("c", "C"),21
language("cpp", "C++"),22
language("csharp", "C#"),23
language("css", "CSS"),24
language("dart", "Dart"),25
language("dockerFile", "DockerFile"),26
language("dos", "DOS"),27
language("go", "Go"),28
language("graphql", "GraphQL"),29
language("html", "HTML"),30
language("http", "HTTP"),31
language("java", "Java"),32
language("javascript", "JavaScript"),33
language("json", "JSON"),34
language("jsp", "JSP"),35
language("jsx", "JSX"),36
language("kotlin", "Kotlin"),37
language("kql", "KQL"),38
language("latex", "LaTeX"),39
language("lisp", "Lisp"),40
language("markdown", "Markdown"),41
language("objectivec", "Objective-C"),42
language("octave", "Octave"),43
language("perl", "Perl"),44
language("php", "PHP"),45
language("powershell", "PowerShell"),46
language("python", "Python"),47
language("r", "R"),48
language("ruby", "Ruby"),49
language("rust", "Rust"),50
language("scala", "Scala"),51
language("scss", "SCSS"),52
language("sql", "SQL"),53
language("swift", "Swift"),54
language("typescript", "TypeScript"),55
language("vbnet", "VB.NET"),56
language("vbscript", "VBScript"),57
language("verilog", "Verilog"),58
language("vhdl", "VHDL"),59
language("xml", "XML"),60
language("yaml", "YAML"),61
];62
63
/// Short names people type after ``` that mean one of Teams' languages.64
const ALIASES: &[(&str, &str)] = &[65
("text", PLAIN_LANGUAGE),66
("txt", PLAIN_LANGUAGE),67
("sh", "bash"),68
("shell", "bash"),69
("zsh", "bash"),70
("c++", "cpp"),71
("cs", "csharp"),72
("c#", "csharp"),73
("docker", "dockerFile"),74
("bat", "dos"),75
("cmd", "dos"),76
("golang", "go"),77
("js", "javascript"),78
("kt", "kotlin"),79
("tex", "latex"),80
("md", "markdown"),81
("objc", "objectivec"),82
("matlab", "octave"),83
("ps1", "powershell"),84
("py", "python"),85
("rb", "ruby"),86
("rs", "rust"),87
("ts", "typescript"),88
("tsx", "typescript"),89
("vb", "vbnet"),90
("svg", "xml"),91
("yml", "yaml"),92
];93
94
/// Teams' language for an id or a common short name, in any case.95
pub fn code_language(id: &str) -> Option<&'static CodeLanguage> {96
let id = ALIASES97
.iter()98
.find(|(alias, _)| alias.eq_ignore_ascii_case(id))99
.map_or(id, |(_, target)| target);100
CODE_LANGUAGES101
.iter()102
.find(|language| language.id.eq_ignore_ascii_case(id))103
}104
105
#[cfg(test)]106
mod tests {107
use super::*;108
109
#[test]110
fn ids_names_and_short_names_find_teams_languages() {111
assert_eq!(112
code_language("dockerfile").map(|l| l.id),113
Some("dockerFile")114
);115
assert_eq!(code_language("py").map(|l| l.name), Some("Python"));116
assert_eq!(code_language("SHELL").map(|l| l.name), Some("Bash"));117
assert_eq!(code_language("brainfuck"), None);118
assert!(ALIASES.iter().all(|(_, id)| code_language(id).is_some()));119
}120
}@@ -12,6 +12,8 @@ pub const MAX_DEPTH: u8 = 2;
12
12
pub const MAX_HEADING: u8 = 3;
13
13
pub const OBJECT_MARK: char = '\u{FFFC}';
14
14
pub const RULE_MARK: char = '\u{FFFA}';
15
/// The marker of a code block's first line: the composer shows the block's header there.
16
pub const CODE_HEADER_MARK: char = '\u{FFF9}';
15
17
pub const MAX_INDENT: u8 = 8;
16
18
pub const INDENT_PIXELS: u32 = 40;
17
19
pub const RULE_HTML: &str = "<hr>";
@@ -783,6 +785,20 @@ impl Draft {
783
785
return None;
784
786
}
785
787
let before = &self.text[content.start..cursor];
788
// Teams opens the block on the third backtick; undo gives back the fence for ```lang + Enter.
789
if self.lines[index] == LineKind::Text && before == FENCE && cursor == content.end {
790
self.splice(content.clone(), "", &[]);
791
let cursor = self.set_line_kind(index, LineKind::Code(None), None, content.start);
792
// A block of the same language right below joins this one under its header.
793
let cursor = self.repair(cursor);
794
return Some((
795
cursor,
796
TypingStyle {
797
at: cursor,
798
..TypingStyle::default()
799
},
800
));
801
}
786
802
if self.lines[index] == LineKind::Text
787
803
&& let Some((kind, number)) = line_shortcut(before)
788
804
{
@@ -880,7 +896,8 @@ impl Draft {
880
896
LineKind::Text => {
881
897
let language = fence_language(&self.text[content.clone()])?;
882
898
self.splice(content.clone(), "", &[]);
883
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
899
let cursor = self.set_line_kind(index, LineKind::Code(language), None, content.start);
900
Some(self.repair(cursor))
884
901
}
885
902
LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,
886
903
LineKind::Indent(_) if !shift => None,
@@ -900,10 +917,17 @@ impl Draft {
900
917
Some(cursor + 1)
901
918
}
902
919
LineKind::Code(_) => {
920
// The third Enter leaves: two empty lines end the block, one stays code.
903
921
let last_of_block = self.lines.get(index + 1) != Some(&kind);
904
let block_continues_above = index > 0 && self.lines[index - 1] == kind;
905
if content.is_empty() && last_of_block && block_continues_above && !shift {
906
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));
922
let empty_line_above = index >= 2
923
&& self.lines[index - 1] == kind
924
&& self.lines[index - 2] == kind
925
&& self.content_range(index - 1).is_empty();
926
if content.is_empty() && last_of_block && empty_line_above && !shift {
927
let above = self.line_ranges()[index - 1].start;
928
self.splice(above..content.start, "", &[]);
929
let cursor = self.set_line_kind(index - 1, LineKind::Text, None, above);
930
return Some(self.repair(cursor));
907
931
}
908
932
self.splice(cursor..cursor, "\n", &[]);
909
933
Some(cursor + 1)
@@ -985,10 +1009,9 @@ impl Draft {
985
1009
match &kind {
986
1010
LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None,
987
1011
LineKind::Code(_) => {
988
let first_of_block = index == 0 || self.lines[index - 1] != kind;
989
(cursor == line.start && first_of_block).then(|| {
990
self.lines[index] = LineKind::Text;
991
cursor
1012
(cursor <= content.start && self.first_of_block(index)).then(|| {
1013
let cursor = self.set_line_kind(index, LineKind::Text, None, cursor);
1014
self.repair(cursor)
992
1015
})
993
1016
}
994
1017
LineKind::Table(_) => None,
@@ -1153,6 +1176,36 @@ impl Draft {
1153
1176
self.repair(0);
1154
1177
}
1155
1178
1179
/// The lines of the code block at `cursor`: the run of code lines with one language.
1180
pub fn code_block_at(&self, cursor: usize) -> Option<Range<usize>> {
1181
let index = self.line_at(cursor);
1182
let kind = self.lines.get(index)?;
1183
if !matches!(kind, LineKind::Code(_)) {
1184
return None;
1185
}
1186
let start = self.lines[..index]
1187
.iter()
1188
.rposition(|other| other != kind)
1189
.map_or(0, |before| before + 1);
1190
let end = index
1191
+ self.lines[index..]
1192
.iter()
1193
.take_while(|other| *other == kind)
1194
.count();
1195
Some(start..end)
1196
}
1197
1198
/// Only the header marks change: a block that now matches the next one merges with it.
1199
pub fn set_code_language(&mut self, cursor: usize, language: Option<String>) {
1200
if let Some(block) = self.code_block_at(cursor) {
1201
self.journal = Journal::default();
1202
for kind in &mut self.lines[block] {
1203
*kind = LineKind::Code(language.clone());
1204
}
1205
self.repair(cursor);
1206
}
1207
}
1208
1156
1209
pub fn table(&self, index: usize) -> Option<&Table> {
1157
1210
match self.lines.get(index)? {
1158
1211
LineKind::Table(table) => Some(table),
@@ -1451,7 +1504,8 @@ impl Draft {
1451
1504
let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE);
1452
1505
html.push_str(&format!(
1453
1506
"<pre class=\"language-{} skipProofing\" spellcheck=\"false\"><code>",
1454
escape_html(&language.to_ascii_lowercase())
1507
// Teams' ids are case-sensitive: `dockerFile`.
1508
escape_html(language)
1455
1509
));
1456
1510
let code = run
1457
1511
.iter()
@@ -1718,11 +1772,48 @@ impl Draft {
1718
1772
})
1719
1773
.unwrap_or(1),
1720
1774
},
1775
LineKind::Code(_) if self.first_of_block(index) => {
1776
return CODE_HEADER_MARK.to_string();
1777
}
1721
1778
_ => 1,
1722
1779
};
1723
1780
marker_text(kind, number)
1724
1781
}
1725
1782
1783
fn first_of_block(&self, index: usize) -> bool {
1784
index == 0 || self.lines[index - 1] != self.lines[index]
1785
}
1786
1787
/// Only the first line of a code block holds the header mark.
1788
fn repair_code_headers(&mut self, mut cursor: usize) -> usize {
1789
let stray: Vec<usize> = self
1790
.text
1791
.match_indices(CODE_HEADER_MARK)
1792
.map(|(at, _)| at)
1793
.filter(|at| {
1794
let index = self.line_at(*at);
1795
!matches!(self.lines[index], LineKind::Code(_))
1796
|| !self.first_of_block(index)
1797
|| self.line_ranges()[index].start != *at
1798
})
1799
.collect();
1800
for at in stray.into_iter().rev() {
1801
let mark = at..at + CODE_HEADER_MARK.len_utf8();
1802
self.splice(mark.clone(), "", &[]);
1803
if cursor > at {
1804
cursor -= (cursor - at).min(mark.len());
1805
}
1806
}
1807
for index in 0..self.lines.len() {
1808
if matches!(self.lines[index], LineKind::Code(_)) {
1809
let marker = self.marker_range(index);
1810
let expected = self.expected_marker(index, None);
1811
cursor = self.replace_marker(marker, &expected, cursor);
1812
}
1813
}
1814
cursor
1815
}
1816
1726
1817
fn set_line_kind(
1727
1818
&mut self,
1728
1819
index: usize,
@@ -1798,6 +1889,7 @@ impl Draft {
1798
1889
/// List items whose marker was edited away become text; numbered items are renumbered.
1799
1890
fn repair(&mut self, cursor: usize) -> usize {
1800
1891
let mut cursor = self.repair_objects(cursor);
1892
cursor = self.repair_code_headers(cursor);
1801
1893
for index in 0..self.lines.len() {
1802
1894
let kind = self.lines[index].clone();
1803
1895
if !kind.is_list() {
@@ -1858,6 +1950,7 @@ fn marker_len(kind: &LineKind, line: &str) -> usize {
1858
1950
}
1859
1951
}
1860
1952
LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length),
1953
LineKind::Code(_) if line.starts_with(CODE_HEADER_MARK) => CODE_HEADER_MARK.len_utf8(),
1861
1954
_ => 0,
1862
1955
}
1863
1956
}
@@ -1892,7 +1985,14 @@ fn fence_language(line: &str) -> Option<Option<String>> {
1892
1985
let valid = info
1893
1986
.chars()
1894
1987
.all(|character| character.is_alphanumeric() || "+#-_.".contains(character));
1895
valid.then(|| (!info.is_empty()).then(|| info.to_lowercase()))
1988
valid.then(|| teams_language(info))
1989
}
1990
1991
/// The id Teams knows for a typed language, so ```py sends `language-python`; Plain Text is none.
1992
fn teams_language(info: &str) -> Option<String> {
1993
let id = crate::code_language(info)
1994
.map_or_else(|| info.to_lowercase(), |language| language.id.to_owned());
1995
(!info.is_empty() && id != crate::PLAIN_LANGUAGE).then_some(id)
1896
1996
}
1897
1997
1898
1998
fn valid_inner(inner: &str) -> bool {
@@ -3037,28 +3137,95 @@ mod tests {
3037
3137
3038
3138
#[test]
3039
3139
fn fence_and_enter_open_a_code_block_that_enter_continues() {
3040
let mut draft = typed_draft("```rust");
3140
let mut draft = Draft::plain("```rust");
3041
3141
let cursor = draft.break_line(draft.text().len(), false).unwrap();
3042
assert_eq!((draft.text(), cursor), ("", 0));
3142
assert_eq!((draft.text(), cursor), ("\u{FFF9}", 3));
3043
3143
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);
3044
3144
typed(&mut draft, "fn x() {}");
3045
3145
let cursor = draft.break_line(draft.text().len(), false).unwrap();
3046
3146
assert_eq!(draft.lines().len(), 2);
3047
assert_eq!(draft.break_line(cursor, false), Some(cursor));
3147
let cursor = draft.break_line(cursor, false).unwrap();
3148
assert_eq!(draft.lines().len(), 3, "one empty line stays code");
3149
assert_eq!(draft.lines()[2], LineKind::Code(Some("rust".into())));
3150
let end = draft.break_line(cursor, false).unwrap();
3151
assert_eq!(
3152
draft.lines().len(),
3153
2,
3154
"the third Enter drops both empty lines"
3155
);
3048
3156
assert_eq!(draft.lines()[1], LineKind::Text);
3157
assert_eq!(end, draft.line_ranges()[1].start);
3049
3158
assert_eq!(
3050
3159
draft.to_html(),
3051
3160
"<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"
3052
3161
);
3053
3162
}
3054
3163
3164
#[test]
3165
fn a_fence_opens_a_code_block_only_alone_on_a_plain_line() {
3166
assert_eq!(typed_draft("a ```").lines(), [LineKind::Text]);
3167
assert_eq!(typed_draft("> ```").lines(), [LineKind::Quote]);
3168
let mut draft = Draft::plain("x");
3169
draft.apply_edit("```x", 3, None);
3170
assert!(draft.convert_typed(3).is_none());
3171
assert_eq!(draft.text(), "```x");
3172
}
3173
3174
#[test]
3175
fn a_language_goes_to_the_whole_code_block_at_the_cursor_only() {
3176
let mut draft = Draft::from_markdown("```\na\nb\n```\nx\n```\nc\n```");
3177
draft.set_code_language(0, Some("go".into()));
3178
assert_eq!(
3179
draft.lines(),
3180
[
3181
LineKind::Code(Some("go".into())),
3182
LineKind::Code(Some("go".into())),
3183
LineKind::Text,
3184
LineKind::Code(None),
3185
]
3186
);
3187
assert_eq!(draft.code_block_at(draft.text().find('b').unwrap()), Some(0..2));
3188
assert_eq!(draft.code_block_at(draft.text().len() - 1), Some(3..4));
3189
draft.set_code_language(draft.text().find('x').unwrap(), Some("c".into()));
3190
assert_eq!(draft.lines()[2], LineKind::Text);
3191
assert!(draft.to_html().starts_with("<pre class=\"language-go "));
3192
}
3193
3194
#[test]
3195
fn the_block_keeps_its_first_line_when_enter_leaves_it() {
3196
let mut draft = typed_draft("```");
3197
let cursor = draft.break_line(draft.text().len(), false).unwrap();
3198
let cursor = draft.break_line(cursor, false).unwrap();
3199
draft.break_line(cursor, false).unwrap();
3200
assert_eq!(draft.lines(), [LineKind::Code(None), LineKind::Text]);
3201
}
3202
3203
#[test]
3204
fn a_fence_above_a_block_of_its_language_joins_it_under_one_header() {
3205
let mut draft = Draft::from_markdown("x\n```python\nb\n```");
3206
let fenced = format!("```python{}", &draft.text()[1..]);
3207
draft.apply_edit(&fenced, "```python".len(), None);
3208
draft.break_line("```python".len(), false).unwrap();
3209
assert_eq!(draft.text().matches(CODE_HEADER_MARK).count(), 1);
3210
assert!(draft.to_html().contains("language-python"));
3211
let docker = Draft::from_lines(&[DraftLine {
3212
kind: LineKind::Code(Some("dockerFile".into())),
3213
number: None,
3214
content: "FROM x".into(),
3215
marks: Vec::new(),
3216
}]);
3217
assert!(docker.to_html().starts_with("<pre class=\"language-dockerFile "));
3218
}
3219
3055
3220
#[test]
3056
3221
fn markdown_inside_code_stays_literal() {
3057
3222
let mut draft = typed_draft("```");
3058
let cursor = draft.break_line(3, false).unwrap();
3059
assert_eq!(cursor, 0);
3223
assert_eq!(
3224
(draft.text(), draft.lines()),
3225
("\u{FFF9}", &[LineKind::Code(None)][..])
3226
);
3060
3227
typed(&mut draft, "a **b**");
3061
assert_eq!(draft.text(), "a **b**");
3228
assert_eq!(draft.text(), "\u{FFF9}a **b**");
3062
3229
assert!(draft.marks().is_empty());
3063
3230
}
3064
3231
@@ -3142,7 +3309,7 @@ mod tests {
3142
3309
<blockquote>q1<br>q2</blockquote>\
3143
3310
<ul><li>a<ul><li>b</li></ul></li></ul>\
3144
3311
<ol><li>x</li><li>y</li></ol>\
3145
<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"
3312
<pre class=\"language-python skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"
3146
3313
);
3147
3314
}
3148
3315
@@ -3346,7 +3513,7 @@ mod tests {
3346
3513
#[test]
3347
3514
fn code_lines_hold_only_their_content() {
3348
3515
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");
3349
assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");
3516
assert_eq!(draft.text(), "\u{FFF9}let a = 1;\n\u{2003}b");
3350
3517
assert_eq!(
3351
3518
draft.to_html(),
3352
3519
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>"
@@ -3367,7 +3534,7 @@ mod tests {
3367
3534
3368
3535
#[test]
3369
3536
fn code_indentation_is_kept_on_paste_split_and_send() {
3370
let mut draft = typed_draft("```py");
3537
let mut draft = Draft::plain("```py");
3371
3538
let cursor = draft.break_line(draft.text().len(), false).unwrap();
3372
3539
let pasted = "def f():\n return 1";
3373
3540
let mut next = draft.text().to_owned();
@@ -3375,10 +3542,10 @@ mod tests {
3375
3542
draft.apply_edit(&next, cursor + pasted.len(), None);
3376
3543
assert_eq!(
3377
3544
draft.to_html(),
3378
"<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"
3545
"<pre class=\"language-python skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"
3379
3546
);
3380
3547
let mut split = Draft::from_markdown("```\n a b\n```");
3381
let after_a = " a".len();
3548
let after_a = "\u{FFF9} a".len();
3382
3549
split.break_line(after_a, false).unwrap();
3383
3550
assert_eq!(
3384
3551
split.to_html(),
@@ -12,6 +12,8 @@ pub const MAX_DEPTH: u8 = 2;12
pub const MAX_HEADING: u8 = 3;12
pub const MAX_HEADING: u8 = 3;13
pub const OBJECT_MARK: char = '\u{FFFC}';13
pub const OBJECT_MARK: char = '\u{FFFC}';14
pub const RULE_MARK: char = '\u{FFFA}';14
pub const RULE_MARK: char = '\u{FFFA}';15
/// The marker of a code block's first line: the composer shows the block's header there.16
pub const CODE_HEADER_MARK: char = '\u{FFF9}';15
pub const MAX_INDENT: u8 = 8;17
pub const MAX_INDENT: u8 = 8;16
pub const INDENT_PIXELS: u32 = 40;18
pub const INDENT_PIXELS: u32 = 40;17
pub const RULE_HTML: &str = "<hr>";19
pub const RULE_HTML: &str = "<hr>";@@ -783,6 +785,20 @@ impl Draft {783
return None;785
return None;784
}786
}785
let before = &self.text[content.start..cursor];787
let before = &self.text[content.start..cursor];788
// Teams opens the block on the third backtick; undo gives back the fence for ```lang + Enter.789
if self.lines[index] == LineKind::Text && before == FENCE && cursor == content.end {790
self.splice(content.clone(), "", &[]);791
let cursor = self.set_line_kind(index, LineKind::Code(None), None, content.start);792
// A block of the same language right below joins this one under its header.793
let cursor = self.repair(cursor);794
return Some((795
cursor,796
TypingStyle {797
at: cursor,798
..TypingStyle::default()799
},800
));801
}786
if self.lines[index] == LineKind::Text802
if self.lines[index] == LineKind::Text787
&& let Some((kind, number)) = line_shortcut(before)803
&& let Some((kind, number)) = line_shortcut(before)788
{804
{@@ -880,7 +896,8 @@ impl Draft {880
LineKind::Text => {896
LineKind::Text => {881
let language = fence_language(&self.text[content.clone()])?;897
let language = fence_language(&self.text[content.clone()])?;882
self.splice(content.clone(), "", &[]);898
self.splice(content.clone(), "", &[]);883
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))899
let cursor = self.set_line_kind(index, LineKind::Code(language), None, content.start);900
Some(self.repair(cursor))884
}901
}885
LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,902
LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,886
LineKind::Indent(_) if !shift => None,903
LineKind::Indent(_) if !shift => None,@@ -900,10 +917,17 @@ impl Draft {900
Some(cursor + 1)917
Some(cursor + 1)901
}918
}902
LineKind::Code(_) => {919
LineKind::Code(_) => {920
// The third Enter leaves: two empty lines end the block, one stays code.903
let last_of_block = self.lines.get(index + 1) != Some(&kind);921
let last_of_block = self.lines.get(index + 1) != Some(&kind);904
let block_continues_above = index > 0 && self.lines[index - 1] == kind;922
let empty_line_above = index >= 2905
if content.is_empty() && last_of_block && block_continues_above && !shift {923
&& self.lines[index - 1] == kind906
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));924
&& self.lines[index - 2] == kind925
&& self.content_range(index - 1).is_empty();926
if content.is_empty() && last_of_block && empty_line_above && !shift {927
let above = self.line_ranges()[index - 1].start;928
self.splice(above..content.start, "", &[]);929
let cursor = self.set_line_kind(index - 1, LineKind::Text, None, above);930
return Some(self.repair(cursor));907
}931
}908
self.splice(cursor..cursor, "\n", &[]);932
self.splice(cursor..cursor, "\n", &[]);909
Some(cursor + 1)933
Some(cursor + 1)@@ -985,10 +1009,9 @@ impl Draft {985
match &kind {1009
match &kind {986
LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None,1010
LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None,987
LineKind::Code(_) => {1011
LineKind::Code(_) => {988
let first_of_block = index == 0 || self.lines[index - 1] != kind;1012
(cursor <= content.start && self.first_of_block(index)).then(|| {989
(cursor == line.start && first_of_block).then(|| {1013
let cursor = self.set_line_kind(index, LineKind::Text, None, cursor);990
self.lines[index] = LineKind::Text;1014
self.repair(cursor)991
cursor992
})1015
})993
}1016
}994
LineKind::Table(_) => None,1017
LineKind::Table(_) => None,@@ -1153,6 +1176,36 @@ impl Draft {1153
self.repair(0);1176
self.repair(0);1154
}1177
}1155
1178
1179
/// The lines of the code block at `cursor`: the run of code lines with one language.1180
pub fn code_block_at(&self, cursor: usize) -> Option<Range<usize>> {1181
let index = self.line_at(cursor);1182
let kind = self.lines.get(index)?;1183
if !matches!(kind, LineKind::Code(_)) {1184
return None;1185
}1186
let start = self.lines[..index]1187
.iter()1188
.rposition(|other| other != kind)1189
.map_or(0, |before| before + 1);1190
let end = index1191
+ self.lines[index..]1192
.iter()1193
.take_while(|other| *other == kind)1194
.count();1195
Some(start..end)1196
}1197
1198
/// Only the header marks change: a block that now matches the next one merges with it.1199
pub fn set_code_language(&mut self, cursor: usize, language: Option<String>) {1200
if let Some(block) = self.code_block_at(cursor) {1201
self.journal = Journal::default();1202
for kind in &mut self.lines[block] {1203
*kind = LineKind::Code(language.clone());1204
}1205
self.repair(cursor);1206
}1207
}1208
1156
pub fn table(&self, index: usize) -> Option<&Table> {1209
pub fn table(&self, index: usize) -> Option<&Table> {1157
match self.lines.get(index)? {1210
match self.lines.get(index)? {1158
LineKind::Table(table) => Some(table),1211
LineKind::Table(table) => Some(table),@@ -1451,7 +1504,8 @@ impl Draft {1451
let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE);1504
let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE);1452
html.push_str(&format!(1505
html.push_str(&format!(1453
"<pre class=\"language-{} skipProofing\" spellcheck=\"false\"><code>",1506
"<pre class=\"language-{} skipProofing\" spellcheck=\"false\"><code>",1454
escape_html(&language.to_ascii_lowercase())1507
// Teams' ids are case-sensitive: `dockerFile`.1508
escape_html(language)1455
));1509
));1456
let code = run1510
let code = run1457
.iter()1511
.iter()@@ -1718,11 +1772,48 @@ impl Draft {1718
})1772
})1719
.unwrap_or(1),1773
.unwrap_or(1),1720
},1774
},1775
LineKind::Code(_) if self.first_of_block(index) => {1776
return CODE_HEADER_MARK.to_string();1777
}1721
_ => 1,1778
_ => 1,1722
};1779
};1723
marker_text(kind, number)1780
marker_text(kind, number)1724
}1781
}1725
1782
1783
fn first_of_block(&self, index: usize) -> bool {1784
index == 0 || self.lines[index - 1] != self.lines[index]1785
}1786
1787
/// Only the first line of a code block holds the header mark.1788
fn repair_code_headers(&mut self, mut cursor: usize) -> usize {1789
let stray: Vec<usize> = self1790
.text1791
.match_indices(CODE_HEADER_MARK)1792
.map(|(at, _)| at)1793
.filter(|at| {1794
let index = self.line_at(*at);1795
!matches!(self.lines[index], LineKind::Code(_))1796
|| !self.first_of_block(index)1797
|| self.line_ranges()[index].start != *at1798
})1799
.collect();1800
for at in stray.into_iter().rev() {1801
let mark = at..at + CODE_HEADER_MARK.len_utf8();1802
self.splice(mark.clone(), "", &[]);1803
if cursor > at {1804
cursor -= (cursor - at).min(mark.len());1805
}1806
}1807
for index in 0..self.lines.len() {1808
if matches!(self.lines[index], LineKind::Code(_)) {1809
let marker = self.marker_range(index);1810
let expected = self.expected_marker(index, None);1811
cursor = self.replace_marker(marker, &expected, cursor);1812
}1813
}1814
cursor1815
}1816
1726
fn set_line_kind(1817
fn set_line_kind(1727
&mut self,1818
&mut self,1728
index: usize,1819
index: usize,@@ -1798,6 +1889,7 @@ impl Draft {1798
/// List items whose marker was edited away become text; numbered items are renumbered.1889
/// List items whose marker was edited away become text; numbered items are renumbered.1799
fn repair(&mut self, cursor: usize) -> usize {1890
fn repair(&mut self, cursor: usize) -> usize {1800
let mut cursor = self.repair_objects(cursor);1891
let mut cursor = self.repair_objects(cursor);1892
cursor = self.repair_code_headers(cursor);1801
for index in 0..self.lines.len() {1893
for index in 0..self.lines.len() {1802
let kind = self.lines[index].clone();1894
let kind = self.lines[index].clone();1803
if !kind.is_list() {1895
if !kind.is_list() {@@ -1858,6 +1950,7 @@ fn marker_len(kind: &LineKind, line: &str) -> usize {1858
}1950
}1859
}1951
}1860
LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length),1952
LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length),1953
LineKind::Code(_) if line.starts_with(CODE_HEADER_MARK) => CODE_HEADER_MARK.len_utf8(),1861
_ => 0,1954
_ => 0,1862
}1955
}1863
}1956
}@@ -1892,7 +1985,14 @@ fn fence_language(line: &str) -> Option<Option<String>> {1892
let valid = info1985
let valid = info1893
.chars()1986
.chars()1894
.all(|character| character.is_alphanumeric() || "+#-_.".contains(character));1987
.all(|character| character.is_alphanumeric() || "+#-_.".contains(character));1895
valid.then(|| (!info.is_empty()).then(|| info.to_lowercase()))1988
valid.then(|| teams_language(info))1989
}1990
1991
/// The id Teams knows for a typed language, so ```py sends `language-python`; Plain Text is none.1992
fn teams_language(info: &str) -> Option<String> {1993
let id = crate::code_language(info)1994
.map_or_else(|| info.to_lowercase(), |language| language.id.to_owned());1995
(!info.is_empty() && id != crate::PLAIN_LANGUAGE).then_some(id)1896
}1996
}1897
1997
1898
fn valid_inner(inner: &str) -> bool {1998
fn valid_inner(inner: &str) -> bool {@@ -3037,28 +3137,95 @@ mod tests {3037
3137
3038
#[test]3138
#[test]3039
fn fence_and_enter_open_a_code_block_that_enter_continues() {3139
fn fence_and_enter_open_a_code_block_that_enter_continues() {3040
let mut draft = typed_draft("```rust");3140
let mut draft = Draft::plain("```rust");3041
let cursor = draft.break_line(draft.text().len(), false).unwrap();3141
let cursor = draft.break_line(draft.text().len(), false).unwrap();3042
assert_eq!((draft.text(), cursor), ("", 0));3142
assert_eq!((draft.text(), cursor), ("\u{FFF9}", 3));3043
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);3143
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);3044
typed(&mut draft, "fn x() {}");3144
typed(&mut draft, "fn x() {}");3045
let cursor = draft.break_line(draft.text().len(), false).unwrap();3145
let cursor = draft.break_line(draft.text().len(), false).unwrap();3046
assert_eq!(draft.lines().len(), 2);3146
assert_eq!(draft.lines().len(), 2);3047
assert_eq!(draft.break_line(cursor, false), Some(cursor));3147
let cursor = draft.break_line(cursor, false).unwrap();3148
assert_eq!(draft.lines().len(), 3, "one empty line stays code");3149
assert_eq!(draft.lines()[2], LineKind::Code(Some("rust".into())));3150
let end = draft.break_line(cursor, false).unwrap();3151
assert_eq!(3152
draft.lines().len(),3153
2,3154
"the third Enter drops both empty lines"3155
);3048
assert_eq!(draft.lines()[1], LineKind::Text);3156
assert_eq!(draft.lines()[1], LineKind::Text);3157
assert_eq!(end, draft.line_ranges()[1].start);3049
assert_eq!(3158
assert_eq!(3050
draft.to_html(),3159
draft.to_html(),3051
"<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"3160
"<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"3052
);3161
);3053
}3162
}3054
3163
3164
#[test]3165
fn a_fence_opens_a_code_block_only_alone_on_a_plain_line() {3166
assert_eq!(typed_draft("a ```").lines(), [LineKind::Text]);3167
assert_eq!(typed_draft("> ```").lines(), [LineKind::Quote]);3168
let mut draft = Draft::plain("x");3169
draft.apply_edit("```x", 3, None);3170
assert!(draft.convert_typed(3).is_none());3171
assert_eq!(draft.text(), "```x");3172
}3173
3174
#[test]3175
fn a_language_goes_to_the_whole_code_block_at_the_cursor_only() {3176
let mut draft = Draft::from_markdown("```\na\nb\n```\nx\n```\nc\n```");3177
draft.set_code_language(0, Some("go".into()));3178
assert_eq!(3179
draft.lines(),3180
[3181
LineKind::Code(Some("go".into())),3182
LineKind::Code(Some("go".into())),3183
LineKind::Text,3184
LineKind::Code(None),3185
]3186
);3187
assert_eq!(draft.code_block_at(draft.text().find('b').unwrap()), Some(0..2));3188
assert_eq!(draft.code_block_at(draft.text().len() - 1), Some(3..4));3189
draft.set_code_language(draft.text().find('x').unwrap(), Some("c".into()));3190
assert_eq!(draft.lines()[2], LineKind::Text);3191
assert!(draft.to_html().starts_with("<pre class=\"language-go "));3192
}3193
3194
#[test]3195
fn the_block_keeps_its_first_line_when_enter_leaves_it() {3196
let mut draft = typed_draft("```");3197
let cursor = draft.break_line(draft.text().len(), false).unwrap();3198
let cursor = draft.break_line(cursor, false).unwrap();3199
draft.break_line(cursor, false).unwrap();3200
assert_eq!(draft.lines(), [LineKind::Code(None), LineKind::Text]);3201
}3202
3203
#[test]3204
fn a_fence_above_a_block_of_its_language_joins_it_under_one_header() {3205
let mut draft = Draft::from_markdown("x\n```python\nb\n```");3206
let fenced = format!("```python{}", &draft.text()[1..]);3207
draft.apply_edit(&fenced, "```python".len(), None);3208
draft.break_line("```python".len(), false).unwrap();3209
assert_eq!(draft.text().matches(CODE_HEADER_MARK).count(), 1);3210
assert!(draft.to_html().contains("language-python"));3211
let docker = Draft::from_lines(&[DraftLine {3212
kind: LineKind::Code(Some("dockerFile".into())),3213
number: None,3214
content: "FROM x".into(),3215
marks: Vec::new(),3216
}]);3217
assert!(docker.to_html().starts_with("<pre class=\"language-dockerFile "));3218
}3219
3055
#[test]3220
#[test]3056
fn markdown_inside_code_stays_literal() {3221
fn markdown_inside_code_stays_literal() {3057
let mut draft = typed_draft("```");3222
let mut draft = typed_draft("```");3058
let cursor = draft.break_line(3, false).unwrap();3223
assert_eq!(3059
assert_eq!(cursor, 0);3224
(draft.text(), draft.lines()),3225
("\u{FFF9}", &[LineKind::Code(None)][..])3226
);3060
typed(&mut draft, "a **b**");3227
typed(&mut draft, "a **b**");3061
assert_eq!(draft.text(), "a **b**");3228
assert_eq!(draft.text(), "\u{FFF9}a **b**");3062
assert!(draft.marks().is_empty());3229
assert!(draft.marks().is_empty());3063
}3230
}3064
3231
@@ -3142,7 +3309,7 @@ mod tests {3142
<blockquote>q1<br>q2</blockquote>\3309
<blockquote>q1<br>q2</blockquote>\3143
<ul><li>a<ul><li>b</li></ul></li></ul>\3310
<ul><li>a<ul><li>b</li></ul></li></ul>\3144
<ol><li>x</li><li>y</li></ol>\3311
<ol><li>x</li><li>y</li></ol>\3145
<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"3312
<pre class=\"language-python skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"3146
);3313
);3147
}3314
}3148
3315
@@ -3346,7 +3513,7 @@ mod tests {3346
#[test]3513
#[test]3347
fn code_lines_hold_only_their_content() {3514
fn code_lines_hold_only_their_content() {3348
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");3515
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");3349
assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");3516
assert_eq!(draft.text(), "\u{FFF9}let a = 1;\n\u{2003}b");3350
assert_eq!(3517
assert_eq!(3351
draft.to_html(),3518
draft.to_html(),3352
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>"3519
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>"@@ -3367,7 +3534,7 @@ mod tests {3367
3534
3368
#[test]3535
#[test]3369
fn code_indentation_is_kept_on_paste_split_and_send() {3536
fn code_indentation_is_kept_on_paste_split_and_send() {3370
let mut draft = typed_draft("```py");3537
let mut draft = Draft::plain("```py");3371
let cursor = draft.break_line(draft.text().len(), false).unwrap();3538
let cursor = draft.break_line(draft.text().len(), false).unwrap();3372
let pasted = "def f():\n return 1";3539
let pasted = "def f():\n return 1";3373
let mut next = draft.text().to_owned();3540
let mut next = draft.text().to_owned();@@ -3375,10 +3542,10 @@ mod tests {3375
draft.apply_edit(&next, cursor + pasted.len(), None);3542
draft.apply_edit(&next, cursor + pasted.len(), None);3376
assert_eq!(3543
assert_eq!(3377
draft.to_html(),3544
draft.to_html(),3378
"<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"3545
"<pre class=\"language-python skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"3379
);3546
);3380
let mut split = Draft::from_markdown("```\n a b\n```");3547
let mut split = Draft::from_markdown("```\n a b\n```");3381
let after_a = " a".len();3548
let after_a = "\u{FFF9} a".len();3382
split.break_line(after_a, false).unwrap();3549
split.break_line(after_a, false).unwrap();3383
assert_eq!(3550
assert_eq!(3384
split.to_html(),3551
split.to_html(),@@ -22,6 +22,7 @@ mod chat_paging;
22
22
mod chat_send;
23
23
mod chat_settings_sync;
24
24
mod cloud_files;
25
mod code_languages;
25
26
mod copilot;
26
27
mod default_reactions;
27
28
mod download;
@@ -137,15 +138,16 @@ pub use chatsvc::{
137
138
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
138
139
parse_language_settings, target_patch,
139
140
};
141
pub use code_languages::{CODE_LANGUAGES, CodeLanguage, PLAIN_LANGUAGE, code_language};
140
142
pub use default_reactions::{
141
143
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,
142
144
store_account_default_reactions,
143
145
};
144
146
pub use download::LibraryFile;
145
147
pub use draft::{
146
Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH, MAX_INDENT, Mark,
147
MarkKind, OBJECT_MARK, RULE_MARK, SizeStep, TypingStyle, changed_span, has_markdown, link_url,
148
map_offset, reverse_edits,
148
CODE_HEADER_MARK, Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH,
149
MAX_INDENT, Mark, MarkKind, OBJECT_MARK, RULE_MARK, SizeStep, TypingStyle, changed_span,
150
has_markdown, link_url, map_offset, reverse_edits,
149
151
};
150
152
pub use emoticon_tags::{EmoticonTag, emoticon_tags};
151
153
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
@@ -188,7 +190,7 @@ pub use receipts::{ReceiptReader, ReceiptState};
188
190
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
189
191
pub use scheduled::NOTES_CHAT_ID;
190
192
pub use skin_tone::{skin_tone, store_account_skin_tone};
191
pub use spans::{FontSize, Span, html_to_spans};
193
pub use spans::{CODE_BLOCK_ITEMTYPE, FontSize, Span, html_to_spans};
192
194
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
193
195
pub use stored::{
194
196
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
@@ -22,6 +22,7 @@ mod chat_paging;22
mod chat_send;22
mod chat_send;23
mod chat_settings_sync;23
mod chat_settings_sync;24
mod cloud_files;24
mod cloud_files;25
mod code_languages;25
mod copilot;26
mod copilot;26
mod default_reactions;27
mod default_reactions;27
mod download;28
mod download;@@ -137,15 +138,16 @@ pub use chatsvc::{137
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,138
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,138
parse_language_settings, target_patch,139
parse_language_settings, target_patch,139
};140
};141
pub use code_languages::{CODE_LANGUAGES, CodeLanguage, PLAIN_LANGUAGE, code_language};140
pub use default_reactions::{142
pub use default_reactions::{141
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,143
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,142
store_account_default_reactions,144
store_account_default_reactions,143
};145
};144
pub use download::LibraryFile;146
pub use download::LibraryFile;145
pub use draft::{147
pub use draft::{146
Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH, MAX_INDENT, Mark,148
CODE_HEADER_MARK, Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH,147
MarkKind, OBJECT_MARK, RULE_MARK, SizeStep, TypingStyle, changed_span, has_markdown, link_url,149
MAX_INDENT, Mark, MarkKind, OBJECT_MARK, RULE_MARK, SizeStep, TypingStyle, changed_span,148
map_offset, reverse_edits,150
has_markdown, link_url, map_offset, reverse_edits,149
};151
};150
pub use emoticon_tags::{EmoticonTag, emoticon_tags};152
pub use emoticon_tags::{EmoticonTag, emoticon_tags};151
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};153
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};@@ -188,7 +190,7 @@ pub use receipts::{ReceiptReader, ReceiptState};188
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};190
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};189
pub use scheduled::NOTES_CHAT_ID;191
pub use scheduled::NOTES_CHAT_ID;190
pub use skin_tone::{skin_tone, store_account_skin_tone};192
pub use skin_tone::{skin_tone, store_account_skin_tone};191
pub use spans::{FontSize, Span, html_to_spans};193
pub use spans::{CODE_BLOCK_ITEMTYPE, FontSize, Span, html_to_spans};192
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};194
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};193
pub use stored::{195
pub use stored::{194
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,196
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,@@ -80,13 +80,14 @@ const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
80
80
const LANGUAGE_PREFIX: &str = "language-";
81
81
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
82
82
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
83
pub const CODE_BLOCK_ITEMTYPE: &str = "http://schema.skype.com/CodeBlockEditor";
83
84
const MAX_HEADING_LEVEL: u8 = 3;
84
85
const MARK_BACKGROUND: u32 = 0xffff00;
85
86
const MAX_CONSECUTIVE_BREAKS: usize = 2;
86
87
const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];
87
88
const INDENT_STEP_PIXELS: f32 = 40.;
88
89
const MAX_INDENT_LEVEL: u8 = 8;
89
const PLAIN_LANGUAGE: &str = "plaintext";
90
use crate::code_languages::PLAIN_LANGUAGE;
90
91
91
92
pub fn html_to_spans(html: &str) -> Vec<Span> {
92
93
let fragment = Html::parse_fragment(html);
@@ -115,6 +116,12 @@ fn convert_children(element: ElementRef<'_>) -> Vec<Span> {
115
116
let Some(child_element) = ElementRef::wrap(child) else {
116
117
continue;
117
118
};
119
// The empty paragraph Teams puts before a code block only links it to its editor.
120
if child_element.value().attr("itemtype") == Some(CODE_BLOCK_ITEMTYPE)
121
&& raw_text(child_element).trim().is_empty()
122
{
123
continue;
124
}
118
125
let is_block = BLOCK_ELEMENTS.contains(&child_element.value().name());
119
126
if (is_block || break_pending) && !spans.is_empty() {
120
127
spans.push(Span::LineBreak);
@@ -407,8 +414,9 @@ fn language_of(element: ElementRef<'_>) -> Option<String> {
407
414
element
408
415
.value()
409
416
.classes()
410
.find_map(|class| class.strip_prefix(LANGUAGE_PREFIX))
411
.filter(|language| !language.is_empty())
417
.filter_map(|class| class.strip_prefix(LANGUAGE_PREFIX))
418
// Teams marks a language it guessed with this second class.
419
.find(|language| !language.is_empty() && *language != "was-auto-selected")
412
420
.map(str::to_owned)
413
421
}
414
422
@@ -80,13 +80,14 @@ const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];80
const LANGUAGE_PREFIX: &str = "language-";80
const LANGUAGE_PREFIX: &str = "language-";81
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";81
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";82
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";82
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";83
pub const CODE_BLOCK_ITEMTYPE: &str = "http://schema.skype.com/CodeBlockEditor";83
const MAX_HEADING_LEVEL: u8 = 3;84
const MAX_HEADING_LEVEL: u8 = 3;84
const MARK_BACKGROUND: u32 = 0xffff00;85
const MARK_BACKGROUND: u32 = 0xffff00;85
const MAX_CONSECUTIVE_BREAKS: usize = 2;86
const MAX_CONSECUTIVE_BREAKS: usize = 2;86
const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];87
const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];87
const INDENT_STEP_PIXELS: f32 = 40.;88
const INDENT_STEP_PIXELS: f32 = 40.;88
const MAX_INDENT_LEVEL: u8 = 8;89
const MAX_INDENT_LEVEL: u8 = 8;89
const PLAIN_LANGUAGE: &str = "plaintext";90
use crate::code_languages::PLAIN_LANGUAGE;90
91
91
pub fn html_to_spans(html: &str) -> Vec<Span> {92
pub fn html_to_spans(html: &str) -> Vec<Span> {92
let fragment = Html::parse_fragment(html);93
let fragment = Html::parse_fragment(html);@@ -115,6 +116,12 @@ fn convert_children(element: ElementRef<'_>) -> Vec<Span> {115
let Some(child_element) = ElementRef::wrap(child) else {116
let Some(child_element) = ElementRef::wrap(child) else {116
continue;117
continue;117
};118
};119
// The empty paragraph Teams puts before a code block only links it to its editor.120
if child_element.value().attr("itemtype") == Some(CODE_BLOCK_ITEMTYPE)121
&& raw_text(child_element).trim().is_empty()122
{123
continue;124
}118
let is_block = BLOCK_ELEMENTS.contains(&child_element.value().name());125
let is_block = BLOCK_ELEMENTS.contains(&child_element.value().name());119
if (is_block || break_pending) && !spans.is_empty() {126
if (is_block || break_pending) && !spans.is_empty() {120
spans.push(Span::LineBreak);127
spans.push(Span::LineBreak);@@ -407,8 +414,9 @@ fn language_of(element: ElementRef<'_>) -> Option<String> {407
element414
element408
.value()415
.value()409
.classes()416
.classes()410
.find_map(|class| class.strip_prefix(LANGUAGE_PREFIX))417
.filter_map(|class| class.strip_prefix(LANGUAGE_PREFIX))411
.filter(|language| !language.is_empty())418
// Teams marks a language it guessed with this second class.419
.find(|language| !language.is_empty() && *language != "was-auto-selected")412
.map(str::to_owned)420
.map(str::to_owned)413
}421
}414
422
@@ -535,5 +535,5 @@ fn code_blocks_send_the_teams_pre_code_shape_and_read_back_line_breaks() {
535
535
);
536
536
let back = Draft::from_spans(&html_to_spans(&html));
537
537
assert_eq!(back.lines(), [LineKind::Code(None), LineKind::Code(None)]);
538
assert_eq!(back.text(), "a < b\n c");
538
assert_eq!(back.text(), "\u{FFF9}a < b\n c");
539
539
}
@@ -535,5 +535,5 @@ fn code_blocks_send_the_teams_pre_code_shape_and_read_back_line_breaks() {535
);535
);536
let back = Draft::from_spans(&html_to_spans(&html));536
let back = Draft::from_spans(&html_to_spans(&html));537
assert_eq!(back.lines(), [LineKind::Code(None), LineKind::Code(None)]);537
assert_eq!(back.lines(), [LineKind::Code(None), LineKind::Code(None)]);538
assert_eq!(back.text(), "a < b\n c");538
assert_eq!(back.text(), "\u{FFF9}a < b\n c");539
}539
}@@ -540,3 +540,32 @@ fn org_emoji_keep_their_image_and_name() {
540
540
vec![text(":crying_cat:")]
541
541
);
542
542
}
543
544
#[test]
545
fn the_teams_code_block_marker_adds_no_empty_line() {
546
let spans = html_to_spans(
547
"<p>before</p><p itemtype=\"http://schema.skype.com/CodeBlockEditor\" id=\"x_codeBlockEditor-1\"> </p><pre class=\"language-py\" itemid=\"codeBlockEditor-1\"><code>x</code></pre>",
548
);
549
assert_eq!(
550
spans,
551
[
552
Span::Text("before".into()),
553
Span::LineBreak,
554
Span::CodeBlock {
555
language: Some("py".into()),
556
code: "x".into()
557
}
558
]
559
);
560
}
561
562
#[test]
563
fn teams_auto_selected_code_keeps_its_language() {
564
let spans = html_to_spans(
565
"<pre class=\"language-python language-was-auto-selected\"><code><span class=\"hljs-keyword\">def</span> f</code></pre>",
566
);
567
assert!(
568
matches!(&spans[..], [Span::CodeBlock { language: Some(language), .. }] if language == "python"),
569
"{spans:?}"
570
);
571
}
@@ -540,3 +540,32 @@ fn org_emoji_keep_their_image_and_name() {540
vec![text(":crying_cat:")]540
vec![text(":crying_cat:")]541
);541
);542
}542
}543
544
#[test]545
fn the_teams_code_block_marker_adds_no_empty_line() {546
let spans = html_to_spans(547
"<p>before</p><p itemtype=\"http://schema.skype.com/CodeBlockEditor\" id=\"x_codeBlockEditor-1\"> </p><pre class=\"language-py\" itemid=\"codeBlockEditor-1\"><code>x</code></pre>",548
);549
assert_eq!(550
spans,551
[552
Span::Text("before".into()),553
Span::LineBreak,554
Span::CodeBlock {555
language: Some("py".into()),556
code: "x".into()557
}558
]559
);560
}561
562
#[test]563
fn teams_auto_selected_code_keeps_its_language() {564
let spans = html_to_spans(565
"<pre class=\"language-python language-was-auto-selected\"><code><span class=\"hljs-keyword\">def</span> f</code></pre>",566
);567
assert!(568
matches!(&spans[..], [Span::CodeBlock { language: Some(language), .. }] if language == "python"),569
"{spans:?}"570
);571
}@@ -34,6 +34,8 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in
34
34
| `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |
35
35
| `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |
36
36
| `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |
37
| `src/input/base/inline_tokens.rs`, `src/input/editor/display_map/text_wrapper.rs`, `src/input/base/element.rs`, `src/input/base/token_presentation.rs` | `InlineToken::header()` / `is_header()` (a block token), `InlineMetric.opens_row`; a header at a line end gets an empty row after it; a header is placed without the line indent and is offered the width up to `RIGHT_MARGIN` | a code block's header row in the composer, with the caret on the row below it even when the line has no text yet |
38
| `src/input/base/state.rs`, `src/input/base/element.rs` | `set_line_labels(Vec<(offset, SharedString)>, color)`; `paint_line_labels()` paints each label right-aligned before its offset, on the row that shows it | code line numbers in the line indent, without characters in the text |
37
39
| `src/tooltip.rs` | `TooltipRequest::while_alive(Weak<()>)`; the overlay drops content whose trigger token is gone, checked on render and on the next frame | the trigger's element state is dropped only after a frame without it, so the check runs one frame later |
38
40
39
41
## Limits
@@ -34,6 +34,8 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in34
| `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |34
| `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |35
| `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |35
| `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |36
| `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |36
| `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |37
| `src/input/base/inline_tokens.rs`, `src/input/editor/display_map/text_wrapper.rs`, `src/input/base/element.rs`, `src/input/base/token_presentation.rs` | `InlineToken::header()` / `is_header()` (a block token), `InlineMetric.opens_row`; a header at a line end gets an empty row after it; a header is placed without the line indent and is offered the width up to `RIGHT_MARGIN` | a code block's header row in the composer, with the caret on the row below it even when the line has no text yet |38
| `src/input/base/state.rs`, `src/input/base/element.rs` | `set_line_labels(Vec<(offset, SharedString)>, color)`; `paint_line_labels()` paints each label right-aligned before its offset, on the row that shows it | code line numbers in the line indent, without characters in the text |37
| `src/tooltip.rs` | `TooltipRequest::while_alive(Weak<()>)`; the overlay drops content whose trigger token is gone, checked on render and on the next frame | the trigger's element state is dropped only after a frame without it, so the check runs one frame later |39
| `src/tooltip.rs` | `TooltipRequest::while_alive(Weak<()>)`; the overlay drops content whose trigger token is gone, checked on render and on the next frame | the trigger's element state is dropped only after a frame without it, so the check runs one frame later |38
40
39
## Limits41
## Limits@@ -1863,6 +1863,7 @@ impl<M: InputModeKind> TextElement<M> {
1863
1863
range: span.range(),
1864
1864
width: token_size.width,
1865
1865
height: span.token().is_block().then_some(token_size.height),
1866
opens_row: span.token().is_header(),
1866
1867
})
1867
1868
})
1868
1869
.collect();
@@ -2102,11 +2103,16 @@ impl<M: InputModeKind> TextElement<M> {
2102
2103
{
2103
2104
let baseline_offset =
2104
2105
layout.lines[ix].inline_offset_at(position.y, layout.line_height);
2106
let header_shift = if span.token().is_header() {
2107
state.display_map.line_indent(start)
2108
} else {
2109
px(0.)
2110
};
2105
2111
placements.push((
2106
2112
state.token_context(span, layout.line_height, width),
2107
2113
bounds.origin
2108
2114
+ position
2109
+ point(layout.line_number_width, y + baseline_offset),
2115
+ point(layout.line_number_width - header_shift, y + baseline_offset),
2110
2116
));
2111
2117
}
2112
2118
}
@@ -2144,6 +2150,60 @@ impl<M: InputModeKind> TextElement<M> {
2144
2150
out
2145
2151
}
2146
2152
2153
fn paint_line_labels(
2154
&self,
2155
line: &LineLayout,
2156
row: usize,
2157
origin: Point<Pixels>,
2158
layout: &LastLayout,
2159
window: &mut Window,
2160
cx: &mut App,
2161
) {
2162
const GAP: f32 = 8.;
2163
let state = self.state.read(cx);
2164
if state.line_labels.is_empty() {
2165
return;
2166
}
2167
let start = state.text.line_start_offset(row);
2168
let end = state.text.line_end_offset(row);
2169
let first = state
2170
.line_labels
2171
.partition_point(|(offset, _)| *offset < start);
2172
let style = window.text_style();
2173
let font_size = style.font_size.to_pixels(window.rem_size());
2174
let labels: Vec<_> = state.line_labels[first..]
2175
.iter()
2176
.take_while(|(offset, _)| *offset <= end)
2177
.cloned()
2178
.collect();
2179
let color = state.line_label_color;
2180
for (offset, label) in labels {
2181
let Some(position) = line.position_for_index(offset - start, layout, false) else {
2182
continue;
2183
};
2184
let run = TextRun {
2185
len: label.len(),
2186
font: style.font(),
2187
color,
2188
background_color: None,
2189
underline: None,
2190
strikethrough: None,
2191
};
2192
let shaped = window
2193
.text_system()
2194
.shape_line(label, font_size, &[run], None);
2195
let x = position.x - px(GAP) - shaped.width;
2196
_ = shaped.paint(
2197
origin + point(x, position.y),
2198
layout.line_height,
2199
TextAlign::Left,
2200
None,
2201
window,
2202
cx,
2203
);
2204
}
2205
}
2206
2147
2207
#[allow(clippy::too_many_arguments)]
2148
2208
fn layout_lines(
2149
2209
state: &InputBaseState<M>,
@@ -3409,6 +3469,7 @@ impl<M: InputModeKind> Element for TextElement<M> {
3409
3469
window,
3410
3470
cx,
3411
3471
);
3472
self.paint_line_labels(line, row, p, &prepaint.last_layout, window, cx);
3412
3473
offset_y += line.size(line_height).height;
3413
3474
3414
3475
if Some(row) == prepaint.current_row {
@@ -1863,6 +1863,7 @@ impl<M: InputModeKind> TextElement<M> {1863
range: span.range(),1863
range: span.range(),1864
width: token_size.width,1864
width: token_size.width,1865
height: span.token().is_block().then_some(token_size.height),1865
height: span.token().is_block().then_some(token_size.height),1866
opens_row: span.token().is_header(),1866
})1867
})1867
})1868
})1868
.collect();1869
.collect();@@ -2102,11 +2103,16 @@ impl<M: InputModeKind> TextElement<M> {2102
{2103
{2103
let baseline_offset =2104
let baseline_offset =2104
layout.lines[ix].inline_offset_at(position.y, layout.line_height);2105
layout.lines[ix].inline_offset_at(position.y, layout.line_height);2106
let header_shift = if span.token().is_header() {2107
state.display_map.line_indent(start)2108
} else {2109
px(0.)2110
};2105
placements.push((2111
placements.push((2106
state.token_context(span, layout.line_height, width),2112
state.token_context(span, layout.line_height, width),2107
bounds.origin2113
bounds.origin2108
+ position2114
+ position2109
+ point(layout.line_number_width, y + baseline_offset),2115
+ point(layout.line_number_width - header_shift, y + baseline_offset),2110
));2116
));2111
}2117
}2112
}2118
}@@ -2144,6 +2150,60 @@ impl<M: InputModeKind> TextElement<M> {2144
out2150
out2145
}2151
}2146
2152
2153
fn paint_line_labels(2154
&self,2155
line: &LineLayout,2156
row: usize,2157
origin: Point<Pixels>,2158
layout: &LastLayout,2159
window: &mut Window,2160
cx: &mut App,2161
) {2162
const GAP: f32 = 8.;2163
let state = self.state.read(cx);2164
if state.line_labels.is_empty() {2165
return;2166
}2167
let start = state.text.line_start_offset(row);2168
let end = state.text.line_end_offset(row);2169
let first = state2170
.line_labels2171
.partition_point(|(offset, _)| *offset < start);2172
let style = window.text_style();2173
let font_size = style.font_size.to_pixels(window.rem_size());2174
let labels: Vec<_> = state.line_labels[first..]2175
.iter()2176
.take_while(|(offset, _)| *offset <= end)2177
.cloned()2178
.collect();2179
let color = state.line_label_color;2180
for (offset, label) in labels {2181
let Some(position) = line.position_for_index(offset - start, layout, false) else {2182
continue;2183
};2184
let run = TextRun {2185
len: label.len(),2186
font: style.font(),2187
color,2188
background_color: None,2189
underline: None,2190
strikethrough: None,2191
};2192
let shaped = window2193
.text_system()2194
.shape_line(label, font_size, &[run], None);2195
let x = position.x - px(GAP) - shaped.width;2196
_ = shaped.paint(2197
origin + point(x, position.y),2198
layout.line_height,2199
TextAlign::Left,2200
None,2201
window,2202
cx,2203
);2204
}2205
}2206
2147
#[allow(clippy::too_many_arguments)]2207
#[allow(clippy::too_many_arguments)]2148
fn layout_lines(2208
fn layout_lines(2149
state: &InputBaseState<M>,2209
state: &InputBaseState<M>,@@ -3409,6 +3469,7 @@ impl<M: InputModeKind> Element for TextElement<M> {3409
window,3469
window,3410
cx,3470
cx,3411
);3471
);3472
self.paint_line_labels(line, row, p, &prepaint.last_layout, window, cx);3412
offset_y += line.size(line_height).height;3473
offset_y += line.size(line_height).height;3413
3474
3414
if Some(row) == prepaint.current_row {3475
if Some(row) == prepaint.current_row {@@ -14,6 +14,7 @@ pub struct InlineToken {
14
14
text: SharedString,
15
15
label: SharedString,
16
16
block: bool,
17
header: bool,
17
18
}
18
19
19
20
impl InlineToken {
@@ -24,6 +25,7 @@ impl InlineToken {
24
25
label: text.clone(),
25
26
text,
26
27
block: false,
28
header: false,
27
29
}
28
30
}
29
31
pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {
@@ -38,6 +40,16 @@ impl InlineToken {
38
40
pub fn is_block(&self) -> bool {
39
41
self.block
40
42
}
43
/// A block token that heads its line: it spans the row without the line indent, and
44
/// the rest of the line starts on the next row, also when it is empty.
45
pub fn header(mut self) -> Self {
46
self.block = true;
47
self.header = true;
48
self
49
}
50
pub fn is_header(&self) -> bool {
51
self.header
52
}
41
53
pub fn id(&self) -> &SharedString {
42
54
&self.id
43
55
}
@@ -14,6 +14,7 @@ pub struct InlineToken {14
text: SharedString,14
text: SharedString,15
label: SharedString,15
label: SharedString,16
block: bool,16
block: bool,17
header: bool,17
}18
}18
19
19
impl InlineToken {20
impl InlineToken {@@ -24,6 +25,7 @@ impl InlineToken {24
label: text.clone(),25
label: text.clone(),25
text,26
text,26
block: false,27
block: false,28
header: false,27
}29
}28
}30
}29
pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {31
pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {@@ -38,6 +40,16 @@ impl InlineToken {38
pub fn is_block(&self) -> bool {40
pub fn is_block(&self) -> bool {39
self.block41
self.block40
}42
}43
/// A block token that heads its line: it spans the row without the line indent, and44
/// the rest of the line starts on the next row, also when it is empty.45
pub fn header(mut self) -> Self {46
self.block = true;47
self.header = true;48
self49
}50
pub fn is_header(&self) -> bool {51
self.header52
}41
pub fn id(&self) -> &SharedString {53
pub fn id(&self) -> &SharedString {42
&self.id54
&self.id43
}55
}@@ -365,6 +365,9 @@ pub struct InputBaseState<M: InputModeKind> {
365
365
/// Real per-frame bounds of the placed token elements, keyed by token
366
366
/// start offset; used for hover payloads and stale-hover reconciliation.
367
367
pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,
368
/// Text painted right-aligned in the indent before a byte offset, e.g. line numbers.
369
pub(super) line_labels: Vec<(usize, SharedString)>,
370
pub(super) line_label_color: gpui::Hsla,
368
371
/// The currently hovered token: its entered span, last measured bounds,
369
372
/// and UTF-16 range as of entry. Retained so hover exit can still be
370
373
/// delivered when the token is removed, replaced, scrolled out, or
@@ -733,6 +736,8 @@ impl<M: InputModeKind> InputBaseState<M> {
733
736
document_revision: 0,
734
737
token_presentation: Default::default(),
735
738
token_bounds: Default::default(),
739
line_labels: Vec::new(),
740
line_label_color: gpui::Hsla::default(),
736
741
hovered_token: None,
737
742
pending_token_hover_exits: Vec::new(),
738
743
token_layout_cache: None,
@@ -11206,6 +11211,23 @@ impl<M: crate::input::MultiLineMode> InputBaseState<M> {
11206
11211
cx.notify();
11207
11212
}
11208
11213
11214
/// Each label is painted right-aligned before its byte offset, in `color`, on the row
11215
/// that shows the offset; meant for the line indent. Set them again on change.
11216
pub fn set_line_labels(
11217
&mut self,
11218
mut labels: Vec<(usize, SharedString)>,
11219
color: gpui::Hsla,
11220
cx: &mut Context<Self>,
11221
) {
11222
labels.retain(|(offset, _)| *offset <= self.text.len());
11223
labels.sort_by_key(|(offset, _)| *offset);
11224
if labels != self.line_labels || color != self.line_label_color {
11225
self.line_labels = labels;
11226
self.line_label_color = color;
11227
cx.notify();
11228
}
11229
}
11230
11209
11231
/// Every row of the line starting at each byte offset starts `indent` further right,
11210
11232
/// and wraps that much earlier. Combines with a hanging indent on the same line.
11211
11233
/// Entries for offsets that are not line starts are ignored; set them again on change.
@@ -365,6 +365,9 @@ pub struct InputBaseState<M: InputModeKind> {365
/// Real per-frame bounds of the placed token elements, keyed by token365
/// Real per-frame bounds of the placed token elements, keyed by token366
/// start offset; used for hover payloads and stale-hover reconciliation.366
/// start offset; used for hover payloads and stale-hover reconciliation.367
pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,367
pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,368
/// Text painted right-aligned in the indent before a byte offset, e.g. line numbers.369
pub(super) line_labels: Vec<(usize, SharedString)>,370
pub(super) line_label_color: gpui::Hsla,368
/// The currently hovered token: its entered span, last measured bounds,371
/// The currently hovered token: its entered span, last measured bounds,369
/// and UTF-16 range as of entry. Retained so hover exit can still be372
/// and UTF-16 range as of entry. Retained so hover exit can still be370
/// delivered when the token is removed, replaced, scrolled out, or373
/// delivered when the token is removed, replaced, scrolled out, or@@ -733,6 +736,8 @@ impl<M: InputModeKind> InputBaseState<M> {733
document_revision: 0,736
document_revision: 0,734
token_presentation: Default::default(),737
token_presentation: Default::default(),735
token_bounds: Default::default(),738
token_bounds: Default::default(),739
line_labels: Vec::new(),740
line_label_color: gpui::Hsla::default(),736
hovered_token: None,741
hovered_token: None,737
pending_token_hover_exits: Vec::new(),742
pending_token_hover_exits: Vec::new(),738
token_layout_cache: None,743
token_layout_cache: None,@@ -11206,6 +11211,23 @@ impl<M: crate::input::MultiLineMode> InputBaseState<M> {11206
cx.notify();11211
cx.notify();11207
}11212
}11208
11213
11214
/// Each label is painted right-aligned before its byte offset, in `color`, on the row11215
/// that shows the offset; meant for the line indent. Set them again on change.11216
pub fn set_line_labels(11217
&mut self,11218
mut labels: Vec<(usize, SharedString)>,11219
color: gpui::Hsla,11220
cx: &mut Context<Self>,11221
) {11222
labels.retain(|(offset, _)| *offset <= self.text.len());11223
labels.sort_by_key(|(offset, _)| *offset);11224
if labels != self.line_labels || color != self.line_label_color {11225
self.line_labels = labels;11226
self.line_label_color = color;11227
cx.notify();11228
}11229
}11230
11209
/// Every row of the line starting at each byte offset starts `indent` further right,11231
/// Every row of the line starting at each byte offset starts `indent` further right,11210
/// and wraps that much earlier. Combines with a hanging indent on the same line.11232
/// and wraps that much earlier. Combines with a hanging indent on the same line.11211
/// Entries for offsets that are not line starts are ignored; set them again on change.11233
/// Entries for offsets that are not line starts are ignored; set them again on change.@@ -235,7 +235,12 @@ impl<M: InputModeKind> InputBaseState<M> {
235
235
disabled: self.disabled,
236
236
readonly: self.readonly,
237
237
line_height,
238
available_width: width,
238
// A header spans its row up to where block decorations end.
239
available_width: if span.token().is_header() {
240
width + super::element::RIGHT_MARGIN
241
} else {
242
width
243
},
239
244
}
240
245
}
241
246
/// The token starting at `start`, paired with the listener that opens it.
@@ -235,7 +235,12 @@ impl<M: InputModeKind> InputBaseState<M> {235
disabled: self.disabled,235
disabled: self.disabled,236
readonly: self.readonly,236
readonly: self.readonly,237
line_height,237
line_height,238
available_width: width,238
// A header spans its row up to where block decorations end.239
available_width: if span.token().is_header() {240
width + super::element::RIGHT_MARGIN241
} else {242
width243
},239
}244
}240
}245
}241
/// The token starting at `start`, paired with the listener that opens it.246
/// The token starting at `start`, paired with the listener that opens it.@@ -205,6 +205,8 @@ pub(crate) struct InlineMetric {
205
205
pub(crate) range: Range<usize>,
206
206
pub(crate) width: Pixels,
207
207
pub(crate) height: Option<Pixels>,
208
/// A header token: what follows it on its line starts a row, even when nothing does.
209
pub(crate) opens_row: bool,
208
210
}
209
211
210
212
fn block_rows_of(
@@ -737,7 +739,10 @@ impl TextWrapper {
737
739
let wrap_width =
738
740
(wrap_width - line_indent_at(&line_indents, line_start)).max(px(1.));
739
741
let line_indented = line_indent_at(&line_indents, line_start) > px(0.);
740
measured_wrap_boundaries(
742
let header_ends_line = tokens
743
.iter()
744
.any(|token| token.opens_row && token.range.end == line_str.len());
745
let mut boundaries = measured_wrap_boundaries(
741
746
line_str,
742
747
wrap_width,
743
748
wrapping_indent,
@@ -756,7 +761,14 @@ impl TextWrapper {
756
761
}
757
762
width + shape(offset..range.end)
758
763
},
759
)
764
);
765
if header_ends_line && boundaries.last().is_none_or(|last| last.ix < line_str.len()) {
766
boundaries.push(gpui::Boundary {
767
ix: line_str.len(),
768
next_indent: 0,
769
});
770
}
771
boundaries
760
772
},
761
773
&mut |line_start, rows| {
762
774
if !has_scaled {
@@ -1014,10 +1026,8 @@ impl TextWrapper {
1014
1026
}
1015
1027
}
1016
1028
1017
// Reset of the line
1018
if prev_boundary_ix < line.len() || prev_boundary_ix == 0 {
1019
wrapped_lines.push(prev_boundary_ix..line.len());
1020
}
1029
// Reset of the line; a boundary at the end (after a header token) opens an empty row.
1030
wrapped_lines.push(prev_boundary_ix..line.len());
1021
1031
1022
1032
let mut blocks =
1023
1033
block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);
@@ -1736,6 +1746,7 @@ mod tests {
1736
1746
range: token.clone(),
1737
1747
width: px(32.),
1738
1748
height: None,
1749
opens_row: false,
1739
1750
}]),
1740
1751
cx,
1741
1752
);
@@ -205,6 +205,8 @@ pub(crate) struct InlineMetric {205
pub(crate) range: Range<usize>,205
pub(crate) range: Range<usize>,206
pub(crate) width: Pixels,206
pub(crate) width: Pixels,207
pub(crate) height: Option<Pixels>,207
pub(crate) height: Option<Pixels>,208
/// A header token: what follows it on its line starts a row, even when nothing does.209
pub(crate) opens_row: bool,208
}210
}209
211
210
fn block_rows_of(212
fn block_rows_of(@@ -737,7 +739,10 @@ impl TextWrapper {737
let wrap_width =739
let wrap_width =738
(wrap_width - line_indent_at(&line_indents, line_start)).max(px(1.));740
(wrap_width - line_indent_at(&line_indents, line_start)).max(px(1.));739
let line_indented = line_indent_at(&line_indents, line_start) > px(0.);741
let line_indented = line_indent_at(&line_indents, line_start) > px(0.);740
measured_wrap_boundaries(742
let header_ends_line = tokens743
.iter()744
.any(|token| token.opens_row && token.range.end == line_str.len());745
let mut boundaries = measured_wrap_boundaries(741
line_str,746
line_str,742
wrap_width,747
wrap_width,743
wrapping_indent,748
wrapping_indent,@@ -756,7 +761,14 @@ impl TextWrapper {756
}761
}757
width + shape(offset..range.end)762
width + shape(offset..range.end)758
},763
},759
)764
);765
if header_ends_line && boundaries.last().is_none_or(|last| last.ix < line_str.len()) {766
boundaries.push(gpui::Boundary {767
ix: line_str.len(),768
next_indent: 0,769
});770
}771
boundaries760
},772
},761
&mut |line_start, rows| {773
&mut |line_start, rows| {762
if !has_scaled {774
if !has_scaled {@@ -1014,10 +1026,8 @@ impl TextWrapper {1014
}1026
}1015
}1027
}1016
1028
1017
// Reset of the line1029
// Reset of the line; a boundary at the end (after a header token) opens an empty row.1018
if prev_boundary_ix < line.len() || prev_boundary_ix == 0 {1030
wrapped_lines.push(prev_boundary_ix..line.len());1019
wrapped_lines.push(prev_boundary_ix..line.len());1020
}1021
1031
1022
let mut blocks =1032
let mut blocks =1023
block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);1033
block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);@@ -1736,6 +1746,7 @@ mod tests {1736
range: token.clone(),1746
range: token.clone(),1737
width: px(32.),1747
width: px(32.),1738
height: None,1748
height: None,1749
opens_row: false,1739
}]),1750
}]),1740
cx,1751
cx,1741
);1752
);