Skip to content

Commit 3d2fd90

Browse files
feat: add sort_by "filetype" (#2302)
* feat: adds new type of sorting based on vim's filetype detection * fix(ft/sorter): fallbacks to C.name when both ft's are nil or equal * feat: adds new type of sorting based on vim's filetype detection --------- Co-authored-by: Alexander Courtis <alex@courtis.org>
1 parent 4af5722 commit 3d2fd90

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

doc/nvim-tree-lua.txt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -568,15 +568,16 @@ Reloads the explorer every time a buffer is written to.
568568

569569
*nvim-tree.sort_by*
570570
Changes how files within the same directory are sorted.
571-
Can be one of `name`, `case_sensitive`, `modification_time`, `extension` or a
572-
function.
571+
Can be one of `name`, `case_sensitive`, `modification_time`, `extension`,
572+
`filetype` or a function.
573573
Type: `string` | `function(nodes)`, Default: `"name"`
574574

575575
Function may perform a sort or return a string with one of the above
576576
methods. It is passed a table of nodes to be sorted, each node containing:
577577
- `absolute_path`: `string`
578578
- `executable`: `boolean`
579579
- `extension`: `string`
580+
- `filetype`: `string`
580581
- `link_to`: `string`
581582
- `name`: `string`
582583
- `type`: `"directory"` | `"file"` | `"link"`

lua/nvim-tree/explorer/sorters.lua

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ function M.sort(t)
8080
absolute_path = n.absolute_path,
8181
executable = n.executable,
8282
extension = n.extension,
83+
filetype = vim.filetype.match { filename = n.name },
8384
link_to = n.link_to,
8485
name = n.name,
8586
type = n.type,
@@ -191,6 +192,32 @@ function C.extension(a, b)
191192
return a.extension:lower() <= b.extension:lower()
192193
end
193194

195+
function C.filetype(a, b)
196+
local a_ft = vim.filetype.match { filename = a.name }
197+
local b_ft = vim.filetype.match { filename = b.name }
198+
199+
-- directories first
200+
if a.nodes and not b.nodes then
201+
return true
202+
elseif not a.nodes and b.nodes then
203+
return false
204+
end
205+
206+
-- one is nil, the other wins
207+
if a_ft and not b_ft then
208+
return true
209+
elseif not a_ft and b_ft then
210+
return false
211+
end
212+
213+
-- same filetype or both nil, sort by name
214+
if a_ft == b_ft then
215+
return C.name(a, b)
216+
end
217+
218+
return a_ft < b_ft
219+
end
220+
194221
function M.setup(opts)
195222
M.config = {}
196223
M.config.sort_by = opts.sort_by

0 commit comments

Comments
 (0)