on master help sign in
make diagnostics stick to word boundaries

Diagnostics are currently extended if text is inserted at their end. This is desirable when inserting text after an identifier. For example consider: let foo = 2; --- unused variable Renaming the identifier should extend the diagnostic: let foobar = 2; ------ unused variable This is currently implemented in helix but as a consequence adding whitespaces or a type hint also extends the diagnostic: let foo = 2; -------- unused variable let foo: Bar = 2; -------- unused variable In these cases the diagnostic should remain unchanged: let foo = 2; --- unused variable let foo: Bar = 2; --- unused variable As a heuristic helix will now only extend diagnostics that end on a word char if new chars are appended to the word (so not for punctuation/ whitespace). The idea for this mapping was inspired for the word level tracking vscode uses for many positions. While VSCode doesn't currently update diagnostics after receiving publishDiagnostic it does use this system for inlay hints for example. Similarly, the new association mechanism implemented here can be used for word level tracking of inlay hints. A similar mapping function is implemented for word starts. Together these can be used to make a diagnostic stick to a word. If that word is removed that diagnostic is automatically removed too. This is the exact same behavior VSCode inlay hints eixibit.

commit515ef17207878b78e4f5eda8bf710fa0aa1eae87 authorPascal Kuthe <pascal.kuthe@semimod.de> dateSun 26 Mar 2023, 18:14 (4 years ago) parent8653e1b
4 files changed+112−28
helix-core/src/diagnostic.rs+4 helix-core/src/transaction.rs+73−14 helix-term/src/application.rs+10−1 helix-view/src/document.rs+25−13
helix-core/src/diagnostic.rs+4
@@ -39,6 +39,10 @@ pub enum DiagnosticTag {
3939#[derive(Debug, Clone)]
4040pub struct Diagnostic {
4141 pub range: Range,
42+ // whether this diagnostic ends at the end of(or inside) a word
43+ pub ends_at_word: bool,
44+ pub starts_at_word: bool,
45+ pub zero_width: bool,
4246 pub line: usize,
4347 pub message: String,
4448 pub severity: Option<Severity>,
helix-core/src/transaction.rs+73−14
@@ -1,7 +1,7 @@
11use ropey::RopeSlice;
22use smallvec::SmallVec;
33
4−use crate::{Range, Rope, Selection, Tendril};
4+use crate::{chars::char_is_word, Range, Rope, Selection, Tendril};
55use std::{borrow::Cow, iter::once};
66
77/// (from, to, replacement)
@@ -23,6 +23,30 @@ pub enum Operation {
2323pub enum Assoc {
2424 Before,
2525 After,
26+ /// Acts like `After` if a word character is inserted
27+ /// after the position, otherwise acts like `Before`
28+ AfterWord,
29+ /// Acts like `Before` if a word character is inserted
30+ /// before the position, otherwise acts like `After`
31+ BeforeWord,
32+}
33+
34+impl Assoc {
35+ /// Whether to stick to gaps
36+ fn stay_at_gaps(self) -> bool {
37+ !matches!(self, Self::BeforeWord | Self::AfterWord)
38+ }
39+
40+ fn insert_offset(self, s: &str) -> usize {
41+ let chars = s.chars().count();
42+ match self {
43+ Assoc::After => chars,
44+ Assoc::AfterWord => s.chars().take_while(|&c| char_is_word(c)).count(),
45+ // return position before inserted text
46+ Assoc::Before => 0,
47+ Assoc::BeforeWord => chars - s.chars().rev().take_while(|&c| char_is_word(c)).count(),
48+ }
49+ }
2650}
2751
2852#[derive(Debug, Default, Clone, PartialEq, Eq)]
@@ -415,8 +439,6 @@ impl ChangeSet {
415439 map!(|pos, _| (old_end > pos).then_some(new_pos), i);
416440 }
417441 Insert(s) => {
418− let ins = s.chars().count();
419−
420442 // a subsequent delete means a replace, consume it
421443 if let Some((_, Delete(len))) = iter.peek() {
422444 iter.next();
@@ -424,13 +446,13 @@ impl ChangeSet {
424446 old_end = old_pos + len;
425447 // in range of replaced text
426448 map!(
427− |pos, assoc| (old_end > pos).then(|| {
449+ |pos, assoc: Assoc| (old_end > pos).then(|| {
428450 // at point or tracking before
429− if pos == old_pos || assoc == Assoc::Before {
451+ if pos == old_pos && assoc.stay_at_gaps() {
430452 new_pos
431453 } else {
432454 // place to end of insert
433− new_pos + ins
455+ new_pos + assoc.insert_offset(s)
434456 }
435457 }),
436458 i
@@ -438,20 +460,15 @@ impl ChangeSet {
438460 } else {
439461 // at insert point
440462 map!(
441− |pos, assoc| (old_pos == pos).then(|| {
463+ |pos, assoc: Assoc| (old_pos == pos).then(|| {
442464 // return position before inserted text
443− if assoc == Assoc::Before {
444− new_pos
445− } else {
446− // after text
447− new_pos + ins
448− }
465+ new_pos + assoc.insert_offset(s)
449466 }),
450467 i
451468 );
452469 }
453470
454− new_pos += ins;
471+ new_pos += s.chars().count();
455472 }
456473 }
457474 old_pos = old_end;
@@ -884,6 +901,48 @@ mod test {
884901 let mut positions = [4, 2];
885902 cs.update_positions(positions.iter_mut().map(|pos| (pos, Assoc::After)));
886903 assert_eq!(positions, [4, 2]);
904+ // stays at word boundary
905+ let cs = ChangeSet {
906+ changes: vec![
907+ Retain(2), // <space><space>
908+ Insert(" ab".into()),
909+ Retain(2), // cd
910+ Insert("de ".into()),
911+ ],
912+ len: 4,
913+ len_after: 10,
914+ };
915+ assert_eq!(cs.map_pos(2, Assoc::BeforeWord), 3);
916+ assert_eq!(cs.map_pos(4, Assoc::AfterWord), 9);
917+ let cs = ChangeSet {
918+ changes: vec![
919+ Retain(1), // <space>
920+ Insert(" b".into()),
921+ Delete(1), // c
922+ Retain(1), // d
923+ Insert("e ".into()),
924+ Delete(1), // <space>
925+ ],
926+ len: 5,
927+ len_after: 7,
928+ };
929+ assert_eq!(cs.map_pos(1, Assoc::BeforeWord), 2);
930+ assert_eq!(cs.map_pos(3, Assoc::AfterWord), 5);
931+ let cs = ChangeSet {
932+ changes: vec![
933+ Retain(1), // <space>
934+ Insert("a".into()),
935+ Delete(2), // <space>b
936+ Retain(1), // d
937+ Insert("e".into()),
938+ Delete(1), // f
939+ Retain(1), // <space>
940+ ],
941+ len: 5,
942+ len_after: 7,
943+ };
944+ assert_eq!(cs.map_pos(2, Assoc::BeforeWord), 1);
945+ assert_eq!(cs.map_pos(4, Assoc::AfterWord), 4);
887946 }
888947
889948 #[test]
helix-term/src/application.rs+10−1
@@ -1,6 +1,7 @@
11use arc_swap::{access::Map, ArcSwap};
22use futures_util::Stream;
33use helix_core::{
4+ chars::char_is_word,
45 diagnostic::{DiagnosticTag, NumberOrString},
56 path::get_relative_path,
67 pos_at_coords, syntax, Selection,
@@ -811,7 +812,6 @@ impl Application {
811812 log::warn!("lsp position out of bounds - {:?}", diagnostic);
812813 return None;
813814 };
814−
815815 let severity =
816816 diagnostic.severity.map(|severity| match severity {
817817 DiagnosticSeverity::ERROR => Error,
@@ -863,8 +863,17 @@ impl Application {
863863 Vec::new()
864864 };
865865
866+ let ends_at_word = start != end
867+ && end != 0
868+ && text.get_char(end - 1).map_or(false, char_is_word);
869+ let starts_at_word = start != end
870+ && text.get_char(start).map_or(false, char_is_word);
871+
866872 Some(Diagnostic {
867873 range: Range { start, end },
874+ ends_at_word,
875+ starts_at_word,
876+ zero_width: start == end,
868877 line: diagnostic.range.start.line as usize,
869878 message: diagnostic.message.clone(),
870879 severity,
helix-view/src/document.rs+25−13
@@ -1213,20 +1213,32 @@ impl Document {
12131213
12141214 let changes = transaction.changes();
12151215
1216− changes.update_positions(
1217− self.diagnostics
1218− .iter_mut()
1219− .map(|diagnostic| (&mut diagnostic.range.start, Assoc::After)),
1220− );
1221− changes.update_positions(
1222− self.diagnostics
1223− .iter_mut()
1224− .map(|diagnostic| (&mut diagnostic.range.end, Assoc::After)),
1225− );
1226− // map state.diagnostics over changes::map_pos too
1227− for diagnostic in &mut self.diagnostics {
1216+ // map diagnostics over changes too
1217+ changes.update_positions(self.diagnostics.iter_mut().map(|diagnostic| {
1218+ let assoc = if diagnostic.starts_at_word {
1219+ Assoc::BeforeWord
1220+ } else {
1221+ Assoc::After
1222+ };
1223+ (&mut diagnostic.range.start, assoc)
1224+ }));
1225+ changes.update_positions(self.diagnostics.iter_mut().map(|diagnostic| {
1226+ let assoc = if diagnostic.ends_at_word {
1227+ Assoc::AfterWord
1228+ } else {
1229+ Assoc::Before
1230+ };
1231+ (&mut diagnostic.range.end, assoc)
1232+ }));
1233+ self.diagnostics.retain_mut(|diagnostic| {
1234+ if diagnostic.range.start > diagnostic.range.end
1235+ || (!diagnostic.zero_width && diagnostic.range.start == diagnostic.range.end)
1236+ {
1237+ return false;
1238+ }
12281239 diagnostic.line = self.text.char_to_line(diagnostic.range.start);
1229− }
1240+ true
1241+ });
12301242
12311243 self.diagnostics
12321244 .sort_unstable_by_key(|diagnostic| diagnostic.range);