@@ -0,0 +1,105 @@
1+use crate::{find_first_non_whitespace_char2, Change, RopeSlice, State, Transaction};
9+) -> (bool, Vec<usize>, usize) {
10+ // selection ranges map char_to_line from() .. to()
11+ let mut commented = true;
12+ let mut skipped = Vec::new();
13+ let mut min = usize::MAX; // minimum col for find_first_non_whitespace_char
15+ let line_slice = text.line(line);
16+ if let Some(pos) = find_first_non_whitespace_char2(line_slice) {
17+ let len = line_slice.len_chars();
23+ // line can be shorter than pos + token len
24+ let fragment = Cow::from(line_slice.slice(pos..std::cmp::min(pos + token.len(), len)));
26+ if fragment != token {
27+ // as soon as one of the non-blank lines doesn't have a comment, the whole block is
28+ // considered uncommented.
36+ (commented, skipped, min)
39+fn toggle_line_comments(state: &State) -> Transaction {
40+ let text = state.doc.slice(..);
41+ let mut changes: Vec<Change> = Vec::new();
45+ for selection in state.selection.ranges() {
46+ let start = text.char_to_line(selection.from());
47+ let end = text.char_to_line(selection.to());
48+ let lines = start..end + 1;
49+ let (commented, skipped, min) = find_line_comment(token, text, lines.clone());
51+ changes.reserve(end - start - skipped.len());
54+ if skipped.contains(&line) {
58+ let pos = text.line_to_char(line) + min;
62+ changes.push((pos, pos, Some(format!("{} ", token).into())))
65+ let margin = 1; // TODO: margin is hardcoded 1 but could easily be 0
66+ changes.push((pos, pos + token.len() + margin, None))
70+ Transaction::change(state, changes.into_iter())
78+ fn test_find_line_comment() {
79+ use crate::{Rope, Selection};
81+ // four lines, two space indented, except for line 1 which is blank.
82+ let doc = Rope::from(" 1\n\n 2\n 3");
84+ let mut state = State::new(doc);
85+ // select whole document
86+ state.selection = Selection::single(0, state.doc.len_chars() - 1);
88+ let text = state.doc.slice(..);
90+ let res = find_line_comment("//", text, 0..3);
91+ // (commented = true, skipped = [line 1], min = col 2)
92+ assert_eq!(res, (false, vec![1], 2));
95+ let transaction = toggle_line_comments(&state);
96+ transaction.apply(&mut state);
98+ assert_eq!(state.doc, " // 1\n\n // 2\n // 3");
101+ let transaction = toggle_line_comments(&state);
102+ transaction.apply(&mut state);
103+ assert_eq!(state.doc, " 1\n\n 2\n 3");