kak-tree-sitter 3.2.1

Server between Kakoune and tree-sitter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! Tree-sitter state (i.e. highlighting, tree walking, etc.)

use std::{
  collections::{HashMap, hash_map::Entry},
  time::Duration,
};

use ropey::RopeSlice;
use tree_house::text_object::CapturedNode;
use tree_house_bindings::{InactiveQueryCursor, Node};

use crate::{
  error::OhNo,
  kakoune::{
    buffer::BufferId,
    selection::{ObjectFlags, Pos, Sel, SelectMode},
    text_objects::OperationMode,
  },
  server::triple_buffer::TripleBufferReader,
  tree_sitter::languages::Languages,
};

use super::{highlighting::KakHighlightRange, languages::Language, nav};

/// Lang-keyed trees.
#[derive(Default)]
pub struct Trees {
  trees: HashMap<BufferId, TreeState>,
}

impl Trees {
  /// Create or update a tree.
  pub fn compute(
    &mut self,
    languages: &Languages,
    lang: &Language,
    id: &BufferId,
  ) -> Result<&mut TreeState, OhNo> {
    match self.trees.entry(id.clone()) {
      Entry::Occupied(entry) => {
        let tree = entry.into_mut();
        tree.change_lang(languages, lang)?;
        Ok(tree)
      }

      Entry::Vacant(entry) => {
        let tree = TreeState::new(languages, lang)?;
        Ok(entry.insert(tree))
      }
    }
  }

  pub fn get_tree(&self, id: &BufferId) -> Result<&TreeState, OhNo> {
    self
      .trees
      .get(id)
      .ok_or_else(|| OhNo::UnknownBuffer { id: id.clone() })
  }

  pub fn get_tree_mut(&mut self, id: &BufferId) -> Result<&mut TreeState, OhNo> {
    self
      .trees
      .get_mut(id)
      .ok_or_else(|| OhNo::UnknownBuffer { id: id.clone() })
  }

  pub fn delete_tree(&mut self, id: &BufferId) {
    self.trees.remove(id);
  }

  pub fn clean_session(&mut self, session: &str) {
    self.trees.retain(|id, _| id.session() != session);
  }
}

/// State around a tree.
///
/// A tree-sitter tree represents a parsed buffer in a given state. It can be walked with queries and updated.
pub struct TreeState {
  buf: String,
  lang_name: String,
  lang: tree_house::Language,
  syntax: tree_house::Syntax,
}

impl TreeState {
  pub fn new(languages: &Languages, lang: &Language) -> Result<Self, OhNo> {
    let syntax = tree_house::Syntax::new(
      RopeSlice::from(""),
      lang.language(),
      Duration::from_millis(100),
      languages,
    )
    .map_err(|err| OhNo::TreeHouse {
      err: err.to_string(),
    })?;

    Ok(Self {
      buf: String::default(),
      lang_name: lang.name.clone(),
      lang: lang.language(),
      syntax,
    })
  }

  pub fn lang_name(&self) -> &str {
    &self.lang_name
  }

  pub fn change_lang(&mut self, languages: &Languages, lang: &Language) -> Result<(), OhNo> {
    lang.lang_name().clone_into(&mut self.lang_name);
    self.recompute_tree(languages)
  }

  /// Read a triple buffer to replace our internal buffer.
  ///
  /// Return `true` if the buffer has changed.
  pub fn update_buf(
    &mut self,
    languages: &Languages,
    reader: TripleBufferReader,
  ) -> Result<bool, OhNo> {
    let changed = reader.read_to(&mut self.buf);

    if changed {
      self.recompute_tree(languages)?;
    }

    Ok(changed)
  }

  pub fn recompute_tree(&mut self, languages: &Languages) -> Result<(), OhNo> {
    self.syntax = tree_house::Syntax::new(
      RopeSlice::from(self.buf.as_str()),
      self.lang,
      Duration::from_millis(100),
      languages,
    )
    .map_err(|err| OhNo::TreeHouse {
      err: err.to_string(),
    })?;

    Ok(())
  }

  pub fn highlight(&mut self, langs: &Languages) -> Result<Vec<KakHighlightRange>, OhNo> {
    let rope = RopeSlice::from(self.buf.as_str());

    log::trace!("highlighting buffer: {rope:?}",);
    let highlighter = tree_house::highlighter::Highlighter::new(&self.syntax, rope, langs, ..);

    let hls = KakHighlightRange::from_tree_house(rope, highlighter);

    Ok(hls)
  }

  /// Get the text-objects for the given pattern.
  ///
  /// This function takes in a list of selections and a mode of operation, and return new selections, depending on the
  /// mode.
  pub fn text_objects(
    &self,
    lang: &Language,
    pattern: &str,
    selections: &[Sel],
    mode: &OperationMode,
  ) -> Result<Vec<Sel>, OhNo> {
    let query = lang
      .textobject_query
      .as_ref()
      .ok_or(OhNo::UnsupportedTextObjects)?;

    let buf = RopeSlice::from(self.buf.as_str());

    // get captures’ nodes for the given pattern; this is a function because the pattern might be dynamically recomputed
    // (e.g. object mode)
    let get_captures_nodes = |pattern| {
      let nodes = query
        .capture_nodes(
          pattern,
          self.syntax.tree().root_node(),
          buf,
          InactiveQueryCursor::default(),
        )
        .map(|iter| {
          iter.map(|captured| match captured {
            CapturedNode::Single(node) => node,

            // SAFETY: `nodes` is guaranteed to always have at least one node
            CapturedNode::Grouped(nodes) => nodes.into_iter().next().unwrap(),
          })
        })
        .ok_or(OhNo::UnknownTextObjectQuery {
          pattern: pattern.to_owned(),
        })?;

      <Result<_, OhNo>>::Ok(nodes)
    };

    let sels = match mode {
      OperationMode::SearchNext => {
        let mut nodes = get_captures_nodes(pattern)?;
        selections
          .iter()
          .flat_map(|sel| Self::tree_sitter_search_next_text_object(buf, sel, &mut nodes))
          .collect()
      }

      OperationMode::SearchPrev => {
        let mut nodes = get_captures_nodes(pattern)?;
        selections
          .iter()
          .flat_map(|sel| Self::tree_sitter_search_prev_text_object(buf, sel, &mut nodes))
          .collect()
      }

      OperationMode::SearchExtendNext => {
        let mut nodes = get_captures_nodes(pattern)?;
        selections
          .iter()
          .flat_map(|sel| Self::tree_sitter_search_extend_next_text_object(buf, sel, &mut nodes))
          .collect()
      }

      OperationMode::SearchExtendPrev => {
        let mut nodes = get_captures_nodes(pattern)?;
        selections
          .iter()
          .flat_map(|sel| Self::tree_sitter_search_extend_prev_text_object(buf, sel, &mut nodes))
          .collect()
      }

      OperationMode::FindNext => {
        let mut nodes = get_captures_nodes(pattern)?;
        selections
          .iter()
          .flat_map(|sel| Self::tree_sitter_find_text_object(buf, sel, &mut nodes, false))
          .collect()
      }

      OperationMode::FindPrev => {
        let mut nodes = get_captures_nodes(pattern)?;
        selections
          .iter()
          .flat_map(|sel| Self::tree_sitter_find_text_object(buf, sel, &mut nodes, true))
          .collect()
      }

      OperationMode::ExtendNext => {
        let mut nodes = get_captures_nodes(pattern)?;
        selections
          .iter()
          .flat_map(|sel| Self::tree_sitter_extend_text_object(buf, sel, &mut nodes, false))
          .collect()
      }

      OperationMode::ExtendPrev => {
        let mut nodes = get_captures_nodes(pattern)?;
        selections
          .iter()
          .flat_map(|sel| Self::tree_sitter_extend_text_object(buf, sel, &mut nodes, true))
          .collect()
      }

      OperationMode::Select => {
        let mut nodes = get_captures_nodes(pattern)?;
        selections
          .iter()
          .flat_map(|sel| {
            Self::tree_sitter_select_text_object(buf, sel, &mut nodes).collect::<Vec<_>>()
          })
          .collect()
      }

      OperationMode::Object { mode, flags } => {
        let flags = ObjectFlags::parse_kak_str(flags);

        let pattern = format!(
          "{pattern}.{}",
          if flags.inner { "inside" } else { "around" }
        );
        let mut nodes = get_captures_nodes(&pattern)?;

        selections
          .iter()
          .flat_map(|sel| Self::tree_sitter_object_text_object(buf, sel, &mut nodes, *mode, flags))
          .collect()
      }
    };

    Ok(sels)
  }

  /// Search the next text-object for a given selection.
  fn tree_sitter_search_next_text_object<'a>(
    buf: RopeSlice,
    sel: &Sel,
    nodes: impl Iterator<Item = Node<'a>>,
  ) -> Option<Sel> {
    let p = sel.anchor.max(sel.cursor);
    let node = Self::tree_sitter_node_after(buf, &p, nodes)?;
    let start = Pos::from_tree_sitter(buf, node.start_byte());
    let mut end = Pos::from_tree_sitter(buf, node.end_byte());
    end.col -= 1;

    Some(sel.replace(&start, &end))
  }

  /// Search the prev text-object for a given selection.
  fn tree_sitter_search_prev_text_object<'a>(
    buf: RopeSlice,
    sel: &Sel,
    nodes: impl Iterator<Item = Node<'a>>,
  ) -> Option<Sel> {
    let p = sel.anchor.min(sel.cursor);
    let node = Self::tree_sitter_node_before(buf, &p, nodes)?;
    let start = Pos::from_tree_sitter(buf, node.start_byte());
    let mut end = Pos::from_tree_sitter(buf, node.end_byte());
    end.col -= 1;

    Some(sel.replace(&start, &end))
  }

  /// Search-extend the next text-object for a given selection.
  fn tree_sitter_search_extend_next_text_object<'a>(
    buf: RopeSlice,
    sel: &Sel,
    nodes: impl Iterator<Item = Node<'a>>,
  ) -> Option<Sel> {
    let node = Self::tree_sitter_node_after(buf, &sel.cursor, nodes)?;
    let cursor = Pos::from_tree_sitter(buf, node.start_byte());

    Some(Sel {
      anchor: sel.anchor,
      cursor,
    })
  }

  /// Search extend the prev text-object for a given selection.
  fn tree_sitter_search_extend_prev_text_object<'a>(
    buf: RopeSlice,
    sel: &Sel,
    nodes: impl Iterator<Item = Node<'a>>,
  ) -> Option<Sel> {
    let node = Self::tree_sitter_node_before(buf, &sel.cursor, nodes)?;
    let cursor = Pos::from_tree_sitter(buf, node.start_byte());

    Some(Sel {
      anchor: sel.anchor,
      cursor,
    })
  }

  /// Find the next/prev text-object for a given selection.
  fn tree_sitter_find_text_object<'a>(
    buf: RopeSlice,
    sel: &Sel,
    nodes: impl Iterator<Item = Node<'a>>,
    is_prev: bool,
  ) -> Option<Sel> {
    let node = if is_prev {
      Self::tree_sitter_node_before(buf, &sel.cursor, nodes)?
    } else {
      Self::tree_sitter_node_after(buf, &sel.cursor, nodes)?
    };
    let cursor = Pos::from_tree_sitter(buf, node.start_byte());
    let anchor = sel.cursor;

    Some(Sel { anchor, cursor })
  }

  /// Extend onto the next/prev text-object for a given selection.
  fn tree_sitter_extend_text_object<'node>(
    buf: RopeSlice,
    sel: &Sel,
    nodes: impl Iterator<Item = Node<'node>>,
    is_prev: bool,
  ) -> Option<Sel> {
    let node = if is_prev {
      Self::tree_sitter_node_before(buf, &sel.cursor, nodes)?
    } else {
      Self::tree_sitter_node_after(buf, &sel.cursor, nodes)?
    };
    let cursor = Pos::from_tree_sitter(buf, node.start_byte());
    let anchor = sel.anchor;

    Some(Sel { anchor, cursor })
  }

  /// Select text-object occurrences inside the current selection.
  fn tree_sitter_select_text_object<'node>(
    buf: RopeSlice,
    sel: &Sel,
    nodes: impl Iterator<Item = Node<'node>>,
  ) -> impl Iterator<Item = Sel> {
    nodes
      .filter(move |node| sel.selects(buf, node))
      .map(move |node| {
        let start = Pos::from_tree_sitter(buf, node.start_byte());
        let end = Pos::from_tree_sitter(buf, node.end_byte());
        sel.replace(&start, &end)
      })
  }

  /// Object-mode text-objects.
  ///
  /// Object-mode is a special in Kakoune aggregating many features, allowing to match inner / whole objects. The
  /// tree-sitter version enhances the mode with all possible tree-sitter capture groups.
  fn tree_sitter_object_text_object<'node>(
    buf: RopeSlice,
    sel: &Sel,
    nodes: impl Iterator<Item = Node<'node>>,
    mode: SelectMode,
    flags: ObjectFlags,
  ) -> Option<Sel> {
    let node = Self::tree_sitter_narrowest_enclosing_node(buf, &sel.cursor, nodes)?;

    match mode {
      // extend only moves the cursor
      SelectMode::Extend => {
        let anchor = sel.anchor;
        let cursor = if flags.to_begin {
          Pos::from_tree_sitter(buf, node.start_byte())
        } else if flags.to_end {
          let mut p = Pos::from_tree_sitter(buf, node.end_byte());
          p.col -= 1;
          p
        } else {
          return None;
        };

        Some(Sel { anchor, cursor })
      }

      SelectMode::Replace => {
        // brute force but eh it works lol
        if flags.to_begin && !flags.to_end {
          let anchor = sel.cursor;
          let cursor = Pos::from_tree_sitter(buf, node.start_byte());
          Some(Sel { anchor, cursor })
        } else if !flags.to_begin && flags.to_end {
          let anchor = sel.cursor;
          let mut cursor = Pos::from_tree_sitter(buf, node.end_byte());
          cursor.col -= 1;
          Some(Sel { anchor, cursor })
        } else if flags.to_begin && flags.to_end {
          let anchor = Pos::from_tree_sitter(buf, node.start_byte());
          let mut cursor = Pos::from_tree_sitter(buf, node.end_byte());
          cursor.col -= 1;
          Some(Sel { anchor, cursor })
        } else {
          None
        }
      }
    }
  }

  /// Get the next node after given position.
  fn tree_sitter_node_after<'a>(
    buf: RopeSlice,
    p: &Pos,
    nodes: impl Iterator<Item = Node<'a>>,
  ) -> Option<Node<'a>> {
    let mut candidates = nodes
      .filter(|node| &Pos::from_tree_sitter(buf, node.start_byte()) > p)
      .collect::<Vec<_>>();

    candidates.sort_by_key(|node| node.start_byte());
    candidates.into_iter().next()
  }

  /// Get the previous node before a given position.
  fn tree_sitter_node_before<'a>(
    buf: RopeSlice,
    p: &Pos,
    nodes: impl Iterator<Item = Node<'a>>,
  ) -> Option<Node<'a>> {
    let mut candidates = nodes
      .filter(|node| &Pos::from_tree_sitter(buf, node.start_byte()) < p)
      .collect::<Vec<_>>();

    candidates.sort_by_key(|node| node.start_byte());
    candidates.into_iter().next_back()
  }

  /// Get the narrowest enclosing node of a given position.
  fn tree_sitter_narrowest_enclosing_node<'a>(
    buf: RopeSlice,
    p: &Pos,
    nodes: impl Iterator<Item = Node<'a>>,
  ) -> Option<Node<'a>> {
    let mut candidates = nodes
      .filter(|node| {
        &Pos::from_tree_sitter(buf, node.start_byte()) < p
          && &Pos::from_tree_sitter(buf, node.end_byte()) > p
      })
      .collect::<Vec<_>>();

    candidates.sort_by_key(|node| node.start_byte());
    candidates.into_iter().next_back()
  }

  /// Navigate the tree.
  ///
  /// This function will apply the direction on all selections, expanding or collapsing them. If a selection is not
  /// spanning on a node, the closet node is selected first, so that if you have the cursor and anchor at the same
  /// location and you want to select the next child, your cursor will expand to the whole nearest enclosing node first.
  pub fn tree_sitter_nav_tree(&self, selections: &[Sel], dir: nav::Dir) -> Vec<Sel> {
    let buf = RopeSlice::from(self.buf.as_str());

    selections
      .iter()
      .map(|sel| {
        self
          .tree_sitter_find_sel_node(buf, sel)
          .and_then(|node| {
            // if our selection is not the same as the node, we pick the node
            if !sel.fully_selects(buf, &node) {
              log::debug!("selection {sel:?} doesn’t fully select node {node:?}");
              return Some(node);
            }

            log::debug!("walking node {node:?} for dir {dir:?}");
            log::debug!("  parent: {:?}", node.parent());
            log::debug!("  1st child: {:?}", node.child(0));
            log::debug!("  next sibling: {:?}", node.next_sibling());

            let res = match dir {
              nav::Dir::Parent => node.parent(),
              nav::Dir::FirstChild => node.child(0),
              nav::Dir::LastChild => node
                .child_count()
                .checked_sub(1)
                .and_then(|i| node.child(i)),
              nav::Dir::FirstSibling => node.parent().and_then(|parent| parent.child(0)),
              nav::Dir::LastSibling => node.parent().and_then(|parent| {
                parent
                  .child_count()
                  .checked_sub(1)
                  .and_then(|i| parent.child(i))
              }),
              nav::Dir::PrevSibling { cousin } if cousin => {
                Self::tree_sitter_find_prev_sibling_or_cousin(&node)
              }
              nav::Dir::NextSibling { cousin } if cousin => {
                Self::tree_sitter_find_next_sibling_or_cousin(&node)
              }
              nav::Dir::PrevSibling { .. } => node.prev_sibling(),
              nav::Dir::NextSibling { .. } => node.next_sibling(),
            };

            log::debug!("navigated to node: {res:?}");
            res
          })
          .map(|node| sel.replace_with_node(buf, &node))
          .unwrap_or_else(|| sel.clone())
      })
      .collect()
  }

  /// Find the node for a selection.
  fn tree_sitter_find_sel_node(&self, buf: RopeSlice, sel: &Sel) -> Option<Node<'_>> {
    log::trace!("finding node for selection {sel:?}");

    let start = sel.anchor.min(sel.cursor);
    let mut end = sel.cursor.max(sel.anchor);
    end.col += 1; // Kakoune ranges are inclusive
    let node = self
      .syntax
      .tree()
      .root_node()
      // FIXME: we need bytes here…
      .descendant_for_byte_range(start.into_tree_sitter(buf) as _, end.into_tree_sitter(buf) as _);

    log::trace!("found node: {node:?}");

    node
  }

  /// Get the next sibiling or cousin.
  fn tree_sitter_find_next_sibling_or_cousin<'a>(node: &Node<'a>) -> Option<Node<'a>> {
    node.next_sibling().or_else(|| {
      let parent = node.parent()?;
      let parent_sibling = parent.next_sibling()?;

      if parent_sibling.child_count() > 0 {
        parent_sibling.child(0)
      } else {
        None
      }
    })
  }

  /// Get the previous sibiling or cousin.
  fn tree_sitter_find_prev_sibling_or_cousin<'a>(node: &Node<'a>) -> Option<Node<'a>> {
    node.prev_sibling().or_else(|| {
      let parent = node.parent()?;
      let parent_sibling = parent.prev_sibling()?;

      if parent_sibling.child_count() > 0 {
        parent_sibling.child(parent_sibling.child_count() - 1)
      } else {
        None
      }
    })
  }
}