Debian Codegraph @

helix-core/src/comment.rs

raw symbols SCIP
1 //! This module contains the functionality toggle comments on lines over the selection
2 //! using the comment character defined in the user's `languages.toml`
3
4 use smallvec::SmallVec;
5
6 use crate::{
7 syntax::config::BlockCommentToken, Change, Range, Rope, RopeSlice, Selection, Tendril,
8 Transaction,
9 };
10 use helix_stdx::rope::RopeSliceExt;
11 use std::borrow::Cow;
12
13 pub const DEFAULT_COMMENT_TOKEN: &str = "#";
14
15 /// Returns the longest matching comment token of the given line (if it exists).
16 pub fn get_comment_token<'a, S: AsRef<str>>(
17 text: RopeSlice,
18 tokens: &'a [S],
19 line_num: usize,
20 ) -> Option<&'a str> {
21 let line = text.line(line_num);
22 let start = line.first_non_whitespace_char()?;
23
24 tokens
25 .iter()
26 .map(AsRef::as_ref)
27 .filter(|token| line.slice(start..).starts_with(token))
28 .max_by_key(|token| token.len())
29 }
30
31 /// Given text, a comment token, and a set of line indices, returns the following:
32 /// - Whether the given lines should be considered commented
33 /// - If any of the lines are uncommented, all lines are considered as such.
34 /// - The lines to change for toggling comments
35 /// - This is all provided lines excluding blanks lines.
36 /// - The column of the comment tokens
37 /// - Column of existing tokens, if the lines are commented; column to place tokens at otherwise.
38 /// - The margin to the right of the comment tokens
39 /// - Defaults to `1`. If any existing comment token is not followed by a space, changes to `0`.
40 fn find_line_comment(
41 token: &str,
42 text: RopeSlice,
43 lines: impl IntoIterator<Item = usize>,
44 ) -> (bool, Vec<usize>, usize, usize) {
45 let mut commented = true;
46 let mut to_change = Vec::new();
47 let mut min = usize::MAX; // minimum col for first_non_whitespace_char
48 let mut margin = 1;
49 let token_len = token.chars().count();
50
51 for line in lines {
52 let line_slice = text.line(line);
53 if let Some(pos) = line_slice.first_non_whitespace_char() {
54 let len = line_slice.len_chars();
55
56 min = std::cmp::min(min, pos);
57
58 // line can be shorter than pos + token len
59 let fragment = Cow::from(line_slice.slice(pos..std::cmp::min(pos + token.len(), len)));
60
61 // as soon as one of the non-blank lines doesn't have a comment, the whole block is
62 // considered uncommented.
63 if fragment != token {
64 commented = false;
65 }
66
67 // determine margin of 0 or 1 for uncommenting; if any comment token is not followed by a space,
68 // a margin of 0 is used for all lines.
69 if !matches!(line_slice.get_char(pos + token_len), Some(c) if c == ' ') {
70 margin = 0;
71 }
72
73 // blank lines don't get pushed.
74 to_change.push(line);
75 }
76 }
77
78 (commented, to_change, min, margin)
79 }
80
81 #[must_use]
82 pub fn toggle_line_comments(doc: &Rope, selection: &Selection, token: Option<&str>) -> Transaction {
83 let text = doc.slice(..);
84
85 let token = token.unwrap_or(DEFAULT_COMMENT_TOKEN);
86 let comment = Tendril::from(format!("{} ", token));
87
88 let mut lines: Vec<usize> = Vec::with_capacity(selection.len());
89
90 let mut min_next_line = 0;
91 for selection in selection {
92 let (start, end) = selection.line_range(text);
93 let start = start.clamp(min_next_line, text.len_lines());
94 let end = (end + 1).min(text.len_lines());
95
96 lines.extend(start..end);
97 min_next_line = end;
98 }
99
100 let (commented, to_change, min, margin) = find_line_comment(token, text, lines);
101
102 let mut changes: Vec<Change> = Vec::with_capacity(to_change.len());
103
104 for line in to_change {
105 let pos = text.line_to_char(line) + min;
106
107 if !commented {
108 // comment line
109 changes.push((pos, pos, Some(comment.clone())));
110 } else {
111 // uncomment line
112 changes.push((pos, pos + token.len() + margin, None));
113 }
114 }
115
116 Transaction::change(doc, changes.into_iter())
117 }
118
119 #[derive(Debug, PartialEq, Eq)]
120 pub enum CommentChange {
121 Commented {
122 range: Range,
123 start_pos: usize,
124 end_pos: usize,
125 start_margin: bool,
126 end_margin: bool,
127 start_token: String,
128 end_token: String,
129 },
130 Uncommented {
131 range: Range,
132 start_pos: usize,
133 end_pos: usize,
134 start_token: String,
135 end_token: String,
136 },
137 Whitespace {
138 range: Range,
139 },
140 }
141
142 pub fn find_block_comments(
143 tokens: &[BlockCommentToken],
144 text: RopeSlice,
145 selection: &Selection,
146 ) -> (bool, Vec<CommentChange>) {
147 let mut commented = true;
148 let mut only_whitespace = true;
149 let mut comment_changes = Vec::with_capacity(selection.len());
150 let default_tokens = tokens.first().cloned().unwrap_or_default();
151 let mut start_token = default_tokens.start.clone();
152 let mut end_token = default_tokens.end.clone();
153
154 let mut tokens = tokens.to_vec();
155 // sort the tokens by length, so longer tokens will match first
156 tokens.sort_by(|a, b| {
157 if a.start.len() == b.start.len() {
158 b.end.len().cmp(&a.end.len())
159 } else {
160 b.start.len().cmp(&a.start.len())
161 }
162 });
163 for range in selection {
164 let selection_slice = range.slice(text);
165 if let (Some(start_pos), Some(end_pos)) = (
166 selection_slice.first_non_whitespace_char(),
167 selection_slice.last_non_whitespace_char(),
168 ) {
169 let mut line_commented = false;
170 let mut after_start = 0;
171 let mut before_end = 0;
172 let len = (end_pos + 1) - start_pos;
173
174 for BlockCommentToken { start, end } in &tokens {
175 let start_len = start.chars().count();
176 let end_len = end.chars().count();
177 after_start = start_pos + start_len;
178 before_end = end_pos.saturating_sub(end_len);
179
180 if len >= start_len + end_len {
181 let start_fragment = selection_slice.slice(start_pos..after_start);
182 let end_fragment = selection_slice.slice(before_end + 1..end_pos + 1);
183
184 // block commented with these tokens
185 if start_fragment == start.as_str() && end_fragment == end.as_str() {
186 start_token = start.to_string();
187 end_token = end.to_string();
188 line_commented = true;
189 break;
190 }
191 }
192 }
193
194 if !line_commented {
195 comment_changes.push(CommentChange::Uncommented {
196 range: *range,
197 start_pos,
198 end_pos,
199 start_token: default_tokens.start.clone(),
200 end_token: default_tokens.end.clone(),
201 });
202 commented = false;
203 } else {
204 comment_changes.push(CommentChange::Commented {
205 range: *range,
206 start_pos,
207 end_pos,
208 start_margin: selection_slice.get_char(after_start) == Some(' '),
209 end_margin: after_start != before_end
210 && (selection_slice.get_char(before_end) == Some(' ')),
211 start_token: start_token.to_string(),
212 end_token: end_token.to_string(),
213 });
214 }
215 only_whitespace = false;
216 } else {
217 comment_changes.push(CommentChange::Whitespace { range: *range });
218 }
219 }
220 if only_whitespace {
221 commented = false;
222 }
223 (commented, comment_changes)
224 }
225
226 #[must_use]
227 pub fn create_block_comment_transaction(
228 doc: &Rope,
229 selection: &Selection,
230 commented: bool,
231 comment_changes: Vec<CommentChange>,
232 ) -> (Transaction, SmallVec<[Range; 1]>) {
233 let mut changes: Vec<Change> = Vec::with_capacity(selection.len() * 2);
234 let mut ranges: SmallVec<[Range; 1]> = SmallVec::with_capacity(selection.len());
235 let mut offs = 0;
236 for change in comment_changes {
237 if commented {
238 if let CommentChange::Commented {
239 range,
240 start_pos,
241 end_pos,
242 start_token,
243 end_token,
244 start_margin,
245 end_margin,
246 } = change
247 {
248 let from = range.from();
249 changes.push((
250 from + start_pos,
251 from + start_pos + start_token.len() + start_margin as usize,
252 None,
253 ));
254 changes.push((
255 from + end_pos - end_token.len() - end_margin as usize + 1,
256 from + end_pos + 1,
257 None,
258 ));
259 }
260 } else {
261 // uncommented so manually map ranges through changes
262 match change {
263 CommentChange::Uncommented {
264 range,
265 start_pos,
266 end_pos,
267 start_token,
268 end_token,
269 } => {
270 let from = range.from();
271 changes.push((
272 from + start_pos,
273 from + start_pos,
274 Some(Tendril::from(format!("{} ", start_token))),
275 ));
276 changes.push((
277 from + end_pos + 1,
278 from + end_pos + 1,
279 Some(Tendril::from(format!(" {}", end_token))),
280 ));
281
282 let offset = start_token.chars().count() + end_token.chars().count() + 2;
283 ranges.push(
284 Range::new(from + offs, from + offs + end_pos + 1 + offset)
285 .with_direction(range.direction()),
286 );
287 offs += offset;
288 }
289 CommentChange::Commented { range, .. } | CommentChange::Whitespace { range } => {
290 ranges.push(Range::new(range.from() + offs, range.to() + offs));
291 }
292 }
293 }
294 }
295 (Transaction::change(doc, changes.into_iter()), ranges)
296 }
297
298 #[must_use]
299 pub fn toggle_block_comments(
300 doc: &Rope,
301 selection: &Selection,
302 tokens: &[BlockCommentToken],
303 ) -> Transaction {
304 let text = doc.slice(..);
305 let (commented, comment_changes) = find_block_comments(tokens, text, selection);
306 let (mut transaction, ranges) =
307 create_block_comment_transaction(doc, selection, commented, comment_changes);
308 if !commented {
309 transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
310 }
311 transaction
312 }
313
314 pub fn split_lines_of_selection(text: RopeSlice, selection: &Selection) -> Selection {
315 let mut ranges = SmallVec::new();
316 for range in selection.ranges() {
317 let (line_start, line_end) = range.line_range(text.slice(..));
318 let mut pos = text.line_to_char(line_start);
319 for line in text.slice(pos..text.line_to_char(line_end + 1)).lines() {
320 let start = pos;
321 pos += line.len_chars();
322 ranges.push(Range::new(start, pos));
323 }
324 }
325 Selection::new(ranges, 0)
326 }
327
328 #[cfg(test)]
329 mod test {
330 use super::*;
331
332 mod find_line_comment {
333 use super::*;
334
335 #[test]
336 fn not_commented() {
337 // four lines, two space indented, except for line 1 which is blank.
338 let doc = Rope::from(" 1\n\n 2\n 3");
339
340 let text = doc.slice(..);
341
342 let res = find_line_comment("//", text, 0..3);
343 // (commented = false, to_change = [line 0, line 2], min = col 2, margin = 0)
344 assert_eq!(res, (false, vec![0, 2], 2, 0));
345 }
346
347 #[test]
348 fn is_commented() {
349 // three lines where the second line is empty.
350 let doc = Rope::from("// hello\n\n// there");
351
352 let res = find_line_comment("//", doc.slice(..), 0..3);
353
354 // (commented = true, to_change = [line 0, line 2], min = col 0, margin = 1)
355 assert_eq!(res, (true, vec![0, 2], 0, 1));
356 }
357 }
358
359 // TODO: account for uncommenting with uneven comment indentation
360 mod toggle_line_comment {
361 use super::*;
362
363 #[test]
364 fn comment() {
365 // four lines, two space indented, except for line 1 which is blank.
366 let mut doc = Rope::from(" 1\n\n 2\n 3");
367 // select whole document
368 let selection = Selection::single(0, doc.len_chars() - 1);
369
370 let transaction = toggle_line_comments(&doc, &selection, None);
371 transaction.apply(&mut doc);
372
373 assert_eq!(doc, " # 1\n\n # 2\n # 3");
374 }
375
376 #[test]
377 fn uncomment() {
378 let mut doc = Rope::from(" # 1\n\n # 2\n # 3");
379 let mut selection = Selection::single(0, doc.len_chars() - 1);
380
381 let transaction = toggle_line_comments(&doc, &selection, None);
382 transaction.apply(&mut doc);
383 selection = selection.map(transaction.changes());
384
385 assert_eq!(doc, " 1\n\n 2\n 3");
386 assert!(selection.len() == 1); // to ignore the selection unused warning
387 }
388
389 #[test]
390 fn uncomment_0_margin_comments() {
391 let mut doc = Rope::from(" #1\n\n #2\n #3");
392 let mut selection = Selection::single(0, doc.len_chars() - 1);
393
394 let transaction = toggle_line_comments(&doc, &selection, None);
395 transaction.apply(&mut doc);
396 selection = selection.map(transaction.changes());
397
398 assert_eq!(doc, " 1\n\n 2\n 3");
399 assert!(selection.len() == 1); // to ignore the selection unused warning
400 }
401
402 #[test]
403 fn uncomment_0_margin_comments_with_no_space() {
404 let mut doc = Rope::from("#");
405 let mut selection = Selection::single(0, doc.len_chars() - 1);
406
407 let transaction = toggle_line_comments(&doc, &selection, None);
408 transaction.apply(&mut doc);
409 selection = selection.map(transaction.changes());
410 assert_eq!(doc, "");
411 assert!(selection.len() == 1); // to ignore the selection unused warning
412 }
413 }
414
415 #[test]
416 fn test_find_block_comments() {
417 // three lines 5 characters.
418 let mut doc = Rope::from("1\n2\n3");
419 // select whole document
420 let selection = Selection::single(0, doc.len_chars());
421
422 let text = doc.slice(..);
423
424 let res = find_block_comments(&[BlockCommentToken::default()], text, &selection);
425
426 assert_eq!(
427 res,
428 (
429 false,
430 vec![CommentChange::Uncommented {
431 range: Range::new(0, 5),
432 start_pos: 0,
433 end_pos: 4,
434 start_token: "/*".to_string(),
435 end_token: "*/".to_string(),
436 }]
437 )
438 );
439
440 // comment
441 let transaction = toggle_block_comments(&doc, &selection, &[BlockCommentToken::default()]);
442 transaction.apply(&mut doc);
443
444 assert_eq!(doc, "/* 1\n2\n3 */");
445
446 // uncomment
447 let selection = Selection::single(0, doc.len_chars());
448 let transaction = toggle_block_comments(&doc, &selection, &[BlockCommentToken::default()]);
449 transaction.apply(&mut doc);
450 assert_eq!(doc, "1\n2\n3");
451
452 // don't panic when there is just a space in comment
453 doc = Rope::from("/* */");
454 let selection = Selection::single(0, doc.len_chars());
455 let transaction = toggle_block_comments(&doc, &selection, &[BlockCommentToken::default()]);
456 transaction.apply(&mut doc);
457 assert_eq!(doc, "");
458 }
459
460 /// Test, if `get_comment_tokens` works, even if the content of the file includes chars, whose
461 /// byte size unequal the amount of chars
462 #[test]
463 fn test_get_comment_with_char_boundaries() {
464 let rope = Rope::from("··");
465 let tokens = ["//", "///"];
466
467 assert_eq!(
468 super::get_comment_token(rope.slice(..), tokens.as_slice(), 0),
469 None
470 );
471 }
472
473 /// Test for `get_comment_token`.
474 ///
475 /// Assuming the comment tokens are stored as `["///", "//"]`, `get_comment_token` should still
476 /// return `///` instead of `//` if the user is in a doc-comment section.
477 #[test]
478 fn test_use_longest_comment() {
479 let text = Rope::from(" /// amogus");
480 let tokens = ["///", "//"];
481
482 assert_eq!(
483 super::get_comment_token(text.slice(..), tokens.as_slice(), 0),
484 Some("///")
485 );
486 }
487 }