Skip to content

feat: add sort_by "filetype" #2302

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions doc/nvim-tree-lua.txt
Original file line number Diff line number Diff line change
Expand Up @@ -568,15 +568,16 @@ Reloads the explorer every time a buffer is written to.

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

Function may perform a sort or return a string with one of the above
methods. It is passed a table of nodes to be sorted, each node containing:
- `absolute_path`: `string`
- `executable`: `boolean`
- `extension`: `string`
- `filetype`: `string`
- `link_to`: `string`
- `name`: `string`
- `type`: `"directory"` | `"file"` | `"link"`
Expand Down
27 changes: 27 additions & 0 deletions lua/nvim-tree/explorer/sorters.lua
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ function M.sort(t)
absolute_path = n.absolute_path,
executable = n.executable,
extension = n.extension,
filetype = vim.filetype.match { filename = n.name },
link_to = n.link_to,
name = n.name,
type = n.type,
Expand Down Expand Up @@ -191,6 +192,32 @@ function C.extension(a, b)
return a.extension:lower() <= b.extension:lower()
end

function C.filetype(a, b)
local a_ft = vim.filetype.match { filename = a.name }
local b_ft = vim.filetype.match { filename = b.name }

-- directories first
if a.nodes and not b.nodes then
return true
elseif not a.nodes and b.nodes then
return false
end

-- one is nil, the other wins
if a_ft and not b_ft then
return true
elseif not a_ft and b_ft then
return false
end

-- same filetype or both nil, sort by name
if a_ft == b_ft then
return C.name(a, b)
end

return a_ft < b_ft
end

function M.setup(opts)
M.config = {}
M.config.sort_by = opts.sort_by
Expand Down