robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
22.4 KiB714 linesraw
1--- @brief
2--- Snippet expansion and navigation.
3---
4--- Internal autocmds live in the `nvim.snippet` augroup. To disable them (e.g.
5--- to manage sessions yourself), clear it:
6---
7--- ```lua
8--- vim.api.nvim_clear_autocmds({ group = 'nvim.snippet', buffer = 0 })
9--- ```
10---
11--- Heads-up: |vim.snippet.jump()| re-registers them on every jump.
12
13local G = vim.lsp._snippet_grammar
14local snippet_group = vim.api.nvim_create_augroup('nvim.snippet')
15local snippet_ns = vim.api.nvim_create_namespace('nvim.snippet')
16local hl_group = 'SnippetTabstop'
17local hl_group_active = 'SnippetTabstopActive'
18
19--- Returns the 0-based cursor position.
20---
21--- @return integer, integer
22local function cursor_pos()
23  local cursor = vim.api.nvim_win_get_cursor(0)
24  return cursor[1] - 1, cursor[2]
25end
26
27--- Resolves variables (like `$name` or `${name:default}`) as follows:
28--- - When a variable is unknown (i.e.: its name is not recognized in any of the cases below), return `nil`.
29--- - When a variable isn't set, return its default (if any) or an empty string.
30---
31--- Note that in some cases, the default is ignored since it's not clear how to distinguish an empty
32--- value from an unset value (e.g.: `TM_CURRENT_LINE`).
33---
34--- @param var string
35--- @param default string
36--- @return string?
37local function resolve_variable(var, default)
38  --- @param str string
39  --- @return string
40  local function expand_or_default(str)
41    local expansion = vim.fn.expand(str) --[[@as string]]
42    return expansion == '' and default or expansion
43  end
44
45  if var == 'TM_SELECTED_TEXT' then
46    -- Snippets are expanded in insert mode only, so there's no selection.
47    return default
48  elseif var == 'TM_CURRENT_LINE' then
49    return vim.api.nvim_get_current_line()
50  elseif var == 'TM_CURRENT_WORD' then
51    return expand_or_default('<cword>')
52  elseif var == 'TM_LINE_INDEX' then
53    return tostring(vim.fn.line('.') - 1)
54  elseif var == 'TM_LINE_NUMBER' then
55    return tostring(vim.fn.line('.'))
56  elseif var == 'TM_FILENAME' then
57    return expand_or_default('%:t')
58  elseif var == 'TM_FILENAME_BASE' then
59    return expand_or_default('%:t:r')
60  elseif var == 'TM_DIRECTORY' then
61    return expand_or_default('%:p:h:t')
62  elseif var == 'TM_FILEPATH' then
63    return expand_or_default('%:p')
64  end
65
66  -- Unknown variable.
67  return nil
68end
69
70--- Transforms the given text into an array of lines (so no line contains `\n`).
71---
72--- @param text string|string[]
73--- @return string[]
74local function text_to_lines(text)
75  text = type(text) == 'string' and { text } or text
76  --- @cast text string[]
77  return vim.split(table.concat(text), '\n', { plain = true })
78end
79
80--- Computes the 0-based position of a tabstop located at the end of `snippet` and spanning
81--- `placeholder` (if given).
82---
83--- @param snippet string[]
84--- @param placeholder string?
85--- @return Range4
86local function compute_tabstop_range(snippet, placeholder)
87  local cursor_row, cursor_col = cursor_pos()
88  local snippet_text = text_to_lines(snippet)
89  local placeholder_text = text_to_lines(placeholder or '')
90  local start_row = cursor_row + #snippet_text - 1
91  local start_col = #(snippet_text[#snippet_text] or '')
92
93  -- Add the cursor's column offset to the first line.
94  if start_row == cursor_row then
95    start_col = start_col + cursor_col
96  end
97
98  local end_row = start_row + #placeholder_text - 1
99  local end_col = (start_row == end_row and start_col or 0)
100    + #(placeholder_text[#placeholder_text] or '')
101
102  return { start_row, start_col, end_row, end_col }
103end
104
105--- Returns the range spanned by the respective extmark.
106---
107--- @param bufnr integer
108--- @param extmark_id integer
109--- @return Range4
110local function get_extmark_range(bufnr, extmark_id)
111  -- Snippet and tabstop marks are created with both end positions.
112  local mark = vim.api.nvim_buf_get_extmark_by_id(bufnr, snippet_ns, extmark_id, { details = true })
113  --- @cast mark [integer, integer, { end_row: integer, end_col: integer }]
114
115  return { mark[1], mark[2], mark[3].end_row, mark[3].end_col }
116end
117
118--- @class (private) vim.snippet.Tabstop
119--- @field extmark_id integer
120--- @field bufnr integer
121--- @field index integer
122--- @field placement integer
123--- @field choices? string[]
124local Tabstop = {}
125
126--- Creates a new tabstop.
127---
128--- @package
129--- @param index integer
130--- @param buf integer
131--- @param placement integer
132--- @param range Range4
133--- @param choices? string[]
134--- @return vim.snippet.Tabstop
135function Tabstop.new(index, buf, placement, range, choices)
136  local extmark_id = vim.api.nvim_buf_set_extmark(buf, snippet_ns, range[1], range[2], {
137    right_gravity = true,
138    end_right_gravity = false,
139    end_line = range[3],
140    end_col = range[4],
141    hl_group = index == 1 and hl_group_active or hl_group,
142  })
143
144  local self = setmetatable({
145    extmark_id = extmark_id,
146    bufnr = buf,
147    index = index,
148    placement = placement,
149    choices = choices,
150  }, { __index = Tabstop })
151
152  return self
153end
154
155--- Returns the tabstop's range.
156---
157--- @package
158--- @return Range4
159function Tabstop:get_range()
160  return get_extmark_range(self.bufnr, self.extmark_id)
161end
162
163--- Returns the text spanned by the tabstop.
164---
165--- @package
166--- @return string
167function Tabstop:get_text()
168  local range = self:get_range()
169  return table.concat(
170    vim.api.nvim_buf_get_text(self.bufnr, range[1], range[2], range[3], range[4]),
171    '\n'
172  )
173end
174
175--- Sets the tabstop's text.
176---
177--- @package
178--- @param text string
179function Tabstop:set_text(text)
180  local range = self:get_range()
181  vim.api.nvim_buf_set_text(self.bufnr, range[1], range[2], range[3], range[4], text_to_lines(text))
182end
183
184---@alias (private) vim.snippet.TabStopGravity
185--- | "expand" Expand the current tabstop on text insert
186--- | "lock" The tabstop should NOT move on text insert
187--- | "shift" The tabstop should move on text insert (default)
188
189--- Sets the right gravity of the tabstop's extmark.
190--- Sets the active highlight group for current ("expand") tabstops
191---
192---@package
193---@param target vim.snippet.TabStopGravity
194function Tabstop:set_gravity(target)
195  local hl = hl_group
196  local right_gravity = true
197  local end_right_gravity = true
198
199  if target == 'expand' then
200    hl = hl_group_active
201    right_gravity = false
202    end_right_gravity = true
203  elseif target == 'lock' then
204    right_gravity = false
205    end_right_gravity = false
206  end
207
208  local range = self:get_range()
209  vim.api.nvim_buf_del_extmark(self.bufnr, snippet_ns, self.extmark_id)
210  self.extmark_id = vim.api.nvim_buf_set_extmark(self.bufnr, snippet_ns, range[1], range[2], {
211    right_gravity = right_gravity,
212    end_right_gravity = end_right_gravity,
213    end_line = range[3],
214    end_col = range[4],
215    hl_group = hl,
216  })
217end
218
219--- @class (private) vim.snippet.Session
220--- @field bufnr integer
221--- @field extmark_id integer
222--- @field tabstops table<integer, vim.snippet.Tabstop[]>
223--- @field tabstop_placements integer[]
224--- @field current_tabstop vim.snippet.Tabstop
225--- @field tab_keymaps { i: table<string, any>?, s: table<string, any>? }
226--- @field shift_tab_keymaps { i: table<string, any>?, s: table<string, any>? }
227local Session = {}
228
229--- Creates a new snippet session in the current buffer.
230---
231--- @package
232--- @param buf integer
233--- @param snippet_extmark integer
234--- @param tabstop_data table<integer, { placement: integer, range: Range4, choices?: string[] }[]>
235--- @return vim.snippet.Session
236function Session.new(buf, snippet_extmark, tabstop_data)
237  local self = setmetatable({
238    bufnr = buf,
239    extmark_id = snippet_extmark,
240    tabstops = {},
241    tabstop_placements = {},
242    current_tabstop = Tabstop.new(0, buf, 0, { 0, 0, 0, 0 }),
243    tab_keymaps = { i = nil, s = nil },
244    shift_tab_keymaps = { i = nil, s = nil },
245  }, { __index = Session })
246
247  -- Create the tabstops.
248  for index, ranges in pairs(tabstop_data) do
249    for _, data in ipairs(ranges) do
250      self.tabstops[index] = self.tabstops[index] or {}
251      table.insert(
252        self.tabstops[index],
253        Tabstop.new(index, self.bufnr, data.placement, data.range, data.choices)
254      )
255      table.insert(self.tabstop_placements, data.placement)
256    end
257  end
258
259  return self
260end
261
262--- Returns the destination tabstop index when jumping in the given direction.
263---
264--- @package
265--- @param direction vim.snippet.Direction
266--- @return integer?
267function Session:get_dest_index(direction)
268  local tabstop_indexes = vim.tbl_keys(self.tabstops) --- @type integer[]
269  table.sort(tabstop_indexes)
270  for i, index in ipairs(tabstop_indexes) do
271    if index == self.current_tabstop.index then
272      local dest_index = tabstop_indexes[i + direction] --- @type integer?
273      -- When jumping forwards, $0 is the last tabstop.
274      if not dest_index and direction == 1 then
275        dest_index = 0
276      end
277      -- When jumping backwards, make sure we don't think that $0 is the first tabstop.
278      if dest_index == 0 and direction == -1 then
279        dest_index = nil
280      end
281      return dest_index
282    end
283  end
284end
285
286--- Sets the right gravity for all the tabstops.
287---
288--- @package
289function Session:set_gravity()
290  local index = self.current_tabstop.index
291  local all_tabstop_placements = self.tabstop_placements
292  local dest_tabstop_placements = {}
293
294  for _, tabstop in ipairs(self.tabstops[index]) do
295    tabstop:set_gravity('expand')
296    table.insert(dest_tabstop_placements, tabstop.placement)
297  end
298
299  for i, tabstops in pairs(self.tabstops) do
300    if i ~= index then
301      for _, tabstop in ipairs(tabstops) do
302        local placement = tabstop.placement + 1
303        -- Check if there other tabstops directly adjacent
304        while
305          vim.list_contains(all_tabstop_placements, placement)
306          and not vim.list_contains(dest_tabstop_placements, placement)
307        do
308          placement = placement + 1
309        end
310
311        if vim.list_contains(dest_tabstop_placements, placement) then
312          tabstop:set_gravity('lock')
313        else
314          tabstop:set_gravity('shift')
315        end
316      end
317    end
318  end
319end
320
321local M = { _sessions = {} }
322
323--- Displays the choices for the given tabstop as completion items.
324---
325--- @param tabstop vim.snippet.Tabstop
326local function display_choices(tabstop)
327  assert(tabstop.choices, 'Tabstop has no choices')
328
329  local text = tabstop:get_text()
330  local found_text = false
331
332  local start_col = tabstop:get_range()[2] + 1
333  local matches = {} --- @type table[]
334  for _, choice in ipairs(tabstop.choices) do
335    if choice ~= text then
336      matches[#matches + 1] = { word = choice }
337    else
338      found_text = true
339    end
340  end
341
342  if found_text then
343    table.insert(matches, 1, text)
344  end
345
346  vim.defer_fn(function()
347    vim.fn.complete(start_col, matches)
348  end, 100)
349end
350
351--- Select the given tabstop range.
352---
353--- @param tabstop vim.snippet.Tabstop
354local function select_tabstop(tabstop)
355  --- @param keys string
356  local function feedkeys(keys)
357    keys = vim.api.nvim_replace_termcodes(keys, true, false, true)
358    vim.api.nvim_feedkeys(keys, 'n', true)
359  end
360
361  local range = tabstop:get_range()
362  local mode = vim.fn.mode()
363
364  if vim.fn.pumvisible() ~= 0 then
365    -- Close the choice completion menu if open.
366    vim.fn.complete(vim.fn.col('.'), {})
367  end
368
369  -- Move the cursor to the start of the tabstop.
370  vim.api.nvim_win_set_cursor(0, { range[1] + 1, range[2] })
371
372  -- For empty, choice and the final tabstops, start insert mode at the end of the range.
373  if tabstop.choices or tabstop.index == 0 or (range[1] == range[3] and range[2] == range[4]) then
374    if mode ~= 'i' then
375      if mode == 's' then
376        feedkeys('<Esc>')
377      end
378      vim.cmd.startinsert({ bang = range[4] >= #vim.api.nvim_get_current_line() })
379    end
380    if tabstop.choices then
381      vim.fn.cursor(range[3] + 1, range[4] + 1)
382      display_choices(tabstop)
383    end
384  else
385    -- Else, select the tabstop's text.
386    -- Need this exact order so cannot mix regular API calls with feedkeys, which
387    -- are not executed immediately. Use <Cmd> to set the cursor position.
388    local keys = {
389      mode ~= 'n' and '<Esc>' or '',
390      ('<Cmd>call cursor(%s,%s)<CR>'):format(range[1] + 1, range[2] + 1),
391      'v',
392      ('<Cmd>call cursor(%s,%s)<CR>'):format(range[3] + 1, range[4]),
393      'o<c-g><c-r>_',
394    }
395    feedkeys(table.concat(keys))
396  end
397end
398
399--- Sets up the necessary autocommands for snippet expansion.
400---
401--- @param bufnr integer
402local function setup_autocmds(bufnr)
403  local nvim_on = require('vim._core.util').nvim_on
404  nvim_on({ 'CursorMoved', 'CursorMovedI' }, snippet_group, {
405    desc = 'Update snippet state when the cursor moves',
406    buf = bufnr,
407  }, function()
408    -- Just update the tabstop in insert and select modes.
409    if not vim.fn.mode():match('^[isS]') then
410      return
411    end
412
413    local cursor_row, cursor_col = cursor_pos()
414
415    -- The cursor left the snippet region.
416    local snippet_range = get_extmark_range(bufnr, M._session.extmark_id)
417    if
418      cursor_row < snippet_range[1]
419      or (cursor_row == snippet_range[1] and cursor_col < snippet_range[2])
420      or cursor_row > snippet_range[3]
421      or (cursor_row == snippet_range[3] and cursor_col > snippet_range[4])
422    then
423      M.stop()
424      return true
425    end
426
427    for tabstop_index, tabstops in pairs(M._session.tabstops) do
428      for _, tabstop in ipairs(tabstops) do
429        local range = tabstop:get_range()
430        if
431          (cursor_row > range[1] or (cursor_row == range[1] and cursor_col >= range[2]))
432          and (cursor_row < range[3] or (cursor_row == range[3] and cursor_col <= range[4]))
433        then
434          if tabstop_index ~= 0 then
435            return
436          end
437        end
438      end
439    end
440
441    -- The cursor is either not on a tabstop or we reached the end, so exit the session.
442    M.stop()
443    return true
444  end)
445
446  nvim_on({ 'TextChanged', 'TextChangedI', 'TextChangedP' }, snippet_group, {
447    desc = 'Update active tabstops when buffer text changes',
448    buf = bufnr,
449  }, function()
450    -- Check that the snippet hasn't been deleted.
451    local snippet_range = get_extmark_range(M._session.bufnr, M._session.extmark_id)
452    if
453      (snippet_range[1] == snippet_range[3] and snippet_range[2] == snippet_range[4])
454      or snippet_range[3] + 1 > vim.fn.line('$')
455    then
456      M.stop()
457    end
458
459    if not M.active() then
460      return true
461    end
462
463    -- Sync the tabstops in the current group.
464    local current_tabstop = M._session.current_tabstop
465    local current_text = current_tabstop:get_text()
466    for _, tabstop in ipairs(M._session.tabstops[current_tabstop.index]) do
467      if tabstop.extmark_id ~= current_tabstop.extmark_id then
468        tabstop:set_text(current_text)
469      end
470    end
471  end)
472
473  nvim_on('BufLeave', snippet_group, {
474    desc = 'Stop the snippet session when leaving the buffer',
475    buf = bufnr,
476  }, function()
477    M.stop()
478  end)
479
480  nvim_on('ModeChanged', snippet_group, {
481    desc = 'Stop the snippet session when leaving select mode',
482    buf = bufnr,
483  }, function(args)
484    if args.match ~= 's:n' and args.match ~= 'i:n' then
485      return
486    end
487    vim.schedule(function()
488      if not M.active() or vim.api.nvim_get_mode().mode:match('^[siRS\19]') then
489        return
490      end
491      M.stop()
492    end)
493  end)
494end
495
496--- Expands the given snippet text.
497--- Refer to https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax
498--- for the specification of valid input.
499---
500--- Tabstops are highlighted with |hl-SnippetTabstop| and |hl-SnippetTabstopActive|.
501---
502--- @param input string
503function M.expand(input)
504  local snippet = G.parse(input)
505  local snippet_text = {}
506  ---@type string
507  local base_indent = vim.api.nvim_get_current_line():match('^%s*') or ''
508
509  -- Get the placeholders we should use for each tabstop index.
510  --- @type table<integer, string>
511  local placeholders = {}
512  for _, child in ipairs(snippet.data.children) do
513    local type, data = child.type, child.data
514    if type == G.NodeType.Placeholder then
515      --- @cast data vim.snippet.PlaceholderData
516      local tabstop, value = data.tabstop, tostring(data.value)
517      if placeholders[tabstop] and placeholders[tabstop] ~= value then
518        error('Snippet has multiple placeholders for tabstop $' .. tabstop)
519      end
520      placeholders[tabstop] = value
521    end
522  end
523
524  -- Keep track of tabstop nodes during expansion.
525  --- @type table<integer, { placement: integer, range: Range4, choices?: string[] }[]>
526  local tabstop_data = {}
527
528  --- @param placement integer
529  --- @param index integer
530  --- @param placeholder? string
531  --- @param choices? string[]
532  local function add_tabstop(placement, index, placeholder, choices)
533    tabstop_data[index] = tabstop_data[index] or {}
534    local range = compute_tabstop_range(snippet_text, placeholder)
535    table.insert(tabstop_data[index], { placement = placement, range = range, choices = choices })
536  end
537
538  --- Appends the given text to the snippet, taking care of indentation.
539  ---
540  --- @param text string|string[]
541  local function append_to_snippet(text)
542    local shiftwidth = vim.fn.shiftwidth()
543    local curbuf = vim.api.nvim_get_current_buf()
544    local expandtab = vim.bo[curbuf].expandtab
545
546    local lines = {} --- @type string[]
547    for i, line in ipairs(text_to_lines(text)) do
548      -- Replace tabs by spaces.
549      if expandtab then
550        line = line:gsub('\t', (' '):rep(shiftwidth)) --- @type string
551      end
552      -- Add the base indentation.
553      if i > 1 then
554        line = base_indent .. line
555      end
556      lines[#lines + 1] = line
557    end
558
559    table.insert(snippet_text, table.concat(lines, '\n'))
560  end
561
562  for index, child in ipairs(snippet.data.children) do
563    local type, data = child.type, child.data
564    if type == G.NodeType.Tabstop then
565      --- @cast data vim.snippet.TabstopData
566      local placeholder = placeholders[data.tabstop]
567      add_tabstop(index, data.tabstop, placeholder)
568      if placeholder then
569        append_to_snippet(placeholder)
570      end
571    elseif type == G.NodeType.Placeholder then
572      --- @cast data vim.snippet.PlaceholderData
573      local value = placeholders[data.tabstop]
574      add_tabstop(index, data.tabstop, value)
575      append_to_snippet(value)
576    elseif type == G.NodeType.Choice then
577      --- @cast data vim.snippet.ChoiceData
578      add_tabstop(index, data.tabstop, nil, data.values)
579    elseif type == G.NodeType.Variable then
580      --- @cast data vim.snippet.VariableData
581      -- Try to get the variable's value.
582      local value = resolve_variable(data.name, data.default and tostring(data.default) or '')
583      if not value then
584        -- Unknown variable, make this a tabstop and use the variable name as a placeholder.
585        value = data.name
586        local tabstop_indexes = vim.tbl_keys(tabstop_data)
587        local tabstop_index = math.max(unpack((#tabstop_indexes == 0 and { 0 }) or tabstop_indexes))
588          + 1
589        add_tabstop(index, tabstop_index, value)
590      end
591      append_to_snippet(value)
592    elseif type == G.NodeType.Text then
593      --- @cast data vim.snippet.TextData
594      append_to_snippet(data.text)
595    end
596  end
597
598  -- $0, which defaults to the end of the snippet, defines the final cursor position.
599  -- Make sure the snippet has exactly one of these.
600  if vim.tbl_contains(vim.tbl_keys(tabstop_data), 0) then
601    assert(#tabstop_data[0] == 1, 'Snippet has multiple $0 tabstops')
602  else
603    add_tabstop(#snippet.data.children + 1, 0)
604  end
605
606  snippet_text = text_to_lines(snippet_text)
607
608  -- Insert the snippet text.
609  local bufnr = vim.api.nvim_get_current_buf()
610  local cursor_row, cursor_col = cursor_pos()
611  vim.api.nvim_buf_set_text(bufnr, cursor_row, cursor_col, cursor_row, cursor_col, snippet_text)
612
613  -- Create the session.
614  local snippet_extmark = vim.api.nvim_buf_set_extmark(bufnr, snippet_ns, cursor_row, cursor_col, {
615    end_line = cursor_row + #snippet_text - 1,
616    end_col = #snippet_text > 1 and #snippet_text[#snippet_text] or cursor_col + #snippet_text[1],
617    right_gravity = false,
618    end_right_gravity = true,
619  })
620  M._session = Session.new(bufnr, snippet_extmark, tabstop_data)
621  table.insert(M._sessions, M._session)
622
623  -- Jump to the first tabstop.
624  M.jump(1)
625end
626
627--- @alias vim.snippet.Direction -1 | 1
628
629--- Jumps to the next (or previous) placeholder in the current snippet, if possible.
630---
631--- By default `<Tab>` is setup to jump if a snippet is active. The default mapping looks like:
632---
633--- ```lua
634--- vim.keymap.set({ 'i', 's' }, '<Tab>', function()
635---    if vim.snippet.active({ direction = 1 }) then
636---      return '<Cmd>lua vim.snippet.jump(1)<CR>'
637---    else
638---      return '<Tab>'
639---    end
640---  end, { desc = '...', expr = true, silent = true })
641--- ```
642---
643--- @param direction (vim.snippet.Direction) Navigation direction. -1 for previous, 1 for next.
644function M.jump(direction)
645  -- Get the tabstop index to jump to.
646  local dest_index = M._session and M._session:get_dest_index(direction)
647  if not dest_index then
648    return
649  end
650
651  -- Find the tabstop with the lowest range.
652  local tabstops = M._session.tabstops[dest_index]
653  local dest = assert(tabstops[1])
654  for _, tabstop in ipairs(tabstops) do
655    local dest_range, range = dest:get_range(), tabstop:get_range()
656    if (range[1] < dest_range[1]) or (range[1] == dest_range[1] and range[2] < dest_range[2]) then
657      dest = tabstop
658    end
659  end
660
661  -- Clear the autocommands so that we can move the cursor freely while selecting the tabstop.
662  vim.api.nvim_clear_autocmds({ group = snippet_group, buf = M._session.bufnr })
663
664  M._session.current_tabstop = dest
665  M._session:set_gravity()
666  select_tabstop(dest)
667
668  -- The cursor is not on a tabstop so exit the session.
669  if dest.index == 0 then
670    M.stop()
671    return
672  end
673
674  -- Restore the autocommands.
675  setup_autocmds(M._session.bufnr)
676end
677
678--- @class vim.snippet.ActiveFilter
679--- @field direction vim.snippet.Direction Navigation direction. -1 for previous, 1 for next.
680
681--- Returns `true` if there's an active snippet in the current buffer,
682--- applying the given filter if provided.
683---
684--- @param filter? vim.snippet.ActiveFilter Filter to constrain the search with:
685--- - `direction` (vim.snippet.Direction): Navigation direction. Will return `true` if the snippet
686--- can be jumped in the given direction.
687--- @return boolean
688function M.active(filter)
689  local active = M._session ~= nil and M._session.bufnr == vim.api.nvim_get_current_buf()
690
691  local in_direction = true
692  if active and filter and filter.direction then
693    in_direction = M._session:get_dest_index(filter.direction) ~= nil
694  end
695
696  return active and in_direction
697end
698
699--- Exits the current snippet.
700function M.stop()
701  if not M.active() then
702    return
703  end
704
705  if #M._sessions == 1 then
706    vim.api.nvim_clear_autocmds({ group = snippet_group, buf = M._session.bufnr })
707    vim.api.nvim_buf_clear_namespace(M._session.bufnr, snippet_ns, 0, -1)
708  end
709
710  table.remove(M._sessions)
711  M._session = #M._sessions > 0 and M._sessions[#M._sessions] or nil
712end
713
714return M