Skip to content

Commit

Permalink
ft_func: translate treesitter-language to filetypes (close #1174).
Browse files Browse the repository at this point in the history
Sometimes the treesitter-language-name coincides with the filetype (like for cpp), but in other cases, these are wholly different (lang: latex, filetype: tex/sty/cls). So, to be more accomodating and forego the need on the users part to define the correct `ls.filetype_extend`, we resolve language to filetypes in here.
  • Loading branch information
leiserfg authored May 17, 2024
1 parent 78296bf commit 03c607c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 12 deletions.
2 changes: 1 addition & 1 deletion doc/luasnip.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
*luasnip.txt* For NVIM v0.8.0 Last change: 2024 May 16
*luasnip.txt* For NVIM v0.8.0 Last change: 2024 May 17

==============================================================================
Table of Contents *luasnip-table-of-contents*
Expand Down
34 changes: 23 additions & 11 deletions lua/luasnip/extras/filetype_functions.lua
Original file line number Diff line number Diff line change
@@ -1,27 +1,39 @@
local function fts_from_ts_lang(lang)
local fts = {}
-- In case of someone using nvim <= 0.9
if vim.treesitter.language and vim.treesitter.language.get_filetypes then
fts = vim.treesitter.language.get_filetypes(lang)
end
-- Keep lang as part of the result, for backward compatibility
if not vim.list_contains(fts, lang) then
table.insert(fts, lang)
end
return fts
end

local function from_cursor_pos()
-- get_parser errors if parser not present (no grammar for language).
local has_parser, parser = pcall(vim.treesitter.get_parser)

if has_parser then
local cursor = require("luasnip.util.util").get_cursor_0ind()
-- assumption: languagetree uses 0-indexed byte-ranges.
return {
parser
:language_for_range({
cursor[1],
cursor[2],
cursor[1],
cursor[2],
})
:lang(),
}
local lang = parser
:language_for_range({
cursor[1],
cursor[2],
cursor[1],
cursor[2],
})
:lang()
return fts_from_ts_lang(lang)
else
return {}
end
end

local function from_filetype()
return vim.split(vim.bo.filetype, ".", true)
return vim.split(vim.bo.filetype, ".", { plain = true, trimemtpy = false })
end

-- NOTE: Beware that the resulting filetypes may differ from the ones in `vim.bo.filetype`. (for
Expand Down

0 comments on commit 03c607c

Please sign in to comment.