diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index e29383c..f398353 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -17,3 +17,14 @@ jobs: - name: Lint run: sudo make lint + + stylua: + name: stylua + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + - uses: JohnnyMorganz/stylua-action@1.0.0 + with: + token: ${{ secrets.GITHUB_TOKEN }} + # CLI arguments + args: --color always --check lua/ diff --git a/.stylua.toml b/.stylua.toml new file mode 100644 index 0000000..df96b7b --- /dev/null +++ b/.stylua.toml @@ -0,0 +1,6 @@ +column_width = 120 +line_endings = "Unix" +indent_type = "Spaces" +indent_width = 2 +quote_style = "AutoPreferDouble" +no_call_parentheses = true diff --git a/lua/telescope/WIP.lua b/lua/telescope/WIP.lua index cacb438..a01b3eb 100644 --- a/lua/telescope/WIP.lua +++ b/lua/telescope/WIP.lua @@ -1,18 +1,17 @@ - -local make_entry = require('telescope.make_entry') -local actions = require('telescope.actions') -local action_state = require('telescope.actions.state') -local finders = require('telescope.finders') -local previewers = require('telescope.previewers') -local pickers = require('telescope.pickers') -local sorters = require('telescope.sorters') +local make_entry = require "telescope.make_entry" +local actions = require "telescope.actions" +local action_state = require "telescope.actions.state" +local finders = require "telescope.finders" +local previewers = require "telescope.previewers" +local pickers = require "telescope.pickers" +local sorters = require "telescope.sorters" local WIP = {} WIP.git_diff = function() local file_picker = pickers.new { previewer = previewers.new_termopen { - command = "git diff %s" + command = "git diff %s", }, } @@ -24,13 +23,13 @@ WIP.git_diff = function() fn_command = function() return { - command = 'git', - args = {'ls-files', '-m'} + command = "git", + args = { "ls-files", "-m" }, } end, }, - sorter = sorters.get_norcalli_sorter() + sorter = sorters.get_norcalli_sorter(), } end @@ -43,12 +42,12 @@ WIP.completion = function(opts) end local lsp_reference_finder = finders.new { - results = results + results = results, } -- TODO: Open the help text for the line. local reference_picker = pickers.new(opts, { - prompt = 'vim.api Help Reference', + prompt = "vim.api Help Reference", finder = lsp_reference_finder, sorter = sorters.get_norcalli_sorter(), previewer = previewers.help, @@ -57,12 +56,11 @@ WIP.completion = function(opts) reference_picker:find {} end - WIP.reloader = function(opts) opts = opts or {} pickers.new(opts, { - prompt = 'Packages', + prompt = "Packages", finder = finders.new_table { results = vim.tbl_keys(package.loaded), entry_maker = make_entry.gen_from_string(opts), @@ -78,11 +76,11 @@ WIP.reloader = function(opts) print(vim.inspect(selection)) end - map('i', '', reload_package) - map('n', '', reload_package) + map("i", "", reload_package) + map("n", "", reload_package) return true - end + end, }):find() end diff --git a/lua/telescope/_compat.lua b/lua/telescope/_compat.lua index 6253074..42a3dfd 100644 --- a/lua/telescope/_compat.lua +++ b/lua/telescope/_compat.lua @@ -21,7 +21,7 @@ vim.deepcopy = (function() return copy end, - ['function'] = _id or function(orig) + ["function"] = _id or function(orig) local ok, dumped = pcall(string.dump, orig) if not ok then error(debug.traceback(dumped)) @@ -41,7 +41,7 @@ vim.deepcopy = (function() end, number = _id, string = _id, - ['nil'] = _id, + ["nil"] = _id, boolean = _id, } @@ -50,7 +50,7 @@ vim.deepcopy = (function() if f then return f(orig) else - error("Cannot deepcopy object of type "..type(orig)) + error("Cannot deepcopy object of type " .. type(orig)) end end end)() diff --git a/lua/telescope/_extensions/init.lua b/lua/telescope/_extensions/init.lua index b2775dc..4204c3f 100644 --- a/lua/telescope/_extensions/init.lua +++ b/lua/telescope/_extensions/init.lua @@ -6,13 +6,13 @@ extensions._config = {} extensions.manager = setmetatable({}, { __index = function(t, k) -- See if this extension exists. - local ok, ext = pcall(require, 'telescope._extensions.' .. k) + local ok, ext = pcall(require, "telescope._extensions." .. k) if not ok then error("This extension doesn't exist or is not installed: " .. k .. "\n" .. ext) end if ext.setup then - ext.setup(extensions._config[k] or {}, require('telescope.config').values) + ext.setup(extensions._config[k] or {}, require("telescope.config").values) end t[k] = ext.exports or {} diff --git a/lua/telescope/actions/history.lua b/lua/telescope/actions/history.lua index 48a24ca..c4eb8c8 100644 --- a/lua/telescope/actions/history.lua +++ b/lua/telescope/actions/history.lua @@ -1,5 +1,5 @@ -local conf = require('telescope.config').values -local Path = require('plenary.path') +local conf = require("telescope.config").values +local Path = require "plenary.path" local uv = vim.loop @@ -37,7 +37,9 @@ local write_async = function(path, txt, flag) end) end -local append_async = function(path, txt) write_async(path, txt, "a") end +local append_async = function(path, txt) + write_async(path, txt, "a") +end local histories = {} @@ -86,7 +88,9 @@ end --- Will reset the history index to the default initial state. Will happen after the picker closed function histories.History:reset() - if not self.enabled then return end + if not self.enabled then + return + end self._reset(self) end @@ -95,7 +99,9 @@ end ---@param picker table: the current picker object ---@param no_reset boolean: On default it will reset the state at the end. If you don't want to do this set to true function histories.History:append(line, picker, no_reset) - if not self.enabled then return end + if not self.enabled then + return + end self._append(self, line, picker, no_reset) end @@ -105,11 +111,15 @@ end ---@return string: the next history item function histories.History:get_next(line, picker) if not self.enabled then - print("You are cycling to next the history item but history is disabled.", - "Read ':help telescope.defaults.history'") + print( + "You are cycling to next the history item but history is disabled.", + "Read ':help telescope.defaults.history'" + ) return false end - if self._pre_get then self._pre_get(self, line, picker) end + if self._pre_get then + self._pre_get(self, line, picker) + end local next_idx = self.index + 1 if next_idx <= #self.content then @@ -126,15 +136,21 @@ end ---@return string: the previous history item function histories.History:get_prev(line, picker) if not self.enabled then - print("You are cycling to previous the history item but history is disabled.", - "Read ':help telescope.defaults.history'") + print( + "You are cycling to previous the history item but history is disabled.", + "Read ':help telescope.defaults.history'" + ) return false end - if self._pre_get then self._pre_get(self, line, picker) end + if self._pre_get then + self._pre_get(self, line, picker) + end local next_idx = self.index - 1 if self.index == #self.content + 1 then - if line ~= '' then self:append(line, picker, true) end + if line ~= "" then + self:append(line, picker, true) + end end if next_idx >= 1 then self.index = next_idx @@ -147,10 +163,12 @@ end --- --- It will keep one unified history across all pickers. histories.get_simple_history = function() - return histories.new({ + return histories.new { init = function(obj) local p = Path:new(obj.path) - if not p:exists() then p:touch({ parents = true }) end + if not p:exists() then + p:touch { parents = true } + end obj.content = Path:new(obj.path):readlines() obj.index = #obj.content @@ -160,7 +178,7 @@ histories.get_simple_history = function() self.index = #self.content + 1 end, append = function(self, line, _, no_reset) - if line ~= '' then + if line ~= "" then if self.content[#self.content] ~= line then table.insert(self.content, line) @@ -170,9 +188,9 @@ histories.get_simple_history = function() for i = diff, 1, -1 do table.remove(self.content, i) end - write_async(self.path, table.concat(self.content, '\n') .. '\n', 'w') + write_async(self.path, table.concat(self.content, "\n") .. "\n", "w") else - append_async(self.path, line .. '\n') + append_async(self.path, line .. "\n") end end end @@ -180,7 +198,7 @@ histories.get_simple_history = function() self:reset() end end, - }) + } end return histories diff --git a/lua/telescope/actions/init.lua b/lua/telescope/actions/init.lua index 929622d..7e61e63 100644 --- a/lua/telescope/actions/init.lua +++ b/lua/telescope/actions/init.lua @@ -9,30 +9,36 @@ local a = vim.api -local log = require('telescope.log') -local state = require('telescope.state') -local utils = require('telescope.utils') -local p_scroller = require('telescope.pickers.scroller') +local log = require "telescope.log" +local state = require "telescope.state" +local utils = require "telescope.utils" +local p_scroller = require "telescope.pickers.scroller" -local action_state = require('telescope.actions.state') -local action_utils = require('telescope.actions.utils') -local action_set = require('telescope.actions.set') +local action_state = require "telescope.actions.state" +local action_utils = require "telescope.actions.utils" +local action_set = require "telescope.actions.set" -local transform_mod = require('telescope.actions.mt').transform_mod +local transform_mod = require("telescope.actions.mt").transform_mod local actions = setmetatable({}, { __index = function(_, k) -- TODO(conni2461): Remove deprecated messages - if k:find('goto_file_selection') then - error("`" .. k .. "` is removed and no longer usable. " .. - "Use `require('telescope.actions').select_` instead. Take a look at developers.md for more Information.") - elseif k == '_goto_file_selection' then - error("`_goto_file_selection` is deprecated and no longer replaceable. " .. - "Use `require('telescope.actions.set').edit` instead. Take a look at developers.md for more Information.") + if k:find "goto_file_selection" then + error( + "`" + .. k + .. "` is removed and no longer usable. " + .. "Use `require('telescope.actions').select_` instead. Take a look at developers.md for more Information." + ) + elseif k == "_goto_file_selection" then + error( + "`_goto_file_selection` is deprecated and no longer replaceable. " + .. "Use `require('telescope.actions.set').edit` instead. Take a look at developers.md for more Information." + ) end error("Key does not exist for 'telescope.actions': " .. tostring(k)) - end + end, }) -- TODO(conni2461): Remove deprecated messages @@ -40,29 +46,25 @@ local action_is_deprecated = function(name, err) local messager = err and error or log.info return messager( - string.format("`actions.%s()` is deprecated." - .. "Use require('telescope.actions.state').%s() instead", - name, - name - ) + string.format("`actions.%s()` is deprecated." .. "Use require('telescope.actions.state').%s() instead", name, name) ) end function actions.get_selected_entry() -- TODO(1.0): Remove - action_is_deprecated("get_selected_entry") + action_is_deprecated "get_selected_entry" return action_state.get_selected_entry() end function actions.get_current_line() -- TODO(1.0): Remove - action_is_deprecated("get_current_line") + action_is_deprecated "get_current_line" return action_state.get_current_line() end function actions.get_current_picker(prompt_bufnr) -- TODO(1.0): Remove - action_is_deprecated("get_current_picker") + action_is_deprecated "get_current_picker" return action_state.get_current_picker(prompt_bufnr) end @@ -96,31 +98,27 @@ end ---@param prompt_bufnr number: The prompt bufnr function actions.move_to_top(prompt_bufnr) local current_picker = actions.get_current_picker(prompt_bufnr) - current_picker:set_selection(p_scroller.top(current_picker.sorting_strategy, - current_picker.max_results, - current_picker.manager:num_results() - )) + current_picker:set_selection( + p_scroller.top(current_picker.sorting_strategy, current_picker.max_results, current_picker.manager:num_results()) + ) end --- Move to the middle of the picker ---@param prompt_bufnr number: The prompt bufnr function actions.move_to_middle(prompt_bufnr) local current_picker = actions.get_current_picker(prompt_bufnr) - current_picker:set_selection(p_scroller.middle( - current_picker.sorting_strategy, - current_picker.max_results, - current_picker.manager:num_results() - )) + current_picker:set_selection( + p_scroller.middle(current_picker.sorting_strategy, current_picker.max_results, current_picker.manager:num_results()) + ) end --- Move to the bottom of the picker ---@param prompt_bufnr number: The prompt bufnr function actions.move_to_bottom(prompt_bufnr) local current_picker = actions.get_current_picker(prompt_bufnr) - current_picker:set_selection(p_scroller.bottom(current_picker.sorting_strategy, - current_picker.max_results, - current_picker.manager:num_results() - )) + current_picker:set_selection( + p_scroller.bottom(current_picker.sorting_strategy, current_picker.max_results, current_picker.manager:num_results()) + ) end --- Add current entry to multi select @@ -193,7 +191,7 @@ function actions.preview_scrolling_down(prompt_bufnr) end function actions.center(_) - vim.cmd(':normal! zz') + vim.cmd ":normal! zz" end actions.select_default = { @@ -205,7 +203,7 @@ actions.select_default = { end, action = function(prompt_bufnr) return action_set.select(prompt_bufnr, "default") - end + end, } actions.select_horizontal = { @@ -217,7 +215,7 @@ actions.select_horizontal = { end, action = function(prompt_bufnr) return action_set.select(prompt_bufnr, "horizontal") - end + end, } actions.select_vertical = { @@ -229,7 +227,7 @@ actions.select_vertical = { end, action = function(prompt_bufnr) return action_set.select(prompt_bufnr, "vertical") - end + end, } actions.select_tab = { @@ -241,7 +239,7 @@ actions.select_tab = { end, action = function(prompt_bufnr) return action_set.select(prompt_bufnr, "tab") - end + end, } -- TODO: consider adding float! @@ -265,7 +263,7 @@ end function actions.close_pum(_) if 0 ~= vim.fn.pumvisible() then - vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("", true, true, true), 'n', true) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("", true, true, true), "n", true) end end @@ -299,7 +297,7 @@ end actions.edit_command_line = function(prompt_bufnr) local entry = action_state.get_selected_entry(prompt_bufnr) actions.close(prompt_bufnr) - a.nvim_feedkeys(a.nvim_replace_termcodes(":" .. entry.value , true, false, true), "t", true) + a.nvim_feedkeys(a.nvim_replace_termcodes(":" .. entry.value, true, false, true), "t", true) end actions.set_command_line = function(prompt_bufnr) @@ -313,7 +311,7 @@ end actions.edit_search_line = function(prompt_bufnr) local entry = action_state.get_selected_entry(prompt_bufnr) actions.close(prompt_bufnr) - a.nvim_feedkeys(a.nvim_replace_termcodes("/" .. entry.value , true, false, true), "t", true) + a.nvim_feedkeys(a.nvim_replace_termcodes("/" .. entry.value, true, false, true), "t", true) end actions.set_search_line = function(prompt_bufnr) @@ -352,7 +350,7 @@ actions.paste_register = function(prompt_bufnr) -- ensure that the buffer can be written to if vim.api.nvim_buf_get_option(vim.api.nvim_get_current_buf(), "modifiable") then - print("Paste!") + print "Paste!" vim.api.nvim_paste(entry.content, true, -1) end end @@ -361,22 +359,22 @@ actions.run_builtin = function(prompt_bufnr) local entry = action_state.get_selected_entry(prompt_bufnr) actions._close(prompt_bufnr, true) - if string.match(entry.text," : ") then + if string.match(entry.text, " : ") then -- Call appropriate function from extensions - local split_string = vim.split(entry.text," : ") + local split_string = vim.split(entry.text, " : ") local ext = split_string[1] local func = split_string[2] - require('telescope').extensions[ext][func]() + require("telescope").extensions[ext][func]() else -- Call appropriate telescope builtin - require('telescope.builtin')[entry.text]() + require("telescope.builtin")[entry.text]() end end actions.insert_symbol = function(prompt_bufnr) local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - vim.api.nvim_put({selection.value[1]}, '', true, true) + vim.api.nvim_put({ selection.value[1] }, "", true, true) end -- TODO: Think about how to do this. @@ -397,25 +395,23 @@ actions.git_create_branch = function(prompt_bufnr) local new_branch = action_state.get_current_line() if new_branch == "" then - print('Please enter the name of the new branch to create') + print "Please enter the name of the new branch to create" else local confirmation = vim.fn.input(string.format('Create new branch "%s"? [y/n]: ', new_branch)) - if string.len(confirmation) == 0 or string.sub(string.lower(confirmation), 0, 1) ~= 'y' then + if string.len(confirmation) == 0 or string.sub(string.lower(confirmation), 0, 1) ~= "y" then print(string.format('Didn\'t create branch "%s"', new_branch)) return end actions.close(prompt_bufnr) - local _, ret, stderr = utils.get_os_command_output({ 'git', 'checkout', '-b', new_branch }, cwd) + local _, ret, stderr = utils.get_os_command_output({ "git", "checkout", "-b", new_branch }, cwd) if ret == 0 then - print(string.format('Switched to a new branch: %s', new_branch)) + print(string.format("Switched to a new branch: %s", new_branch)) else - print(string.format( - 'Error when creating new branch: %s Git returned "%s"', - new_branch, - table.concat(stderr, ' ') - )) + print( + string.format('Error when creating new branch: %s Git returned "%s"', new_branch, table.concat(stderr, " ")) + ) end end end @@ -425,15 +421,11 @@ end actions.git_apply_stash = function(prompt_bufnr) local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - local _, ret, stderr = utils.get_os_command_output({ 'git', 'stash', 'apply', '--index', selection.value }) + local _, ret, stderr = utils.get_os_command_output { "git", "stash", "apply", "--index", selection.value } if ret == 0 then print("applied: " .. selection.value) else - print(string.format( - 'Error when applying: %s. Git returned: "%s"', - selection.value, - table.concat(stderr, ' ') - )) + print(string.format('Error when applying: %s. Git returned: "%s"', selection.value, table.concat(stderr, " "))) end end @@ -443,15 +435,11 @@ actions.git_checkout = function(prompt_bufnr) local cwd = action_state.get_current_picker(prompt_bufnr).cwd local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - local _, ret, stderr = utils.get_os_command_output({ 'git', 'checkout', selection.value }, cwd) + local _, ret, stderr = utils.get_os_command_output({ "git", "checkout", selection.value }, cwd) if ret == 0 then print("Checked out: " .. selection.value) else - print(string.format( - 'Error when checking out: %s. Git returned: "%s"', - selection.value, - table.concat(stderr, ' ') - )) + print(string.format('Error when checking out: %s. Git returned: "%s"', selection.value, table.concat(stderr, " "))) end end @@ -463,20 +451,16 @@ actions.git_switch_branch = function(prompt_bufnr) local cwd = action_state.get_current_picker(prompt_bufnr).cwd local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - local pattern = '^refs/remotes/%w+/' + local pattern = "^refs/remotes/%w+/" local branch = selection.value if string.match(selection.refname, pattern) then - branch = string.gsub(selection.refname, pattern, '') + branch = string.gsub(selection.refname, pattern, "") end - local _, ret, stderr = utils.get_os_command_output({ 'git', 'switch', branch }, cwd) + local _, ret, stderr = utils.get_os_command_output({ "git", "switch", branch }, cwd) if ret == 0 then print("Switched to: " .. branch) else - print(string.format( - 'Error when switching to: %s. Git returned: "%s"', - selection.value, - table.concat(stderr, ' ') - )) + print(string.format('Error when switching to: %s. Git returned: "%s"', selection.value, table.concat(stderr, " "))) end end @@ -486,15 +470,13 @@ actions.git_track_branch = function(prompt_bufnr) local cwd = action_state.get_current_picker(prompt_bufnr).cwd local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - local _, ret, stderr = utils.get_os_command_output({ 'git', 'checkout', '--track', selection.value }, cwd) + local _, ret, stderr = utils.get_os_command_output({ "git", "checkout", "--track", selection.value }, cwd) if ret == 0 then print("Tracking branch: " .. selection.value) else - print(string.format( - 'Error when tracking branch: %s. Git returned: "%s"', - selection.value, - table.concat(stderr, ' ') - )) + print( + string.format('Error when tracking branch: %s. Git returned: "%s"', selection.value, table.concat(stderr, " ")) + ) end end @@ -504,19 +486,19 @@ actions.git_delete_branch = function(prompt_bufnr) local cwd = action_state.get_current_picker(prompt_bufnr).cwd local selection = action_state.get_selected_entry() - local confirmation = vim.fn.input('Do you really wanna delete branch ' .. selection.value .. '? [Y/n] ') - if confirmation ~= '' and string.lower(confirmation) ~= 'y' then return end + local confirmation = vim.fn.input("Do you really wanna delete branch " .. selection.value .. "? [Y/n] ") + if confirmation ~= "" and string.lower(confirmation) ~= "y" then + return + end actions.close(prompt_bufnr) - local _, ret, stderr = utils.get_os_command_output({ 'git', 'branch', '-D', selection.value }, cwd) + local _, ret, stderr = utils.get_os_command_output({ "git", "branch", "-D", selection.value }, cwd) if ret == 0 then print("Deleted branch: " .. selection.value) else - print(string.format( - 'Error when deleting branch: %s. Git returned: "%s"', - selection.value, - table.concat(stderr, ' ') - )) + print( + string.format('Error when deleting branch: %s. Git returned: "%s"', selection.value, table.concat(stderr, " ")) + ) end end @@ -526,19 +508,19 @@ actions.git_rebase_branch = function(prompt_bufnr) local cwd = action_state.get_current_picker(prompt_bufnr).cwd local selection = action_state.get_selected_entry() - local confirmation = vim.fn.input('Do you really wanna rebase branch ' .. selection.value .. '? [Y/n] ') - if confirmation ~= '' and string.lower(confirmation) ~= 'y' then return end + local confirmation = vim.fn.input("Do you really wanna rebase branch " .. selection.value .. "? [Y/n] ") + if confirmation ~= "" and string.lower(confirmation) ~= "y" then + return + end actions.close(prompt_bufnr) - local _, ret, stderr = utils.get_os_command_output({ 'git', 'rebase', selection.value }, cwd) + local _, ret, stderr = utils.get_os_command_output({ "git", "rebase", selection.value }, cwd) if ret == 0 then print("Rebased branch: " .. selection.value) else - print(string.format( - 'Error when rebasing branch: %s. Git returned: "%s"', - selection.value, - table.concat(stderr, ' ') - )) + print( + string.format('Error when rebasing branch: %s. Git returned: "%s"', selection.value, table.concat(stderr, " ")) + ) end end @@ -546,7 +528,7 @@ actions.git_checkout_current_buffer = function(prompt_bufnr) local cwd = actions.get_current_picker(prompt_bufnr).cwd local selection = actions.get_selected_entry() actions.close(prompt_bufnr) - utils.get_os_command_output({ 'git', 'checkout', selection.value, '--', selection.file }, cwd) + utils.get_os_command_output({ "git", "checkout", selection.value, "--", selection.file }, cwd) end --- Stage/unstage selected file @@ -555,10 +537,10 @@ actions.git_staging_toggle = function(prompt_bufnr) local cwd = action_state.get_current_picker(prompt_bufnr).cwd local selection = action_state.get_selected_entry() - if selection.status:sub(2) == ' ' then - utils.get_os_command_output({ 'git', 'restore', '--staged', selection.value }, cwd) + if selection.status:sub(2) == " " then + utils.get_os_command_output({ "git", "restore", "--staged", selection.value }, cwd) else - utils.get_os_command_output({ 'git', 'add', selection.value }, cwd) + utils.get_os_command_output({ "git", "add", selection.value }, cwd) end end @@ -582,7 +564,7 @@ local send_selected_to_qf = function(prompt_bufnr, mode, target) actions.close(prompt_bufnr) - if target == 'loclist' then + if target == "loclist" then vim.fn.setloclist(picker.original_win_id, qf_entries, mode) else vim.fn.setqflist(qf_entries, mode) @@ -600,7 +582,7 @@ local send_all_to_qf = function(prompt_bufnr, mode, target) actions.close(prompt_bufnr) - if target == 'loclist' then + if target == "loclist" then vim.fn.setloclist(picker.original_win_id, qf_entries, mode) else vim.fn.setqflist(qf_entries, mode) @@ -609,42 +591,42 @@ end --- Sends the selected entries to the quickfix list, replacing the previous entries. actions.send_selected_to_qflist = function(prompt_bufnr) - send_selected_to_qf(prompt_bufnr, 'r') + send_selected_to_qf(prompt_bufnr, "r") end --- Adds the selected entries to the quickfix list, keeping the previous entries. actions.add_selected_to_qflist = function(prompt_bufnr) - send_selected_to_qf(prompt_bufnr, 'a') + send_selected_to_qf(prompt_bufnr, "a") end --- Sends all entries to the quickfix list, replacing the previous entries. actions.send_to_qflist = function(prompt_bufnr) - send_all_to_qf(prompt_bufnr, 'r') + send_all_to_qf(prompt_bufnr, "r") end --- Adds all entries to the quickfix list, keeping the previous entries. actions.add_to_qflist = function(prompt_bufnr) - send_all_to_qf(prompt_bufnr, 'a') + send_all_to_qf(prompt_bufnr, "a") end - --- Sends the selected entries to the location list, replacing the previous entries. +--- Sends the selected entries to the location list, replacing the previous entries. actions.send_selected_to_loclist = function(prompt_bufnr) - send_selected_to_qf(prompt_bufnr, 'r', 'loclist') + send_selected_to_qf(prompt_bufnr, "r", "loclist") end - --- Adds the selected entries to the location list, keeping the previous entries. +--- Adds the selected entries to the location list, keeping the previous entries. actions.add_selected_to_loclist = function(prompt_bufnr) - send_selected_to_qf(prompt_bufnr, 'a', 'loclist') + send_selected_to_qf(prompt_bufnr, "a", "loclist") end - --- Sends all entries to the location list, replacing the previous entries. +--- Sends all entries to the location list, replacing the previous entries. actions.send_to_loclist = function(prompt_bufnr) - send_all_to_qf(prompt_bufnr, 'r', 'loclist') + send_all_to_qf(prompt_bufnr, "r", "loclist") end - --- Adds all entries to the location list, keeping the previous entries. +--- Adds all entries to the location list, keeping the previous entries. actions.add_to_loclist = function(prompt_bufnr) - send_all_to_qf(prompt_bufnr, 'a', 'loclist') + send_all_to_qf(prompt_bufnr, "a", "loclist") end local smart_send = function(prompt_bufnr, mode, target) @@ -659,25 +641,25 @@ end --- Sends the selected entries to the quickfix list, replacing the previous entries. --- If no entry was selected, sends all entries. actions.smart_send_to_qflist = function(prompt_bufnr) - smart_send(prompt_bufnr, 'r') + smart_send(prompt_bufnr, "r") end --- Adds the selected entries to the quickfix list, keeping the previous entries. --- If no entry was selected, adds all entries. actions.smart_add_to_qflist = function(prompt_bufnr) - smart_send(prompt_bufnr, 'a') + smart_send(prompt_bufnr, "a") end --- Sends the selected entries to the location list, replacing the previous entries. --- If no entry was selected, sends all entries. actions.smart_send_to_loclist = function(prompt_bufnr) - smart_send(prompt_bufnr, 'r', 'loclist') + smart_send(prompt_bufnr, "r", "loclist") end --- Adds the selected entries to the location list, keeping the previous entries. --- If no entry was selected, adds all entries. actions.smart_add_to_loclist = function(prompt_bufnr) - smart_send(prompt_bufnr, 'a', 'loclist') + smart_send(prompt_bufnr, "a", "loclist") end actions.complete_tag = function(prompt_bufnr) @@ -686,14 +668,14 @@ actions.complete_tag = function(prompt_bufnr) local delimiter = current_picker.sorter._delimiter if not tags then - print('No tag pre-filtering set for this picker') + print "No tag pre-filtering set for this picker" return end -- format tags to match filter_function local prefilter_tags = {} for tag, _ in pairs(tags) do - table.insert(prefilter_tags, string.format('%s%s%s ', delimiter, tag:lower(), delimiter)) + table.insert(prefilter_tags, string.format("%s%s%s ", delimiter, tag:lower(), delimiter)) end local line = action_state.get_current_line() @@ -713,14 +695,13 @@ actions.complete_tag = function(prompt_bufnr) end if vim.tbl_isempty(filtered_tags) then - print('No matches found') + print "No matches found" return end -- incremental completion by substituting string starting from col - #line byte offset local col = vim.api.nvim_win_get_cursor(0)[2] + 1 vim.fn.complete(col - #line, filtered_tags) - end actions.cycle_history_next = function(prompt_bufnr) @@ -729,7 +710,9 @@ actions.cycle_history_next = function(prompt_bufnr) local line = action_state.get_current_line() local entry = history:get_next(line, current_picker) - if entry == false then return end + if entry == false then + return + end current_picker:reset_prompt() if entry ~= nil then @@ -743,7 +726,9 @@ actions.cycle_history_prev = function(prompt_bufnr) local line = action_state.get_current_line() local entry = history:get_prev(line, current_picker) - if entry == false then return end + if entry == false then + return + end if entry ~= nil then current_picker:reset_prompt() current_picker:set_prompt(entry) diff --git a/lua/telescope/actions/mt.lua b/lua/telescope/actions/mt.lua index 7f233cf..adb3293 100644 --- a/lua/telescope/actions/mt.lua +++ b/lua/telescope/actions/mt.lua @@ -27,11 +27,7 @@ action_mt.create = function(mod) end local result = { - run_replace_or_original( - t._replacements[action_name], - mod[action_name], - ... - ) + run_replace_or_original(t._replacements[action_name], mod[action_name], ...), } for _, res in ipairs(result) do table.insert(values, res) @@ -128,7 +124,7 @@ action_mt.create = function(mod) end action_mt.transform = function(k, mt, mod, v) - local res = setmetatable({k}, mt) + local res = setmetatable({ k }, mt) if type(v) == "table" then res._static_pre[k] = v.pre res._static_post[k] = v.post diff --git a/lua/telescope/actions/set.lua b/lua/telescope/actions/set.lua index 6ad786b..e246fd7 100644 --- a/lua/telescope/actions/set.lua +++ b/lua/telescope/actions/set.lua @@ -12,18 +12,18 @@ local a = vim.api -local log = require('telescope.log') -local Path = require('plenary.path') -local state = require('telescope.state') +local log = require "telescope.log" +local Path = require "plenary.path" +local state = require "telescope.state" -local action_state = require('telescope.actions.state') +local action_state = require "telescope.actions.state" -local transform_mod = require('telescope.actions.mt').transform_mod +local transform_mod = require("telescope.actions.mt").transform_mod local action_set = setmetatable({}, { __index = function(_, k) error("'telescope.actions.set' does not have a value: " .. tostring(k)) - end + end, }) --- Move the current selection of a picker {change} rows. @@ -65,16 +65,16 @@ end local edit_buffer do local map = { - edit = 'buffer', - new = 'sbuffer', - vnew = 'vert sbuffer', - tabedit = 'tab sb', + edit = "buffer", + new = "sbuffer", + vnew = "vert sbuffer", + tabedit = "tab sb", } edit_buffer = function(command, bufnr) command = map[command] if command == nil then - error('There was no associated buffer command') + error "There was no associated buffer command" end vim.cmd(string.format("%s %d", command, bufnr)) end @@ -88,7 +88,7 @@ action_set.edit = function(prompt_bufnr, command) local entry = action_state.get_selected_entry() if not entry then - print("[telescope] Nothing currently selected") + print "[telescope] Nothing currently selected" return end @@ -105,7 +105,7 @@ action_set.edit = function(prompt_bufnr, command) -- to put stuff into `filename` local value = entry.value if not value then - print("Could not do anything with blank line...") + print "Could not do anything with blank line..." return end @@ -122,7 +122,7 @@ action_set.edit = function(prompt_bufnr, command) local entry_bufnr = entry.bufnr - require('telescope.actions').close(prompt_bufnr) + require("telescope.actions").close(prompt_bufnr) if entry_bufnr then edit_buffer(command, entry_bufnr) @@ -136,7 +136,7 @@ action_set.edit = function(prompt_bufnr, command) end if row and col then - local ok, err_msg = pcall(a.nvim_win_set_cursor, 0, {row, col}) + local ok, err_msg = pcall(a.nvim_win_set_cursor, 0, { row, col }) if not ok then log.debug("Failed to move to cursor:", err_msg, row, col) end @@ -147,11 +147,11 @@ end ---@param prompt_bufnr number: The prompt bufnr ---@param direction number: The direction of the scrolling -- Valid directions include: "1", "-1" -action_set.scroll_previewer = function (prompt_bufnr, direction) +action_set.scroll_previewer = function(prompt_bufnr, direction) local previewer = action_state.get_current_picker(prompt_bufnr).previewer -- Check if we actually have a previewer - if (type(previewer) ~= "table" or previewer.scroll_fn == nil) then + if type(previewer) ~= "table" or previewer.scroll_fn == nil then return end diff --git a/lua/telescope/actions/state.lua b/lua/telescope/actions/state.lua index 192c44d..0be2c3f 100644 --- a/lua/telescope/actions/state.lua +++ b/lua/telescope/actions/state.lua @@ -6,19 +6,19 @@ --- Generally used from within other |telescope.actions| ---@brief ]] -local global_state = require('telescope.state') -local conf = require('telescope.config').values +local global_state = require "telescope.state" +local conf = require("telescope.config").values local action_state = {} --- Get the current entry function action_state.get_selected_entry() - return global_state.get_global_key('selected_entry') + return global_state.get_global_key "selected_entry" end --- Gets the current line function action_state.get_current_line() - return global_state.get_global_key('current_line') + return global_state.get_global_key "current_line" end --- Gets the current picker @@ -38,10 +38,10 @@ function action_state.select_key_to_edit_key(type) end function action_state.get_current_history() - local history = global_state.get_global_key("history") + local history = global_state.get_global_key "history" if not history then if conf.history == false or type(conf.history) ~= "table" then - history = require('telescope.actions.history').get_simple_history() + history = require("telescope.actions.history").get_simple_history() global_state.set_global_key("history", history) else history = conf.history.handler() diff --git a/lua/telescope/actions/utils.lua b/lua/telescope/actions/utils.lua index 73045e7..f2abfe1 100644 --- a/lua/telescope/actions/utils.lua +++ b/lua/telescope/actions/utils.lua @@ -6,7 +6,7 @@ --- Generally used from within other |telescope.actions| ---@brief ]] -local action_state = require('telescope.actions.state') +local action_state = require "telescope.actions.state" local utils = {} @@ -33,12 +33,12 @@ local utils = {} ---@param prompt_bufnr number: The prompt bufnr ---@param f function: Function to map onto entries of picker that takes (entry, index, row) as viable arguments function utils.map_entries(prompt_bufnr, f) - vim.validate{ - f = {f, "function"} + vim.validate { + f = { f, "function" }, } local current_picker = action_state.get_current_picker(prompt_bufnr) local index = 1 - -- indices are 1-indexed, rows are 0-indexed + -- indices are 1-indexed, rows are 0-indexed for entry in current_picker.manager:iter() do local row = current_picker:get_row(index) f(entry, index, row) @@ -69,8 +69,8 @@ end ---@param prompt_bufnr number: The prompt bufnr ---@param f function: Function to map onto selection of picker that takes (selection) as a viable argument function utils.map_selections(prompt_bufnr, f) - vim.validate{ - f = {f, "function"} + vim.validate { + f = { f, "function" }, } local current_picker = action_state.get_current_picker(prompt_bufnr) for _, selection in ipairs(current_picker:get_multi_selection()) do diff --git a/lua/telescope/algos/fzy.lua b/lua/telescope/algos/fzy.lua index f6622d0..bf322ab 100644 --- a/lua/telescope/algos/fzy.lua +++ b/lua/telescope/algos/fzy.lua @@ -7,12 +7,12 @@ -- > matches on consecutive letters and starts of words. This allows matching -- > using acronyms or different parts of the path." - J Hawthorn -local has_path, Path = pcall(require, 'plenary.path') +local has_path, Path = pcall(require, "plenary.path") if not has_path then Path = { path = { - separator = '/' - } + separator = "/", + }, } end @@ -48,11 +48,11 @@ function fzy.has_match(needle, haystack) end local function is_lower(c) - return c:match("%l") + return c:match "%l" end local function is_upper(c) - return c:match("%u") + return c:match "%u" end local function precompute_bonus(haystack) @@ -93,7 +93,7 @@ local function compute(needle, haystack, D, M) haystack_chars[i] = lower_haystack:sub(i, i) end - for i=1,n do + for i = 1, n do D[i] = {} M[i] = {} @@ -147,7 +147,7 @@ function fzy.positions(needle, haystack) return {} elseif n == m then local consecutive = {} - for i=1,n do + for i = 1, n do consecutive[i] = i end return consecutive @@ -160,11 +160,10 @@ function fzy.positions(needle, haystack) local positions = {} local match_required = false local j = m - for i=n,1,-1 do + for i = n, 1, -1 do while j >= 1 do if D[i][j] ~= SCORE_MIN and (match_required or D[i][j] == M[i][j]) then - match_required = (i ~= 1) and (j ~= 1) and ( - M[i][j] == D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE) + match_required = (i ~= 1) and (j ~= 1) and (M[i][j] == D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE) positions[i] = j j = j - 1 break diff --git a/lua/telescope/algos/linked_list.lua b/lua/telescope/algos/linked_list.lua index cf1c47d..6015e1e 100644 --- a/lua/telescope/algos/linked_list.lua +++ b/lua/telescope/algos/linked_list.lua @@ -1,4 +1,3 @@ - local LinkedList = {} LinkedList.__index = LinkedList @@ -27,7 +26,7 @@ end local create_node = function(item) return { - item = item + item = item, } end @@ -122,7 +121,6 @@ function LinkedList:place_after(index, node, item) new_node.next.prev = new_node end - if self.track_at then if index == self.track_at then self._tracked_node = new_node @@ -166,7 +164,6 @@ function LinkedList:place_before(index, node, item) new_node.next.prev = new_node end - if self.track_at then if index == self.track_at - 1 then self._tracked_node = node @@ -176,7 +173,7 @@ function LinkedList:place_before(index, node, item) elseif final_size > self.track_at then self._tracked_node = self._tracked_node.prev else - return + return end end @@ -184,7 +181,6 @@ function LinkedList:place_before(index, node, item) end end - -- Do you even do this in linked lists...? -- function LinkedList:remove(item) -- end diff --git a/lua/telescope/algos/string_distance.lua b/lua/telescope/algos/string_distance.lua index de40e14..c2c5ead 100644 --- a/lua/telescope/algos/string_distance.lua +++ b/lua/telescope/algos/string_distance.lua @@ -1,12 +1,14 @@ - local function min(a, b, c) local min_val = a - if b < min_val then min_val = b end - if c < min_val then min_val = c end + if b < min_val then + min_val = b + end + if c < min_val then + min_val = c + end return min_val - end ---------------------------------- @@ -16,34 +18,35 @@ end -- @treturn number the levenshtein distance -- @within Metrics return function(s1, s2) - if s1 == s2 then return 0 end - if s1:len() == 0 then return s2:len() end - if s2:len() == 0 then return s1:len() end - if s1:len() < s2:len() then s1, s2 = s2, s1 end - - local t = {} - for i=1, #s1+1 do - t[i] = {i-1} + if s1 == s2 then + return 0 + end + if s1:len() == 0 then + return s2:len() + end + if s2:len() == 0 then + return s1:len() + end + if s1:len() < s2:len() then + s1, s2 = s2, s1 end - for i=1, #s2+1 do - t[1][i] = i-1 + local t = {} + for i = 1, #s1 + 1 do + t[i] = { i - 1 } + end + + for i = 1, #s2 + 1 do + t[1][i] = i - 1 end local cost - for i=2, #s1+1 do - - for j=2, #s2+1 do - cost = (s1:sub(i-1,i-1) == s2:sub(j-1,j-1) and 0) or 1 - t[i][j] = min( - t[i-1][j] + 1, - t[i][j-1] + 1, - t[i-1][j-1] + cost) + for i = 2, #s1 + 1 do + for j = 2, #s2 + 1 do + cost = (s1:sub(i - 1, i - 1) == s2:sub(j - 1, j - 1) and 0) or 1 + t[i][j] = min(t[i - 1][j] + 1, t[i][j - 1] + 1, t[i - 1][j - 1] + cost) end - end - return t[#s1+1][#s2+1] - + return t[#s1 + 1][#s2 + 1] end - diff --git a/lua/telescope/builtin/files.lua b/lua/telescope/builtin/files.lua index 2156223..08249eb 100644 --- a/lua/telescope/builtin/files.lua +++ b/lua/telescope/builtin/files.lua @@ -1,16 +1,16 @@ -local actions = require('telescope.actions') -local action_state = require('telescope.actions.state') -local action_set = require('telescope.actions.set') -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local pickers = require('telescope.pickers') -local previewers = require('telescope.previewers') -local utils = require('telescope.utils') -local conf = require('telescope.config').values -local log = require('telescope.log') +local actions = require "telescope.actions" +local action_state = require "telescope.actions.state" +local action_set = require "telescope.actions.set" +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local pickers = require "telescope.pickers" +local previewers = require "telescope.previewers" +local utils = require "telescope.utils" +local conf = require("telescope.config").values +local log = require "telescope.log" -local scan = require('plenary.scandir') -local Path = require('plenary.path') +local scan = require "plenary.scandir" +local Path = require "plenary.path" local os_sep = Path.path.sep local flatten = vim.tbl_flatten @@ -19,13 +19,19 @@ local filter = vim.tbl_filter local files = {} local escape_chars = function(string) - return string.gsub(string, "[%(|%)|\\|%[|%]|%-|%{%}|%?|%+|%*|%^|%$]", { - ["\\"] = "\\\\", ["-"] = "\\-", - ["("] = "\\(", [")"] = "\\)", - ["["] = "\\[", ["]"] = "\\]", - ["{"] = "\\{", ["}"] = "\\}", - ["?"] = "\\?", ["+"] = "\\+", - ["*"] = "\\*", ["^"] = "\\^", + return string.gsub(string, "[%(|%)|\\|%[|%]|%-|%{%}|%?|%+|%*|%^|%$]", { + ["\\"] = "\\\\", + ["-"] = "\\-", + ["("] = "\\(", + [")"] = "\\)", + ["["] = "\\[", + ["]"] = "\\]", + ["{"] = "\\{", + ["}"] = "\\}", + ["?"] = "\\?", + ["+"] = "\\+", + ["*"] = "\\*", + ["^"] = "\\^", ["$"] = "\\$", }) end @@ -42,11 +48,15 @@ files.live_grep = function(opts) local filelist = {} if grep_open_files then - local bufnrs = filter(function(b) - if 1 ~= vim.fn.buflisted(b) then return false end + local bufnrs = filter(function(b) + if 1 ~= vim.fn.buflisted(b) then + return false + end return true end, vim.api.nvim_list_bufs()) - if not next(bufnrs) then return end + if not next(bufnrs) then + return + end for _, bufnr in ipairs(bufnrs) do local file = vim.api.nvim_buf_get_name(bufnr) @@ -59,35 +69,33 @@ files.live_grep = function(opts) end local live_grepper = finders.new_job(function(prompt) - -- TODO: Probably could add some options for smart case and whatever else rg offers. + -- TODO: Probably could add some options for smart case and whatever else rg offers. - if not prompt or prompt == "" then - return nil - end + if not prompt or prompt == "" then + return nil + end - prompt = escape_chars(prompt) + prompt = escape_chars(prompt) - local search_list = {} + local search_list = {} - if search_dirs then - table.insert(search_list, search_dirs) - else - table.insert(search_list, '.') - end + if search_dirs then + table.insert(search_list, search_dirs) + else + table.insert(search_list, ".") + end - if grep_open_files then - search_list = filelist - end + if grep_open_files then + search_list = filelist + end - return flatten { vimgrep_arguments, prompt, search_list } - end, - opts.entry_maker or make_entry.gen_from_vimgrep(opts), - opts.max_results, - opts.cwd - ) + return flatten { vimgrep_arguments, prompt, search_list } + end, opts.entry_maker or make_entry.gen_from_vimgrep( + opts + ), opts.max_results, opts.cwd) pickers.new(opts, { - prompt_title = 'Live Grep', + prompt_title = "Live Grep", finder = live_grepper, previewer = conf.grep_previewer(opts), sorter = conf.generic_sorter(opts), @@ -103,7 +111,7 @@ files.grep_string = function(opts) local vimgrep_arguments = opts.vimgrep_arguments or conf.vimgrep_arguments local search_dirs = opts.search_dirs - local word = opts.search or vim.fn.expand("") + local word = opts.search or vim.fn.expand "" local search = opts.use_regex and word or escape_chars(word) local word_match = opts.word_match opts.entry_maker = opts.entry_maker or make_entry.gen_from_vimgrep(opts) @@ -119,11 +127,11 @@ files.grep_string = function(opts) table.insert(args, vim.fn.expand(path)) end else - table.insert(args, '.') + table.insert(args, ".") end pickers.new(opts, { - prompt_title = 'Find Word', + prompt_title = "Find Word", finder = finders.new_oneshot_job(args, opts), previewer = conf.grep_previewer(opts), sorter = conf.generic_sorter(opts), @@ -139,71 +147,87 @@ files.find_files = function(opts) local search_dirs = opts.search_dirs if search_dirs then - for k,v in pairs(search_dirs) do + for k, v in pairs(search_dirs) do search_dirs[k] = vim.fn.expand(v) end end if not find_command then - if 1 == vim.fn.executable("fd") then - find_command = { 'fd', '--type', 'f' } - if hidden then table.insert(find_command, '--hidden') end - if follow then table.insert(find_command, '-L') end + if 1 == vim.fn.executable "fd" then + find_command = { "fd", "--type", "f" } + if hidden then + table.insert(find_command, "--hidden") + end + if follow then + table.insert(find_command, "-L") + end if search_dirs then - table.insert(find_command, '.') - for _,v in pairs(search_dirs) do + table.insert(find_command, ".") + for _, v in pairs(search_dirs) do table.insert(find_command, v) end end - elseif 1 == vim.fn.executable("fdfind") then - find_command = { 'fdfind', '--type', 'f' } - if hidden then table.insert(find_command, '--hidden') end - if follow then table.insert(find_command, '-L') end + elseif 1 == vim.fn.executable "fdfind" then + find_command = { "fdfind", "--type", "f" } + if hidden then + table.insert(find_command, "--hidden") + end + if follow then + table.insert(find_command, "-L") + end if search_dirs then - table.insert(find_command, '.') - for _,v in pairs(search_dirs) do + table.insert(find_command, ".") + for _, v in pairs(search_dirs) do table.insert(find_command, v) end end - elseif 1 == vim.fn.executable("rg") then - find_command = { 'rg', '--files' } - if hidden then table.insert(find_command, '--hidden') end - if follow then table.insert(find_command, '-L') end + elseif 1 == vim.fn.executable "rg" then + find_command = { "rg", "--files" } + if hidden then + table.insert(find_command, "--hidden") + end + if follow then + table.insert(find_command, "-L") + end if search_dirs then - for _,v in pairs(search_dirs) do + for _, v in pairs(search_dirs) do table.insert(find_command, v) end end - elseif 1 == vim.fn.executable("find") and vim.fn.has('win32') == 0 then - find_command = { 'find', '.', '-type', 'f' } + elseif 1 == vim.fn.executable "find" and vim.fn.has "win32" == 0 then + find_command = { "find", ".", "-type", "f" } if not hidden then - table.insert(find_command, { '-not', '-path', "*/.*" }) + table.insert(find_command, { "-not", "-path", "*/.*" }) find_command = flatten(find_command) end - if follow then table.insert(find_command, '-L') end + if follow then + table.insert(find_command, "-L") + end if search_dirs then table.remove(find_command, 2) - for _,v in pairs(search_dirs) do + for _, v in pairs(search_dirs) do table.insert(find_command, 2, v) end end - elseif 1 == vim.fn.executable("where") then - find_command = { 'where', '/r', '.', '*'} + elseif 1 == vim.fn.executable "where" then + find_command = { "where", "/r", ".", "*" } if hidden ~= nil then - log.warn('The `hidden` key is not available for the Windows `where` command in `find_files`.') + log.warn "The `hidden` key is not available for the Windows `where` command in `find_files`." end if follow ~= nil then - log.warn('The `follow` key is not available for the Windows `where` command in `find_files`.') + log.warn "The `follow` key is not available for the Windows `where` command in `find_files`." end if search_dirs ~= nil then - log.warn('The `search_dirs` key is not available for the Windows `where` command in `find_files`.') + log.warn "The `search_dirs` key is not available for the Windows `where` command in `find_files`." end end end if not find_command then - print("You need to install either find, fd, or rg. " .. - "You can also submit a PR to add support for another file finder :)") + print( + "You need to install either find, fd, or rg. " + .. "You can also submit a PR to add support for another file finder :)" + ) return end @@ -214,11 +238,8 @@ files.find_files = function(opts) opts.entry_maker = opts.entry_maker or make_entry.gen_from_file(opts) pickers.new(opts, { - prompt_title = 'Find Files', - finder = finders.new_oneshot_job( - find_command, - opts - ), + prompt_title = "Find Files", + finder = finders.new_oneshot_job(find_command, opts), previewer = conf.file_previewer(opts), sorter = conf.file_sorter(opts), }):find() @@ -228,11 +249,11 @@ local function prepare_match(entry, kind) local entries = {} if entry.node then - entry["kind"] = kind - table.insert(entries, entry) + entry["kind"] = kind + table.insert(entries, entry) else for name, item in pairs(entry) do - vim.list_extend(entries, prepare_match(item, name)) + vim.list_extend(entries, prepare_match(item, name)) end end @@ -248,71 +269,76 @@ files.file_browser = function(opts) opts.depth = opts.depth or 1 opts.cwd = opts.cwd and vim.fn.expand(opts.cwd) or vim.loop.cwd() - opts.new_finder = opts.new_finder or function(path) - opts.cwd = path - local data = {} + opts.new_finder = opts.new_finder + or function(path) + opts.cwd = path + local data = {} - scan.scan_dir(path, { - hidden = opts.hidden or false, - add_dirs = true, - depth = opts.depth, - on_insert = function(entry, typ) - table.insert(data, typ == 'directory' and (entry .. os_sep) or entry) - end - }) - table.insert(data, 1, '..' .. os_sep) + scan.scan_dir(path, { + hidden = opts.hidden or false, + add_dirs = true, + depth = opts.depth, + on_insert = function(entry, typ) + table.insert(data, typ == "directory" and (entry .. os_sep) or entry) + end, + }) + table.insert(data, 1, ".." .. os_sep) - local maker = function() - local mt = {} - mt.cwd = opts.cwd - mt.display = function(entry) - local hl_group - local display = utils.transform_path(opts, entry.value) - if is_dir(entry.value) then - display = display .. os_sep - if not opts.disable_devicons then - display = (opts.dir_icon or "") .. " " .. display - hl_group = "Default" + local maker = function() + local mt = {} + mt.cwd = opts.cwd + mt.display = function(entry) + local hl_group + local display = utils.transform_path(opts, entry.value) + if is_dir(entry.value) then + display = display .. os_sep + if not opts.disable_devicons then + display = (opts.dir_icon or "") .. " " .. display + hl_group = "Default" + end + else + display, hl_group = utils.transform_devicons(entry.value, display, opts.disable_devicons) end - else - display, hl_group = utils.transform_devicons(entry.value, display, opts.disable_devicons) - end - if hl_group then - return display, { { {1, 3}, hl_group } } - else - return display - end - end - - mt.__index = function(t, k) - local raw = rawget(mt, k) - if raw then return raw end - - if k == "path" then - local retpath = Path:new({t.cwd, t.value}):absolute() - if not vim.loop.fs_access(retpath, "R", nil) then - retpath = t.value + if hl_group then + return display, { { { 1, 3 }, hl_group } } + else + return display end - if is_dir(t.value) then retpath = retpath .. os_sep end - return retpath end - return rawget(t, rawget({ value = 1 }, k)) + mt.__index = function(t, k) + local raw = rawget(mt, k) + if raw then + return raw + end + + if k == "path" then + local retpath = Path:new({ t.cwd, t.value }):absolute() + if not vim.loop.fs_access(retpath, "R", nil) then + retpath = t.value + end + if is_dir(t.value) then + retpath = retpath .. os_sep + end + return retpath + end + + return rawget(t, rawget({ value = 1 }, k)) + end + + return function(line) + local tbl = { line } + tbl.ordinal = Path:new(line):make_relative(opts.cwd) + return setmetatable(tbl, mt) + end end - return function(line) - local tbl = {line} - tbl.ordinal = Path:new(line):make_relative(opts.cwd) - return setmetatable(tbl, mt) - end + return finders.new_table { results = data, entry_maker = maker() } end - return finders.new_table { results = data, entry_maker = maker() } - end - pickers.new(opts, { - prompt_title = 'File Browser', + prompt_title = "File Browser", finder = opts.new_finder(opts.cwd), previewer = conf.file_previewer(opts), sorter = conf.file_sorter(opts), @@ -330,28 +356,38 @@ files.file_browser = function(opts) local current_picker = action_state.get_current_picker(prompt_bufnr) local file = action_state.get_current_line() if file == "" then - print('To create a new file or directory(add ' .. os_sep .. ' at the end of file) ' .. - 'write the desired new into the prompt and press . ' .. - 'It works for not existing nested input as well.' .. - 'Example: this' .. os_sep .. 'is' .. os_sep .. 'a' .. os_sep .. 'new_file.lua') + print( + "To create a new file or directory(add " + .. os_sep + .. " at the end of file) " + .. "write the desired new into the prompt and press . " + .. "It works for not existing nested input as well." + .. "Example: this" + .. os_sep + .. "is" + .. os_sep + .. "a" + .. os_sep + .. "new_file.lua" + ) return end local fpath = current_picker.cwd .. os_sep .. file if not is_dir(fpath) then actions.close(prompt_bufnr) - Path:new(fpath):touch({ parents = true }) - vim.cmd(string.format(':e %s', fpath)) + Path:new(fpath):touch { parents = true } + vim.cmd(string.format(":e %s", fpath)) else - Path:new(fpath:sub(1, -2)):mkdir({ parents = true }) + Path:new(fpath:sub(1, -2)):mkdir { parents = true } local new_cwd = vim.fn.expand(fpath) current_picker.cwd = new_cwd current_picker:refresh(opts.new_finder(new_cwd), { reset_prompt = true }) end end - map('i', '', create_new_file) - map('n', '', create_new_file) + map("i", "", create_new_file) + map("n", "", create_new_file) return true end, }):find() @@ -361,19 +397,19 @@ end files.treesitter = function(opts) opts.show_line = utils.get_default(opts.show_line, true) - local has_nvim_treesitter, _ = pcall(require, 'nvim-treesitter') + local has_nvim_treesitter, _ = pcall(require, "nvim-treesitter") if not has_nvim_treesitter then - print('You need to install nvim-treesitter') + print "You need to install nvim-treesitter" return end - local parsers = require('nvim-treesitter.parsers') + local parsers = require "nvim-treesitter.parsers" if not parsers.has_parser() then - print('No parser for the current buffer') + print "No parser for the current buffer" return end - local ts_locals = require('nvim-treesitter.locals') + local ts_locals = require "nvim-treesitter.locals" local bufnr = opts.bufnr or vim.api.nvim_get_current_buf() local results = {} @@ -389,16 +425,16 @@ files.treesitter = function(opts) end pickers.new(opts, { - prompt_title = 'Treesitter Symbols', - finder = finders.new_table { + prompt_title = "Treesitter Symbols", + finder = finders.new_table { results = results, - entry_maker = opts.entry_maker or make_entry.gen_from_treesitter(opts) + entry_maker = opts.entry_maker or make_entry.gen_from_treesitter(opts), }, previewer = conf.grep_previewer(opts), - sorter = conf.prefilter_sorter{ + sorter = conf.prefilter_sorter { tag = "kind", - sorter = conf.generic_sorter(opts) - } + sorter = conf.generic_sorter(opts), + }, }):find() end @@ -420,7 +456,7 @@ files.current_buffer_fuzzy_find = function(opts) }) end - local ts_ok, ts_parsers = pcall(require, 'nvim-treesitter.parsers') + local ts_ok, ts_parsers = pcall(require, "nvim-treesitter.parsers") if ts_ok then filetype = ts_parsers.ft_to_lang(filetype) end @@ -454,7 +490,7 @@ files.current_buffer_fuzzy_find = function(opts) else local row = row1 + 1 for index = col1, #lines[row] do - line_highlights[row][index] = hl + line_highlights[row][index] = hl end while row < row2 + 1 do @@ -472,7 +508,7 @@ files.current_buffer_fuzzy_find = function(opts) end pickers.new(opts, { - prompt_title = 'Current Buffer Fuzzy', + prompt_title = "Current Buffer Fuzzy", finder = finders.new_table { results = lines_with_numbers, entry_maker = opts.entry_maker or make_entry.gen_from_buffer_lines(opts), @@ -488,15 +524,15 @@ files.current_buffer_fuzzy_find = function(opts) } return true - end + end, }):find() end files.tags = function(opts) - local ctags_file = opts.ctags_file or 'tags' + local ctags_file = opts.ctags_file or "tags" if not vim.loop.fs_open(vim.fn.expand(ctags_file, true), "r", 438) then - print('Tags file does not exists. Create one with ctags -R') + print "Tags file does not exists. Create one with ctags -R" return end @@ -505,10 +541,10 @@ files.tags = function(opts) local data = assert(vim.loop.fs_read(fd, stat.size, 0)) assert(vim.loop.fs_close(fd)) - local results = vim.split(data, '\n') + local results = vim.split(data, "\n") - pickers.new(opts,{ - prompt_title = 'Tags', + pickers.new(opts, { + prompt_title = "Tags", finder = finders.new_table { results = results, entry_maker = opts.entry_maker or make_entry.gen_from_ctags(opts), @@ -521,29 +557,29 @@ files.tags = function(opts) local selection = action_state.get_selected_entry() if selection.scode then - local scode = string.gsub(selection.scode, '[$]$', '') + local scode = string.gsub(selection.scode, "[$]$", "") scode = string.gsub(scode, [[\\]], [[\]]) scode = string.gsub(scode, [[\/]], [[/]]) - scode = string.gsub(scode, '[*]', [[\*]]) + scode = string.gsub(scode, "[*]", [[\*]]) - vim.cmd('norm! gg') + vim.cmd "norm! gg" vim.fn.search(scode) - vim.cmd('norm! zz') + vim.cmd "norm! zz" else - vim.api.nvim_win_set_cursor(0, {selection.lnum, 0}) + vim.api.nvim_win_set_cursor(0, { selection.lnum, 0 }) end end, } return true - end + end, }):find() end files.current_buffer_tags = function(opts) return files.tags(vim.tbl_extend("force", { - prompt_title = 'Current Buffer Tags', + prompt_title = "Current Buffer Tags", only_current_file = true, - path_display = 'hidden', + path_display = "hidden", }, opts)) end diff --git a/lua/telescope/builtin/git.lua b/lua/telescope/builtin/git.lua index b9438ce..4bf0283 100644 --- a/lua/telescope/builtin/git.lua +++ b/lua/telescope/builtin/git.lua @@ -1,15 +1,15 @@ -local actions = require('telescope.actions') -local action_state = require('telescope.actions.state') -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local pickers = require('telescope.pickers') -local previewers = require('telescope.previewers') -local utils = require('telescope.utils') -local entry_display = require('telescope.pickers.entry_display') -local strings = require('plenary.strings') -local Path = require('plenary.path') +local actions = require "telescope.actions" +local action_state = require "telescope.actions.state" +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local pickers = require "telescope.pickers" +local previewers = require "telescope.previewers" +local utils = require "telescope.utils" +local entry_display = require "telescope.pickers.entry_display" +local strings = require "plenary.strings" +local Path = require "plenary.path" -local conf = require('telescope.config').values +local conf = require("telescope.config").values local git = {} @@ -17,7 +17,7 @@ git.files = function(opts) local show_untracked = utils.get_default(opts.show_untracked, true) local recurse_submodules = utils.get_default(opts.recurse_submodules, false) if show_untracked and recurse_submodules then - error("Git does not support both --others and --recurse-submodules") + error "Git does not support both --others and --recurse-submodules" end -- By creating the entry maker after the cwd options, @@ -25,13 +25,16 @@ git.files = function(opts) opts.entry_maker = opts.entry_maker or make_entry.gen_from_file(opts) pickers.new(opts, { - prompt_title = 'Git Files', + prompt_title = "Git Files", finder = finders.new_oneshot_job( - vim.tbl_flatten( { - "git", "ls-files", "--exclude-standard", "--cached", + vim.tbl_flatten { + "git", + "ls-files", + "--exclude-standard", + "--cached", show_untracked and "--others" or nil, - recurse_submodules and "--recurse-submodules" or nil - } ), + recurse_submodules and "--recurse-submodules" or nil, + }, opts ), previewer = conf.file_previewer(opts), @@ -41,11 +44,16 @@ end git.commits = function(opts) local results = utils.get_os_command_output({ - 'git', 'log', '--pretty=oneline', '--abbrev-commit', '--', '.' + "git", + "log", + "--pretty=oneline", + "--abbrev-commit", + "--", + ".", }, opts.cwd) pickers.new(opts, { - prompt_title = 'Git Commits', + prompt_title = "Git Commits", finder = finders.new_table { results = results, entry_maker = opts.entry_maker or make_entry.gen_from_git_commits(opts), @@ -60,17 +68,20 @@ git.commits = function(opts) attach_mappings = function() actions.select_default:replace(actions.git_checkout) return true - end + end, }):find() end git.stash = function(opts) local results = utils.get_os_command_output({ - 'git', '--no-pager', 'stash', 'list', + "git", + "--no-pager", + "stash", + "list", }, opts.cwd) pickers.new(opts, { - prompt_title = 'Git Stash', + prompt_title = "Git Stash", finder = finders.new_table { results = results, entry_maker = opts.entry_maker or make_entry.gen_from_git_stash(), @@ -80,7 +91,7 @@ git.stash = function(opts) attach_mappings = function() actions.select_default:replace(actions.git_apply_stash) return true - end + end, }):find() end @@ -90,14 +101,18 @@ local get_current_buf_line = function(winnr) end git.bcommits = function(opts) - opts.current_line = (not opts.current_file) and get_current_buf_line(0) or nil - opts.current_file = opts.current_file or vim.fn.expand('%') + opts.current_line = not opts.current_file and get_current_buf_line(0) or nil + opts.current_file = opts.current_file or vim.fn.expand "%" local results = utils.get_os_command_output({ - 'git', 'log', '--pretty=oneline', '--abbrev-commit', opts.current_file + "git", + "log", + "--pretty=oneline", + "--abbrev-commit", + opts.current_file, }, opts.cwd) pickers.new(opts, { - prompt_title = 'Git BCommits', + prompt_title = "Git BCommits", finder = finders.new_table { results = results, entry_maker = opts.entry_maker or make_entry.gen_from_git_commits(opts), @@ -112,64 +127,67 @@ git.bcommits = function(opts) attach_mappings = function() actions.select_default:replace(actions.git_checkout_current_buffer) local transfrom_file = function() - return opts.current_file and Path:new(opts.current_file):make_relative(opts.cwd) or '' + return opts.current_file and Path:new(opts.current_file):make_relative(opts.cwd) or "" end local get_buffer_of_orig = function(selection) - local value = selection.value .. ':' .. transfrom_file() - local content = utils.get_os_command_output({ 'git', '--no-pager', 'show', value }, opts.cwd) + local value = selection.value .. ":" .. transfrom_file() + local content = utils.get_os_command_output({ "git", "--no-pager", "show", value }, opts.cwd) local bufnr = vim.api.nvim_create_buf(false, true) vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, content) - vim.api.nvim_buf_set_name(bufnr, 'Original') + vim.api.nvim_buf_set_name(bufnr, "Original") return bufnr end local vimdiff = function(selection, command) local ft = vim.bo.filetype - vim.cmd("diffthis") + vim.cmd "diffthis" local bufnr = get_buffer_of_orig(selection) vim.cmd(string.format("%s %s", command, bufnr)) vim.bo.filetype = ft - vim.cmd("diffthis") + vim.cmd "diffthis" - vim.cmd(string.format( - "autocmd WinClosed ++nested ++once :lua vim.api.nvim_buf_delete(%s, { force = true })", - bufnr, - bufnr)) + vim.cmd( + string.format( + "autocmd WinClosed ++nested ++once :lua vim.api.nvim_buf_delete(%s, { force = true })", + bufnr, + bufnr + ) + ) end actions.select_vertical:replace(function(prompt_bufnr) actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() - vimdiff(selection, 'leftabove vert sbuffer') + vimdiff(selection, "leftabove vert sbuffer") end) actions.select_horizontal:replace(function(prompt_bufnr) actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() - vimdiff(selection, 'belowright sbuffer') + vimdiff(selection, "belowright sbuffer") end) actions.select_tab:replace(function(prompt_bufnr) actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() - vim.cmd('tabedit ' .. transfrom_file()) - vimdiff(selection, 'leftabove vert sbuffer') + vim.cmd("tabedit " .. transfrom_file()) + vimdiff(selection, "leftabove vert sbuffer") end) return true - end + end, }):find() end git.branches = function(opts) - local format = '%(HEAD)' - .. '%(refname)' - .. '%(authorname)' - .. '%(upstream:lstrip=2)' - .. '%(committerdate:format-local:%Y/%m/%d%H:%M:%S)' - local output = utils.get_os_command_output({ 'git', 'for-each-ref', '--perl', '--format', format }, opts.cwd) + local format = "%(HEAD)" + .. "%(refname)" + .. "%(authorname)" + .. "%(upstream:lstrip=2)" + .. "%(committerdate:format-local:%Y/%m/%d%H:%M:%S)" + local output = utils.get_os_command_output({ "git", "for-each-ref", "--perl", "--format", format }, opts.cwd) local results = {} local widths = { @@ -179,7 +197,7 @@ git.branches = function(opts) committerdate = 0, } local unescape_single_quote = function(v) - return string.gsub(v, "\\([\\'])", "%1") + return string.gsub(v, "\\([\\'])", "%1") end local parse_line = function(line) local fields = vim.split(string.sub(line, 2, -2), "''", true) @@ -191,21 +209,21 @@ git.branches = function(opts) committerdate = fields[5], } local prefix - if vim.startswith(entry.refname, 'refs/remotes/') then - prefix = 'refs/remotes/' - elseif vim.startswith(entry.refname, 'refs/heads/') then - prefix = 'refs/heads/' + if vim.startswith(entry.refname, "refs/remotes/") then + prefix = "refs/remotes/" + elseif vim.startswith(entry.refname, "refs/heads/") then + prefix = "refs/heads/" else return end local index = 1 - if entry.head ~= '*' then + if entry.head ~= "*" then index = #results + 1 end - entry.name = string.sub(entry.refname, string.len(prefix)+1) + entry.name = string.sub(entry.refname, string.len(prefix) + 1) for key, value in pairs(widths) do - widths[key] = math.max(value, strings.strdisplaywidth(entry[key] or '')) + widths[key] = math.max(value, strings.strdisplaywidth(entry[key] or "")) end if string.len(entry.upstream) > 0 then widths.upstream_indicator = 2 @@ -228,22 +246,22 @@ git.branches = function(opts) { width = widths.upstream_indicator }, { width = widths.upstream }, { width = widths.committerdate }, - } + }, } local make_display = function(entry) return displayer { - {entry.head}, - {entry.name, 'TelescopeResultsIdentifier'}, - {entry.authorname}, - {string.len(entry.upstream) > 0 and '=>' or ''}, - {entry.upstream, 'TelescopeResultsIdentifier'}, - {entry.committerdate} + { entry.head }, + { entry.name, "TelescopeResultsIdentifier" }, + { entry.authorname }, + { string.len(entry.upstream) > 0 and "=>" or "" }, + { entry.upstream, "TelescopeResultsIdentifier" }, + { entry.committerdate }, } end pickers.new(opts, { - prompt_title = 'Git Branches', + prompt_title = "Git Branches", finder = finders.new_table { results = results, entry_maker = function(entry) @@ -251,58 +269,60 @@ git.branches = function(opts) entry.ordinal = entry.name entry.display = make_display return entry - end + end, }, previewer = previewers.git_branch_log.new(opts), sorter = conf.file_sorter(opts), attach_mappings = function(_, map) actions.select_default:replace(actions.git_checkout) - map('i', '', actions.git_track_branch) - map('n', '', actions.git_track_branch) + map("i", "", actions.git_track_branch) + map("n", "", actions.git_track_branch) - map('i', '', actions.git_rebase_branch) - map('n', '', actions.git_rebase_branch) + map("i", "", actions.git_rebase_branch) + map("n", "", actions.git_rebase_branch) - map('i', '', actions.git_create_branch) - map('n', '', actions.git_create_branch) + map("i", "", actions.git_create_branch) + map("n", "", actions.git_create_branch) - map('i', '', actions.git_switch_branch) - map('n', '', actions.git_switch_branch) + map("i", "", actions.git_switch_branch) + map("n", "", actions.git_switch_branch) - map('i', '', actions.git_delete_branch) - map('n', '', actions.git_delete_branch) + map("i", "", actions.git_delete_branch) + map("n", "", actions.git_delete_branch) return true - end + end, }):find() end git.status = function(opts) local gen_new_finder = function() local expand_dir = utils.if_nil(opts.expand_dir, true, opts.expand_dir) - local git_cmd = {'git', 'status', '-s', '--', '.'} + local git_cmd = { "git", "status", "-s", "--", "." } if expand_dir then - table.insert(git_cmd, table.getn(git_cmd) - 1, '-u') + table.insert(git_cmd, table.getn(git_cmd) - 1, "-u") end local output = utils.get_os_command_output(git_cmd, opts.cwd) if table.getn(output) == 0 then - print('No changes found') + print "No changes found" return end return finders.new_table { results = output, - entry_maker = opts.entry_maker or make_entry.gen_from_git_status(opts) + entry_maker = opts.entry_maker or make_entry.gen_from_git_status(opts), } end local initial_finder = gen_new_finder() - if not initial_finder then return end + if not initial_finder then + return + end pickers.new(opts, { - prompt_title = 'Git Status', + prompt_title = "Git Status", finder = initial_finder, previewer = previewers.git_file_diff.new(opts), sorter = conf.file_sorter(opts), @@ -313,10 +333,10 @@ git.status = function(opts) end, } - map('i', '', actions.git_staging_toggle) - map('n', '', actions.git_staging_toggle) + map("i", "", actions.git_staging_toggle) + map("n", "", actions.git_staging_toggle) return true - end + end, }):find() end @@ -334,7 +354,7 @@ local set_opts_cwd = function(opts) if ret ~= 0 then local output = utils.get_os_command_output({ "git", "rev-parse", "--is-inside-work-tree" }, opts.cwd) if output[1] ~= "true" then - error(opts.cwd .. ' is not a git directory') + error(opts.cwd .. " is not a git directory") end else if use_git_root then diff --git a/lua/telescope/builtin/init.lua b/lua/telescope/builtin/init.lua index 0bb1dc3..54b2d48 100644 --- a/lua/telescope/builtin/init.lua +++ b/lua/telescope/builtin/init.lua @@ -52,9 +52,9 @@ --- This will use the default configuration options. Other configuration options are still in flux at the moment ---@brief ]] -if 1 ~= vim.fn.has('nvim-0.5') then - vim.api.nvim_err_writeln("This plugins requires neovim 0.5") - vim.api.nvim_err_writeln("Please update your neovim.") +if 1 ~= vim.fn.has "nvim-0.5" then + vim.api.nvim_err_writeln "This plugins requires neovim 0.5" + vim.api.nvim_err_writeln "Please update your neovim." return end @@ -70,14 +70,14 @@ local builtin = {} ---@param opts table: options to pass to the picker ---@field grep_open_files boolean: if true, restrict search to open files only, mutually exclusive with `search_dirs` ---@field search_dirs table: directory/directories to search in, mutually exclusive with `grep_open_files` -builtin.live_grep = require('telescope.builtin.files').live_grep +builtin.live_grep = require("telescope.builtin.files").live_grep --- Searches for the string under your cursor in your current working directory ---@param opts table: options to pass to the picker ---@field search string: the query to search ---@field search_dirs table: directory/directories to search in ---@field use_regex boolean: if true, special characters won't be escaped, allows for using regex (default is false) -builtin.grep_string = require('telescope.builtin.files').grep_string +builtin.grep_string = require("telescope.builtin.files").grep_string --- Lists files in your current working directory, respects .gitignore ---@param opts table: options to pass to the picker @@ -85,7 +85,7 @@ builtin.grep_string = require('telescope.builtin.files').grep_string ---@field follow boolean: if true, follows symlinks (i.e. uses `-L` flag for the `find` command) ---@field hidden boolean: determines whether to show hidden files or not (default is false) ---@field search_dirs table: directory/directories to search in -builtin.find_files = require('telescope.builtin.files').find_files +builtin.find_files = require("telescope.builtin.files").find_files --- This is an alias for the `find_files` picker builtin.fd = builtin.find_files @@ -102,28 +102,28 @@ builtin.fd = builtin.find_files ---@field cwd string: directory path to browse (default is cwd) ---@field depth number: file tree depth to display (default is 1) ---@field dir_icon string: change the icon for a directory. default:  -builtin.file_browser = require('telescope.builtin.files').file_browser +builtin.file_browser = require("telescope.builtin.files").file_browser --- Lists function names, variables, and other symbols from treesitter queries --- - Default keymaps: --- - ``: show autocompletion menu to prefilter your query by kind of ts node you want to see (i.e. `:var:`) ---@field show_line boolean: if true, shows the row:column that the result is found at (default is true) -builtin.treesitter = require('telescope.builtin.files').treesitter +builtin.treesitter = require("telescope.builtin.files").treesitter --- Live fuzzy search inside of the currently open buffer ---@param opts table: options to pass to the picker -builtin.current_buffer_fuzzy_find = require('telescope.builtin.files').current_buffer_fuzzy_find +builtin.current_buffer_fuzzy_find = require("telescope.builtin.files").current_buffer_fuzzy_find --- Lists tags in current directory with tag location file preview (users are required to run ctags -R to generate tags --- or update when introducing new changes) ---@param opts table: options to pass to the picker ---@field ctags_file string: specify a particular ctags file to use ---@field show_line boolean: if true, shows the content of the line the tag is found on in the picker (default is true) -builtin.tags = require('telescope.builtin.files').tags +builtin.tags = require("telescope.builtin.files").tags --- Lists all of the tags for the currently open buffer, with a preview ---@param opts table: options to pass to the picker -builtin.current_buffer_tags = require('telescope.builtin.files').current_buffer_tags +builtin.current_buffer_tags = require("telescope.builtin.files").current_buffer_tags -- -- @@ -138,14 +138,14 @@ builtin.current_buffer_tags = require('telescope.builtin.files').current_buffer_ ---@param opts table: options to pass to the picker ---@field show_untracked boolean: if true, adds `--others` flag to command and shows untracked files (default is true) ---@field recurse_submodules boolean: if true, adds the `--recurse-submodules` flag to command (default is false) -builtin.git_files = require('telescope.builtin.git').files +builtin.git_files = require("telescope.builtin.git").files --- Lists commits for current directory with diff preview --- - Default keymaps: --- - ``: checks out the currently selected commit ---@param opts table: options to pass to the picker ---@field cwd string: specify the path of the repo -builtin.git_commits = require('telescope.builtin.git').commits +builtin.git_commits = require("telescope.builtin.git").commits --- Lists commits for current buffer with diff preview --- - Default keymaps or your overriden `select_` keys: @@ -156,7 +156,7 @@ builtin.git_commits = require('telescope.builtin.git').commits ---@param opts table: options to pass to the picker ---@field cwd string: specify the path of the repo ---@field current_file string: specify the current file that should be used for bcommits (default: current buffer) -builtin.git_bcommits = require('telescope.builtin.git').bcommits +builtin.git_bcommits = require("telescope.builtin.git").bcommits --- List branches for current directory, with output from `git log --oneline` shown in the preview window --- - Default keymaps: @@ -166,20 +166,20 @@ builtin.git_bcommits = require('telescope.builtin.git').bcommits --- - ``: creates a new branch, with confirmation prompt before creation --- - ``: deletes the currently selected branch, with confirmation prompt before deletion ---@param opts table: options to pass to the picker -builtin.git_branches = require('telescope.builtin.git').branches +builtin.git_branches = require("telescope.builtin.git").branches --- Lists git status for current directory --- - Default keymaps: --- - ``: stages or unstages the currently selected file --- - ``: opens the currently selected file ---@param opts table: options to pass to the picker -builtin.git_status = require('telescope.builtin.git').status +builtin.git_status = require("telescope.builtin.git").status --- Lists stash items in current repository --- - Default keymaps: --- - ``: runs `git apply` for currently selected stash ---@param opts table: options to pass to the picker -builtin.git_stash = require('telescope.builtin.git').stash +builtin.git_stash = require("telescope.builtin.git").stash -- -- @@ -189,59 +189,59 @@ builtin.git_stash = require('telescope.builtin.git').stash --- Lists all of the community maintained pickers built into Telescope ---@param opts table: options to pass to the picker -builtin.builtin = require('telescope.builtin.internal').builtin +builtin.builtin = require("telescope.builtin.internal").builtin --- Use the telescope... ---@param opts table: options to pass to the picker -builtin.planets = require('telescope.builtin.internal').planets +builtin.planets = require("telescope.builtin.internal").planets --- Lists symbols inside of data/telescope-sources/*.json found in your runtime path. Check README for more info ---@param opts table: options to pass to the picker -builtin.symbols = require('telescope.builtin.internal').symbols +builtin.symbols = require("telescope.builtin.internal").symbols --- Lists available plugin/user commands and runs them on `` ---@param opts table: options to pass to the picker -builtin.commands = require('telescope.builtin.internal').commands +builtin.commands = require("telescope.builtin.internal").commands --- Lists items in the quickfix list, jumps to location on `` ---@param opts table: options to pass to the picker -builtin.quickfix = require('telescope.builtin.internal').quickfix +builtin.quickfix = require("telescope.builtin.internal").quickfix --- Lists items from the current window's location list, jumps to location on `` ---@param opts table: options to pass to the picker -builtin.loclist = require('telescope.builtin.internal').loclist +builtin.loclist = require("telescope.builtin.internal").loclist --- Lists previously open files, opens on `` ---@param opts table: options to pass to the picker -builtin.oldfiles = require('telescope.builtin.internal').oldfiles +builtin.oldfiles = require("telescope.builtin.internal").oldfiles --- Lists commands that were executed recently, and reruns them on `` --- - Default keymaps: --- - ``: open the command line with the text of the currently selected result populated in it ---@param opts table: options to pass to the picker -builtin.command_history = require('telescope.builtin.internal').command_history +builtin.command_history = require("telescope.builtin.internal").command_history --- Lists searches that were executed recently, and reruns them on `` --- - Default keymaps: --- - ``: open a search window with the text of the currently selected search result populated in it ---@param opts table: options to pass to the picker -builtin.search_history = require('telescope.builtin.internal').search_history +builtin.search_history = require("telescope.builtin.internal").search_history --- Lists vim options, allows you to edit the current value on `` ---@param opts table: options to pass to the picker -builtin.vim_options = require('telescope.builtin.internal').vim_options +builtin.vim_options = require("telescope.builtin.internal").vim_options --- Lists available help tags and opens a new window with the relevant help info on `` ---@param opts table: options to pass to the picker -builtin.help_tags = require('telescope.builtin.internal').help_tags +builtin.help_tags = require("telescope.builtin.internal").help_tags --- Lists manpage entries, opens them in a help window on `` ---@param opts table: options to pass to the picker -builtin.man_pages = require('telescope.builtin.internal').man_pages +builtin.man_pages = require("telescope.builtin.internal").man_pages --- Lists lua modules and reloads them on `` ---@param opts table: options to pass to the picker -builtin.reloader = require('telescope.builtin.internal').reloader +builtin.reloader = require("telescope.builtin.internal").reloader --- Lists open buffers in current neovim instance, opens selected buffer on `` ---@param opts table: options to pass to the picker @@ -251,50 +251,50 @@ builtin.reloader = require('telescope.builtin.internal').reloader ---@field sort_lastused boolean: Sorts current and last buffer to the top and selects the lastused (default false) ---@field sort_mru boolean: Sorts all buffers after most recent used. Not just the current and last one (default false) ---@field bufnr_width number: Defines the width of the buffer numbers in front of the filenames -builtin.buffers = require('telescope.builtin.internal').buffers +builtin.buffers = require("telescope.builtin.internal").buffers --- Lists available colorschemes and applies them on `` ---@param opts table: options to pass to the picker ---@field enable_preview boolean: if true, will preview the selected color -builtin.colorscheme = require('telescope.builtin.internal').colorscheme +builtin.colorscheme = require("telescope.builtin.internal").colorscheme --- Lists vim marks and their value, jumps to the mark on `` ---@param opts table: options to pass to the picker -builtin.marks = require('telescope.builtin.internal').marks +builtin.marks = require("telescope.builtin.internal").marks --- Lists vim registers, pastes the contents of the register on `` --- - Default keymaps: --- - ``: edit the contents of the currently selected register ---@param opts table: options to pass to the picker -builtin.registers = require('telescope.builtin.internal').registers +builtin.registers = require("telescope.builtin.internal").registers --- Lists normal mode keymappings, runs the selected keymap on `` ---@param opts table: options to pass to the picker -builtin.keymaps = require('telescope.builtin.internal').keymaps +builtin.keymaps = require("telescope.builtin.internal").keymaps --- Lists all available filetypes, sets currently open buffer's filetype to selected filetype in Telescope on `` ---@param opts table: options to pass to the picker -builtin.filetypes = require('telescope.builtin.internal').filetypes +builtin.filetypes = require("telescope.builtin.internal").filetypes --- Lists all available highlights ---@param opts table: options to pass to the picker -builtin.highlights = require('telescope.builtin.internal').highlights +builtin.highlights = require("telescope.builtin.internal").highlights --- Lists vim autocommands and goes to their declaration on `` ---@param opts table: options to pass to the picker -builtin.autocommands = require('telescope.builtin.internal').autocommands +builtin.autocommands = require("telescope.builtin.internal").autocommands --- Lists spelling suggestions for the current word under the cursor, replaces word with selected suggestion on `` ---@param opts table: options to pass to the picker -builtin.spell_suggest = require('telescope.builtin.internal').spell_suggest +builtin.spell_suggest = require("telescope.builtin.internal").spell_suggest --- Lists the tag stack for the current window, jumps to tag on `` ---@param opts table: options to pass to the picker -builtin.tagstack = require('telescope.builtin.internal').tagstack +builtin.tagstack = require("telescope.builtin.internal").tagstack --- Lists items from Vim's jumplist, jumps to location on `` ---@param opts table: options to pass to the picker -builtin.jumplist = require('telescope.builtin.internal').jumplist +builtin.jumplist = require("telescope.builtin.internal").jumplist -- -- @@ -304,23 +304,23 @@ builtin.jumplist = require('telescope.builtin.internal').jumplist --- Lists LSP references for word under the cursor, jumps to reference on `` ---@param opts table: options to pass to the picker -builtin.lsp_references = require('telescope.builtin.lsp').references +builtin.lsp_references = require("telescope.builtin.lsp").references --- Goto the definition of the word under the cursor, if there's only one, otherwise show all options in Telescope ---@param opts table: options to pass to the picker -builtin.lsp_definitions = require('telescope.builtin.lsp').definitions +builtin.lsp_definitions = require("telescope.builtin.lsp").definitions --- Goto the implementation of the word under the cursor if there's only one, otherwise show all options in Telescope ---@param opts table: options to pass to the picker -builtin.lsp_implementations = require('telescope.builtin.lsp').implementations +builtin.lsp_implementations = require("telescope.builtin.lsp").implementations --- Lists any LSP actions for the word under the cursor which can be triggered with `` ---@param opts table: options to pass to the picker -builtin.lsp_code_actions = require('telescope.builtin.lsp').code_actions +builtin.lsp_code_actions = require("telescope.builtin.lsp").code_actions --- Lists any LSP actions for a given range, that can be triggered with `` ---@param opts table: options to pass to the picker -builtin.lsp_range_code_actions = require('telescope.builtin.lsp').range_code_actions +builtin.lsp_range_code_actions = require("telescope.builtin.lsp").range_code_actions --- Lists LSP document symbols in the current buffer --- - Default keymaps: @@ -328,7 +328,7 @@ builtin.lsp_range_code_actions = require('telescope.builtin.lsp').range_code_act ---@param opts table: options to pass to the picker ---@field ignore_filename type: string with file to ignore ---@field symbols string|table: filter results by symbol kind(s) -builtin.lsp_document_symbols = require('telescope.builtin.lsp').document_symbols +builtin.lsp_document_symbols = require("telescope.builtin.lsp").document_symbols --- Lists LSP document symbols in the current workspace --- - Default keymaps: @@ -336,13 +336,13 @@ builtin.lsp_document_symbols = require('telescope.builtin.lsp').document_symbols ---@param opts table: options to pass to the picker ---@field ignore_filename string: file(s) to ignore ---@field symbols string|table: filter results by symbol kind(s) -builtin.lsp_workspace_symbols = require('telescope.builtin.lsp').workspace_symbols +builtin.lsp_workspace_symbols = require("telescope.builtin.lsp").workspace_symbols --- Dynamically lists LSP for all workspace symbols --- - Default keymaps: --- - ``: show autocompletion menu to prefilter your query by type of symbol you want to see (i.e. `:variable:`) ---@param opts table: options to pass to the picker -builtin.lsp_dynamic_workspace_symbols = require('telescope.builtin.lsp').dynamic_workspace_symbols +builtin.lsp_dynamic_workspace_symbols = require("telescope.builtin.lsp").dynamic_workspace_symbols --- Lists LSP diagnostics for the current buffer --- - Fields: @@ -355,7 +355,7 @@ builtin.lsp_dynamic_workspace_symbols = require('telescope.builtin.lsp').dynamic ---@field severity_bound string|number: keep diagnostics equal or less severe wrt severity name (string) or id (number) ---@field no_sign bool: hide LspDiagnosticSigns from Results (default is false) ---@field line_width number: set length of diagnostic entry text in Results -builtin.lsp_document_diagnostics = require('telescope.builtin.lsp').diagnostics +builtin.lsp_document_diagnostics = require("telescope.builtin.lsp").diagnostics --- Lists LSP diagnostics for the current workspace if supported, otherwise searches in all open buffers --- - Fields: @@ -368,10 +368,10 @@ builtin.lsp_document_diagnostics = require('telescope.builtin.lsp').diagnostics ---@field severity_bound string|number: keep diagnostics equal or less severe wrt severity name (string) or id (number) ---@field no_sign bool: hide LspDiagnosticSigns from Results (default is false) ---@field line_width number: set length of diagnostic entry text in Results -builtin.lsp_workspace_diagnostics = require('telescope.builtin.lsp').workspace_diagnostics +builtin.lsp_workspace_diagnostics = require("telescope.builtin.lsp").workspace_diagnostics local apply_config = function(mod) - local pickers_conf = require('telescope.config').pickers + local pickers_conf = require("telescope.config").pickers for k, v in pairs(mod) do local pconf = vim.deepcopy(pickers_conf[k] or {}) if pconf.theme then diff --git a/lua/telescope/builtin/internal.lua b/lua/telescope/builtin/internal.lua index ad6293c..5355d5f 100644 --- a/lua/telescope/builtin/internal.lua +++ b/lua/telescope/builtin/internal.lua @@ -1,15 +1,15 @@ -local actions = require('telescope.actions') -local action_set = require('telescope.actions.set') -local action_state = require('telescope.actions.state') -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local Path = require('plenary.path') -local pickers = require('telescope.pickers') -local previewers = require('telescope.previewers') -local sorters = require('telescope.sorters') -local utils = require('telescope.utils') +local actions = require "telescope.actions" +local action_set = require "telescope.actions.set" +local action_state = require "telescope.actions.state" +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local Path = require "plenary.path" +local pickers = require "telescope.pickers" +local previewers = require "telescope.previewers" +local sorters = require "telescope.sorters" +local utils = require "telescope.utils" -local conf = require('telescope.config').values +local conf = require("telescope.config").values local filter = vim.tbl_filter @@ -25,7 +25,7 @@ internal.builtin = function(opts) local objs = {} - for k, v in pairs(require'telescope.builtin') do + for k, v in pairs(require "telescope.builtin") do local debug_info = debug.getinfo(v) table.insert(objs, { filename = string.sub(debug_info.source, 2), @@ -33,11 +33,11 @@ internal.builtin = function(opts) }) end - local title = 'Telescope Builtin' + local title = "Telescope Builtin" if opts.include_extensions then - title = 'Telescope Pickers' - for ext, funcs in pairs(require'telescope'.extensions) do + title = "Telescope Pickers" + for ext, funcs in pairs(require("telescope").extensions) do for func_name, func_obj in pairs(funcs) do local debug_info = debug.getinfo(func_obj) table.insert(objs, { @@ -50,7 +50,7 @@ internal.builtin = function(opts) pickers.new(opts, { prompt_title = title, - finder = finders.new_table { + finder = finders.new_table { results = objs, entry_maker = function(entry) return { @@ -58,44 +58,44 @@ internal.builtin = function(opts) text = entry.text, display = entry.text, ordinal = entry.text, - filename = entry.filename + filename = entry.filename, } - end + end, }, previewer = previewers.builtin.new(opts), sorter = conf.generic_sorter(opts), attach_mappings = function(_) actions.select_default:replace(actions.run_builtin) return true - end + end, }):find() end internal.planets = function(opts) local show_pluto = opts.show_pluto or false - local sourced_file = require('plenary.debug_utils').sourced_filepath() + local sourced_file = require("plenary.debug_utils").sourced_filepath() local base_directory = vim.fn.fnamemodify(sourced_file, ":h:h:h:h") - local globbed_files = vim.fn.globpath(base_directory .. '/data/memes/planets/', '*', true, true) + local globbed_files = vim.fn.globpath(base_directory .. "/data/memes/planets/", "*", true, true) local acceptable_files = {} for _, v in ipairs(globbed_files) do - if show_pluto or not v:find("pluto") then - table.insert(acceptable_files,vim.fn.fnamemodify(v, ':t')) + if show_pluto or not v:find "pluto" then + table.insert(acceptable_files, vim.fn.fnamemodify(v, ":t")) end end - pickers.new { - prompt_title = 'Planets', + pickers.new({ + prompt_title = "Planets", finder = finders.new_table { results = acceptable_files, entry_maker = function(line) return { ordinal = line, display = line, - filename = base_directory .. '/data/memes/planets/' .. line, + filename = base_directory .. "/data/memes/planets/" .. line, } - end + end, }, previewer = previewers.cat.new(opts), sorter = conf.generic_sorter(opts), @@ -109,14 +109,16 @@ internal.planets = function(opts) return true end, - }:find() + }):find() end internal.symbols = function(opts) - local files = vim.api.nvim_get_runtime_file('data/telescope-sources/*.json', true) + local files = vim.api.nvim_get_runtime_file("data/telescope-sources/*.json", true) if table.getn(files) == 0 then - print("No sources found! Check out https://github.com/nvim-telescope/telescope-symbols.nvim " .. - "for some prebuild symbols or how to create you own symbol source.") + print( + "No sources found! Check out https://github.com/nvim-telescope/telescope-symbols.nvim " + .. "for some prebuild symbols or how to create you own symbol source." + ) return end @@ -142,31 +144,31 @@ internal.symbols = function(opts) end pickers.new(opts, { - prompt_title = 'Symbols', - finder = finders.new_table { - results = results, + prompt_title = "Symbols", + finder = finders.new_table { + results = results, entry_maker = function(entry) return { value = entry, - ordinal = entry[1] .. ' ' .. entry[2], - display = entry[1] .. ' ' .. entry[2], + ordinal = entry[1] .. " " .. entry[2], + display = entry[1] .. " " .. entry[2], } - end + end, }, sorter = conf.generic_sorter(opts), attach_mappings = function(_) actions.select_default:replace(actions.insert_symbol) return true - end + end, }):find() end internal.commands = function(opts) pickers.new(opts, { - prompt_title = 'Commands', + prompt_title = "Commands", finder = finders.new_table { results = (function() - local command_iter = vim.api.nvim_get_commands({}) + local command_iter = vim.api.nvim_get_commands {} local commands = {} for _, cmd in pairs(command_iter) do @@ -195,7 +197,7 @@ internal.commands = function(opts) end) return true - end + end, }):find() end @@ -207,9 +209,9 @@ internal.quickfix = function(opts) end pickers.new(opts, { - prompt_title = 'Quickfix', - finder = finders.new_table { - results = locations, + prompt_title = "Quickfix", + finder = finders.new_table { + results = locations, entry_maker = opts.entry_maker or make_entry.gen_from_quickfix(opts), }, previewer = conf.qflist_previewer(opts), @@ -230,9 +232,9 @@ internal.loclist = function(opts) end pickers.new(opts, { - prompt_title = 'Loclist', - finder = finders.new_table { - results = locations, + prompt_title = "Loclist", + finder = finders.new_table { + results = locations, entry_maker = opts.entry_maker or make_entry.gen_from_quickfix(opts), }, previewer = conf.qflist_previewer(opts), @@ -248,8 +250,8 @@ internal.oldfiles = function(opts) local results = {} if opts.include_current_session then - for _, buffer in ipairs(vim.split(vim.fn.execute(':buffers! t'), "\n")) do - local match = tonumber(string.match(buffer, '%s*(%d+)')) + for _, buffer in ipairs(vim.split(vim.fn.execute ":buffers! t", "\n")) do + local match = tonumber(string.match(buffer, "%s*(%d+)")) if match then local file = vim.api.nvim_buf_get_name(match) if vim.loop.fs_stat(file) and match ~= current_buffer then @@ -267,15 +269,15 @@ internal.oldfiles = function(opts) if opts.cwd_only then local cwd = vim.loop.cwd() - cwd = cwd:gsub([[\]],[[\\]]) + cwd = cwd:gsub([[\]], [[\\]]) results = vim.tbl_filter(function(file) return vim.fn.matchstrpos(file, cwd)[2] ~= -1 end, results) end pickers.new(opts, { - prompt_title = 'Oldfiles', - finder = finders.new_table{ + prompt_title = "Oldfiles", + finder = finders.new_table { results = results, entry_maker = opts.entry_maker or make_entry.gen_from_file(opts), }, @@ -285,7 +287,7 @@ internal.oldfiles = function(opts) end internal.command_history = function(opts) - local history_string = vim.fn.execute('history cmd') + local history_string = vim.fn.execute "history cmd" local history_list = vim.split(history_string, "\n") local results = {} @@ -296,15 +298,15 @@ internal.command_history = function(opts) end pickers.new(opts, { - prompt_title = 'Command History', + prompt_title = "Command History", finder = finders.new_table(results), sorter = conf.generic_sorter(opts), attach_mappings = function(_, map) - map('i', '', actions.set_command_line) - map('n', '', actions.set_command_line) - map('n', '', actions.edit_command_line) - map('i', '', actions.edit_command_line) + map("i", "", actions.set_command_line) + map("n", "", actions.set_command_line) + map("n", "", actions.edit_command_line) + map("i", "", actions.edit_command_line) -- TODO: Find a way to insert the text... it seems hard. -- map('i', '', actions.insert_value, { expr = true }) @@ -315,7 +317,7 @@ internal.command_history = function(opts) end internal.search_history = function(opts) - local search_string = vim.fn.execute('history search') + local search_string = vim.fn.execute "history search" local search_list = vim.split(search_string, "\n") local results = {} @@ -326,15 +328,15 @@ internal.search_history = function(opts) end pickers.new(opts, { - prompt_title = 'Search History', + prompt_title = "Search History", finder = finders.new_table(results), sorter = conf.generic_sorter(opts), attach_mappings = function(_, map) - map('i', '', actions.set_search_line) - map('n', '', actions.set_search_line) - map('n', '', actions.edit_search_line) - map('i', '', actions.edit_search_line) + map("i", "", actions.set_search_line) + map("n", "", actions.set_search_line) + map("n", "", actions.edit_search_line) + map("i", "", actions.edit_search_line) -- TODO: Find a way to insert the text... it seems hard. -- map('i', '', actions.insert_value, { expr = true }) @@ -346,12 +348,10 @@ end internal.vim_options = function(opts) -- Load vim options. - local vim_opts = loadfile( - Path:new({utils.data_directory(), 'options', 'options.lua'}):absolute() - )().options + local vim_opts = loadfile(Path:new({ utils.data_directory(), "options", "options.lua" }):absolute())().options pickers.new(opts, { - prompt_title = 'options', + prompt_title = "options", finder = finders.new_table { results = vim_opts, entry_maker = opts.entry_maker or make_entry.gen_from_vimoptions(opts), @@ -403,7 +403,7 @@ internal.vim_options = function(opts) end) return true - end + end, }):find() end @@ -411,9 +411,9 @@ internal.help_tags = function(opts) opts.lang = utils.get_default(opts.lang, vim.o.helplang) opts.fallback = utils.get_default(opts.fallback, true) - local langs = vim.split(opts.lang, ',', true) - if opts.fallback and not vim.tbl_contains(langs, 'en') then - table.insert(langs, 'en') + local langs = vim.split(opts.lang, ",", true) + if opts.fallback and not vim.tbl_contains(langs, "en") then + table.insert(langs, "en") end local langs_map = {} for _, lang in ipairs(langs) do @@ -426,18 +426,18 @@ internal.help_tags = function(opts) if tag_files[lang] then table.insert(tag_files[lang], file) else - tag_files[lang] = {file} + tag_files[lang] = { file } end end end local help_files = {} - local all_files = vim.fn.globpath(vim.o.runtimepath, 'doc/*', 1, 1) + local all_files = vim.fn.globpath(vim.o.runtimepath, "doc/*", 1, 1) for _, fullpath in ipairs(all_files) do local file = utils.path_tail(fullpath) - if file == 'tags' then - add_tag_file('en', fullpath) - elseif file:match('^tags%-..$') then + if file == "tags" then + add_tag_file("en", fullpath) + elseif file:match "^tags%-..$" then local lang = file:sub(-2) add_tag_file(lang, fullpath) else @@ -450,10 +450,10 @@ internal.help_tags = function(opts) local delimiter = string.char(9) for _, lang in ipairs(langs) do for _, file in ipairs(tag_files[lang] or {}) do - local lines = vim.split(Path:new(file):read(), '\n', true) + local lines = vim.split(Path:new(file):read(), "\n", true) for _, line in ipairs(lines) do -- TODO: also ignore tagComment starting with ';' - if not line:match'^!_TAG_' then + if not line:match "^!_TAG_" then local fields = vim.split(line, delimiter, true) if #fields == 3 and not tags_map[fields[1]] then table.insert(tags, { @@ -470,16 +470,16 @@ internal.help_tags = function(opts) end pickers.new(opts, { - prompt_title = 'Help', + prompt_title = "Help", finder = finders.new_table { results = tags, entry_maker = function(entry) return { - value = entry.name .. '@' .. entry.lang, + value = entry.name .. "@" .. entry.lang, display = entry.name, ordinal = entry.name, filename = entry.filename, - cmd = entry.cmd + cmd = entry.cmd, } end, }, @@ -489,51 +489,51 @@ internal.help_tags = function(opts) action_set.select:replace(function(_, cmd) local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - if cmd == 'default' or cmd == 'horizontal' then - vim.cmd('help ' .. selection.value) - elseif cmd == 'vertical' then - vim.cmd('vert bo help ' .. selection.value) - elseif cmd == 'tab' then - vim.cmd('tab help ' .. selection.value) + if cmd == "default" or cmd == "horizontal" then + vim.cmd("help " .. selection.value) + elseif cmd == "vertical" then + vim.cmd("vert bo help " .. selection.value) + elseif cmd == "tab" then + vim.cmd("tab help " .. selection.value) end end) return true - end + end, }):find() end internal.man_pages = function(opts) - opts.sections = utils.get_default(opts.sections, {'1'}) - assert(vim.tbl_islist(opts.sections), 'sections should be a list') + opts.sections = utils.get_default(opts.sections, { "1" }) + assert(vim.tbl_islist(opts.sections), "sections should be a list") opts.man_cmd = utils.get_lazy_default(opts.man_cmd, function() - local is_darwin = vim.loop.os_uname().sysname == 'Darwin' - return is_darwin and {'apropos', ' '} or {'apropos', ''} + local is_darwin = vim.loop.os_uname().sysname == "Darwin" + return is_darwin and { "apropos", " " } or { "apropos", "" } end) opts.entry_maker = opts.entry_maker or make_entry.gen_from_apropos(opts) pickers.new(opts, { - prompt_title = 'Man', - finder = finders.new_oneshot_job(opts.man_cmd, opts), + prompt_title = "Man", + finder = finders.new_oneshot_job(opts.man_cmd, opts), previewer = previewers.man.new(opts), sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) action_set.select:replace(function(_, cmd) local selection = action_state.get_selected_entry() - local args = selection.section .. ' ' .. selection.value + local args = selection.section .. " " .. selection.value actions.close(prompt_bufnr) - if cmd == 'default' or cmd == 'horizontal' then - vim.cmd('Man ' .. args) - elseif cmd == 'vertical' then - vim.cmd('vert bo Man ' .. args) - elseif cmd == 'tab' then - vim.cmd('tab Man ' .. args) + if cmd == "default" or cmd == "horizontal" then + vim.cmd("Man " .. args) + elseif cmd == "vertical" then + vim.cmd("vert bo Man " .. args) + elseif cmd == "tab" then + vim.cmd("tab Man " .. args) end end) return true - end + end, }):find() end @@ -543,9 +543,11 @@ internal.reloader = function(opts) -- filter out packages we don't want and track the longest package name opts.column_len = 0 for index, module_name in pairs(package_list) do - if type(require(module_name)) ~= 'table' or - module_name:sub(1,1) == "_" or - package.searchpath(module_name, package.path) == nil then + if + type(require(module_name)) ~= "table" + or module_name:sub(1, 1) == "_" + or package.searchpath(module_name, package.path) == nil + then table.remove(package_list, index) elseif #module_name > opts.column_len then opts.column_len = #module_name @@ -553,7 +555,7 @@ internal.reloader = function(opts) end pickers.new(opts, { - prompt_title = 'Packages', + prompt_title = "Packages", finder = finders.new_table { results = package_list, entry_maker = opts.entry_maker or make_entry.gen_from_packages(opts), @@ -566,19 +568,19 @@ internal.reloader = function(opts) local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - require('plenary.reload').reload_module(selection.value) + require("plenary.reload").reload_module(selection.value) print(string.format("[%s] - module reloaded", selection.value)) end) return true - end + end, }):find() end internal.buffers = function(opts) local bufnrs = filter(function(b) if 1 ~= vim.fn.buflisted(b) then - return false + return false end -- only hide unloaded buffers if opts.show_all_buffers is false, keep them listed if true or nil if opts.show_all_buffers == false and not vim.api.nvim_buf_is_loaded(b) then @@ -592,7 +594,9 @@ internal.buffers = function(opts) end return true end, vim.api.nvim_list_bufs()) - if not next(bufnrs) then return end + if not next(bufnrs) then + return + end if opts.sort_mru then table.sort(bufnrs, function(a, b) return vim.fn.getbufinfo(a)[1].lastused > vim.fn.getbufinfo(b)[1].lastused @@ -602,7 +606,7 @@ internal.buffers = function(opts) local buffers = {} local default_selection_idx = 1 for _, bufnr in ipairs(bufnrs) do - local flag = bufnr == vim.fn.bufnr('') and '%' or (bufnr == vim.fn.bufnr('#') and '#' or ' ') + local flag = bufnr == vim.fn.bufnr "" and "%" or (bufnr == vim.fn.bufnr "#" and "#" or " ") if opts.sort_lastused and not opts.ignore_current_buffer and flag == "#" then default_selection_idx = 2 @@ -628,10 +632,10 @@ internal.buffers = function(opts) end pickers.new(opts, { - prompt_title = 'Buffers', - finder = finders.new_table { + prompt_title = "Buffers", + finder = finders.new_table { results = buffers, - entry_maker = opts.entry_maker or make_entry.gen_from_buffer(opts) + entry_maker = opts.entry_maker or make_entry.gen_from_buffer(opts), }, previewer = conf.grep_previewer(opts), sorter = conf.generic_sorter(opts), @@ -640,7 +644,7 @@ internal.buffers = function(opts) end internal.colorscheme = function(opts) - local before_color = vim.api.nvim_exec('colorscheme', true) + local before_color = vim.api.nvim_exec("colorscheme", true) local need_restore = true local colors = opts.colors or { before_color } @@ -652,10 +656,7 @@ internal.colorscheme = function(opts) colors, vim.tbl_filter(function(color) return color ~= before_color - end, vim.fn.getcompletion( - '', - 'color' - )) + end, vim.fn.getcompletion("", "color")) ) local previewer @@ -681,7 +682,7 @@ internal.colorscheme = function(opts) del_win(status.preview_win) del_win(status.preview_border_win) end - vim.cmd('colorscheme ' .. entry.value) + vim.cmd("colorscheme " .. entry.value) end, } else @@ -697,14 +698,14 @@ internal.colorscheme = function(opts) local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) end - vim.cmd('colorscheme ' .. entry.value) + vim.cmd("colorscheme " .. entry.value) end, } end end local picker = pickers.new(opts, { - prompt_title = 'Change Colorscheme', + prompt_title = "Change Colorscheme", finder = finders.new_table { results = colors, }, @@ -716,7 +717,7 @@ internal.colorscheme = function(opts) actions.close(prompt_bufnr) need_restore = false - vim.cmd('colorscheme ' .. selection.value) + vim.cmd("colorscheme " .. selection.value) end) return true @@ -729,7 +730,7 @@ internal.colorscheme = function(opts) picker.close_windows = function(status) close_windows(status) if need_restore then - vim.cmd('colorscheme ' .. before_color) + vim.cmd("colorscheme " .. before_color) end end end @@ -744,8 +745,8 @@ internal.marks = function(opts) -- Pop off the header. table.remove(marks_table, 1) - pickers.new(opts,{ - prompt_title = 'Marks', + pickers.new(opts, { + prompt_title = "Marks", finder = finders.new_table { results = marks_table, entry_maker = opts.entry_maker or make_entry.gen_from_marks(opts), @@ -756,7 +757,7 @@ internal.marks = function(opts) end internal.registers = function(opts) - local registers_table = {"\"", "_", "#", "=", "_", "/", "*", "+", ":", ".", "%"} + local registers_table = { '"', "_", "#", "=", "_", "/", "*", "+", ":", ".", "%" } -- named for i = 0, 9 do @@ -768,8 +769,8 @@ internal.registers = function(opts) table.insert(registers_table, string.char(i)) end - pickers.new(opts,{ - prompt_title = 'Registers', + pickers.new(opts, { + prompt_title = "Registers", finder = finders.new_table { results = registers_table, entry_maker = opts.entry_maker or make_entry.gen_from_registers(opts), @@ -778,7 +779,7 @@ internal.registers = function(opts) sorter = sorters.get_levenshtein_sorter(), attach_mappings = function(_, map) actions.select_default:replace(actions.paste_register) - map('i', '', actions.edit_register) + map("i", "", actions.edit_register) return true end, @@ -787,7 +788,7 @@ end -- TODO: make filtering include the mapping and the action internal.keymaps = function(opts) - local modes = {"n", "i", "c"} + local modes = { "n", "i", "c" } local keymaps_table = {} for _, mode in pairs(modes) do @@ -802,7 +803,7 @@ internal.keymaps = function(opts) end pickers.new(opts, { - prompt_title = 'Key Maps', + prompt_title = "Key Maps", finder = finders.new_table { results = keymaps_table, entry_maker = function(line) @@ -810,29 +811,27 @@ internal.keymaps = function(opts) valid = line ~= "", value = line, ordinal = utils.display_termcodes(line.lhs) .. line.rhs, - display = line.mode .. ' ' .. utils.display_termcodes(line.lhs) .. ' ' .. line.rhs + display = line.mode .. " " .. utils.display_termcodes(line.lhs) .. " " .. line.rhs, } - end + end, }, sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() - vim.api.nvim_feedkeys( - vim.api.nvim_replace_termcodes(selection.value.lhs, true, false, true), - "t", true) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(selection.value.lhs, true, false, true), "t", true) return actions.close(prompt_bufnr) end) return true - end + end, }):find() end internal.filetypes = function(opts) - local filetypes = vim.fn.getcompletion('', 'filetype') + local filetypes = vim.fn.getcompletion("", "filetype") pickers.new(opts, { - prompt_title = 'Filetypes', + prompt_title = "Filetypes", finder = finders.new_table { results = filetypes, }, @@ -841,28 +840,28 @@ internal.filetypes = function(opts) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - vim.cmd('setfiletype ' .. selection[1]) + vim.cmd("setfiletype " .. selection[1]) end) return true - end + end, }):find() end internal.highlights = function(opts) - local highlights = vim.fn.getcompletion('', 'highlight') + local highlights = vim.fn.getcompletion("", "highlight") pickers.new(opts, { - prompt_title = 'Highlights', + prompt_title = "Highlights", finder = finders.new_table { results = highlights, - entry_maker = opts.entry_maker or make_entry.gen_from_highlights(opts) + entry_maker = opts.entry_maker or make_entry.gen_from_highlights(opts), }, sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - vim.cmd('hi ' .. selection.value) + vim.cmd("hi " .. selection.value) end) return true end, @@ -873,10 +872,10 @@ end internal.autocommands = function(opts) local autocmd_table = {} - local pattern = {} + local pattern = {} pattern.BUFFER = "" - pattern.EVENT = "[%a]+" - pattern.GROUP = "[%a%d_:]+" + pattern.EVENT = "[%a]+" + pattern.GROUP = "[%a%d_:]+" pattern.INDENT = "^%s%s%s%s" -- match indentation of 4 spaces local event, group, ft_pat, cmd, source_file, source_lnum @@ -902,7 +901,7 @@ internal.autocommands = function(opts) -- non event/group lines ft_pat = line:match(pattern.INDENT .. "(%S+)") if ft_pat then - if ft_pat:match("^%d+") then + if ft_pat:match "^%d+" then ft_pat = "" end current_ft = ft_pat @@ -920,13 +919,13 @@ internal.autocommands = function(opts) end if current_ft and cmd then - source_file, source_lnum = line:match("Last set from (.*) line (.*)") + source_file, source_lnum = line:match "Last set from (.*) line (.*)" if source_file then local autocmd = {} - autocmd.event = current_event - autocmd.group = current_group - autocmd.ft_pattern = current_ft - autocmd.command = cmd + autocmd.event = current_event + autocmd.group = current_group + autocmd.ft_pattern = current_ft + autocmd.command = cmd autocmd.source_file = source_file autocmd.source_lnum = source_lnum table.insert(autocmd_table, autocmd) @@ -937,12 +936,12 @@ internal.autocommands = function(opts) end local cmd_output = vim.fn.execute("verb autocmd *", "silent") - for line in cmd_output:gmatch("[^\r\n]+") do + for line in cmd_output:gmatch "[^\r\n]+" do inner_loop(line) end - pickers.new(opts,{ - prompt_title = 'autocommands', + pickers.new(opts, { + prompt_title = "autocommands", finder = finders.new_table { results = autocmd_table, entry_maker = opts.entry_maker or make_entry.gen_from_autocommands(opts), @@ -953,22 +952,24 @@ internal.autocommands = function(opts) action_set.select:replace(function(_, type) local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - vim.cmd(action_state.select_key_to_edit_key(type) .. ' ' .. selection.value) + vim.cmd(action_state.select_key_to_edit_key(type) .. " " .. selection.value) end) return true - end + end, }):find() end internal.spell_suggest = function(opts) - if not vim.wo.spell then return false end + if not vim.wo.spell then + return false + end - local cursor_word = vim.fn.expand("") + local cursor_word = vim.fn.expand "" local suggestions = vim.fn.spellsuggest(cursor_word) pickers.new(opts, { - prompt_title = 'Spelling Suggestions', + prompt_title = "Spelling Suggestions", finder = finders.new_table { results = suggestions, }, @@ -977,11 +978,11 @@ internal.spell_suggest = function(opts) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - vim.cmd('normal! ciw' .. selection[1]) - vim.cmd('stopinsert') + vim.cmd("normal! ciw" .. selection[1]) + vim.cmd "stopinsert" end) return true - end + end, }):find() end @@ -999,22 +1000,17 @@ internal.tagstack = function(opts) tag.lnum = tag.from[2] tag.col = tag.from[3] - tag.text = vim.api.nvim_buf_get_lines( - tag.bufnr, - tag.lnum - 1, - tag.lnum, - false - )[1] or '' + tag.text = vim.api.nvim_buf_get_lines(tag.bufnr, tag.lnum - 1, tag.lnum, false)[1] or "" end end if vim.tbl_isempty(tags) then - print("No tagstack available") + print "No tagstack available" return end pickers.new(opts, { - prompt_title = 'TagStack', + prompt_title = "TagStack", finder = finders.new_table { results = tags, entry_maker = make_entry.gen_from_quickfix(opts), @@ -1032,14 +1028,14 @@ internal.jumplist = function(opts) local sorted_jumplist = {} for i = #jumplist, 1, -1 do if vim.api.nvim_buf_is_valid(jumplist[i].bufnr) then - jumplist[i].text = vim.api.nvim_buf_get_lines(jumplist[i].bufnr, jumplist[i].lnum, jumplist[i].lnum+1, - false)[1] or '' + jumplist[i].text = vim.api.nvim_buf_get_lines(jumplist[i].bufnr, jumplist[i].lnum, jumplist[i].lnum + 1, false)[1] + or "" table.insert(sorted_jumplist, jumplist[i]) end end pickers.new(opts, { - prompt_title = 'Jumplist', + prompt_title = "Jumplist", finder = finders.new_table { results = sorted_jumplist, entry_maker = make_entry.gen_from_quickfix(opts), diff --git a/lua/telescope/builtin/lsp.lua b/lua/telescope/builtin/lsp.lua index a238796..69b03d8 100644 --- a/lua/telescope/builtin/lsp.lua +++ b/lua/telescope/builtin/lsp.lua @@ -1,16 +1,16 @@ -local actions = require('telescope.actions') -local action_state = require('telescope.actions.state') -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local pickers = require('telescope.pickers') -local entry_display = require('telescope.pickers.entry_display') -local utils = require('telescope.utils') -local strings = require('plenary.strings') -local a = require('plenary.async_lib') +local actions = require "telescope.actions" +local action_state = require "telescope.actions.state" +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local pickers = require "telescope.pickers" +local entry_display = require "telescope.pickers.entry_display" +local utils = require "telescope.utils" +local strings = require "plenary.strings" +local a = require "plenary.async_lib" local async, await = a.async, a.await local channel = a.util.channel -local conf = require('telescope.config').values +local conf = require("telescope.config").values local lsp = {} @@ -36,8 +36,8 @@ lsp.references = function(opts) end pickers.new(opts, { - prompt_title = 'LSP References', - finder = finders.new_table { + prompt_title = "LSP References", + finder = finders.new_table { results = locations, entry_maker = opts.entry_maker or make_entry.gen_from_quickfix(opts), }, @@ -81,11 +81,11 @@ local function list_or_jump(action, title, opts) end lsp.definitions = function(opts) - return list_or_jump("textDocument/definition", 'LSP Definitions', opts) + return list_or_jump("textDocument/definition", "LSP Definitions", opts) end lsp.implementations = function(opts) - return list_or_jump("textDocument/implementation", 'LSP Implementations', opts) + return list_or_jump("textDocument/implementation", "LSP Implementations", opts) end lsp.document_symbols = function(opts) @@ -97,7 +97,7 @@ lsp.document_symbols = function(opts) end if not results_lsp or vim.tbl_isempty(results_lsp) then - print("No results from textDocument/documentSymbol") + print "No results from textDocument/documentSymbol" return end @@ -118,16 +118,16 @@ lsp.document_symbols = function(opts) opts.ignore_filename = opts.ignore_filename or true pickers.new(opts, { - prompt_title = 'LSP Document Symbols', - finder = finders.new_table { + prompt_title = "LSP Document Symbols", + finder = finders.new_table { results = locations, - entry_maker = opts.entry_maker or make_entry.gen_from_lsp_symbols(opts) + entry_maker = opts.entry_maker or make_entry.gen_from_lsp_symbols(opts), }, previewer = conf.qflist_previewer(opts), - sorter = conf.prefilter_sorter{ + sorter = conf.prefilter_sorter { tag = "symbol_type", - sorter = conf.generic_sorter(opts) - } + sorter = conf.generic_sorter(opts), + }, }):find() end @@ -135,7 +135,7 @@ lsp.code_actions = function(opts) local params = opts.params or vim.lsp.util.make_range_params() params.context = { - diagnostics = vim.lsp.diagnostic.get_line_diagnostics() + diagnostics = vim.lsp.diagnostic.get_line_diagnostics(), } local results_lsp, err = vim.lsp.buf_request_sync(0, "textDocument/codeAction", params, opts.timeout or 10000) @@ -146,7 +146,7 @@ lsp.code_actions = function(opts) end if not results_lsp or vim.tbl_isempty(results_lsp) then - print("No results from textDocument/codeAction") + print "No results from textDocument/codeAction" return end @@ -181,7 +181,7 @@ lsp.code_actions = function(opts) end if #results == 0 then - print("No code actions available") + print "No code actions available" return end @@ -196,15 +196,15 @@ lsp.code_actions = function(opts) local function make_display(entry) return displayer { - {entry.idx .. ":", "TelescopePromptPrefix"}, - {entry.command_title}, - {entry.client_name, "TelescopeResultsComment"}, + { entry.idx .. ":", "TelescopePromptPrefix" }, + { entry.command_title }, + { entry.client_name, "TelescopeResultsComment" }, } end pickers.new(opts, { - prompt_title = 'LSP Code Actions', - finder = finders.new_table { + prompt_title = "LSP Code Actions", + finder = finders.new_table { results = results, entry_maker = function(line) return { @@ -216,7 +216,7 @@ lsp.code_actions = function(opts) client_name = line.client_name, display = make_display, } - end + end, }, attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() @@ -243,12 +243,12 @@ lsp.code_actions = function(opts) end lsp.range_code_actions = function(opts) - opts.params = vim.lsp.util.make_given_range_params() - lsp.code_actions(opts) + opts.params = vim.lsp.util.make_given_range_params() + lsp.code_actions(opts) end lsp.workspace_symbols = function(opts) - local params = {query = opts.query or ''} + local params = { query = opts.query or "" } local results_lsp, err = vim.lsp.buf_request_sync(0, "workspace/symbol", params, opts.timeout or 10000) if err then vim.api.nvim_err_writeln("Error when finding workspace symbols: " .. err) @@ -273,24 +273,26 @@ lsp.workspace_symbols = function(opts) end if vim.tbl_isempty(locations) then - print("No results from workspace/symbol. Maybe try a different query: " .. - "Telescope lsp_workspace_symbols query=example") + print( + "No results from workspace/symbol. Maybe try a different query: " + .. "Telescope lsp_workspace_symbols query=example" + ) return end opts.ignore_filename = utils.get_default(opts.ignore_filename, false) pickers.new(opts, { - prompt_title = 'LSP Workspace Symbols', - finder = finders.new_table { + prompt_title = "LSP Workspace Symbols", + finder = finders.new_table { results = locations, - entry_maker = opts.entry_maker or make_entry.gen_from_lsp_symbols(opts) + entry_maker = opts.entry_maker or make_entry.gen_from_lsp_symbols(opts), }, previewer = conf.qflist_previewer(opts), - sorter = conf.prefilter_sorter{ + sorter = conf.prefilter_sorter { tag = "symbol_type", - sorter = conf.generic_sorter(opts) - } + sorter = conf.generic_sorter(opts), + }, }):find() end @@ -300,7 +302,7 @@ local function get_workspace_symbols_requester(bufnr) return async(function(prompt) local tx, rx = channel.oneshot() cancel() - _, cancel = vim.lsp.buf_request(bufnr, "workspace/symbol", {query = prompt}, tx) + _, cancel = vim.lsp.buf_request(bufnr, "workspace/symbol", { query = prompt }, tx) local err, _, results_lsp = await(rx()) assert(not err, err) @@ -314,13 +316,13 @@ lsp.dynamic_workspace_symbols = function(opts) local curr_bufnr = vim.api.nvim_get_current_buf() pickers.new(opts, { - prompt_title = 'LSP Dynamic Workspace Symbols', - finder = finders.new_dynamic { + prompt_title = "LSP Dynamic Workspace Symbols", + finder = finders.new_dynamic { entry_maker = opts.entry_maker or make_entry.gen_from_lsp_symbols(opts), fn = get_workspace_symbols_requester(curr_bufnr), }, previewer = conf.qflist_previewer(opts), - sorter = conf.generic_sorter() + sorter = conf.generic_sorter(), }):find() end @@ -328,29 +330,29 @@ lsp.diagnostics = function(opts) local locations = utils.diagnostics_to_tbl(opts) if vim.tbl_isempty(locations) then - print('No diagnostics found') + print "No diagnostics found" return end - opts.path_display = utils.get_default(opts.path_display, 'hidden') + opts.path_display = utils.get_default(opts.path_display, "hidden") pickers.new(opts, { - prompt_title = 'LSP Document Diagnostics', + prompt_title = "LSP Document Diagnostics", finder = finders.new_table { results = locations, - entry_maker = opts.entry_maker or make_entry.gen_from_lsp_diagnostics(opts) + entry_maker = opts.entry_maker or make_entry.gen_from_lsp_diagnostics(opts), }, previewer = conf.qflist_previewer(opts), - sorter = conf.prefilter_sorter{ + sorter = conf.prefilter_sorter { tag = "type", - sorter = conf.generic_sorter(opts) - } + sorter = conf.generic_sorter(opts), + }, }):find() end lsp.workspace_diagnostics = function(opts) opts = utils.get_default(opts, {}) opts.path_display = utils.get_default(opts.path_display, {}) - opts.prompt_title = 'LSP Workspace Diagnostics' + opts.prompt_title = "LSP Workspace Diagnostics" opts.get_all = true lsp.diagnostics(opts) end @@ -361,14 +363,16 @@ local function check_capabilities(feature) local supported_client = false for _, client in pairs(clients) do supported_client = client.resolved_capabilities[feature] - if supported_client then break end + if supported_client then + break + end end if supported_client then return true else if #clients == 0 then - print("LSP: no client attached") + print "LSP: no client attached" else print("LSP: server does not support " .. feature) end @@ -377,11 +381,11 @@ local function check_capabilities(feature) end local feature_map = { - ["code_actions"] = "code_action", - ["document_symbols"] = "document_symbol", - ["references"] = "find_references", - ["definitions"] = "goto_definition", - ["implementations"] = "implementation", + ["code_actions"] = "code_action", + ["document_symbols"] = "document_symbol", + ["references"] = "find_references", + ["definitions"] = "goto_definition", + ["implementations"] = "implementation", ["workspace_symbols"] = "workspace_symbol", } diff --git a/lua/telescope/command.lua b/lua/telescope/command.lua index 9013ffc..c123b7b 100644 --- a/lua/telescope/command.lua +++ b/lua/telescope/command.lua @@ -1,15 +1,18 @@ -local themes = require('telescope.themes') -local builtin = require('telescope.builtin') -local extensions = require('telescope._extensions').manager -local config = require('telescope.config') +local themes = require "telescope.themes" +local builtin = require "telescope.builtin" +local extensions = require("telescope._extensions").manager +local config = require "telescope.config" local command = {} local arg_value = { - ['nil'] = nil,['""'] = '',['"'] = '' + ["nil"] = nil, + ['""'] = "", + ['"'] = "", } local bool_type = { - ['false'] = false,['true'] = true + ["false"] = false, + ["true"] = true, } -- convert command line string arguments to @@ -18,17 +21,17 @@ local function convert_user_opts(user_opts) local default_opts = config.values local _switch = { - ['boolean'] = function(key,val) - if val == 'false' then + ["boolean"] = function(key, val) + if val == "false" then user_opts[key] = false return end user_opts[key] = true end, - ['number'] = function(key,val) + ["number"] = function(key, val) user_opts[key] = tonumber(val) end, - ['string'] = function(key,val) + ["string"] = function(key, val) if arg_value[val] ~= nil then user_opts[key] = arg_value[val] return @@ -37,22 +40,22 @@ local function convert_user_opts(user_opts) if bool_type[val] ~= nil then user_opts[key] = bool_type[val] end - end + end, } local _switch_metatable = { - __index = function(_,k) - print(string.format('Type of %s does not match',k)) - end + __index = function(_, k) + print(string.format("Type of %s does not match", k)) + end, } - setmetatable(_switch,_switch_metatable) + setmetatable(_switch, _switch_metatable) - for key,val in pairs(user_opts) do + for key, val in pairs(user_opts) do if default_opts[key] ~= nil then - _switch[type(default_opts[key])](key,val) + _switch[type(default_opts[key])](key, val) else - _switch['string'](key,val) + _switch["string"](key, val) end end end @@ -69,14 +72,14 @@ end local function run_command(args) local user_opts = args or {} if next(user_opts) == nil and not user_opts.cmd then - print('[Telescope] your command miss args') + print "[Telescope] your command miss args" return end local cmd = user_opts.cmd local opts = user_opts.opts or {} - local extension_type = user_opts.extension_type or '' - local theme = user_opts.theme or '' + local extension_type = user_opts.extension_type or "" + local theme = user_opts.theme or "" if next(opts) ~= nil then convert_user_opts(opts) @@ -96,7 +99,7 @@ local function run_command(args) return end - if rawget(extensions,cmd) then + if rawget(extensions, cmd) then extensions[cmd][cmd](opts) end end @@ -106,12 +109,12 @@ end -- input in command line `Telescope gh ` -- Returns a list for each extension. function command.get_extensions_subcommand() - local exts = require('telescope._extensions').manager + local exts = require("telescope._extensions").manager local complete_ext_table = {} - for cmd,value in pairs(exts) do + for cmd, value in pairs(exts) do if type(value) == "table" then local subcmds = {} - for key,_ in pairs(value) do + for key, _ in pairs(value) do table.insert(subcmds, key) end complete_ext_table[cmd] = subcmds @@ -121,36 +124,36 @@ function command.get_extensions_subcommand() end local split_keywords = { - ['find_command'] = true, - ['vimgrep_arguments'] = true, - ['sections'] = true, - ['search_dirs'] = true + ["find_command"] = true, + ["vimgrep_arguments"] = true, + ["sections"] = true, + ["search_dirs"] = true, } function command.register_keyword(keyword) split_keywords[keyword] = true end -function command.load_command(cmd,...) - local args = {...} +function command.load_command(cmd, ...) + local args = { ... } if cmd == nil then - run_command({cmd = 'builtin'}) + run_command { cmd = "builtin" } return end local user_opts = {} - user_opts['cmd'] = cmd + user_opts["cmd"] = cmd user_opts.opts = {} - for _,arg in ipairs(args) do - if arg:find('=',1) == nil then - user_opts['extension_type'] = arg + for _, arg in ipairs(args) do + if arg:find("=", 1) == nil then + user_opts["extension_type"] = arg else - local param = vim.split(arg,'=') - if param[1] == 'theme' then - user_opts['theme'] = param[2] + local param = vim.split(arg, "=") + if param[1] == "theme" then + user_opts["theme"] = param[2] elseif split_keywords[param[1]] then - user_opts.opts[param[1]] = vim.split(param[2],',') + user_opts.opts[param[1]] = vim.split(param[2], ",") else user_opts.opts[param[1]] = param[2] end diff --git a/lua/telescope/config.lua b/lua/telescope/config.lua index 4593f7f..8db9cbb 100644 --- a/lua/telescope/config.lua +++ b/lua/telescope/config.lua @@ -38,9 +38,9 @@ local smarter_depth_2_extend = function(priority, base) end for key, val in pairs(priority) do if type(val) ~= "table" then - result[key] = first_non_null(val,result[key]) + result[key] = first_non_null(val, result[key]) else - result[key] = vim.tbl_extend("keep",val,result[key] or {}) + result[key] = vim.tbl_extend("keep", val, result[key] or {}) end end return result @@ -83,10 +83,11 @@ local layout_config_defaults = { cursor = { preview_cutoff = 40, - } + }, } -local layout_config_description = string.format([[ +local layout_config_description = string.format( + [[ Determines the default configuration values for layout strategies. See |telescope.layout| for details of the configurations options for each strategy. @@ -98,10 +99,9 @@ local layout_config_description = string.format([[ of 50%% of the screen width. Default: %s -]], vim.inspect( - layout_config_defaults, - { newline = "\n ", indent = " " } -)) +]], + vim.inspect(layout_config_defaults, { newline = "\n ", indent = " " }) +) -- A table of all the usual defaults for telescope. -- Keys will be the name of the default, @@ -159,19 +159,19 @@ local telescope_defaults = { prompt_prefix = { "> ", [[ Will be shown in front of the prompt. - Default: '> ']] - }, + Default: '> ']] }, selection_caret = { "> ", [[ Will be shown in front of the selection. - Default: '> ']] - }, + Default: '> ']] }, - entry_prefix = { " ", [[ + entry_prefix = { + " ", + [[ Prefix in front of each result entry. Current selection not included. - Default: ' ']] + Default: ' ']], }, initial_mode = { "insert" }, @@ -179,10 +179,11 @@ local telescope_defaults = { border = { true, [[ Boolean defining if borders are added to Telescope windows. - Default: true]] - }, + Default: true]] }, - path_display = { {}, [[ + path_display = { + {}, + [[ Determines how file paths are displayed path_display can be set to an array with a combination of: @@ -212,10 +213,9 @@ local telescope_defaults = { return string.format("%s (%s)", tail, path) end, - Default: {}]] + Default: {}]], }, - borderchars = { { "─", "│", "─", "│", "╭", "╮", "╯", "╰" } }, get_status_text = { @@ -230,7 +230,9 @@ local telescope_defaults = { end, }, - dynamic_preview_title = { false, [[ + dynamic_preview_title = { + false, + [[ Will change the title of the preview window dynamically, where it is supported. Means the preview window will for example show the full filename. @@ -238,11 +240,15 @@ local telescope_defaults = { Default: false]], }, - history = { { - path = vim.fn.stdpath("data") .. os_sep .. "telescope_history", - limit = 100, - handler = function(...) return require('telescope.actions.history').get_simple_history(...) end, - }, [[ + history = { + { + path = vim.fn.stdpath "data" .. os_sep .. "telescope_history", + limit = 100, + handler = function(...) + return require("telescope.actions.history").get_simple_history(...) + end, + }, + [[ This field handles the configuration for prompt history. By default it is a table, with default values (more below). To disable history, set it to false. @@ -271,7 +277,6 @@ local telescope_defaults = { Default: require('telescope.actions.history').get_simple_history ]], - }, -- Builtin configuration @@ -289,7 +294,8 @@ local telescope_defaults = { set_env = { nil }, mappings = { - {}, [[ + {}, + [[ Your mappings to override telescope's default mappings. Format is: diff --git a/lua/telescope/config/resolve.lua b/lua/telescope/config/resolve.lua index 6881830..b62e47d 100644 --- a/lua/telescope/config/resolve.lua +++ b/lua/telescope/config/resolve.lua @@ -90,20 +90,24 @@ That's the next step to scrolling. --]] -local get_default = require('telescope.utils').get_default +local get_default = require("telescope.utils").get_default local resolver = {} local _resolve_map = {} -- Booleans -_resolve_map[function(val) return val == false end] = function(_, val) +_resolve_map[function(val) + return val == false +end] = function(_, val) return function(...) return val end end -- Percentages -_resolve_map[function(val) return type(val) == 'number' and val >= 0 and val < 1 end] = function(selector, val) +_resolve_map[function(val) + return type(val) == "number" and val >= 0 and val < 1 +end] = function(selector, val) return function(...) local selected = select(selector, ...) return math.floor(val * selected) @@ -111,7 +115,9 @@ _resolve_map[function(val) return type(val) == 'number' and val >= 0 and val < 1 end -- Numbers -_resolve_map[function(val) return type(val) == 'number' and val >= 1 end] = function(selector, val) +_resolve_map[function(val) + return type(val) == "number" and val >= 1 +end] = function(selector, val) return function(...) local selected = select(selector, ...) return math.min(val, selected) @@ -126,12 +132,16 @@ end -- function(self, max_columns, max_lines): number -- -- Resulting number is used for this configuration value. -_resolve_map[function(val) return type(val) == 'function' end] = function(_, val) +_resolve_map[function(val) + return type(val) == "function" +end] = function(_, val) return val end -- Add padding option -_resolve_map[function(val) return type(val) == 'table' and val['padding'] ~= nil end] = function(selector, val) +_resolve_map[function(val) + return type(val) == "table" and val["padding"] ~= nil +end] = function(selector, val) local resolve_pad = function(value) for k, v in pairs(_resolve_map) do if k(value) then @@ -139,17 +149,16 @@ _resolve_map[function(val) return type(val) == 'table' and val['padding'] ~= nil end end - error('invalid configuration option for padding:' .. tostring(value)) + error("invalid configuration option for padding:" .. tostring(value)) end return function(...) local selected = select(selector, ...) - local padding = resolve_pad(val['padding']) + local padding = resolve_pad(val["padding"]) return math.floor(selected - 2 * padding(...)) end end - --- Converts input to a function that returns the height. --- The input must take one of four forms: --- 1. 0 <= number < 1
@@ -174,7 +183,7 @@ resolver.resolve_height = function(val) end end - error('invalid configuration option for height:' .. tostring(val)) + error("invalid configuration option for height:" .. tostring(val)) end --- Converts input to a function that returns the width. @@ -201,7 +210,7 @@ resolver.resolve_width = function(val) end end - error('invalid configuration option for width:' .. tostring(val)) + error("invalid configuration option for width:" .. tostring(val)) end -- Win option always returns a table with preview, results, and prompt. @@ -226,7 +235,7 @@ end -- prompt = {...}, -- } resolver.win_option = function(val, default) - if type(val) ~= 'table' or vim.tbl_islist(val) then + if type(val) ~= "table" or vim.tbl_islist(val) then if val == nil then val = default end @@ -236,7 +245,7 @@ resolver.win_option = function(val, default) results = val, prompt = val, } - elseif type(val) == 'table' then + elseif type(val) == "table" then assert(not vim.tbl_islist(val)) local val_to_set = val[1] diff --git a/lua/telescope/debounce.lua b/lua/telescope/debounce.lua index d223e41..6e230b5 100644 --- a/lua/telescope/debounce.lua +++ b/lua/telescope/debounce.lua @@ -5,12 +5,12 @@ local M = {} ---Validates args for `throttle()` and `debounce()`. local function td_validate(fn, ms) - vim.validate{ - fn = { fn, 'f' }, + vim.validate { + fn = { fn, "f" }, ms = { ms, function(v) - return type(v) == 'number' and v > 0 + return type(v) == "number" and v > 0 end, "number > 0", }, @@ -58,8 +58,8 @@ function M.throttle_trailing(fn, ms, last) if not last then function wrapped_fn(...) if not running then - local argv = {...} - local argc = select('#', ...) + local argv = { ... } + local argc = select("#", ...) timer:start(ms, 0, function() running = false @@ -71,8 +71,8 @@ function M.throttle_trailing(fn, ms, last) else local argv, argc function wrapped_fn(...) - argv = {...} - argc = select('#', ...) + argv = { ... } + argc = select("#", ...) if not running then timer:start(ms, 0, function() @@ -126,8 +126,8 @@ function M.debounce_trailing(fn, ms, first) if not first then function wrapped_fn(...) - local argv = {...} - local argc = select('#', ...) + local argv = { ... } + local argc = select("#", ...) timer:start(ms, 0, function() pcall(vim.schedule_wrap(fn), unpack(argv, 1, argc)) @@ -136,8 +136,8 @@ function M.debounce_trailing(fn, ms, first) else local argv, argc function wrapped_fn(...) - argv = argv or {...} - argc = argc or select('#', ...) + argv = argv or { ... } + argc = argc or select("#", ...) timer:start(ms, 0, function() pcall(vim.schedule_wrap(fn), unpack(argv, 1, argc)) @@ -163,16 +163,16 @@ function M.test_defer(bouncer, ms, firstlast) local timeout = ms or 2000 - local bounced = bouncers[bouncer]( - function(i) vim.cmd('echom "' .. bouncer .. ': ' .. i .. '"') end, - timeout, - firstlast - ) + local bounced = bouncers[bouncer](function(i) + vim.cmd('echom "' .. bouncer .. ": " .. i .. '"') + end, timeout, firstlast) - for i, _ in ipairs{1,2,3,4,5} do + for i, _ in ipairs { 1, 2, 3, 4, 5 } do bounced(i) - vim.schedule(function () vim.cmd('echom ' .. i) end) - vim.fn.call("wait", {1000, "v:false"}) + vim.schedule(function() + vim.cmd("echom " .. i) + end) + vim.fn.call("wait", { 1000, "v:false" }) end end diff --git a/lua/telescope/deprecated.lua b/lua/telescope/deprecated.lua index ff33a07..63e85fd 100644 --- a/lua/telescope/deprecated.lua +++ b/lua/telescope/deprecated.lua @@ -9,16 +9,18 @@ deprecated.picker_window_options = function(opts) -- Can be removed in a few weeks. if opts.shorten_path then - table.insert(messages, - "'opts.shorten_path' is no longer valid. Please use 'opts.path_display' instead. " .. - "Please See ':help telescope.changelog-839'" + table.insert( + messages, + "'opts.shorten_path' is no longer valid. Please use 'opts.path_display' instead. " + .. "Please See ':help telescope.changelog-839'" ) end if opts.hide_filename then - table.insert(messages, - "'opts.hide_filename' is no longer valid. Please use 'opts.path_display' instead. " .. - "Please See ':help telescope.changelog-839'" + table.insert( + messages, + "'opts.hide_filename' is no longer valid. Please use 'opts.path_display' instead. " + .. "Please See ':help telescope.changelog-839'" ) end @@ -35,19 +37,22 @@ deprecated.picker_window_options = function(opts) end if opts.results_width then - table.insert(messages, + table.insert( + messages, "'opts.results_width' actually didn't do anything. Please see ':help telescope.changelog-922'" ) end if opts.prompt_position then - table.insert(messages, + table.insert( + messages, "'opts.prompt_position' is no longer valid. Please use 'layout_config.prompt_position' instead." ) end if opts.preview_cutoff then - table.insert(messages, + table.insert( + messages, "'opts.preview_cutoff' is no longer valid. Please use 'layout_config.preview_cutoff' instead." ) end diff --git a/lua/telescope/entry_manager.lua b/lua/telescope/entry_manager.lua index f32d29f..ff8b9ba 100644 --- a/lua/telescope/entry_manager.lua +++ b/lua/telescope/entry_manager.lua @@ -1,6 +1,6 @@ -local log = require("telescope.log") +local log = require "telescope.log" -local LinkedList = require('telescope.algos.linked_list') +local LinkedList = require "telescope.algos.linked_list" --[[ @@ -27,7 +27,7 @@ local EntryManager = {} EntryManager.__index = EntryManager function EntryManager:new(max_results, set_entry, info) - log.trace("Creating entry_manager...") + log.trace "Creating entry_manager..." info = info or {} info.looped = 0 @@ -136,7 +136,7 @@ function EntryManager:add_entry(picker, score, entry) local info = self.info info.maxed = info.maxed or 0 - local new_container = { entry, score, } + local new_container = { entry, score } -- Short circuit for bad scores -- they never need to be displayed. -- Just save them and we'll deal with them later. diff --git a/lua/telescope/finders.lua b/lua/telescope/finders.lua index 62c05a1..7fecd67 100644 --- a/lua/telescope/finders.lua +++ b/lua/telescope/finders.lua @@ -1,12 +1,12 @@ -local Job = require('plenary.job') +local Job = require "plenary.job" -local make_entry = require('telescope.make_entry') -local log = require('telescope.log') -local a = require('plenary.async_lib') +local make_entry = require "telescope.make_entry" +local log = require "telescope.log" +local a = require "plenary.async_lib" local await = a.await -local async_static_finder = require('telescope.finders.async_static_finder') -local async_oneshot_finder = require('telescope.finders.async_oneshot_finder') +local async_static_finder = require "telescope.finders.async_static_finder" +local async_oneshot_finder = require "telescope.finders.async_oneshot_finder" -- local async_job_finder = require('telescope.finders.async_job_finder') local finders = {} @@ -15,7 +15,9 @@ local _callable_obj = function() local obj = {} obj.__index = obj - obj.__call = function(t, ...) return t:_find(...) end + obj.__call = function(t, ...) + return t:_find(...) + end obj.close = function() end @@ -58,10 +60,10 @@ function JobFinder:new(opts) end function JobFinder:_find(prompt, process_result, process_complete) - log.trace("Finding...") + log.trace "Finding..." if self.job and not self.job.is_shutdown then - log.debug("Shutting down old job") + log.debug "Shutting down old job" self.job:shutdown() end @@ -78,7 +80,9 @@ function JobFinder:_find(prompt, process_result, process_complete) end local opts = self:fn_command(prompt) - if not opts then return end + if not opts then + return + end local writer = nil if opts.writer and Job.is_job(opts.writer) then @@ -131,7 +135,9 @@ function DynamicFinder:_find(prompt, process_result, process_complete) local results = await(self.fn(prompt)) for _, result in ipairs(results) do - if process_result(self.entry_maker(result)) then return end + if process_result(self.entry_maker(result)) then + return + end end process_complete() diff --git a/lua/telescope/finders/async_job_finder.lua b/lua/telescope/finders/async_job_finder.lua index ee1b2c7..dfabf98 100644 --- a/lua/telescope/finders/async_job_finder.lua +++ b/lua/telescope/finders/async_job_finder.lua @@ -1,12 +1,12 @@ -local log = require('telescope.log') -local Job = require('plenary.job') +local log = require "telescope.log" +local Job = require "plenary.job" -local async_lib = require('plenary.async_lib') +local async_lib = require "plenary.async_lib" local async = async_lib.async -- local await = async_lib.await local void = async_lib.void -local make_entry = require('telescope.make_entry') +local make_entry = require "telescope.make_entry" return function(opts) local entry_maker = opts.entry_maker or make_entry.gen_from_string() @@ -31,12 +31,14 @@ return function(opts) __call = void(async(function(prompt, process_result, process_complete) print("are we callin anything?", job) if job and not job.is_shutdown then - log.debug("Shutting down old job") + log.debug "Shutting down old job" job:shutdown() end local job_opts = fn_command(prompt) - if not job_opts then return end + if not job_opts then + return + end local writer = nil if job_opts.writer and Job.is_job(job_opts.writer) then diff --git a/lua/telescope/finders/async_oneshot_finder.lua b/lua/telescope/finders/async_oneshot_finder.lua index 2345096..20e5403 100644 --- a/lua/telescope/finders/async_oneshot_finder.lua +++ b/lua/telescope/finders/async_oneshot_finder.lua @@ -1,13 +1,13 @@ -local async_lib = require('plenary.async_lib') +local async_lib = require "plenary.async_lib" local async = async_lib.async local await = async_lib.await local void = async_lib.void local AWAITABLE = 1000 -local make_entry = require('telescope.make_entry') +local make_entry = require "telescope.make_entry" -local Job = require('plenary.job') +local Job = require "plenary.job" return function(opts) opts = opts or {} @@ -22,7 +22,10 @@ return function(opts) local job_started = false local job_completed = false return setmetatable({ - close = function() results = {}; job_started = false end, + close = function() + results = {} + job_started = false + end, results = results, }, { __call = void(async(function(_, prompt, process_result, process_complete) diff --git a/lua/telescope/finders/async_static_finder.lua b/lua/telescope/finders/async_static_finder.lua index 0756551..065b687 100644 --- a/lua/telescope/finders/async_static_finder.lua +++ b/lua/telescope/finders/async_static_finder.lua @@ -1,14 +1,17 @@ -local async_lib = require('plenary.async_lib') +local async_lib = require "plenary.async_lib" local async = async_lib.async local await = async_lib.await local void = async_lib.void -local make_entry = require('telescope.make_entry') +local make_entry = require "telescope.make_entry" return function(opts) local input_results - if vim.tbl_islist(opts) then input_results = opts - else input_results = opts.results end + if vim.tbl_islist(opts) then + input_results = opts + else + input_results = opts.results + end local entry_maker = opts.entry_maker or make_entry.gen_from_string() @@ -28,7 +31,9 @@ return function(opts) }, { __call = void(async(function(_, _, process_result, process_complete) for i, v in ipairs(results) do - if process_result(v) then break end + if process_result(v) then + break + end if i % 1000 == 0 then await(async_lib.scheduler()) diff --git a/lua/telescope/from_entry.lua b/lua/telescope/from_entry.lua index bf63940..937f11f 100644 --- a/lua/telescope/from_entry.lua +++ b/lua/telescope/from_entry.lua @@ -12,9 +12,16 @@ local from_entry = {} function from_entry.path(entry, validate) local path = entry.path and vim.fn.fnameescape(entry.path) or nil - if path == nil then path = entry.filename end - if path == nil then path = entry.value end - if path == nil then print("Invalid entry", vim.inspect(entry)); return end + if path == nil then + path = entry.filename + end + if path == nil then + path = entry.value + end + if path == nil then + print("Invalid entry", vim.inspect(entry)) + return + end if validate and not vim.fn.filereadable(path) then return diff --git a/lua/telescope/init.lua b/lua/telescope/init.lua index 41acb57..17cd910 100644 --- a/lua/telescope/init.lua +++ b/lua/telescope/init.lua @@ -1,6 +1,6 @@ -require('telescope._compat') +require "telescope._compat" -local _extensions = require('telescope._extensions') +local _extensions = require "telescope._extensions" local telescope = {} @@ -33,11 +33,11 @@ function telescope.setup(opts) opts = opts or {} if opts.default then - error("'default' is not a valid value for setup. See 'defaults'") + error "'default' is not a valid value for setup. See 'defaults'" end - require('telescope.config').set_defaults(opts.defaults) - require('telescope.config').set_pickers(opts.pickers) + require("telescope.config").set_defaults(opts.defaults) + require("telescope.config").set_pickers(opts.pickers) _extensions.set_config(opts.extensions) end @@ -55,10 +55,10 @@ end --- Use telescope.extensions to reference any extensions within your configuration.
--- While the docs currently generate this as a function, it's actually a table. Sorry. -telescope.extensions = require('telescope._extensions').manager +telescope.extensions = require("telescope._extensions").manager telescope.__format_setup_keys = function() - local descriptions = require('telescope.config').descriptions + local descriptions = require("telescope.config").descriptions local names = vim.tbl_keys(descriptions) table.sort(names) @@ -70,12 +70,12 @@ telescope.__format_setup_keys = function() table.insert(result, "") table.insert(result, string.format("%s*telescope.defaults.%s*", string.rep(" ", 70 - 20 - #name), name)) table.insert(result, string.format("%s: ~", name)) - for _, line in ipairs(vim.split(desc, '\n')) do + for _, line in ipairs(vim.split(desc, "\n")) do table.insert(result, string.format(" %s", line)) end end - table.insert(result, '') + table.insert(result, "") return result end diff --git a/lua/telescope/log.lua b/lua/telescope/log.lua index c93472b..0d2e0eb 100644 --- a/lua/telescope/log.lua +++ b/lua/telescope/log.lua @@ -1,6 +1,6 @@ -local user = vim.loop.os_getenv("USER") +local user = vim.loop.os_getenv "USER" -return require('plenary.log').new { - plugin = 'telescope', - level = ((user == 'tj' or user == 'tjdevries') and 'debug') or 'warn', +return require("plenary.log").new { + plugin = "telescope", + level = ((user == "tj" or user == "tjdevries") and "debug") or "warn", } diff --git a/lua/telescope/make_entry.lua b/lua/telescope/make_entry.lua index 12da181..e2c6d45 100644 --- a/lua/telescope/make_entry.lua +++ b/lua/telescope/make_entry.lua @@ -1,28 +1,28 @@ -local entry_display = require('telescope.pickers.entry_display') -local utils = require('telescope.utils') -local strings = require('plenary.strings') -local Path = require('plenary.path') +local entry_display = require "telescope.pickers.entry_display" +local utils = require "telescope.utils" +local strings = require "plenary.strings" +local Path = require "plenary.path" local treesitter_type_highlight = { ["associated"] = "TSConstant", - ["constant"] = "TSConstant", - ["field"] = "TSField", - ["function"] = "TSFunction", - ["method"] = "TSMethod", - ["parameter"] = "TSParameter", - ["property"] = "TSProperty", - ["struct"] = "Struct", - ["var"] = "TSVariableBuiltin", + ["constant"] = "TSConstant", + ["field"] = "TSField", + ["function"] = "TSFunction", + ["method"] = "TSMethod", + ["parameter"] = "TSParameter", + ["property"] = "TSProperty", + ["struct"] = "Struct", + ["var"] = "TSVariableBuiltin", } local lsp_type_highlight = { - ["Class"] = "TelescopeResultsClass", + ["Class"] = "TelescopeResultsClass", ["Constant"] = "TelescopeResultsConstant", - ["Field"] = "TelescopeResultsField", + ["Field"] = "TelescopeResultsField", ["Function"] = "TelescopeResultsFunction", - ["Method"] = "TelescopeResultsMethod", + ["Method"] = "TelescopeResultsMethod", ["Property"] = "TelescopeResultsOperator", - ["Struct"] = "TelescopeResultsStruct", + ["Struct"] = "TelescopeResultsStruct", ["Variable"] = "TelescopeResultsVariable", } @@ -38,7 +38,7 @@ do local mt_string_entry = { __index = function(t, k) return rawget(t, rawget(lookup_keys, k)) - end + end, } function make_entry.gen_from_string() @@ -75,7 +75,7 @@ do display, hl_group = utils.transform_devicons(entry.value, display, disable_devicons) if hl_group then - return display, { { {1, 3}, hl_group } } + return display, { { { 1, 3 }, hl_group } } else return display end @@ -83,10 +83,12 @@ do mt_file_entry.__index = function(t, k) local raw = rawget(mt_file_entry, k) - if raw then return raw end + if raw then + return raw + end if k == "path" then - local retpath = Path:new({t.cwd, t.value}):absolute() + local retpath = Path:new({ t.cwd, t.value }):absolute() if not vim.loop.fs_access(retpath, "R", nil) then retpath = t.value end @@ -97,7 +99,7 @@ do end return function(line) - return setmetatable({line}, mt_file_entry) + return setmetatable({ line }, mt_file_entry) end end end @@ -114,17 +116,21 @@ do local ok ok, lnum = pcall(tonumber, lnum) - if not ok then lnum = nil end + if not ok then + lnum = nil + end ok, col = pcall(tonumber, col) - if not ok then col = nil end + if not ok then + col = nil + end t.filename = filename t.lnum = lnum t.col = col t.text = text - return {filename, lnum, col, text} + return { filename, lnum, col, text } end --- Special options: @@ -144,7 +150,7 @@ do if Path:new(t.filename):is_absolute() then return t.filename, false else - return Path:new({t.cwd, t.filename}):absolute(), false + return Path:new({ t.cwd, t.filename }):absolute(), false end end, @@ -187,12 +193,12 @@ do local display, hl_group = utils.transform_devicons( entry.filename, - string.format(display_string, display_filename, coordinates, entry.text), + string.format(display_string, display_filename, coordinates, entry.text), disable_devicons ) if hl_group then - return display, { { {1, 3}, hl_group } } + return display, { { { 1, 3 }, hl_group } } else return display end @@ -200,12 +206,16 @@ do __index = function(t, k) local raw = rawget(mt_vimgrep_entry, k) - if raw then return raw end + if raw then + return raw + end local executor = rawget(execute_keys, k) if executor then local val, save = executor(t) - if save then rawset(t, k, val) end + if save then + rawset(t, k, val) + end return val end @@ -214,7 +224,7 @@ do } return function(line) - return setmetatable({line}, mt_vimgrep_entry) + return setmetatable({ line }, mt_vimgrep_entry) end end end @@ -224,11 +234,11 @@ function make_entry.gen_from_git_stash() if entry == "" then return nil end - local splitted = vim.split(entry, ':') + local splitted = vim.split(entry, ":") return { value = splitted[1], ordinal = splitted[3], - display = splitted[3] + display = splitted[3], } end end @@ -240,14 +250,14 @@ function make_entry.gen_from_git_commits(opts) separator = " ", items = { { width = 8 }, - { remaining = true } - } - } + { remaining = true }, + }, + } local make_display = function(entry) return displayer { - {entry.value, "TelescopeResultsIdentifier"}, - entry.msg + { entry.value, "TelescopeResultsIdentifier" }, + entry.msg, } end @@ -256,7 +266,7 @@ function make_entry.gen_from_git_commits(opts) return nil end - local sha, msg = string.match(entry, '([^ ]+) (.+)') + local sha, msg = string.match(entry, "([^ ]+) (.+)") if not msg then sha = entry @@ -265,10 +275,10 @@ function make_entry.gen_from_git_commits(opts) return { value = sha, - ordinal = sha .. ' ' .. msg, + ordinal = sha .. " " .. msg, msg = msg, display = make_display, - current_file = opts.current_file + current_file = opts.current_file, } end end @@ -281,14 +291,14 @@ function make_entry.gen_from_quickfix(opts) items = { { width = 8 }, { width = 50 }, - { remaining = true } - } + { remaining = true }, + }, } local make_display = function(entry) local filename = utils.transform_path(opts, entry.filename) - local line_info = {table.concat({entry.lnum, entry.col}, ":"), "TelescopeResultsLineNr"} + local line_info = { table.concat({ entry.lnum, entry.col }, ":"), "TelescopeResultsLineNr" } return displayer { line_info, @@ -304,10 +314,7 @@ function make_entry.gen_from_quickfix(opts) valid = true, value = entry, - ordinal = ( - not opts.ignore_filename and filename - or '' - ) .. ' ' .. entry.text, + ordinal = (not opts.ignore_filename and filename or "") .. " " .. entry.text, display = make_display, bufnr = entry.bufnr, @@ -326,9 +333,9 @@ function make_entry.gen_from_lsp_symbols(opts) local bufnr = opts.bufnr or vim.api.nvim_get_current_buf() local display_items = { - { width = opts.symbol_width or 25 }, -- symbol + { width = opts.symbol_width or 25 }, -- symbol { width = opts.symbol_type_width or 8 }, -- symbol type - { remaining = true }, -- filename{:optional_lnum+col} OR content preview + { remaining = true }, -- filename{:optional_lnum+col} OR content preview } if opts.ignore_filename and opts.show_line then @@ -337,8 +344,8 @@ function make_entry.gen_from_lsp_symbols(opts) local displayer = entry_display.create { separator = " ", - hl_chars = { ['['] = 'TelescopeBorder', [']'] = 'TelescopeBorder' }, - items = display_items + hl_chars = { ["["] = "TelescopeBorder", ["]"] = "TelescopeBorder" }, + items = display_items, } local make_display = function(entry) @@ -347,18 +354,13 @@ function make_entry.gen_from_lsp_symbols(opts) -- what to show in the last column: filename or symbol information if opts.ignore_filename then -- ignore the filename and show line preview instead -- TODO: fixme - if ignore_filename is set for workspace, bufnr will be incorrect - msg = vim.api.nvim_buf_get_lines( - bufnr, - entry.lnum - 1, - entry.lnum, - false - )[1] or '' + msg = vim.api.nvim_buf_get_lines(bufnr, entry.lnum - 1, entry.lnum, false)[1] or "" msg = vim.trim(msg) else local filename = utils.transform_path(opts, entry.filename) if opts.show_line then -- show inline line info - filename = filename .. " [" ..entry.lnum .. ":" .. entry.col .. "]" + filename = filename .. " [" .. entry.lnum .. ":" .. entry.col .. "]" end msg = filename end @@ -366,12 +368,12 @@ function make_entry.gen_from_lsp_symbols(opts) local type_highlight = opts.symbol_highlights or lsp_type_highlight local display_columns = { entry.symbol_name, - {entry.symbol_type:lower(), type_highlight[entry.symbol_type], type_highlight[entry.symbol_type]}, + { entry.symbol_type:lower(), type_highlight[entry.symbol_type], type_highlight[entry.symbol_type] }, msg, } if opts.ignore_filename and opts.show_line then - table.insert(display_columns, 2, {entry.lnum .. ":" .. entry.col, "TelescopeResultsLineNr"}) + table.insert(display_columns, 2, { entry.lnum .. ":" .. entry.col, "TelescopeResultsLineNr" }) end return displayer(display_columns) @@ -380,13 +382,13 @@ function make_entry.gen_from_lsp_symbols(opts) return function(entry) local filename = entry.filename or vim.api.nvim_buf_get_name(entry.bufnr) local symbol_msg = entry.text:gsub(".* | ", "") - local symbol_type, symbol_name = symbol_msg:match("%[(.+)%]%s+(.*)") + local symbol_type, symbol_name = symbol_msg:match "%[(.+)%]%s+(.*)" local ordinal = "" if not opts.ignore_filename and filename then ordinal = filename .. " " end - ordinal = ordinal .. symbol_name .. " " .. (symbol_type or "unknown") + ordinal = ordinal .. symbol_name .. " " .. (symbol_type or "unknown") return { valid = true, @@ -412,7 +414,7 @@ function make_entry.gen_from_buffer(opts) local icon_width = 0 if not disable_devicons then - local icon, _ = utils.get_devicons('fname', disable_devicons) + local icon, _ = utils.get_devicons("fname", disable_devicons) icon_width = strings.strdisplaywidth(icon) end @@ -434,21 +436,21 @@ function make_entry.gen_from_buffer(opts) local icon, hl_group = utils.get_devicons(entry.filename, disable_devicons) return displayer { - {entry.bufnr, "TelescopeResultsNumber"}, - {entry.indicator, "TelescopeResultsComment"}, + { entry.bufnr, "TelescopeResultsNumber" }, + { entry.indicator, "TelescopeResultsComment" }, { icon, hl_group }, - display_bufname .. ":" .. entry.lnum - } + display_bufname .. ":" .. entry.lnum, + } end return function(entry) - local bufname = entry.info.name ~= "" and entry.info.name or '[No Name]' + local bufname = entry.info.name ~= "" and entry.info.name or "[No Name]" -- if bufname is inside the cwd, trim that part of the string bufname = Path:new(bufname):normalize(cwd) - local hidden = entry.info.hidden == 1 and 'h' or 'a' - local readonly = vim.api.nvim_buf_get_option(entry.bufnr, 'readonly') and '=' or ' ' - local changed = entry.info.changed == 1 and '+' or ' ' + local hidden = entry.info.hidden == 1 and "h" or "a" + local readonly = vim.api.nvim_buf_get_option(entry.bufnr, "readonly") and "=" or " " + local changed = entry.info.changed == 1 and "+" or " " local indicator = entry.flag .. hidden .. readonly .. changed return { @@ -490,28 +492,23 @@ function make_entry.gen_from_treesitter(opts) local type_highlight = opts.symbol_highlights or treesitter_type_highlight local make_display = function(entry) - local msg = vim.api.nvim_buf_get_lines( - bufnr, - entry.lnum, - entry.lnum, - false - )[1] or '' + local msg = vim.api.nvim_buf_get_lines(bufnr, entry.lnum, entry.lnum, false)[1] or "" msg = vim.trim(msg) local display_columns = { entry.text, - {entry.kind, type_highlight[entry.kind], type_highlight[entry.kind]}, - msg + { entry.kind, type_highlight[entry.kind], type_highlight[entry.kind] }, + msg, } if opts.show_line then - table.insert(display_columns, 2, {entry.lnum .. ":" .. entry.col, "TelescopeResultsLineNr"}) + table.insert(display_columns, 2, { entry.lnum .. ":" .. entry.col, "TelescopeResultsLineNr" }) end return displayer(display_columns) end return function(entry) - local ts_utils = require('nvim-treesitter.ts_utils') + local ts_utils = require "nvim-treesitter.ts_utils" local start_row, start_col, end_row, _ = ts_utils.get_node_range(entry.node) local node_text = ts_utils.get_node_text(entry.node)[1] return { @@ -530,7 +527,7 @@ function make_entry.gen_from_treesitter(opts) col = start_col, text = node_text, start = start_row, - finish = end_row + finish = end_row, } end end @@ -559,9 +556,11 @@ end function make_entry.gen_from_apropos(opts) local sections = {} - if #opts.sections == 1 and opts.sections[1] == 'ALL' then + if #opts.sections == 1 and opts.sections[1] == "ALL" then setmetatable(sections, { - __index = function() return true end, + __index = function() + return true + end, }) else for _, section in ipairs(opts.sections) do @@ -570,7 +569,7 @@ function make_entry.gen_from_apropos(opts) end local displayer = entry_display.create { - separator = ' ', + separator = " ", items = { { width = 30 }, { remaining = true }, @@ -579,21 +578,24 @@ function make_entry.gen_from_apropos(opts) local make_display = function(entry) return displayer { - { entry.keyword, 'TelescopeResultsFunction' }, - entry.description + { entry.keyword, "TelescopeResultsFunction" }, + entry.description, } end return function(line) - local keyword, cmd, section, desc = line:match'^((.-)%s*%(([^)]+)%).-)%s+%-%s+(.*)$' - return keyword and sections[section] and { - value = cmd, - description = desc, - ordinal = cmd, - display = make_display, - section = section, - keyword = keyword, - } or nil + local keyword, cmd, section, desc = line:match "^((.-)%s*%(([^)]+)%).-)%s+%-%s+(.*)$" + return keyword + and sections[section] + and { + value = cmd, + description = desc, + ordinal = cmd, + display = make_display, + section = section, + keyword = keyword, + } + or nil end end @@ -611,7 +613,7 @@ function make_entry.gen_from_marks(_) lnum = cursor_position[2], col = cursor_position[3], start = cursor_position[2], - filename = vim.api.nvim_buf_get_name(cursor_position[1]) + filename = vim.api.nvim_buf_get_name(cursor_position[1]), } end end @@ -619,7 +621,7 @@ end function make_entry.gen_from_registers(_) local displayer = entry_display.create { separator = " ", - hl_chars = { ['['] = 'TelescopeBorder', [']'] = 'TelescopeBorder' }, + hl_chars = { ["["] = "TelescopeBorder", ["]"] = "TelescopeBorder" }, items = { { width = 3 }, { remaining = true }, @@ -629,8 +631,8 @@ function make_entry.gen_from_registers(_) local make_display = function(entry) local content = entry.content return displayer { - {'[' .. entry.value .. ']', "TelescopeResultsNumber"}, - type(content) == 'string' and content:gsub('\n','\\n') or content, + { "[" .. entry.value .. "]", "TelescopeResultsNumber" }, + type(content) == "string" and content:gsub("\n", "\\n") or content, } end @@ -640,7 +642,7 @@ function make_entry.gen_from_registers(_) value = entry, ordinal = entry, content = vim.fn.getreg(entry), - display = make_display + display = make_display, } end end @@ -662,20 +664,22 @@ end function make_entry.gen_from_buffer_lines(opts) local displayer = entry_display.create { - separator = ' │ ', + separator = " │ ", items = { { width = 5 }, - { remaining = true, }, + { remaining = true }, }, } local make_display = function(entry) - return displayer { - { entry.lnum, opts.lnum_highlight_group or 'TelescopeResultsSpecialComment' }, + { entry.lnum, opts.lnum_highlight_group or "TelescopeResultsSpecialComment" }, { - entry.text, function() - if not opts.line_highlights then return {} end + entry.text, + function() + if not opts.line_highlights then + return {} + end local line_hl = opts.line_highlights[entry.lnum] or {} -- TODO: We could probably squash these together if the are the same... @@ -683,17 +687,17 @@ function make_entry.gen_from_buffer_lines(opts) local result = {} for col, hl in pairs(line_hl) do - table.insert(result, { {col, col+1}, hl }) + table.insert(result, { { col, col + 1 }, hl }) end return result - end + end, }, } end return function(entry) - if opts.skip_empty_lines and string.match(entry.text, '^$') then + if opts.skip_empty_lines and string.match(entry.text, "^$") then return end @@ -713,12 +717,12 @@ function make_entry.gen_from_vimoptions() local ok, value_origin local option = { - name = "", - description = "", + name = "", + description = "", current_value = "", default_value = "", - value_type = "", - set_by_user = false, + value_type = "", + set_by_user = false, last_set_from = "", } @@ -772,7 +776,7 @@ function make_entry.gen_from_vimoptions() local displayer = entry_display.create { separator = "", - hl_chars = { ['['] = 'TelescopeBorder', [']'] = 'TelescopeBorder' }, + hl_chars = { ["["] = "TelescopeBorder", ["]"] = "TelescopeBorder" }, items = { { width = 25 }, { width = 12 }, @@ -781,10 +785,9 @@ function make_entry.gen_from_vimoptions() } local make_display = function(entry) - return displayer { - {entry.name, "Keyword"}, - {"["..entry.value_type.."]", "Type"}, + { entry.name, "Keyword" }, + { "[" .. entry.value_type .. "]", "Type" }, utils.display_termcodes(tostring(entry.current_value)), entry.description, } @@ -796,9 +799,9 @@ function make_entry.gen_from_vimoptions() return end - entry.valid = true + entry.valid = true entry.display = make_display - entry.value = line + entry.value = line entry.ordinal = line.full_name -- entry.raw_value = d.raw_value -- entry.last_set_from = d.last_set_from @@ -813,7 +816,7 @@ function make_entry.gen_from_ctags(opts) opts = opts or {} local cwd = vim.fn.expand(opts.cwd or vim.fn.getcwd()) - local current_file = Path:new(vim.fn.expand('%')):normalize(cwd) + local current_file = Path:new(vim.fn.expand "%"):normalize(cwd) local display_items = { { remaining = true }, @@ -855,7 +858,7 @@ function make_entry.gen_from_ctags(opts) end return function(line) - if line == '' or line:sub(1, 1) == '!' then + if line == "" or line:sub(1, 1) == "!" then return nil end @@ -864,7 +867,7 @@ function make_entry.gen_from_ctags(opts) tag, file, scode = string.match(line, '([^\t]+)\t([^\t]+)\t/^\t?(.*)/;"\t+.*') if not tag then -- hasktags gives us: 'tags\tfile\tlnum' - tag, file, lnum = string.match(line, '([^\t]+)\t([^\t]+)\t(%d+).*') + tag, file, lnum = string.match(line, "([^\t]+)\t([^\t]+)\t(%d+).*") end if opts.only_current_file and file ~= current_file then @@ -876,7 +879,7 @@ function make_entry.gen_from_ctags(opts) if opts.only_sort_tags then ordinal = tag else - ordinal = file .. ': ' .. tag + ordinal = file .. ": " .. tag end return { @@ -903,11 +906,12 @@ function make_entry.gen_from_lsp_diagnostics(opts) signs = {} for severity, _ in pairs(lsp_type_diagnostic) do -- pcall to catch entirely unbound or cleared out sign hl group - if type(severity) == 'string' then - local status, sign = pcall( - function() return vim.trim(vim.fn.sign_getdefined("LspDiagnosticsSign" .. severity)[1].text) end) + if type(severity) == "string" then + local status, sign = pcall(function() + return vim.trim(vim.fn.sign_getdefined("LspDiagnosticsSign" .. severity)[1].text) + end) if not status then - sign = severity:sub(1,1) + sign = severity:sub(1, 1) end signs[severity] = sign end @@ -916,13 +920,15 @@ function make_entry.gen_from_lsp_diagnostics(opts) local layout = { { width = utils.if_nil(signs, 8, 10) }, - { remaining = true } + { remaining = true }, } local line_width = utils.get_default(opts.line_width, 45) - if not utils.is_path_hidden(opts) then table.insert(layout, 2, {width = line_width}) end + if not utils.is_path_hidden(opts) then + table.insert(layout, 2, { width = line_width }) + end local displayer = entry_display.create { separator = "▏", - items = layout + items = layout, } local make_display = function(entry) @@ -932,7 +938,7 @@ function make_entry.gen_from_lsp_diagnostics(opts) local pos = string.format("%4d:%2d", entry.lnum, entry.col) local line_info = { (signs and signs[entry.type] .. " " or "") .. pos, - "LspDiagnosticsDefault" .. entry.type + "LspDiagnosticsDefault" .. entry.type, } return displayer { @@ -949,10 +955,7 @@ function make_entry.gen_from_lsp_diagnostics(opts) valid = true, value = entry, - ordinal = ( - not opts.ignore_filename and filename - or '' - ) .. ' ' .. entry.text, + ordinal = (not opts.ignore_filename and filename or "") .. " " .. entry.text, display = make_display, filename = filename, type = entry.type, @@ -965,7 +968,6 @@ function make_entry.gen_from_lsp_diagnostics(opts) end end - function make_entry.gen_from_autocommands(_) local displayer = entry_display.create { separator = "▏", @@ -979,26 +981,26 @@ function make_entry.gen_from_autocommands(_) local make_display = function(entry) return displayer { - {entry.event, "vimAutoEvent"}, - {entry.group , "vimAugroup"}, - {entry.ft_pattern, "vimAutoCmdSfxList"}, - entry.command + { entry.event, "vimAutoEvent" }, + { entry.group, "vimAugroup" }, + { entry.ft_pattern, "vimAutoCmdSfxList" }, + entry.command, } end -- TODO: dump current filtered items to buffer return function(entry) return { - event = entry.event, - group = entry.group, + event = entry.event, + group = entry.group, ft_pattern = entry.ft_pattern, - command = entry.command, - value = string.format("+%d %s", entry.source_lnum, entry.source_file), + command = entry.command, + value = string.format("+%d %s", entry.source_lnum, entry.source_file), source_file = entry.source_file, source_lnum = entry.source_lnum, -- valid = true, - ordinal = entry.event .. " " .. entry.group .. " " .. entry.ft_pattern .. " " .. entry.command, + ordinal = entry.event .. " " .. entry.group .. " " .. entry.ft_pattern .. " " .. entry.command, display = make_display, } end @@ -1018,11 +1020,17 @@ function make_entry.gen_from_commands(_) local make_display = function(entry) local attrs = "" - if entry.bang then attrs = attrs .. "!" end - if entry.bar then attrs = attrs .. "|" end - if entry.register then attrs = attrs .. '"' end + if entry.bang then + attrs = attrs .. "!" + end + if entry.bar then + attrs = attrs .. "|" + end + if entry.register then + attrs = attrs .. '"' + end return displayer { - {entry.name, "TelescopeResultsIdentifier"}, + { entry.name, "TelescopeResultsIdentifier" }, attrs, entry.nargs, entry.complete or "", @@ -1032,28 +1040,28 @@ function make_entry.gen_from_commands(_) return function(entry) return { - name = entry.name, - bang = entry.bang, - nargs = entry.nargs, - complete = entry.complete, - definition = entry.definition, + name = entry.name, + bang = entry.bang, + nargs = entry.nargs, + complete = entry.complete, + definition = entry.definition, -- - value = entry, - valid = true, - ordinal = entry.name, - display = make_display, + value = entry, + valid = true, + ordinal = entry.name, + display = make_display, } end end local git_icon_defaults = { - added = "+", - changed = "~", - copied = ">", - deleted = "-", - renamed = "➡", - unmerged = "‡", - untracked = "?" + added = "+", + changed = "~", + copied = ">", + deleted = "-", + renamed = "➡", + unmerged = "‡", + untracked = "?", } function make_entry.gen_from_git_status(opts) @@ -1061,24 +1069,24 @@ function make_entry.gen_from_git_status(opts) local col_width = ((opts.git_icons and opts.git_icons.added) and opts.git_icons.added:len() + 2) or 2 local displayer = entry_display.create { - separator = "", - items = { - { width = col_width}, - { width = col_width}, + separator = "", + items = { + { width = col_width }, + { width = col_width }, { remaining = true }, - } + }, } local icons = vim.tbl_extend("keep", opts.git_icons or {}, git_icon_defaults) local git_abbrev = { - ["A"] = {icon = icons.added, hl = "TelescopeResultsDiffAdd"}, - ["U"] = {icon = icons.unmerged, hl = "TelescopeResultsDiffAdd"}, - ["M"] = {icon = icons.changed, hl = "TelescopeResultsDiffChange"}, - ["C"] = {icon = icons.copied, hl = "TelescopeResultsDiffChange"}, - ["R"] = {icon = icons.renamed, hl = "TelescopeResultsDiffChange"}, - ["D"] = {icon = icons.deleted, hl = "TelescopeResultsDiffDelete"}, - ["?"] = {icon = icons.untracked, hl = "TelescopeResultsDiffUntracked"}, + ["A"] = { icon = icons.added, hl = "TelescopeResultsDiffAdd" }, + ["U"] = { icon = icons.unmerged, hl = "TelescopeResultsDiffAdd" }, + ["M"] = { icon = icons.changed, hl = "TelescopeResultsDiffChange" }, + ["C"] = { icon = icons.copied, hl = "TelescopeResultsDiffChange" }, + ["R"] = { icon = icons.renamed, hl = "TelescopeResultsDiffChange" }, + ["D"] = { icon = icons.deleted, hl = "TelescopeResultsDiffDelete" }, + ["?"] = { icon = icons.untracked, hl = "TelescopeResultsDiffUntracked" }, } local make_display = function(entry) @@ -1087,24 +1095,26 @@ function make_entry.gen_from_git_status(opts) local status_x = git_abbrev[x] or {} local status_y = git_abbrev[y] or {} - local empty_space = (" ") + local empty_space = " " return displayer { - { status_x.icon or empty_space, status_x.hl}, - { status_y.icon or empty_space, status_y.hl}, + { status_x.icon or empty_space, status_x.hl }, + { status_y.icon or empty_space, status_y.hl }, entry.value, } end - return function (entry) - if entry == '' then return nil end - local mod, file = string.match(entry, '(..).*%s[->%s]?(.+)') + return function(entry) + if entry == "" then + return nil + end + local mod, file = string.match(entry, "(..).*%s[->%s]?(.+)") return { value = file, status = mod, ordinal = entry, display = make_display, - path = Path:new({opts.cwd, file}):absolute() + path = Path:new({ opts.cwd, file }):absolute(), } end end diff --git a/lua/telescope/mappings.lua b/lua/telescope/mappings.lua index bfc153c..e2794a3 100644 --- a/lua/telescope/mappings.lua +++ b/lua/telescope/mappings.lua @@ -1,12 +1,13 @@ -- TODO: Customize keymap local a = vim.api -local actions = require('telescope.actions') -local config = require('telescope.config') +local actions = require "telescope.actions" +local config = require "telescope.config" local mappings = {} -mappings.default_mappings = config.values.default_mappings or { +mappings.default_mappings = config.values.default_mappings + or { i = { [""] = actions.move_selection_next, [""] = actions.move_selection_previous, @@ -28,7 +29,7 @@ mappings.default_mappings = config.values.default_mappings or { [""] = actions.toggle_selection + actions.move_selection_better, [""] = actions.send_to_qflist + actions.open_qflist, [""] = actions.send_selected_to_qflist + actions.open_qflist, - [""] = actions.complete_tag + [""] = actions.complete_tag, }, n = { @@ -58,13 +59,14 @@ mappings.default_mappings = config.values.default_mappings or { }, } -__TelescopeKeymapStore = __TelescopeKeymapStore or setmetatable({}, { - __index = function(t, k) - rawset(t, k, {}) +__TelescopeKeymapStore = __TelescopeKeymapStore + or setmetatable({}, { + __index = function(t, k) + rawset(t, k, {}) - return rawget(t, k) - end -}) + return rawget(t, k) + end, + }) local keymap_store = __TelescopeKeymapStore local _mapping_key_id = 0 @@ -81,7 +83,6 @@ local assign_function = function(prompt_bufnr, func) return func_id end - --[[ Usage: @@ -107,22 +108,20 @@ local telescope_map = function(prompt_bufnr, mode, key_bind, key_func, opts) end opts = opts or {} - if opts.noremap == nil then opts.noremap = true end - if opts.silent == nil then opts.silent = true end + if opts.noremap == nil then + opts.noremap = true + end + if opts.silent == nil then + opts.silent = true + end if type(key_func) == "string" then key_func = actions[key_func] elseif type(key_func) == "table" then if key_func.type == "command" then - a.nvim_buf_set_keymap( - prompt_bufnr, - mode, - key_bind, - key_func[1], - opts or { - silent = true - } - ) + a.nvim_buf_set_keymap(prompt_bufnr, mode, key_bind, key_func[1], opts or { + silent = true, + }) return elseif key_func.type == "action_key" then key_func = actions[key_func[1]] @@ -158,13 +157,7 @@ local telescope_map = function(prompt_bufnr, mode, key_bind, key_func, opts) ) end - a.nvim_buf_set_keymap( - prompt_bufnr, - mode, - key_bind, - map_string, - opts - ) + a.nvim_buf_set_keymap(prompt_bufnr, mode, key_bind, map_string, opts) end mappings.apply_keymap = function(prompt_bufnr, attach_mappings, buffer_keymap) @@ -184,7 +177,7 @@ mappings.apply_keymap = function(prompt_bufnr, attach_mappings, buffer_keymap) if attach_results == nil then error( "Attach mappings must always return a value. `true` means use default mappings, " - .. "`false` means only use attached mappings" + .. "`false` means only use attached mappings" ) end @@ -218,24 +211,15 @@ mappings.apply_keymap = function(prompt_bufnr, attach_mappings, buffer_keymap) end end - vim.cmd(string.format( - [[autocmd BufDelete %s :lua require('telescope.mappings').clear(%s)]], - prompt_bufnr, - prompt_bufnr - )) + vim.cmd( + string.format([[autocmd BufDelete %s :lua require('telescope.mappings').clear(%s)]], prompt_bufnr, prompt_bufnr) + ) end mappings.execute_keymap = function(prompt_bufnr, keymap_identifier) local key_func = keymap_store[prompt_bufnr][keymap_identifier] - assert( - key_func, - string.format( - "Unsure of how we got this failure: %s %s", - prompt_bufnr, - keymap_identifier - ) - ) + assert(key_func, string.format("Unsure of how we got this failure: %s %s", prompt_bufnr, keymap_identifier)) key_func(prompt_bufnr) end diff --git a/lua/telescope/path.lua b/lua/telescope/path.lua index f69fca6..744c2fa 100644 --- a/lua/telescope/path.lua +++ b/lua/telescope/path.lua @@ -1,15 +1,17 @@ -local log = require('telescope.log') +local log = require "telescope.log" local path = {} path.separator = package.config:sub(1, 1) -path.home = vim.fn.expand("~") +path.home = vim.fn.expand "~" path.make_relative = function(filepath, cwd) - if not cwd or not filepath then return filepath end + if not cwd or not filepath then + return filepath + end - if filepath:sub(1, #cwd) == cwd then - local offset = 0 + if filepath:sub(1, #cwd) == cwd then + local offset = 0 -- if cwd does ends in the os separator, we need to take it off if cwd:sub(#cwd, #cwd) ~= path.separator then offset = 1 @@ -23,7 +25,7 @@ end path.shorten = (function() if jit then - local ffi = require('ffi') + local ffi = require "ffi" ffi.cdef [[ typedef unsigned char char_u; char_u *shorten_dir(char_u *str); @@ -49,7 +51,7 @@ path.normalize = function(filepath, cwd) filepath = path.make_relative(filepath, cwd) -- Substitute home directory w/ "~" - filepath = filepath:gsub("^" .. path.home, '~', 1) + filepath = filepath:gsub("^" .. path.home, "~", 1) -- Remove double path separators, it's annoying filepath = filepath:gsub(path.separator .. path.separator, path.separator) @@ -59,9 +61,13 @@ end path.read_file = function(filepath) local fd = vim.loop.fs_open(filepath, "r", 438) - if fd == nil then return '' end + if fd == nil then + return "" + end local stat = assert(vim.loop.fs_fstat(fd)) - if stat.type ~= 'file' then return '' end + if stat.type ~= "file" then + return "" + end local data = assert(vim.loop.fs_read(fd, stat.size, 0)) assert(vim.loop.fs_close(fd)) return data @@ -75,7 +81,9 @@ path.read_file_async = function(filepath, callback) end vim.loop.fs_fstat(fd, function(err_fstat, stat) assert(not err_fstat, err_fstat) - if stat.type ~= 'file' then return callback('') end + if stat.type ~= "file" then + return callback "" + end vim.loop.fs_read(fd, stat.size, 0, function(err_read, data) assert(not err_read, err_read) vim.loop.fs_close(fd, function(err_close) @@ -89,7 +97,7 @@ end return setmetatable({}, { __index = function(_, k) - log.error("telescope.path is deprecated. please use plenary.path instead") + log.error "telescope.path is deprecated. please use plenary.path instead" return path[k] - end + end, }) diff --git a/lua/telescope/pickers.lua b/lua/telescope/pickers.lua index 00b7446..65f8cfe 100644 --- a/lua/telescope/pickers.lua +++ b/lua/telescope/pickers.lua @@ -1,38 +1,38 @@ local a = vim.api -local popup = require('popup') +local popup = require "popup" -local async_lib = require('plenary.async_lib') +local async_lib = require "plenary.async_lib" local async_util = async_lib.util local async = async_lib.async local await = async_lib.await local channel = async_util.channel -require('telescope') +require "telescope" -local actions = require('telescope.actions') -local action_set = require('telescope.actions.set') -local config = require('telescope.config') -local debounce = require('telescope.debounce') -local deprecated = require('telescope.deprecated') -local log = require('telescope.log') -local mappings = require('telescope.mappings') -local state = require('telescope.state') -local utils = require('telescope.utils') +local actions = require "telescope.actions" +local action_set = require "telescope.actions.set" +local config = require "telescope.config" +local debounce = require "telescope.debounce" +local deprecated = require "telescope.deprecated" +local log = require "telescope.log" +local mappings = require "telescope.mappings" +local state = require "telescope.state" +local utils = require "telescope.utils" -local entry_display = require('telescope.pickers.entry_display') -local p_highlighter = require('telescope.pickers.highlights') -local p_scroller = require('telescope.pickers.scroller') -local p_window = require('telescope.pickers.window') +local entry_display = require "telescope.pickers.entry_display" +local p_highlighter = require "telescope.pickers.highlights" +local p_scroller = require "telescope.pickers.scroller" +local p_window = require "telescope.pickers.window" -local EntryManager = require('telescope.entry_manager') -local MultiSelect = require('telescope.pickers.multi') +local EntryManager = require "telescope.entry_manager" +local MultiSelect = require "telescope.pickers.multi" local get_default = utils.get_default -local ns_telescope_matching = a.nvim_create_namespace('telescope_matching') -local ns_telescope_prompt = a.nvim_create_namespace('telescope_prompt') -local ns_telescope_prompt_prefix = a.nvim_create_namespace('telescope_prompt_prefix') +local ns_telescope_matching = a.nvim_create_namespace "telescope_matching" +local ns_telescope_prompt = a.nvim_create_namespace "telescope_prompt" +local ns_telescope_prompt_prefix = a.nvim_create_namespace "telescope_prompt_prefix" local pickers = {} @@ -48,7 +48,7 @@ function Picker:new(opts) opts = opts or {} if opts.layout_strategy and opts.get_window_options then - error("layout_strategy and get_window_options are not compatible keys") + error "layout_strategy and get_window_options are not compatible keys" end -- Reset actions for any replaced / enhanced actions. @@ -76,7 +76,7 @@ function Picker:new(opts) _on_input_filter_cb = opts.on_input_filter_cb or function() end, finder = opts.finder, - sorter = opts.sorter or require('telescope.sorters').empty(), + sorter = opts.sorter or require("telescope.sorters").empty(), all_previewers = opts.previewer, current_previewer_index = 1, @@ -141,7 +141,7 @@ end ---@param index number: The row being displayed ---@return number The row for the picker to display in function Picker:get_row(index) - if self.sorting_strategy == 'ascending' then + if self.sorting_strategy == "ascending" then return index - 1 else return self.max_results - index @@ -153,7 +153,7 @@ end ---@param row number: The row being displayed ---@return number The index in line_manager function Picker:get_index(row) - if self.sorting_strategy == 'ascending' then + if self.sorting_strategy == "ascending" then return row + 1 else return self.max_results - row @@ -161,7 +161,7 @@ function Picker:get_index(row) end function Picker:get_reset_row() - if self.sorting_strategy == 'ascending' then + if self.sorting_strategy == "ascending" then return 0 else return self.max_results - 1 @@ -169,12 +169,14 @@ function Picker:get_reset_row() end function Picker:is_done() - if not self.manager then return true end + if not self.manager then + return true + end end function Picker:clear_extra_rows(results_bufnr) if self:is_done() then - log.trace("Not clearing due to being already complete") + log.trace "Not clearing due to being already complete" return end @@ -184,7 +186,7 @@ function Picker:clear_extra_rows(results_bufnr) end local worst_line, ok, msg - if self.sorting_strategy == 'ascending' then + if self.sorting_strategy == "ascending" then local num_results = self.manager:num_results() worst_line = self.max_results - num_results @@ -231,28 +233,21 @@ function Picker:highlight_one_row(results_bufnr, prompt, display, row) if highlights then for _, hl in ipairs(highlights) do local highlight, start, finish - if type(hl) == 'table' then - highlight = hl.highlight or 'TelescopeMatching' + if type(hl) == "table" then + highlight = hl.highlight or "TelescopeMatching" start = hl.start finish = hl.finish or hl.start - elseif type(hl) == 'number' then - highlight = 'TelescopeMatching' + elseif type(hl) == "number" then + highlight = "TelescopeMatching" start = hl finish = hl else - error('Invalid higlighter fn') + error "Invalid higlighter fn" end - self:_increment('highlights') + self:_increment "highlights" - vim.api.nvim_buf_add_highlight( - results_bufnr, - ns_telescope_matching, - highlight, - row, - start - 1, - finish - ) + vim.api.nvim_buf_add_highlight(results_bufnr, ns_telescope_matching, highlight, row, start - 1, finish) end end @@ -261,7 +256,7 @@ function Picker:highlight_one_row(results_bufnr, prompt, display, row) end function Picker:can_select_row(row) - if self.sorting_strategy == 'ascending' then + if self.sorting_strategy == "ascending" then return row <= self.manager:num_results() else return row >= 0 and row <= self.max_results and row >= self.max_results - self.manager:num_results() @@ -304,47 +299,48 @@ function Picker:find() popup_opts.preview.minheight = popup_opts.preview.height end - local results_win, results_opts = popup.create('', popup_opts.results) + local results_win, results_opts = popup.create("", popup_opts.results) local results_bufnr = a.nvim_win_get_buf(results_win) self.results_bufnr = results_bufnr self.results_win = results_win -- TODO: Should probably always show all the line for results win, so should implement a resize for the windows - a.nvim_win_set_option(results_win, 'wrap', false) - a.nvim_win_set_option(results_win, 'winhl', 'Normal:TelescopeNormal') - a.nvim_win_set_option(results_win, 'winblend', self.window.winblend) + a.nvim_win_set_option(results_win, "wrap", false) + a.nvim_win_set_option(results_win, "winhl", "Normal:TelescopeNormal") + a.nvim_win_set_option(results_win, "winblend", self.window.winblend) local results_border_win = results_opts.border and results_opts.border.win_id if results_border_win then - vim.api.nvim_win_set_option(results_border_win, 'winhl', 'Normal:TelescopeResultsBorder') + vim.api.nvim_win_set_option(results_border_win, "winhl", "Normal:TelescopeResultsBorder") end - local preview_win, preview_opts, preview_bufnr if popup_opts.preview then - preview_win, preview_opts = popup.create('', popup_opts.preview) + preview_win, preview_opts = popup.create("", popup_opts.preview) preview_bufnr = a.nvim_win_get_buf(preview_win) - a.nvim_win_set_option(preview_win, 'winhl', 'Normal:TelescopePreviewNormal') - a.nvim_win_set_option(preview_win, 'winblend', self.window.winblend) + a.nvim_win_set_option(preview_win, "winhl", "Normal:TelescopePreviewNormal") + a.nvim_win_set_option(preview_win, "winblend", self.window.winblend) local preview_border_win = preview_opts and preview_opts.border and preview_opts.border.win_id if preview_border_win then - vim.api.nvim_win_set_option(preview_border_win, 'winhl', 'Normal:TelescopePreviewBorder') + vim.api.nvim_win_set_option(preview_border_win, "winhl", "Normal:TelescopePreviewBorder") end end -- TODO: We need to center this and make it prettier... - local prompt_win, prompt_opts = popup.create('', popup_opts.prompt) + local prompt_win, prompt_opts = popup.create("", popup_opts.prompt) local prompt_bufnr = a.nvim_win_get_buf(prompt_win) - a.nvim_win_set_option(prompt_win, 'winhl', 'Normal:TelescopeNormal') - a.nvim_win_set_option(prompt_win, 'winblend', self.window.winblend) + a.nvim_win_set_option(prompt_win, "winhl", "Normal:TelescopeNormal") + a.nvim_win_set_option(prompt_win, "winblend", self.window.winblend) local prompt_border_win = prompt_opts.border and prompt_opts.border.win_id - if prompt_border_win then vim.api.nvim_win_set_option(prompt_border_win, 'winhl', 'Normal:TelescopePromptBorder') end + if prompt_border_win then + vim.api.nvim_win_set_option(prompt_border_win, "winhl", "Normal:TelescopePromptBorder") + end -- Prompt prefix local prompt_prefix = self.prompt_prefix - if prompt_prefix ~= '' then - a.nvim_buf_set_option(prompt_bufnr, 'buftype', 'prompt') + if prompt_prefix ~= "" then + a.nvim_buf_set_option(prompt_bufnr, "buftype", "prompt") vim.fn.prompt_setprompt(prompt_bufnr, prompt_prefix) end self.prompt_prefix = prompt_prefix @@ -377,8 +373,12 @@ function Picker:find() return end - if not first_line then first_line = 0 end - if not last_line then last_line = 1 end + if not first_line then + first_line = 0 + end + if not last_line then + last_line = 1 + end if first_line > 0 or last_line > 1 then log.debug("ON_LINES: Bad range", first_line, last_line, self:_get_prompt()) @@ -396,7 +396,9 @@ function Picker:find() self.finder = finder end - if self.sorter then self.sorter:_start(prompt) end + if self.sorter then + self.sorter:_start(prompt) + end -- TODO: Entry manager should have a "bulk" setter. This can prevent a lot of redraws from display self.manager = EntryManager:new(self.max_results, self.entry_adder, self.stats) @@ -428,23 +430,27 @@ function Picker:find() self.closed = true -- TODO: Should we actually do this? - collectgarbage(); collectgarbage() + collectgarbage() + collectgarbage() end, }) - if self.sorter then self.sorter:_init() end + if self.sorter then + self.sorter:_init() + end async_lib.run(main_loop()) status_updater() -- TODO: Use WinLeave as well? local on_buf_leave = string.format( [[ autocmd BufLeave ++nested ++once :silent lua require('telescope.pickers').on_close_prompt(%s)]], - prompt_bufnr) + prompt_bufnr + ) - vim.cmd([[augroup PickerInsert]]) - vim.cmd([[ au!]]) - vim.cmd( on_buf_leave) - vim.cmd([[augroup END]]) + vim.cmd [[augroup PickerInsert]] + vim.cmd [[ au!]] + vim.cmd(on_buf_leave) + vim.cmd [[augroup END]] self.prompt_bufnr = prompt_bufnr @@ -452,26 +458,31 @@ function Picker:find() self.preview_border = preview_border local preview_border_win = (preview_border and preview_border.win_id) and preview_border.win_id - state.set_status(prompt_bufnr, setmetatable({ - prompt_bufnr = prompt_bufnr, - prompt_win = prompt_win, - prompt_border_win = prompt_border_win, + state.set_status( + prompt_bufnr, + setmetatable({ + prompt_bufnr = prompt_bufnr, + prompt_win = prompt_win, + prompt_border_win = prompt_border_win, - results_bufnr = results_bufnr, - results_win = results_win, - results_border_win = results_border_win, + results_bufnr = results_bufnr, + results_win = results_win, + results_border_win = results_border_win, - preview_bufnr = preview_bufnr, - preview_win = preview_win, - preview_border_win = preview_border_win, - picker = self, - }, { __mode = 'kv' })) + preview_bufnr = preview_bufnr, + preview_win = preview_win, + preview_border_win = preview_border_win, + picker = self, + }, { + __mode = "kv", + }) + ) mappings.apply_keymap(prompt_bufnr, self.attach_mappings, config.values.mappings) -- Do filetype last, so that users can register at the last second. - pcall(a.nvim_buf_set_option, prompt_bufnr, 'filetype', 'TelescopePrompt') - pcall(a.nvim_buf_set_option, results_bufnr, 'filetype', 'TelescopeResults') + pcall(a.nvim_buf_set_option, prompt_bufnr, "filetype", "TelescopePrompt") + pcall(a.nvim_buf_set_option, results_bufnr, "filetype", "TelescopeResults") if self.default_text then self:set_prompt(self.default_text) @@ -529,7 +540,9 @@ function Picker:delete_selection(delete_cb) -- Sort in reverse order as removing an entry from the table shifts down the -- other elements to close the hole. - table.sort(selection_index, function(x, y) return x > y end) + table.sort(selection_index, function(x, y) + return x > y + end) for _, index in ipairs(selection_index) do local selection = table.remove(self.finder.results, index) delete_cb(selection) @@ -548,7 +561,7 @@ end function Picker:set_prompt(str) -- TODO(conni2461): As soon as prompt_buffers are fix use this: -- vim.api.nvim_buf_set_lines(self.prompt_bufnr, 0, 1, false, { str }) - vim.api.nvim_feedkeys(str, 'n', false) + vim.api.nvim_feedkeys(str, "n", false) end function Picker.close_windows(status) @@ -566,9 +579,7 @@ function Picker.close_windows(status) end local bufnr = vim.api.nvim_win_get_buf(win_id) - if bdelete - and vim.api.nvim_buf_is_valid(bufnr) - and not vim.api.nvim_buf_get_option(bufnr, 'buflisted') then + if bdelete and vim.api.nvim_buf_is_valid(bufnr) and not vim.api.nvim_buf_get_option(bufnr, "buflisted") then vim.cmd(string.format("silent! bdelete! %s", bufnr)) end @@ -650,10 +661,11 @@ end function Picker:_reset_prefix_color(hl_group) self._current_prefix_hl_group = hl_group or nil - if self.prompt_prefix ~= '' then - vim.api.nvim_buf_add_highlight(self.prompt_bufnr, + if self.prompt_prefix ~= "" then + vim.api.nvim_buf_add_highlight( + self.prompt_bufnr, ns_telescope_prompt_prefix, - self._current_prefix_hl_group or 'TelescopePromptPrefix', + self._current_prefix_hl_group or "TelescopePromptPrefix", 0, 0, #self.prompt_prefix @@ -665,26 +677,28 @@ end -- TODO(conni2461): Next two functions only work together otherwise color doesn't work -- Probably a issue with prompt buffers function Picker:change_prompt_prefix(new_prefix, hl_group) - if not new_prefix then return end + if not new_prefix then + return + end - if new_prefix ~= '' then + if new_prefix ~= "" then vim.fn.prompt_setprompt(self.prompt_bufnr, new_prefix) else vim.api.nvim_buf_set_text(self.prompt_bufnr, 0, 0, 0, #self.prompt_prefix, {}) - vim.api.nvim_buf_set_option(self.prompt_bufnr, 'buftype', '') + vim.api.nvim_buf_set_option(self.prompt_bufnr, "buftype", "") end self.prompt_prefix = new_prefix self:_reset_prefix_color(hl_group) end function Picker:reset_prompt(text) - local prompt_text = self.prompt_prefix .. (text or '') + local prompt_text = self.prompt_prefix .. (text or "") vim.api.nvim_buf_set_lines(self.prompt_bufnr, 0, -1, false, { prompt_text }) self:_reset_prefix_color(self._current_prefix_hl_group) if text then - vim.api.nvim_win_set_cursor(self.prompt_win, {1, #prompt_text}) + vim.api.nvim_win_set_cursor(self.prompt_win, { 1, #prompt_text }) end end @@ -693,10 +707,14 @@ end function Picker:refresh(finder, opts) opts = opts or {} if opts.new_prefix then - local handle = type(opts.new_prefix) == 'table' and unpack or function(x) return x end + local handle = type(opts.new_prefix) == "table" and unpack or function(x) + return x + end self:change_prompt_prefix(handle(opts.new_prefix)) end - if opts.reset_prompt then self:reset_prompt() end + if opts.reset_prompt then + self:reset_prompt() + end if finder then self.finder:close() @@ -708,7 +726,9 @@ function Picker:refresh(finder, opts) end function Picker:set_selection(row) - if not self.manager then return end + if not self.manager then + return + end row = self.scroller(self.max_results, self.manager:num_results(), row) @@ -729,11 +749,9 @@ function Picker:set_selection(row) end if row > a.nvim_buf_line_count(results_bufnr) then - log.debug(string.format( - "Should not be possible to get row this large %s %s", - row, - a.nvim_buf_line_count(results_bufnr) - )) + log.debug( + string.format("Should not be possible to get row this large %s %s", row, a.nvim_buf_line_count(results_bufnr)) + ) return end @@ -741,7 +759,9 @@ function Picker:set_selection(row) local entry = self.manager:get_entry(self:get_index(row)) state.set_global_key("selected_entry", entry) - if not entry then return end + if not entry then + return + end -- TODO: Probably should figure out what the rows are that made this happen... -- Probably something with setting a row that's too high for this? @@ -754,14 +774,13 @@ function Picker:set_selection(row) -- Only change the first couple characters, nvim_buf_set_text leaves the existing highlights a.nvim_buf_set_text( results_bufnr, - self._selection_row, 0, - self._selection_row, #self.selection_caret, + self._selection_row, + 0, + self._selection_row, + #self.selection_caret, { self.entry_prefix } ) - self.highlighter:hi_multiselect( - self._selection_row, - self:is_multi_selected(self._selection_entry) - ) + self.highlighter:hi_multiselect(self._selection_row, self:is_multi_selected(self._selection_entry)) -- local display = a.nvim_buf_get_lines(results_bufnr, old_row, old_row + 1, false)[1] -- display = ' ' .. display @@ -781,10 +800,10 @@ function Picker:set_selection(row) -- TODO: You should go back and redraw the highlights for this line from the sorter. -- That's the only smart thing to do. if not a.nvim_buf_is_valid(results_bufnr) then - log.debug("Invalid buf somehow...") + log.debug "Invalid buf somehow..." return end - a.nvim_buf_set_lines(results_bufnr, row, row + 1, false, {display}) + a.nvim_buf_set_lines(results_bufnr, row, row + 1, false, { display }) -- don't highlight the ' ' at the end of caret self.highlighter:hi_selection(row, caret:sub(1, -2)) @@ -813,12 +832,9 @@ end function Picker:refresh_previewer() local status = state.get_status(self.prompt_bufnr) if status.preview_win and self.previewer then - self:_increment("previewed") + self:_increment "previewed" - self.previewer:preview( - self._selection_entry, - status - ) + self.previewer:preview(self._selection_entry, status) if self.preview_border then if config.values.dynamic_preview_title == true then self.preview_border:change_title(self.previewer:dynamic_title(self._selection_entry)) @@ -831,7 +847,9 @@ end function Picker:cycle_previewers(next) local size = #self.all_previewers - if size == 1 then return end + if size == 1 then + return + end self.current_previewer_index = self.current_previewer_index + next if self.current_previewer_index > size then @@ -845,7 +863,9 @@ function Picker:cycle_previewers(next) end function Picker:entry_adder(index, entry, _, insert) - if not entry then return end + if not entry then + return + end local row = self:get_row(index) @@ -867,13 +887,13 @@ function Picker:entry_adder(index, entry, _, insert) local prefix = self.entry_prefix display = prefix .. display - self:_increment("displayed") + self:_increment "displayed" -- TODO: Don't need to schedule this if we schedule the adder. local offset = insert and 0 or 1 vim.schedule(function() if not vim.api.nvim_buf_is_valid(self.results_bufnr) then - log.debug("ON_ENTRY: Invalid buffer") + log.debug "ON_ENTRY: Invalid buffer" return end @@ -885,12 +905,12 @@ function Picker:entry_adder(index, entry, _, insert) end if insert then - if self.sorting_strategy == 'descending' then + if self.sorting_strategy == "descending" then vim.api.nvim_buf_set_lines(self.results_bufnr, 0, 1, false, {}) end end - local set_ok, msg = pcall(vim.api.nvim_buf_set_lines, self.results_bufnr, row, row + offset, false, {display}) + local set_ok, msg = pcall(vim.api.nvim_buf_set_lines, self.results_bufnr, row, row + offset, false, { display }) if set_ok and display_highlights then self.highlighter:hi_display(row, prefix, display_highlights) end @@ -901,14 +921,13 @@ function Picker:entry_adder(index, entry, _, insert) -- This pretty much only fails when people leave newlines in their results. -- So we'll clean it up for them if it fails. - if not set_ok and display:find("\n") then + if not set_ok and display:find "\n" then display = display:gsub("\n", " | ") - vim.api.nvim_buf_set_lines(self.results_bufnr, row, row + 1, false, {display}) + vim.api.nvim_buf_set_lines(self.results_bufnr, row, row + 1, false, { display }) end end) end - function Picker:_reset_track() self.stats.processed = 0 self.stats.displayed = 0 @@ -945,7 +964,6 @@ function Picker:_decrement(key) self.stats[key] = (self.stats[key] or 0) - 1 end - -- TODO: Decide how much we want to use this. -- Would allow for better debugging of items. function Picker:register_completion_callback(cb) @@ -967,7 +985,9 @@ end function Picker:get_status_updater(prompt_win, prompt_bufnr) return function() local text = self:get_status_text() - if self.closed or not vim.api.nvim_buf_is_valid(prompt_bufnr) then return end + if self.closed or not vim.api.nvim_buf_is_valid(prompt_bufnr) then + return + end local current_prompt = vim.api.nvim_buf_get_lines(prompt_bufnr, 0, 1, false)[1] if not current_prompt then return @@ -981,13 +1001,7 @@ function Picker:get_status_updater(prompt_win, prompt_bufnr) local padding = string.rep(" ", vim.api.nvim_win_get_width(prompt_win) - prompt_len - #text - 3) vim.api.nvim_buf_clear_namespace(prompt_bufnr, ns_telescope_prompt, 0, 1) - vim.api.nvim_buf_set_virtual_text( - prompt_bufnr, - ns_telescope_prompt, - 0, - { {padding .. text, "NonText"} }, - {} - ) + vim.api.nvim_buf_set_virtual_text(prompt_bufnr, ns_telescope_prompt, 0, { { padding .. text, "NonText" } }, {}) -- TODO: Wait for bfredl -- vim.api.nvim_buf_set_extmark(prompt_bufnr, ns_telescope_prompt, 0, 0, { @@ -997,11 +1011,10 @@ function Picker:get_status_updater(prompt_win, prompt_bufnr) -- virt_text_pos = "eol", -- }) - self:_increment("status") + self:_increment "status" end end - function Picker:get_result_processor(find_id, prompt, status_updater) local cb_add = function(score, entry) self.manager:add_entry(self, score, entry) @@ -1009,17 +1022,15 @@ function Picker:get_result_processor(find_id, prompt, status_updater) end local cb_filter = function(_) - self:_increment("filtered") + self:_increment "filtered" end return function(entry) - if find_id ~= self._find_id - or self.closed - or self:is_done() then + if find_id ~= self._find_id or self.closed or self:is_done() then return true end - self:_increment("processed") + self:_increment "processed" if not entry or entry.valid == false then return @@ -1029,11 +1040,11 @@ function Picker:get_result_processor(find_id, prompt, status_updater) -- a ton of time on large results. log.trace("Processing result... ", entry) for _, v in ipairs(self.file_ignore_patterns or {}) do - local file = type(entry.value) == 'string' and entry.value or entry.filename + local file = type(entry.value) == "string" and entry.value or entry.filename if file then if string.find(file, v) then log.trace("SKIPPING", entry.value, "because", v) - self:_decrement("processed") + self:_decrement "processed" return end end @@ -1045,18 +1056,20 @@ end function Picker:get_result_completor(results_bufnr, find_id, prompt, status_updater) return function() - if self.closed == true or self:is_done() then return end + if self.closed == true or self:is_done() then + return + end - local selection_strategy = self.selection_strategy or 'reset' + local selection_strategy = self.selection_strategy or "reset" -- TODO: Either: always leave one result or make sure we actually clean up the results when nothing matches - if selection_strategy == 'row' then + if selection_strategy == "row" then if self._selection_row == nil and self.default_selection_index ~= nil then self:set_selection(self:get_row(self.default_selection_index)) else self:set_selection(self:get_selection_row()) end - elseif selection_strategy == 'follow' then + elseif selection_strategy == "follow" then if self._selection_row == nil and self.default_selection_index ~= nil then self:set_selection(self:get_row(self.default_selection_index)) else @@ -1069,53 +1082,53 @@ function Picker:get_result_completor(results_bufnr, find_id, prompt, status_upda self:set_selection(self:get_reset_row()) end end - elseif selection_strategy == 'reset' then + elseif selection_strategy == "reset" then if self.default_selection_index ~= nil then self:set_selection(self:get_row(self.default_selection_index)) else self:set_selection(self:get_reset_row()) end - elseif selection_strategy == 'closest' then + elseif selection_strategy == "closest" then if prompt == "" and self.default_selection_index ~= nil then self:set_selection(self:get_row(self.default_selection_index)) else self:set_selection(self:get_reset_row()) end else - error('Unknown selection strategy: ' .. selection_strategy) + error("Unknown selection strategy: " .. selection_strategy) end local current_line = vim.api.nvim_get_current_line():sub(self.prompt_prefix:len() + 1) - state.set_global_key('current_line', current_line) + state.set_global_key("current_line", current_line) status_updater() self:clear_extra_rows(results_bufnr) self:highlight_displayed_rows(results_bufnr, prompt) - if self.sorter then self.sorter:_finish(prompt) end + if self.sorter then + self.sorter:_finish(prompt) + end self:_on_complete() end end - - pickers.new = function(opts, defaults) local result = {} for k, v in pairs(opts or {}) do - assert(type(k) == 'string', "Should be string, opts") + assert(type(k) == "string", "Should be string, opts") result[k] = v end for k, v in pairs(defaults or {}) do if result[k] == nil then - assert(type(k) == 'string', "Should be string, defaults") + assert(type(k) == "string", "Should be string, defaults") result[k] = v else -- For attach mappings, we want people to be able to pass in another function -- and apply their mappings after we've applied our defaults. - if k == 'attach_mappings' then + if k == "attach_mappings" then local opt_value = result[k] result[k] = function(...) v(...) @@ -1154,5 +1167,4 @@ end pickers._Picker = Picker - return pickers diff --git a/lua/telescope/pickers/_test.lua b/lua/telescope/pickers/_test.lua index eeb9823..2124635 100644 --- a/lua/telescope/pickers/_test.lua +++ b/lua/telescope/pickers/_test.lua @@ -1,9 +1,9 @@ -local assert = require('luassert') -local builtin = require('telescope.builtin') -local log = require('telescope.log') +local assert = require "luassert" +local builtin = require "telescope.builtin" +local log = require "telescope.log" -local Job = require("plenary.job") -local Path = require("plenary.path") +local Job = require "plenary.job" +local Path = require "plenary.path" local tester = {} @@ -36,9 +36,9 @@ local execute_test_case = function(location, key, spec) if not ok then writer { - location = 'Error: ' .. location, + location = "Error: " .. location, case = key, - expected = 'To succeed and return: ' .. tostring(spec[1]), + expected = "To succeed and return: " .. tostring(spec[1]), actual = actual, _type = spec._type, @@ -60,7 +60,7 @@ local end_test_cases = function() end local invalid_test_case = function(k) - writer { case = k, expected = '', actual = k } + writer { case = k, expected = "", actual = k } end_test_cases() end @@ -93,17 +93,17 @@ tester.picker_feed = function(input, test_cases) vim.defer_fn(function() if test_cases.post_typed then for k, v in ipairs(test_cases.post_typed) do - execute_test_case('post_typed', k, v) + execute_test_case("post_typed", k, v) end end - nvim_feed(replace_terms(""), "") + nvim_feed(replace_terms "", "") end, 20) vim.defer_fn(function() if test_cases.post_close then for k, v in ipairs(test_cases.post_close) do - execute_test_case('post_close', k, v) + execute_test_case("post_close", k, v) end end @@ -142,16 +142,13 @@ end local get_results_from_file = function(file) local j = Job:new { - command = 'nvim', + command = "nvim", args = { - '--noplugin', - '-u', - 'scripts/minimal_init.vim', - '-c', - string.format( - [[lua require("telescope.pickers._test")._execute("%s")]], - file - ), + "--noplugin", + "-u", + "scripts/minimal_init.vim", + "-c", + string.format([[lua require("telescope.pickers._test")._execute("%s")]], file), }, } @@ -166,7 +163,6 @@ local get_results_from_file = function(file) return result_table end - local asserters = { _default = assert.are.same, @@ -174,19 +170,12 @@ local asserters = { are_not = assert.are_not.same, } - local check_results = function(results) -- TODO: We should get all the test cases here that fail, not just the first one. for _, v in ipairs(results) do - local assertion = asserters[v._type or 'default'] + local assertion = asserters[v._type or "default"] - assertion( - v.expected, - v.actual, - string.format("Test Case: %s // %s", - v.location, - v.case) - ) + assertion(v.expected, v.actual, string.format("Test Case: %s // %s", v.location, v.case)) end end @@ -208,7 +197,7 @@ tester.run_string = function(contents) end tester.run_file = function(filename) - local file = './lua/tests/pickers/' .. filename .. '.lua' + local file = "./lua/tests/pickers/" .. filename .. ".lua" if not Path:new(file):exists() then assert.are.same("", file) @@ -220,7 +209,7 @@ tester.run_file = function(filename) end tester.not_ = function(val) - val._type = 'are_not' + val._type = "are_not" return val end @@ -233,9 +222,9 @@ tester._execute = function(filename) local f = loadfile(filename) if not f then writer { - location = 'Error: ' .. filename, + location = "Error: " .. filename, case = filename, - expected = 'To succeed', + expected = "To succeed", actual = nil, } end @@ -252,5 +241,4 @@ tester._execute = function(filename) end_test_cases() end - return tester diff --git a/lua/telescope/pickers/_test_helpers.lua b/lua/telescope/pickers/_test_helpers.lua index 63d1a0f..5296c45 100644 --- a/lua/telescope/pickers/_test_helpers.lua +++ b/lua/telescope/pickers/_test_helpers.lua @@ -1,12 +1,12 @@ local test_helpers = {} test_helpers.get_picker = function() - local state = require('telescope.state') + local state = require "telescope.state" return state.get_status(vim.api.nvim_get_current_buf()).picker end test_helpers.get_results_bufnr = function() - local state = require('telescope.state') + local state = require "telescope.state" return state.get_status(vim.api.nvim_get_current_buf()).results_bufnr end @@ -24,9 +24,9 @@ end test_helpers.get_best_result = function() local results = test_helpers.get_results() - local picker = test_helpers.get_picker () + local picker = test_helpers.get_picker() - if picker.sorting_strategy == 'ascending' then + if picker.sorting_strategy == "ascending" then return results[1] else return results[#results] @@ -34,8 +34,8 @@ test_helpers.get_best_result = function() end test_helpers.get_selection = function() - local state = require('telescope.state') - return state.get_global_key('selected_entry') + local state = require "telescope.state" + return state.get_global_key "selected_entry" end test_helpers.get_selection_value = function() @@ -43,13 +43,13 @@ test_helpers.get_selection_value = function() end test_helpers.make_globals = function() - GetFile = test_helpers.get_file -- luacheck: globals GetFile - GetPrompt = test_helpers.get_prompt -- luacheck: globals GetPrompt + GetFile = test_helpers.get_file -- luacheck: globals GetFile + GetPrompt = test_helpers.get_prompt -- luacheck: globals GetPrompt - GetResults = test_helpers.get_results -- luacheck: globals GetResults - GetBestResult = test_helpers.get_best_result -- luacheck: globals GetBestResult + GetResults = test_helpers.get_results -- luacheck: globals GetResults + GetBestResult = test_helpers.get_best_result -- luacheck: globals GetBestResult - GetSelection = test_helpers.get_selection -- luacheck: globals GetSelection + GetSelection = test_helpers.get_selection -- luacheck: globals GetSelection GetSelectionValue = test_helpers.get_selection_value -- luacheck: globals GetSelectionValue end diff --git a/lua/telescope/pickers/entry_display.lua b/lua/telescope/pickers/entry_display.lua index e2be8c0..0982e87 100644 --- a/lua/telescope/pickers/entry_display.lua +++ b/lua/telescope/pickers/entry_display.lua @@ -1,4 +1,4 @@ -local strings = require('plenary.strings') +local strings = require "plenary.strings" local entry_display = {} entry_display.truncate = strings.truncate @@ -9,7 +9,7 @@ entry_display.create = function(configuration) if v.width then local justify = v.right_justify table.insert(generator, function(item) - if type(item) == 'table' then + if type(item) == "table" then return strings.align_str(entry_display.truncate(item[1], v.width), v.width, justify), item[2] else return strings.align_str(entry_display.truncate(item, v.width), v.width, justify) @@ -17,7 +17,7 @@ entry_display.create = function(configuration) end) else table.insert(generator, function(item) - if type(item) == 'table' then + if type(item) == "table" then return item[1], item[2] else return item @@ -37,7 +37,7 @@ entry_display.create = function(configuration) for j = 1, (i - 1) do hl_start = hl_start + #results[j] + (#configuration.separator or 1) end - local hl_end = hl_start + #str:gsub('%s*$', '') + local hl_end = hl_start + #str:gsub("%s*$", "") if type(hl) == "function" then for _, hl_res in ipairs(hl()) do @@ -66,7 +66,7 @@ entry_display.create = function(configuration) local final_str = table.concat(results, configuration.separator or "│") if configuration.hl_chars then for i = 1, #final_str do - local c = final_str:sub(i,i) + local c = final_str:sub(i, i) local hl = configuration.hl_chars[c] if hl then table.insert(highlights, { { i - 1, i }, hl }) @@ -78,21 +78,20 @@ entry_display.create = function(configuration) end end - entry_display.resolve = function(self, entry) local display, display_highlights - if type(entry.display) == 'function' then - self:_increment("display_fn") + if type(entry.display) == "function" then + self:_increment "display_fn" display, display_highlights = entry:display(self) - if type(display) == 'string' then + if type(display) == "string" then return display, display_highlights end else display = entry.display end - if type(display) == 'string' then + if type(display) == "string" then return display, display_highlights end end diff --git a/lua/telescope/pickers/highlights.lua b/lua/telescope/pickers/highlights.lua index 8378e9b..1be289e 100644 --- a/lua/telescope/pickers/highlights.lua +++ b/lua/telescope/pickers/highlights.lua @@ -1,11 +1,11 @@ local a = vim.api -local log = require('telescope.log') +local log = require "telescope.log" local highlights = {} -local ns_telescope_selection = a.nvim_create_namespace('telescope_selection') -local ns_telescope_multiselection = a.nvim_create_namespace('telescope_mulitselection') -local ns_telescope_entry = a.nvim_create_namespace('telescope_entry') +local ns_telescope_selection = a.nvim_create_namespace "telescope_selection" +local ns_telescope_multiselection = a.nvim_create_namespace "telescope_mulitselection" +local ns_telescope_entry = a.nvim_create_namespace "telescope_entry" local Highlighter = {} Highlighter.__index = Highlighter @@ -41,11 +41,12 @@ function Highlighter:hi_display(row, prefix, display_highlights) end function Highlighter:clear_display() - if not self - or not self.picker - or not self.picker.results_bufnr - or not vim.api.nvim_buf_is_valid(self.picker.results_bufnr) - then + if + not self + or not self.picker + or not self.picker.results_bufnr + or not vim.api.nvim_buf_is_valid(self.picker.results_bufnr) + then return end @@ -66,35 +67,23 @@ function Highlighter:hi_selection(row, caret) local results_bufnr = assert(self.picker.results_bufnr, "Must have a results bufnr") a.nvim_buf_clear_namespace(results_bufnr, ns_telescope_selection, 0, -1) - a.nvim_buf_add_highlight( - results_bufnr, - ns_telescope_selection, - 'TelescopeSelectionCaret', - row, - 0, - #caret - ) + a.nvim_buf_add_highlight(results_bufnr, ns_telescope_selection, "TelescopeSelectionCaret", row, 0, #caret) - a.nvim_buf_add_highlight( - results_bufnr, - ns_telescope_selection, - 'TelescopeSelection', - row, - #caret, - -1 - ) + a.nvim_buf_add_highlight(results_bufnr, ns_telescope_selection, "TelescopeSelection", row, #caret, -1) end function Highlighter:hi_multiselect(row, is_selected) local results_bufnr = assert(self.picker.results_bufnr, "Must have a results bufnr") if is_selected then - vim.api.nvim_buf_add_highlight( - results_bufnr, ns_telescope_multiselection, "TelescopeMultiSelection", row, 0, -1 - ) + vim.api.nvim_buf_add_highlight(results_bufnr, ns_telescope_multiselection, "TelescopeMultiSelection", row, 0, -1) else local existing_marks = vim.api.nvim_buf_get_extmarks( - results_bufnr, ns_telescope_multiselection, {row, 0}, {row, -1}, {} + results_bufnr, + ns_telescope_multiselection, + { row, 0 }, + { row, -1 }, + {} ) -- This is still kind of weird to me, since it seems like I'm erasing stuff @@ -102,12 +91,7 @@ function Highlighter:hi_multiselect(row, is_selected) if #existing_marks > 0 then log.trace("Clearning row: ", row) - vim.api.nvim_buf_clear_namespace( - results_bufnr, - ns_telescope_multiselection, - row, - row + 1 - ) + vim.api.nvim_buf_clear_namespace(results_bufnr, ns_telescope_multiselection, row, row + 1) end end end diff --git a/lua/telescope/pickers/layout_strategies.lua b/lua/telescope/pickers/layout_strategies.lua index 4630a64..b97888a 100644 --- a/lua/telescope/pickers/layout_strategies.lua +++ b/lua/telescope/pickers/layout_strategies.lua @@ -34,8 +34,8 @@ --- ---@brief ]] -local resolve = require('telescope.config.resolve') -local p_window = require('telescope.pickers.window') +local resolve = require "telescope.config.resolve" +local p_window = require "telescope.pickers.window" local if_nil = vim.F.if_nil local get_border_size = function(opts) @@ -47,8 +47,7 @@ local get_border_size = function(opts) end local calc_tabline = function(max_lines) - local tbln = (vim.o.showtabline == 2) - or (vim.o.showtabline == 1 and #vim.api.nvim_list_tabpages() > 1) + local tbln = (vim.o.showtabline == 2) or (vim.o.showtabline == 1 and #vim.api.nvim_list_tabpages() > 1) if tbln then max_lines = max_lines - 1 end @@ -88,12 +87,14 @@ local function validate_layout_config(strategy_name, configuration, values, defa local valid_configuration_keys = get_valid_configuration_keys(configuration) -- If no default_layout_config provided, check Telescope's config values - default_layout_config = if_nil(default_layout_config, require('telescope.config').values.layout_config) + default_layout_config = if_nil(default_layout_config, require("telescope.config").values.layout_config) local result = {} local get_value = function(k) -- skip "private" items - if string.sub(k, 1, 1) == "_" then return end + if string.sub(k, 1, 1) == "_" then + return + end local val -- Prioritise options that are specific to this strategy @@ -102,9 +103,7 @@ local function validate_layout_config(strategy_name, configuration, values, defa end -- Handle nested layout config values - if layout_strategies[k] - and strategy_name ~= k - and type(val) == 'table' then + if layout_strategies[k] and strategy_name ~= k and type(val) == "table" then val = vim.tbl_deep_extend("force", default_layout_config[k], val) end @@ -113,8 +112,7 @@ local function validate_layout_config(strategy_name, configuration, values, defa end if val == nil then - if default_layout_config[strategy_name] ~= nil - and default_layout_config[strategy_name][k] ~= nil then + if default_layout_config[strategy_name] ~= nil and default_layout_config[strategy_name][k] ~= nil then val = default_layout_config[strategy_name][k] else val = default_layout_config[k] @@ -129,10 +127,14 @@ local function validate_layout_config(strategy_name, configuration, values, defa if not valid_configuration_keys[k] then -- TODO: At some point we'll move to error here, -- but it's a bit annoying to just straight up crash everyone's stuff. - vim.api.nvim_err_writeln(string.format( - "Unsupported layout_config key for the %s strategy: %s\n%s", - strategy_name, k, vim.inspect(values) - )) + vim.api.nvim_err_writeln( + string.format( + "Unsupported layout_config key for the %s strategy: %s\n%s", + strategy_name, + k, + vim.inspect(values) + ) + ) end result[k] = get_value(k) @@ -163,7 +165,7 @@ layout_strategies._format = function(name) return {} end - local results = {"
", "`picker.layout_config` shared options:"}
+  local results = { "
", "`picker.layout_config` shared options:" }
 
   local strategy_keys = vim.tbl_keys(strategy_config)
   table.sort(strategy_keys, function(a, b)
@@ -171,12 +173,12 @@ layout_strategies._format = function(name)
   end)
 
   local add_value = function(k, val)
-    if type(val) == 'string' then
-      table.insert(results, string.format('  - %s: %s', k, val))
-    elseif type(val) == 'table' then
-      table.insert(results, string.format('  - %s:', k))
+    if type(val) == "string" then
+      table.insert(results, string.format("  - %s: %s", k, val))
+    elseif type(val) == "table" then
+      table.insert(results, string.format("  - %s:", k))
       for _, line in ipairs(val) do
-        table.insert(results, string.format('    - %s', line))
+        table.insert(results, string.format("    - %s", line))
       end
     else
       error("Unknown type:" .. type(val))
@@ -219,13 +221,14 @@ local function make_documented_layout(name, layout_config, layout)
       max_columns,
       max_lines,
       validate_layout_config(
-        name, layout_config, vim.tbl_deep_extend("keep", if_nil(override_layout, {}), if_nil(self.layout_config, {}))
+        name,
+        layout_config,
+        vim.tbl_deep_extend("keep", if_nil(override_layout, {}), if_nil(self.layout_config, {}))
       )
     )
   end
 end
 
-
 --- Horizontal layout has two columns, one for the preview
 --- and one for the prompt and results.
 ---
@@ -249,88 +252,91 @@ end
 --- 
---@eval { ["description"] = require('telescope.pickers.layout_strategies')._format("horizontal") } --- -layout_strategies.horizontal = make_documented_layout('horizontal', vim.tbl_extend("error", shared_options, { - preview_width = { "Change the width of Telescope's preview window", "See |resolver.resolve_width()|", }, +layout_strategies.horizontal = make_documented_layout( + "horizontal", + vim.tbl_extend("error", shared_options, { + preview_width = { "Change the width of Telescope's preview window", "See |resolver.resolve_width()|" }, preview_cutoff = "When columns are less than this value, the preview will be disabled", prompt_position = { "Where to place prompt window.", "Available Values: 'bottom', 'top'" }, -}), function(self, max_columns, max_lines, layout_config) + }), + function(self, max_columns, max_lines, layout_config) + local initial_options = p_window.get_initial_window_options(self) + local preview = initial_options.preview + local results = initial_options.results + local prompt = initial_options.prompt - local initial_options = p_window.get_initial_window_options(self) - local preview = initial_options.preview - local results = initial_options.results - local prompt = initial_options.prompt + local tbln + max_lines, tbln = calc_tabline(max_lines) - local tbln - max_lines, tbln = calc_tabline(max_lines) + local width_opt = layout_config.width + local picker_width = resolve.resolve_width(width_opt)(self, max_columns, max_lines) + local width_padding = math.floor((max_columns - picker_width) / 2) - local width_opt = layout_config.width - local picker_width = resolve.resolve_width(width_opt)(self, max_columns, max_lines) - local width_padding = math.floor((max_columns - picker_width)/2) + local height_opt = layout_config.height + local picker_height = resolve.resolve_height(height_opt)(self, max_columns, max_lines) + local height_padding = math.floor((max_lines - picker_height) / 2) - local height_opt = layout_config.height - local picker_height = resolve.resolve_height(height_opt)(self, max_columns, max_lines) - local height_padding = math.floor((max_lines - picker_height)/2) + if self.previewer and max_columns >= layout_config.preview_cutoff then + preview.width = resolve.resolve_width(if_nil(layout_config.preview_width, function(_, cols) + if cols < 150 then + return math.floor(cols * 0.4) + elseif cols < 200 then + return 80 + else + return 120 + end + end))(self, picker_width, max_lines) + else + preview.width = 0 + end - if self.previewer and max_columns >= layout_config.preview_cutoff then - preview.width = resolve.resolve_width(if_nil(layout_config.preview_width, function(_, cols) - if cols < 150 then - return math.floor(cols * 0.4) - elseif cols < 200 then - return 80 - else - return 120 - end - end))(self, picker_width, max_lines) - else - preview.width = 0 + results.width = picker_width - preview.width + prompt.width = picker_width - preview.width + + prompt.height = 1 + results.height = picker_height - prompt.height - 2 + + if self.previewer then + preview.height = picker_height + else + preview.height = 0 + end + + -- Default value is false, to use the normal horizontal layout + if not layout_config.mirror then + results.col = width_padding + prompt.col = width_padding + preview.col = results.col + results.width + 2 + else + preview.col = width_padding + prompt.col = preview.col + preview.width + 2 + results.col = preview.col + preview.width + 2 + end + + preview.line = height_padding + if layout_config.prompt_position == "top" then + prompt.line = height_padding + results.line = prompt.line + prompt.height + 2 + elseif layout_config.prompt_position == "bottom" then + results.line = height_padding + prompt.line = results.line + results.height + 2 + else + error("Unknown prompt_position: " .. tostring(self.window.prompt_position) .. "\n" .. vim.inspect(layout_config)) + end + + if tbln then + prompt.line = prompt.line + 1 + results.line = results.line + 1 + preview.line = preview.line + 1 + end + + return { + preview = self.previewer and preview.width > 0 and preview, + results = results, + prompt = prompt, + } end - - results.width = picker_width - preview.width - prompt.width = picker_width - preview.width - - prompt.height = 1 - results.height = picker_height - prompt.height - 2 - - if self.previewer then - preview.height = picker_height - else - preview.height = 0 - end - - -- Default value is false, to use the normal horizontal layout - if not layout_config.mirror then - results.col = width_padding - prompt.col = width_padding - preview.col = results.col + results.width + 2 - else - preview.col = width_padding - prompt.col = preview.col + preview.width + 2 - results.col = preview.col + preview.width + 2 - end - - preview.line = height_padding - if layout_config.prompt_position == "top" then - prompt.line = height_padding - results.line = prompt.line + prompt.height + 2 - elseif layout_config.prompt_position == "bottom" then - results.line = height_padding - prompt.line = results.line + results.height + 2 - else - error("Unknown prompt_position: " .. tostring(self.window.prompt_position) .. "\n" .. vim.inspect(layout_config)) - end - - if tbln then - prompt.line = prompt.line + 1 - results.line = results.line + 1 - preview.line = preview.line + 1 - end - - return { - preview = self.previewer and preview.width > 0 and preview, - results = results, - prompt = prompt - } -end) +) --- Centered layout with a combined block of the prompt --- and results aligned to the middle of the screen. @@ -358,67 +364,70 @@ end) ---
---@eval { ["description"] = require("telescope.pickers.layout_strategies")._format("center") } --- -layout_strategies.center = make_documented_layout("center", vim.tbl_extend("error", shared_options, { - preview_cutoff = "When lines are less than this value, the preview will be disabled", -}), function(self, max_columns, max_lines,layout_config) +layout_strategies.center = make_documented_layout( + "center", + vim.tbl_extend("error", shared_options, { + preview_cutoff = "When lines are less than this value, the preview will be disabled", + }), + function(self, max_columns, max_lines, layout_config) + local initial_options = p_window.get_initial_window_options(self) + local preview = initial_options.preview + local results = initial_options.results + local prompt = initial_options.prompt - local initial_options = p_window.get_initial_window_options(self) - local preview = initial_options.preview - local results = initial_options.results - local prompt = initial_options.prompt + local tbln + max_lines, tbln = calc_tabline(max_lines) - local tbln - max_lines, tbln = calc_tabline(max_lines) + -- This sets the width for the whole layout + local width_opt = layout_config.width + local width = resolve.resolve_width(width_opt)(self, max_columns, max_lines) - -- This sets the width for the whole layout - local width_opt = layout_config.width - local width = resolve.resolve_width(width_opt)(self, max_columns, max_lines) + -- This sets the number of results displayed + local res_height_opt = layout_config.height + local res_height = resolve.resolve_height(res_height_opt)(self, max_columns, max_lines) - -- This sets the number of results displayed - local res_height_opt = layout_config.height - local res_height = resolve.resolve_height(res_height_opt)(self, max_columns, max_lines) + local max_results = (res_height > max_lines and max_lines or res_height) + local max_width = (width > max_columns and max_columns or width) - local max_results = (res_height > max_lines and max_lines or res_height) - local max_width = (width > max_columns and max_columns or width) + local bs = get_border_size(self) - local bs = get_border_size(self) + prompt.height = 1 + results.height = max_results - prompt.height = 1 - results.height = max_results + prompt.width = max_width + results.width = max_width + preview.width = max_width - prompt.width = max_width - results.width = max_width - preview.width = max_width + -- Align the prompt and results so halfway up the screen is + -- in the middle of this combined block + prompt.line = (max_lines / 2) - ((max_results + (bs * 2)) / 2) + results.line = prompt.line + 1 + bs - -- Align the prompt and results so halfway up the screen is - -- in the middle of this combined block - prompt.line = (max_lines / 2) - ((max_results + (bs * 2)) / 2) - results.line = prompt.line + 1 + (bs) + preview.line = 1 - preview.line = 1 + if self.previewer and max_lines >= layout_config.preview_cutoff then + preview.height = math.floor(prompt.line - (2 + bs)) + else + preview.height = 0 + end - if self.previewer and max_lines >= layout_config.preview_cutoff then - preview.height = math.floor(prompt.line - (2 + bs)) - else - preview.height = 0 + results.col = math.ceil((max_columns / 2) - (width / 2) - bs) + prompt.col = results.col + preview.col = results.col + + if tbln then + prompt.line = prompt.line + 1 + results.line = results.line + 1 + preview.line = preview.line + 1 + end + + return { + preview = self.previewer and preview.height > 0 and preview, + results = results, + prompt = prompt, + } end - - results.col = math.ceil((max_columns / 2) - (width / 2) - bs) - prompt.col = results.col - preview.col = results.col - - if tbln then - prompt.line = prompt.line + 1 - results.line = results.line + 1 - preview.line = preview.line + 1 - end - - return { - preview = self.previewer and preview.height > 0 and preview, - results = results, - prompt = prompt - } -end) +) --- Cursor layout dynamically positioned below the cursor if possible. --- If there is no place below the cursor it will be placed above. @@ -441,78 +450,81 @@ end) --- │ │ --- └──────────────────────────────────────────────────┘ --- -layout_strategies.cursor = make_documented_layout("cursor", vim.tbl_extend("error", shared_options, { - preview_width = { "Change the width of Telescope's preview window", "See |resolver.resolve_width()|", }, +layout_strategies.cursor = make_documented_layout( + "cursor", + vim.tbl_extend("error", shared_options, { + preview_width = { "Change the width of Telescope's preview window", "See |resolver.resolve_width()|" }, preview_cutoff = "When columns are less than this value, the preview will be disabled", -}), function(self, max_columns, max_lines, layout_config) + }), + function(self, max_columns, max_lines, layout_config) + local initial_options = p_window.get_initial_window_options(self) + local preview = initial_options.preview + local results = initial_options.results + local prompt = initial_options.prompt - local initial_options = p_window.get_initial_window_options(self) - local preview = initial_options.preview - local results = initial_options.results - local prompt = initial_options.prompt + local height_opt = layout_config.height + local height = resolve.resolve_height(height_opt)(self, max_columns, max_lines) - local height_opt = layout_config.height - local height = resolve.resolve_height(height_opt)(self, max_columns, max_lines) + local width_opt = layout_config.width + local width = resolve.resolve_width(width_opt)(self, max_columns, max_lines) - local width_opt = layout_config.width - local width = resolve.resolve_width(width_opt)(self, max_columns, max_lines) + local max_width = (width > max_columns and max_columns or width) - local max_width = (width > max_columns and max_columns or width) + local bs = get_border_size(self) - local bs = get_border_size(self) + prompt.height = 1 + results.height = height + preview.height = results.height + prompt.height + bs - prompt.height = 1 - results.height = height - preview.height = results.height + prompt.height + bs + if self.previewer and max_columns >= layout_config.preview_cutoff then + preview.width = resolve.resolve_width(if_nil(layout_config.preview_width, function(_, cols) + -- By default, previewer takes 2/3 of the layout + return 2 * math.floor(max_width / 3) + end))(self, max_width, max_lines) + else + preview.width = 0 + end - if self.previewer and max_columns >= layout_config.preview_cutoff then - preview.width = resolve.resolve_width(if_nil(layout_config.preview_width, function(_, cols) - -- By default, previewer takes 2/3 of the layout - return 2 * math.floor(max_width / 3) - end))(self, max_width, max_lines) - else - preview.width = 0 + prompt.width = max_width - preview.width + results.width = prompt.width + + local total_height = preview.height + (bs * 2) + local total_width = prompt.width + (bs * 2) + preview.width + bs + + local position = vim.api.nvim_win_get_position(0) + local top_left = { + line = vim.fn.winline() + position[1] + bs, + col = vim.fn.wincol() + position[2], + } + local bot_right = { + line = top_left.line + total_height - 1, + col = top_left.col + total_width - 1, + } + + if bot_right.line > max_lines then + -- position above current line + top_left.line = top_left.line - total_height - 1 + end + if bot_right.col >= max_columns then + -- cap to the right of the screen + top_left.col = max_columns - total_width + end + + prompt.line = top_left.line + results.line = prompt.line + bs + 1 + preview.line = prompt.line + + prompt.col = top_left.col + results.col = prompt.col + preview.col = results.col + (bs * 2) + results.width + + return { + preview = self.previewer and preview.width > 0 and preview, + results = results, + prompt = prompt, + } end - - prompt.width = max_width - preview.width - results.width = prompt.width - - local total_height = preview.height + (bs*2) - local total_width = prompt.width + (bs*2) + preview.width + bs - - local position = vim.api.nvim_win_get_position(0) - local top_left = { - line = vim.fn.winline() + position[1] + bs, - col = vim.fn.wincol() + position[2] - } - local bot_right = { - line = top_left.line + total_height - 1, - col = top_left.col + total_width - 1 - } - - if bot_right.line > max_lines then - -- position above current line - top_left.line = top_left.line - total_height - 1 - end - if bot_right.col >= max_columns then - -- cap to the right of the screen - top_left.col = max_columns - total_width - end - - prompt.line = top_left.line - results.line = prompt.line + bs + 1 - preview.line = prompt.line - - prompt.col = top_left.col - results.col = prompt.col - preview.col = results.col + (bs*2) + results.width - - return { - preview = self.previewer and preview.width > 0 and preview, - results = results, - prompt = prompt - } -end) +) --- Vertical layout stacks the items on top of each other. --- Particularly useful with thinner windows. @@ -537,97 +549,105 @@ end) --- ---@eval { ["description"] = require("telescope.pickers.layout_strategies")._format("vertical") } --- -layout_strategies.vertical = make_documented_layout("vertical", vim.tbl_extend("error", shared_options, { - preview_cutoff = "When lines are less than this value, the preview will be disabled", - preview_height = { "Change the height of Telescope's preview window", "See |resolver.resolve_height()|" }, - prompt_position = { "(unimplemented, but we plan on supporting)" }, -}), function(self, max_columns, max_lines, layout_config) +layout_strategies.vertical = make_documented_layout( + "vertical", + vim.tbl_extend("error", shared_options, { + preview_cutoff = "When lines are less than this value, the preview will be disabled", + preview_height = { "Change the height of Telescope's preview window", "See |resolver.resolve_height()|" }, + prompt_position = { "(unimplemented, but we plan on supporting)" }, + }), + function(self, max_columns, max_lines, layout_config) + local initial_options = p_window.get_initial_window_options(self) + local preview = initial_options.preview + local results = initial_options.results + local prompt = initial_options.prompt - local initial_options = p_window.get_initial_window_options(self) - local preview = initial_options.preview - local results = initial_options.results - local prompt = initial_options.prompt + local tbln + max_lines, tbln = calc_tabline(max_lines) - local tbln - max_lines, tbln = calc_tabline(max_lines) + local width_opt = layout_config.width + local picker_width = resolve.resolve_width(width_opt)(self, max_columns, max_lines) + local width_padding = math.floor((max_columns - picker_width) / 2) - local width_opt = layout_config.width - local picker_width = resolve.resolve_width(width_opt)(self,max_columns,max_lines) - local width_padding = math.floor((max_columns - picker_width)/2) + local height_opt = layout_config.height + local picker_height = resolve.resolve_height(height_opt)(self, max_columns, max_lines) + local height_padding = math.floor((max_lines - picker_height) / 2) - local height_opt = layout_config.height - local picker_height = resolve.resolve_height(height_opt)(self,max_columns,max_lines) - local height_padding = math.floor((max_lines - picker_height)/2) + if self.previewer and max_lines >= layout_config.preview_cutoff then + preview.width = picker_width + else + preview.width = 0 + end + results.width = picker_width + prompt.width = picker_width - if self.previewer and max_lines >= layout_config.preview_cutoff then - preview.width = picker_width - else - preview.width = 0 + local preview_total = 0 + preview.height = 0 + if self.previewer and max_lines >= layout_config.preview_cutoff then + preview.height = resolve.resolve_height(if_nil(layout_config.preview_height, 0.5))( + self, + max_columns, + picker_height + ) + + preview_total = preview.height + 2 + end + + prompt.height = 1 + results.height = picker_height - preview_total - prompt.height - 2 + + results.col, preview.col, prompt.col = width_padding, width_padding, width_padding + + if not layout_config.mirror then + preview.line = height_padding + results.line = (preview.height == 0) and preview.line or preview.line + preview.height + 2 + prompt.line = results.line + results.height + 2 + else + prompt.line = height_padding + results.line = prompt.line + prompt.height + 2 + preview.line = results.line + results.height + 2 + end + + if tbln then + prompt.line = prompt.line + 1 + results.line = results.line + 1 + preview.line = preview.line + 1 + end + + return { + preview = self.previewer and preview.height > 0 and preview, + results = results, + prompt = prompt, + } end - results.width = picker_width - prompt.width = picker_width - - local preview_total = 0 - preview.height = 0 - if self.previewer and max_lines >= layout_config.preview_cutoff then - preview.height = resolve.resolve_height( - if_nil(layout_config.preview_height, 0.5) - )(self, max_columns, picker_height) - - preview_total = preview.height + 2 - end - - prompt.height = 1 - results.height = picker_height - preview_total - prompt.height - 2 - - results.col, preview.col, prompt.col = width_padding, width_padding, width_padding - - if not layout_config.mirror then - preview.line = height_padding - results.line = (preview.height == 0) and preview.line - or preview.line + preview.height + 2 - prompt.line = results.line + results.height + 2 - else - prompt.line = height_padding - results.line = prompt.line + prompt.height + 2 - preview.line = results.line + results.height + 2 - end - - if tbln then - prompt.line = prompt.line + 1 - results.line = results.line + 1 - preview.line = preview.line + 1 - end - - return { - preview = self.previewer and preview.height > 0 and preview, - results = results, - prompt = prompt - } -end) +) --- Flex layout swaps between `horizontal` and `vertical` strategies based on the window width --- - Supports |layout_strategies.vertical| or |layout_strategies.horizontal| features --- ---@eval { ["description"] = require("telescope.pickers.layout_strategies")._format("flex") } --- -layout_strategies.flex = make_documented_layout('flex', vim.tbl_extend("error", shared_options, { - flip_columns = "The number of columns required to move to horizontal mode", - flip_lines = "The number of lines required to move to horizontal mode", - vertical = "Options to pass when switching to vertical layout", - horizontal = "Options to pass when switching to horizontal layout", -}), function(self, max_columns, max_lines, layout_config) - local flip_columns = if_nil(layout_config.flip_columns, 100) - local flip_lines = if_nil(layout_config.flip_lines, 20) +layout_strategies.flex = make_documented_layout( + "flex", + vim.tbl_extend("error", shared_options, { + flip_columns = "The number of columns required to move to horizontal mode", + flip_lines = "The number of lines required to move to horizontal mode", + vertical = "Options to pass when switching to vertical layout", + horizontal = "Options to pass when switching to horizontal layout", + }), + function(self, max_columns, max_lines, layout_config) + local flip_columns = if_nil(layout_config.flip_columns, 100) + local flip_lines = if_nil(layout_config.flip_lines, 20) - if max_columns < flip_columns and max_lines > flip_lines then - return layout_strategies.vertical(self, max_columns, max_lines, layout_config.vertical) - else - return layout_strategies.horizontal(self, max_columns, max_lines, layout_config.horizontal) + if max_columns < flip_columns and max_lines > flip_lines then + return layout_strategies.vertical(self, max_columns, max_lines, layout_config.vertical) + else + return layout_strategies.horizontal(self, max_columns, max_lines, layout_config.horizontal) + end end -end) +) -layout_strategies.current_buffer = make_documented_layout('current_buffer', { +layout_strategies.current_buffer = make_documented_layout("current_buffer", { -- No custom options. -- height, width ignored }, function(self, _, _, _) @@ -663,7 +683,6 @@ layout_strategies.current_buffer = make_documented_layout('current_buffer', { results.height = window_height - prompt.height - 2 - height_padding * 2 end - local win_position = vim.api.nvim_win_get_position(0) local line = win_position[1] @@ -689,82 +708,86 @@ end) --- Bottom pane can be used to create layouts similar to "ivy". --- --- For an easy ivy configuration, see |themes.get_ivy()| -layout_strategies.bottom_pane = make_documented_layout('bottom_pane', vim.tbl_extend("error", shared_options, { - -- No custom options... -}), function(self, max_columns, max_lines, layout_config) - local initial_options = p_window.get_initial_window_options(self) - local results = initial_options.results - local prompt = initial_options.prompt - local preview = initial_options.preview +layout_strategies.bottom_pane = make_documented_layout( + "bottom_pane", + vim.tbl_extend("error", shared_options, { + -- No custom options... + }), + function(self, max_columns, max_lines, layout_config) + local initial_options = p_window.get_initial_window_options(self) + local results = initial_options.results + local prompt = initial_options.prompt + local preview = initial_options.preview - local result_height = if_nil(resolve.resolve_height(layout_config.height)(self,max_columns,max_lines), 25) + local result_height = if_nil(resolve.resolve_height(layout_config.height)(self, max_columns, max_lines), 25) - local prompt_width = max_columns - local col = 0 + local prompt_width = max_columns + local col = 0 - local has_border = not not self.window.border - if has_border then - col = 1 - prompt_width = prompt_width - 2 - end - - local left_side_width - if self.previewer then - left_side_width = math.floor(prompt_width / 2) - - local base_col - if layout_config.mirror then - base_col = 0 - else - base_col = left_side_width + 1 + local has_border = not not self.window.border + if has_border then + col = 1 + prompt_width = prompt_width - 2 end - if has_border then - preview = vim.tbl_deep_extend("force", { - col = base_col + 2, - line = max_lines - result_height + 1, - width = prompt_width - left_side_width - 2, - height = result_height - 1, - }, preview) + local left_side_width + if self.previewer then + left_side_width = math.floor(prompt_width / 2) + + local base_col + if layout_config.mirror then + base_col = 0 + else + base_col = left_side_width + 1 + end + + if has_border then + preview = vim.tbl_deep_extend("force", { + col = base_col + 2, + line = max_lines - result_height + 1, + width = prompt_width - left_side_width - 2, + height = result_height - 1, + }, preview) + else + preview = vim.tbl_deep_extend("force", { + col = base_col, + line = max_lines - result_height, + width = prompt_width - left_side_width, + height = result_height, + }, preview) + end else - preview = vim.tbl_deep_extend("force", { - col = base_col, + preview = nil + left_side_width = prompt_width + end + + local result_col + if layout_config.mirror and self.previewer then + result_col = left_side_width + 2 + if has_border then + left_side_width = left_side_width - 2 + end + else + result_col = col + end + + return { + preview = preview, + prompt = vim.tbl_deep_extend("force", prompt, { + line = max_lines - result_height - 1, + col = col, + height = 1, + width = prompt_width, + }), + results = vim.tbl_deep_extend("force", results, { line = max_lines - result_height, - width = prompt_width - left_side_width, + col = result_col, height = result_height, - }, preview) - end - else - preview = nil - left_side_width = prompt_width + width = left_side_width, + }), + } end - - local result_col - if layout_config.mirror and self.previewer then - result_col = left_side_width + 2 - if has_border then - left_side_width = left_side_width - 2 - end - else - result_col = col - end - - return { - preview = preview, - prompt = vim.tbl_deep_extend("force", prompt, { - line = max_lines - result_height - 1, - col = col, - height = 1, - width = prompt_width, - }), - results = vim.tbl_deep_extend("force", results, { - line = max_lines - result_height, - col = result_col, - height = result_height, - width = left_side_width, - }), - } -end) +) layout_strategies._validate_layout_config = validate_layout_config diff --git a/lua/telescope/pickers/multi.lua b/lua/telescope/pickers/multi.lua index 2896c08..50aa051 100644 --- a/lua/telescope/pickers/multi.lua +++ b/lua/telescope/pickers/multi.lua @@ -1,17 +1,16 @@ - local MultiSelect = {} MultiSelect.__index = MultiSelect function MultiSelect:new() return setmetatable({ - _entries = {} + _entries = {}, }, MultiSelect) end function MultiSelect:get() local marked_entries = {} for entry, count in pairs(self._entries) do - table.insert(marked_entries, {count, entry}) + table.insert(marked_entries, { count, entry }) end table.sort(marked_entries, function(left, right) diff --git a/lua/telescope/pickers/scroller.lua b/lua/telescope/pickers/scroller.lua index d2aed2c..814ac74 100644 --- a/lua/telescope/pickers/scroller.lua +++ b/lua/telescope/pickers/scroller.lua @@ -48,7 +48,7 @@ scroller.create = function(scroll_strategy, sorting_strategy) local scroll_fn = scroll_calculators[scroll_strategy] if not scroll_fn then - error(debug.traceback("Unknown scroll strategy: " .. (scroll_strategy or ''))) + error(debug.traceback("Unknown scroll strategy: " .. (scroll_strategy or ""))) end local calculator = scroll_fn(range_fn) @@ -56,17 +56,27 @@ scroller.create = function(scroll_strategy, sorting_strategy) local result = calculator(max_results, num_results, row) if result < 0 then - error(string.format( - "Must never return a negative row: { result = %s, args = { %s %s %s } }", - result, max_results, num_results, row - )) + error( + string.format( + "Must never return a negative row: { result = %s, args = { %s %s %s } }", + result, + max_results, + num_results, + row + ) + ) end if result >= max_results then - error(string.format( - "Must never exceed max results: { result = %s, args = { %s %s %s } }", - result, max_results, num_results, row - )) + error( + string.format( + "Must never exceed max results: { result = %s, args = { %s %s %s } }", + result, + max_results, + num_results, + row + ) + ) end return result @@ -74,7 +84,7 @@ scroller.create = function(scroll_strategy, sorting_strategy) end scroller.top = function(sorting_strategy, max_results, num_results) - if sorting_strategy == 'ascending' then + if sorting_strategy == "ascending" then return 0 end return (num_results > max_results) and 0 or (max_results - num_results) @@ -83,7 +93,7 @@ end scroller.middle = function(sorting_strategy, max_results, num_results) local mid_pos - if sorting_strategy == 'ascending' then + if sorting_strategy == "ascending" then mid_pos = math.floor(num_results / 2) else mid_pos = math.floor(max_results - num_results / 2) @@ -93,14 +103,14 @@ scroller.middle = function(sorting_strategy, max_results, num_results) end scroller.bottom = function(sorting_strategy, max_results, num_results) - if sorting_strategy == 'ascending' then + if sorting_strategy == "ascending" then return math.min(max_results, num_results) - 1 end return max_results - 1 end scroller.better = function(sorting_strategy) - if sorting_strategy == 'ascending' then + if sorting_strategy == "ascending" then return -1 else return 1 diff --git a/lua/telescope/pickers/window.lua b/lua/telescope/pickers/window.lua index 533fe30..95b89cf 100644 --- a/lua/telescope/pickers/window.lua +++ b/lua/telescope/pickers/window.lua @@ -1,10 +1,10 @@ -local resolve = require("telescope.config.resolve") +local resolve = require "telescope.config.resolve" local p_window = {} function p_window.get_window_options(picker, max_columns, max_lines) local layout_strategy = picker.layout_strategy - local getter = require('telescope.pickers.layout_strategies')[layout_strategy] + local getter = require("telescope.pickers.layout_strategies")[layout_strategy] if not getter then error("Not a valid layout strategy: " .. layout_strategy) @@ -22,7 +22,7 @@ function p_window.get_initial_window_options(picker) border = popup_border.preview, borderchars = popup_borderchars.preview, enter = false, - highlight = false + highlight = false, } local results = { @@ -36,7 +36,7 @@ function p_window.get_initial_window_options(picker) title = picker.prompt_title, border = popup_border.prompt, borderchars = popup_borderchars.prompt, - enter = true + enter = true, } return { @@ -46,5 +46,4 @@ function p_window.get_initial_window_options(picker) } end - return p_window diff --git a/lua/telescope/previewers/buffer_previewer.lua b/lua/telescope/previewers/buffer_previewer.lua index e5669fd..feeaf79 100644 --- a/lua/telescope/previewers/buffer_previewer.lua +++ b/lua/telescope/previewers/buffer_previewer.lua @@ -1,45 +1,45 @@ -local from_entry = require('telescope.from_entry') -local Path = require('plenary.path') -local utils = require('telescope.utils') -local putils = require('telescope.previewers.utils') -local Previewer = require('telescope.previewers.previewer') -local conf = require('telescope.config').values +local from_entry = require "telescope.from_entry" +local Path = require "plenary.path" +local utils = require "telescope.utils" +local putils = require "telescope.previewers.utils" +local Previewer = require "telescope.previewers.previewer" +local conf = require("telescope.config").values -local pfiletype = require('plenary.filetype') -local pscan = require('plenary.scandir') +local pfiletype = require "plenary.filetype" +local pscan = require "plenary.scandir" local buf_delete = utils.buf_delete local defaulter = utils.make_default_callable local previewers = {} -local ns_previewer = vim.api.nvim_create_namespace('telescope.previewers') +local ns_previewer = vim.api.nvim_create_namespace "telescope.previewers" local color_hash = { - ['p'] = 'TelescopePreviewPipe', - ['c'] = 'TelescopePreviewCharDev', - ['d'] = 'TelescopePreviewDirectory', - ['b'] = 'TelescopePreviewBlock', - ['l'] = 'TelescopePreviewLink', - ['s'] = 'TelescopePreviewSocket', - ['.'] = 'TelescopePreviewNormal', - ['r'] = 'TelescopePreviewRead', - ['w'] = 'TelescopePreviewWrite', - ['x'] = 'TelescopePreviewExecute', - ['-'] = 'TelescopePreviewHyphen', - ['T'] = 'TelescopePreviewSticky', - ['S'] = 'TelescopePreviewSticky', - [2] = 'TelescopePreviewSize', - [3] = 'TelescopePreviewUser', - [4] = 'TelescopePreviewGroup', - [5] = 'TelescopePreviewDate', + ["p"] = "TelescopePreviewPipe", + ["c"] = "TelescopePreviewCharDev", + ["d"] = "TelescopePreviewDirectory", + ["b"] = "TelescopePreviewBlock", + ["l"] = "TelescopePreviewLink", + ["s"] = "TelescopePreviewSocket", + ["."] = "TelescopePreviewNormal", + ["r"] = "TelescopePreviewRead", + ["w"] = "TelescopePreviewWrite", + ["x"] = "TelescopePreviewExecute", + ["-"] = "TelescopePreviewHyphen", + ["T"] = "TelescopePreviewSticky", + ["S"] = "TelescopePreviewSticky", + [2] = "TelescopePreviewSize", + [3] = "TelescopePreviewUser", + [4] = "TelescopePreviewGroup", + [5] = "TelescopePreviewDate", } -color_hash[6] = function(line) +color_hash[6] = function(line) return color_hash[line:sub(1, 1)] end local colorize_ls = function(bufnr, data, sections) - local windows_add = Path.path.sep == '\\' and 2 or 0 + local windows_add = Path.path.sep == "\\" and 2 or 0 for lnum, line in ipairs(data) do local section = sections[lnum] for i = 1, section[1].end_index - 1 do -- Highlight permissions @@ -48,7 +48,8 @@ local colorize_ls = function(bufnr, data, sections) end for i = 2, #section do -- highlights size, (user, group), date and name local hl_group = color_hash[i + (i ~= 2 and windows_add or 0)] - vim.api.nvim_buf_add_highlight(bufnr, + vim.api.nvim_buf_add_highlight( + bufnr, ns_previewer, type(hl_group) == "function" and hl_group(line) or hl_group, lnum - 1, @@ -60,14 +61,16 @@ local colorize_ls = function(bufnr, data, sections) end local search_cb_jump = function(self, bufnr, query) - if not query then return end + if not query then + return + end vim.api.nvim_buf_call(bufnr, function() pcall(vim.fn.matchdelete, self.state.hl_id, self.state.winid) vim.cmd "norm! gg" vim.fn.search(query, "W") vim.cmd "norm! zz" - self.state.hl_id = vim.fn.matchadd('TelescopePreviewMatch', query) + self.state.hl_id = vim.fn.matchadd("TelescopePreviewMatch", query) end) end @@ -80,29 +83,44 @@ end previewers.file_maker = function(filepath, bufnr, opts) opts = opts or {} - if opts.use_ft_detect == nil then opts.use_ft_detect = true end + if opts.use_ft_detect == nil then + opts.use_ft_detect = true + end local ft = opts.use_ft_detect and pfiletype.detect(filepath) if opts.bufname ~= filepath then - if not vim.in_fast_event() then filepath = vim.fn.expand(filepath) end + if not vim.in_fast_event() then + filepath = vim.fn.expand(filepath) + end vim.loop.fs_stat(filepath, function(_, stat) - if not stat then return end - if stat.type == 'directory' then + if not stat then + return + end + if stat.type == "directory" then pscan.ls_async(filepath, { hidden = true, group_directories_first = true, on_exit = vim.schedule_wrap(function(data, sections) vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, data) colorize_ls(bufnr, data, sections) - if opts.callback then opts.callback(bufnr) end - end)}) + if opts.callback then + opts.callback(bufnr) + end + end), + }) else Path:new(filepath):_read_async(vim.schedule_wrap(function(data) - if not vim.api.nvim_buf_is_valid(bufnr) then return end - local ok = pcall(vim.api.nvim_buf_set_lines, bufnr, 0, -1, false, vim.split(data, '[\r]?\n')) - if not ok then return end + if not vim.api.nvim_buf_is_valid(bufnr) then + return + end + local ok = pcall(vim.api.nvim_buf_set_lines, bufnr, 0, -1, false, vim.split(data, "[\r]?\n")) + if not ok then + return + end - if opts.callback then opts.callback(bufnr) end + if opts.callback then + opts.callback(bufnr) + end putils.highlighter(bufnr, ft) end)) end @@ -110,7 +128,9 @@ previewers.file_maker = function(filepath, bufnr, opts) else if opts.callback then if vim.in_fast_event() then - vim.schedule(function() opts.callback(bufnr) end) + vim.schedule(function() + opts.callback(bufnr) + end) else opts.callback(bufnr) end @@ -132,11 +152,13 @@ previewers.new_buffer_previewer = function(opts) local old_bufs = {} local bufname_table = {} - local global_state = require'telescope.state' + local global_state = require "telescope.state" local preview_window_id local function get_bufnr(self) - if not self.state then return nil end + if not self.state then + return nil + end return self.state.bufnr end @@ -148,7 +170,9 @@ previewers.new_buffer_previewer = function(opts) end local function get_bufnr_by_bufname(self, value) - if not self.state then return nil end + if not self.state then + return nil + end return bufname_table[value] end @@ -163,7 +187,7 @@ previewers.new_buffer_previewer = function(opts) function opts.title(self) if opt_title then - if type(opt_title) == 'function' then + if type(opt_title) == "function" then return opt_title(self) else return opt_title @@ -181,7 +205,9 @@ previewers.new_buffer_previewer = function(opts) function opts.setup(self) local state = {} - if opt_setup then vim.tbl_deep_extend("force", state, opt_setup(self)) end + if opt_setup then + vim.tbl_deep_extend("force", state, opt_setup(self)) + end return state end @@ -192,7 +218,7 @@ previewers.new_buffer_previewer = function(opts) local last_nr if opts.keep_last_buf then - last_nr = global_state.get_global_key('last_preview_bufnr') + last_nr = global_state.get_global_key "last_preview_bufnr" -- Push in another buffer so the last one will not be cleaned up if preview_window_id then local bufnr = vim.api.nvim_create_buf(false, true) @@ -231,21 +257,23 @@ previewers.new_buffer_previewer = function(opts) end) -- TODO(conni2461): We only have to set options once. Right? - vim.api.nvim_win_set_option(status.preview_win, 'winhl', 'Normal:TelescopePreviewNormal') - vim.api.nvim_win_set_option(status.preview_win, 'signcolumn', 'no') - vim.api.nvim_win_set_option(status.preview_win, 'foldlevel', 100) - vim.api.nvim_win_set_option(status.preview_win, 'wrap', false) + vim.api.nvim_win_set_option(status.preview_win, "winhl", "Normal:TelescopePreviewNormal") + vim.api.nvim_win_set_option(status.preview_win, "signcolumn", "no") + vim.api.nvim_win_set_option(status.preview_win, "foldlevel", 100) + vim.api.nvim_win_set_option(status.preview_win, "wrap", false) self.state.winid = status.preview_win self.state.bufname = nil end - if opts.keep_last_buf then global_state.set_global_key("last_preview_bufnr", self.state.bufnr) end + if opts.keep_last_buf then + global_state.set_global_key("last_preview_bufnr", self.state.bufnr) + end opts.define_preview(self, entry, status) putils.with_preview_window(status, nil, function() - vim.cmd'do User TelescopePreviewerLoaded' + vim.cmd "do User TelescopePreviewerLoaded" end) if opts.get_buffer_by_name then @@ -255,7 +283,9 @@ previewers.new_buffer_previewer = function(opts) if not opts.scroll_fn then function opts.scroll_fn(self, direction) - if not self.state then return end + if not self.state then + return + end local input = direction > 0 and [[]] or [[]] local count = math.abs(direction) @@ -284,11 +314,13 @@ previewers.cat = defaulter(function(opts) define_preview = function(self, entry, status) local p = from_entry.path(entry, true) - if p == nil or p == '' then return end + if p == nil or p == "" then + return + end conf.buffer_previewer_maker(p, self.state.bufnr, { - bufname = self.state.bufname + bufname = self.state.bufname, }) - end + end, } end, {}) @@ -299,8 +331,10 @@ previewers.vimgrep = defaulter(function(opts) local jump_to_line = function(self, bufnr, lnum) if lnum and lnum > 0 then pcall(vim.api.nvim_buf_add_highlight, bufnr, ns_previewer, "TelescopePreviewLine", lnum - 1, 0, -1) - pcall(vim.api.nvim_win_set_cursor, self.state.winid, {lnum, 0}) - vim.api.nvim_buf_call(bufnr, function() vim.cmd"norm! zz" end) + pcall(vim.api.nvim_win_set_cursor, self.state.winid, { lnum, 0 }) + vim.api.nvim_buf_call(bufnr, function() + vim.cmd "norm! zz" + end) end self.state.last_set_bufnr = bufnr @@ -328,24 +362,28 @@ previewers.vimgrep = defaulter(function(opts) define_preview = function(self, entry, status) local p = from_entry.path(entry, true) - if p == nil or p == '' then return end + if p == nil or p == "" then + return + end if self.state.last_set_bufnr then pcall(vim.api.nvim_buf_clear_namespace, self.state.last_set_bufnr, ns_previewer, 0, -1) end -- Workaround for unnamed buffer when using builtin.buffer - if entry.bufnr and (p == '[No Name]' or vim.api.nvim_buf_get_option(entry.bufnr, 'buftype') ~= '') then + if entry.bufnr and (p == "[No Name]" or vim.api.nvim_buf_get_option(entry.bufnr, "buftype") ~= "") then local lines = vim.api.nvim_buf_get_lines(entry.bufnr, 0, -1, false) vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) jump_to_line(self, self.state.bufnr, entry.lnum) else conf.buffer_previewer_maker(p, self.state.bufnr, { bufname = self.state.bufname, - callback = function(bufnr) jump_to_line(self, bufnr, entry.lnum) end + callback = function(bufnr) + jump_to_line(self, bufnr, entry.lnum) + end, }) end - end + end, } end, {}) @@ -355,17 +393,17 @@ previewers.ctags = defaulter(function(_) local determine_jump = function(entry) if entry.scode then return function(self) - local scode = string.gsub(entry.scode, '[$]$', '') + local scode = string.gsub(entry.scode, "[$]$", "") scode = string.gsub(scode, [[\\]], [[\]]) scode = string.gsub(scode, [[\/]], [[/]]) - scode = string.gsub(scode, '[*]', [[\*]]) + scode = string.gsub(scode, "[*]", [[\*]]) pcall(vim.fn.matchdelete, self.state.hl_id, self.state.winid) vim.cmd "norm! gg" vim.fn.search(scode, "W") vim.cmd "norm! zz" - self.state.hl_id = vim.fn.matchadd('TelescopePreviewMatch', scode) + self.state.hl_id = vim.fn.matchadd("TelescopePreviewMatch", scode) end else return function(self, bufnr) @@ -401,9 +439,9 @@ previewers.ctags = defaulter(function(_) vim.api.nvim_buf_call(bufnr, function() determine_jump(entry)(self, bufnr) end) - end + end, }) - end + end, } end, {}) @@ -417,21 +455,21 @@ previewers.builtin = defaulter(function(_) end, define_preview = function(self, entry, status) - local module_name = vim.fn.fnamemodify(entry.filename, ':t:r') + local module_name = vim.fn.fnamemodify(entry.filename, ":t:r") local text if entry.text:sub(1, #module_name) ~= module_name then - text = module_name .. '.' .. entry.text + text = module_name .. "." .. entry.text else - text = entry.text:gsub('_', '.', 1) + text = entry.text:gsub("_", ".", 1) end conf.buffer_previewer_maker(entry.filename, self.state.bufnr, { bufname = self.state.bufname, callback = function(bufnr) search_cb_jump(self, bufnr, text) - end + end, }) - end + end, } end, {}) @@ -452,17 +490,17 @@ previewers.help = defaulter(function(_) conf.buffer_previewer_maker(entry.filename, self.state.bufnr, { bufname = self.state.bufname, callback = function(bufnr) - putils.regex_highlighter(bufnr, 'help') + putils.regex_highlighter(bufnr, "help") search_cb_jump(self, bufnr, query) - end + end, }) - end + end, } end, {}) previewers.man = defaulter(function(opts) local pager = utils.get_lazy_default(opts.PAGER, function() - return vim.fn.executable('col') == 1 and 'col -bx' or '' + return vim.fn.executable "col" == 1 and "col -bx" or "" end) return previewers.new_buffer_previewer { title = "Man Preview", @@ -472,13 +510,13 @@ previewers.man = defaulter(function(opts) define_preview = function(self, entry, status) local win_width = vim.api.nvim_win_get_width(self.state.winid) - putils.job_maker({'man', entry.section, entry.value}, self.state.bufnr, { + putils.job_maker({ "man", entry.section, entry.value }, self.state.bufnr, { env = { ["PAGER"] = pager, ["MANWIDTH"] = win_width }, value = entry.value, - bufname = self.state.bufname + bufname = self.state.bufname, }) - putils.regex_highlighter(self.state.bufnr, 'man') - end + putils.regex_highlighter(self.state.bufnr, "man") + end, } end) @@ -486,21 +524,21 @@ previewers.git_branch_log = defaulter(function(opts) local highlight_buffer = function(bufnr, content) for i = 1, #content do local line = content[i] - local _, hstart = line:find('[%*%s|]*') + local _, hstart = line:find "[%*%s|]*" if hstart then local hend = hstart + 7 if hend < #line then vim.api.nvim_buf_add_highlight(bufnr, ns_previewer, "TelescopeResultsIdentifier", i - 1, hstart - 1, hend) end end - local _, cstart = line:find('- %(') + local _, cstart = line:find "- %(" if cstart then - local cend = string.find(line, '%) ') + local cend = string.find(line, "%) ") if cend then vim.api.nvim_buf_add_highlight(bufnr, ns_previewer, "TelescopeResultsConstant", i - 1, cstart - 1, cend) end end - local dstart, _ = line:find(' %(%d') + local dstart, _ = line:find " %(%d" if dstart then vim.api.nvim_buf_add_highlight(bufnr, ns_previewer, "TelescopeResultsSpecialComment", i - 1, dstart, #line) end @@ -514,19 +552,29 @@ previewers.git_branch_log = defaulter(function(opts) end, define_preview = function(self, entry, status) - local cmd = { 'git', '--no-pager', 'log', '--graph', '--pretty=format:%h -%d %s (%cr)', - '--abbrev-commit', '--date=relative', entry.value } + local cmd = { + "git", + "--no-pager", + "log", + "--graph", + "--pretty=format:%h -%d %s (%cr)", + "--abbrev-commit", + "--date=relative", + entry.value, + } putils.job_maker(cmd, self.state.bufnr, { value = entry.value, bufname = self.state.bufname, cwd = opts.cwd, callback = function(bufnr, content) - if not content then return end + if not content then + return + end highlight_buffer(bufnr, content) - end + end, }) - end + end, } end, {}) @@ -538,13 +586,13 @@ previewers.git_stash_diff = defaulter(function(opts) end, define_preview = function(self, entry, _) - putils.job_maker({ 'git', '--no-pager', 'stash', 'show', '-p', entry.value }, self.state.bufnr, { + putils.job_maker({ "git", "--no-pager", "stash", "show", "-p", entry.value }, self.state.bufnr, { value = entry.value, bufname = self.state.bufname, - cwd = opts.cwd + cwd = opts.cwd, }) - putils.regex_highlighter(self.state.bufnr, 'diff') - end + putils.regex_highlighter(self.state.bufnr, "diff") + end, } end, {}) @@ -557,9 +605,9 @@ previewers.git_commit_diff_to_parent = defaulter(function(opts) end, define_preview = function(self, entry, status) - local cmd = { 'git', '--no-pager', 'diff', entry.value .. '^!' } + local cmd = { "git", "--no-pager", "diff", entry.value .. "^!" } if opts.current_file then - table.insert(cmd, '--') + table.insert(cmd, "--") table.insert(cmd, opts.current_file) end @@ -569,10 +617,10 @@ previewers.git_commit_diff_to_parent = defaulter(function(opts) cwd = opts.cwd, callback = function(bufnr) search_cb_jump(self, bufnr, opts.current_line) - end + end, }) - putils.regex_highlighter(self.state.bufnr, 'diff') - end + putils.regex_highlighter(self.state.bufnr, "diff") + end, } end, {}) @@ -586,9 +634,9 @@ previewers.git_commit_diff_to_head = defaulter(function(opts) end, define_preview = function(self, entry, status) - local cmd = { 'git', '--no-pager', 'diff', '--cached', entry.value } + local cmd = { "git", "--no-pager", "diff", "--cached", entry.value } if opts.current_file then - table.insert(cmd, '--') + table.insert(cmd, "--") table.insert(cmd, opts.current_file) end @@ -598,10 +646,10 @@ previewers.git_commit_diff_to_head = defaulter(function(opts) cwd = opts.cwd, callback = function(bufnr) search_cb_jump(self, bufnr, opts.current_line) - end + end, }) - putils.regex_highlighter(self.state.bufnr, 'diff') - end + putils.regex_highlighter(self.state.bufnr, "diff") + end, } end, {}) @@ -615,10 +663,10 @@ previewers.git_commit_diff_as_was = defaulter(function(opts) end, define_preview = function(self, entry, status) - local cmd = { 'git', '--no-pager', 'show' } + local cmd = { "git", "--no-pager", "show" } local cf = opts.current_file and Path:new(opts.current_file):make_relative(opts.cwd) - local value = cf and (entry.value .. ':' .. cf) or (entry.value) - local ft = cf and pfiletype.detect(value) or 'diff' + local value = cf and (entry.value .. ":" .. cf) or entry.value + local ft = cf and pfiletype.detect(value) or "diff" table.insert(cmd, value) putils.job_maker(cmd, self.state.bufnr, { @@ -627,18 +675,18 @@ previewers.git_commit_diff_as_was = defaulter(function(opts) cwd = opts.cwd, callback = function(bufnr) search_cb_jump(self, bufnr, opts.current_line) - end + end, }) putils.highlighter(self.state.bufnr, ft) - end + end, } end, {}) previewers.git_commit_message = defaulter(function(opts) local hl_map = { - 'TelescopeResultsIdentifier', - 'TelescopePreviewUser', - 'TelescopePreviewDate' + "TelescopeResultsIdentifier", + "TelescopePreviewUser", + "TelescopePreviewDate", } return previewers.new_buffer_previewer { title = "Git Message", @@ -647,23 +695,25 @@ previewers.git_commit_message = defaulter(function(opts) end, define_preview = function(self, entry, status) - local cmd = { 'git', '--no-pager', 'log', '-n 1', entry.value } + local cmd = { "git", "--no-pager", "log", "-n 1", entry.value } putils.job_maker(cmd, self.state.bufnr, { value = entry.value, bufname = self.state.bufname, cwd = opts.cwd, callback = function(bufnr, content) - if not content then return end + if not content then + return + end for k, v in ipairs(hl_map) do - local _, s = content[k]:find('%s') + local _, s = content[k]:find "%s" if s then vim.api.nvim_buf_add_highlight(bufnr, ns_previewer, v, k - 1, s, #content[k]) end end - end + end, }) - end + end, } end, {}) @@ -675,21 +725,23 @@ previewers.git_file_diff = defaulter(function(opts) end, define_preview = function(self, entry, status) - if entry.status and (entry.status == '??' or entry.status == 'A ') then + if entry.status and (entry.status == "??" or entry.status == "A ") then local p = from_entry.path(entry, true) - if p == nil or p == '' then return end + if p == nil or p == "" then + return + end conf.buffer_previewer_maker(p, self.state.bufnr, { - bufname = self.state.bufname + bufname = self.state.bufname, }) else - putils.job_maker({ 'git', '--no-pager', 'diff', entry.value }, self.state.bufnr, { + putils.job_maker({ "git", "--no-pager", "diff", entry.value }, self.state.bufnr, { value = entry.value, bufname = self.state.bufname, - cwd = opts.cwd + cwd = opts.cwd, }) - putils.regex_highlighter(self.state.bufnr, 'diff') + putils.regex_highlighter(self.state.bufnr, "diff") end - end + end, } end, {}) @@ -707,7 +759,7 @@ previewers.autocommands = defaulter(function(_) end, define_preview = function(self, entry, status) - local results = vim.tbl_filter(function (x) + local results = vim.tbl_filter(function(x) return x.group == entry.group end, status.picker.finder.results) @@ -727,9 +779,7 @@ previewers.autocommands = defaulter(function(_) if item == entry then selected_row = idx end - table.insert(display, - string.format(" %-14s▏%-08s %s", item.event, item.ft_pattern, item.command) - ) + table.insert(display, string.format(" %-14s▏%-08s %s", item.event, item.ft_pattern, item.command)) end vim.api.nvim_buf_set_option(self.state.bufnr, "filetype", "vim") @@ -745,7 +795,7 @@ previewers.autocommands = defaulter(function(_) end vim.api.nvim_buf_add_highlight(self.state.bufnr, ns_previewer, "TelescopePreviewLine", selected_row + 1, 0, -1) - vim.api.nvim_win_set_cursor(status.preview_win, {selected_row + 1, 0}) + vim.api.nvim_win_set_cursor(status.preview_win, { selected_row + 1, 0 }) self.state.last_set_bufnr = self.state.bufnr end, @@ -768,12 +818,12 @@ previewers.highlights = defaulter(function(_) define_preview = function(self, entry, status) putils.with_preview_window(status, nil, function() if not self.state.bufname then - local output = vim.split(vim.fn.execute('highlight'), '\n') + local output = vim.split(vim.fn.execute "highlight", "\n") local hl_groups = {} for _, v in ipairs(output) do - if v ~= '' then - if v:sub(1, 1) == ' ' then - local part_of_old = v:match('%s+(.*)') + if v ~= "" then + if v:sub(1, 1) == " " then + local part_of_old = v:match "%s+(.*)" hl_groups[table.getn(hl_groups)] = hl_groups[table.getn(hl_groups)] .. part_of_old else table.insert(hl_groups, v) @@ -783,24 +833,26 @@ previewers.highlights = defaulter(function(_) vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, hl_groups) for k, v in ipairs(hl_groups) do - local startPos = string.find(v, 'xxx', 1, true) - 1 + local startPos = string.find(v, "xxx", 1, true) - 1 local endPos = startPos + 3 - local hlgroup = string.match(v, '([^ ]*)%s+.*') + local hlgroup = string.match(v, "([^ ]*)%s+.*") pcall(vim.api.nvim_buf_add_highlight, self.state.bufnr, 0, hlgroup, k - 1, startPos, endPos) end end pcall(vim.api.nvim_buf_clear_namespace, self.state.bufnr, ns_previewer, 0, -1) vim.cmd "norm! gg" - vim.fn.search(entry.value .. ' ') - local lnum = vim.fn.line('.') + vim.fn.search(entry.value .. " ") + local lnum = vim.fn.line "." -- That one is actually a match but its better to use it like that then matchadd - vim.api.nvim_buf_add_highlight(self.state.bufnr, + vim.api.nvim_buf_add_highlight( + self.state.bufnr, ns_previewer, "TelescopePreviewMatch", lnum - 1, 0, - #entry.value) + #entry.value + ) end) end, } @@ -810,11 +862,13 @@ previewers.display_content = defaulter(function(_) return previewers.new_buffer_previewer { define_preview = function(self, entry, status) putils.with_preview_window(status, nil, function() - assert(type(entry.preview_command) == 'function', - 'entry must provide a preview_command function which will put the content into the buffer') + assert( + type(entry.preview_command) == "function", + "entry must provide a preview_command function which will put the content into the buffer" + ) entry.preview_command(entry, self.state.bufnr) end) - end + end, } end, {}) diff --git a/lua/telescope/previewers/init.lua b/lua/telescope/previewers/init.lua index ce73815..849e2c1 100644 --- a/lua/telescope/previewers/init.lua +++ b/lua/telescope/previewers/init.lua @@ -21,9 +21,9 @@ --- :Telescope find_files previewer=false ---@brief ]] -local Previewer = require('telescope.previewers.previewer') -local term_previewer = require('telescope.previewers.term_previewer') -local buffer_previewer = require('telescope.previewers.buffer_previewer') +local Previewer = require "telescope.previewers.previewer" +local term_previewer = require "telescope.previewers.term_previewer" +local buffer_previewer = require "telescope.previewers.buffer_previewer" local previewers = {} @@ -99,7 +99,6 @@ end --- flexible `buffer_previewer` and is now deprecated. previewers.new_termopen_previewer = term_previewer.new_termopen_previewer - --- Provides a `termopen_previewer` which has the ability to display files. --- It will always show the top of the file and has support for --- `bat`(prioritized) and `cat`. Each entry has to provide either the field @@ -134,7 +133,6 @@ previewers.vimgrep = term_previewer.vimgrep --- case it's configured that way. previewers.qflist = term_previewer.qflist - --- An interface to instantiate a new `buffer_previewer`. --- That means that the content actually lives inside a vim buffer which --- enables us more control over the actual content. For example, we can @@ -241,7 +239,6 @@ previewers.new_buffer_previewer = buffer_previewer.new_buffer_previewer ---@param opts table: keys: `use_ft_detect`, `bufname` and `callback` previewers.buffer_previewer_maker = buffer_previewer.file_maker - --- A previewer that is used to display a file. It uses the `buffer_previewer` --- interface and won't jump to the line. To integrate this one into your --- own picker make sure that the field `path` or `filename` is set for @@ -273,10 +270,10 @@ previewers.vim_buffer_vimgrep = buffer_previewer.vimgrep previewers.vim_buffer_qflist = buffer_previewer.qflist --- A previewer that shows a log of a branch as graph -previewers.git_branch_log = buffer_previewer.git_branch_log +previewers.git_branch_log = buffer_previewer.git_branch_log --- A previewer that shows a diff of a stash -previewers.git_stash_diff = buffer_previewer.git_stash_diff +previewers.git_stash_diff = buffer_previewer.git_stash_diff --- A previewer that shows a diff of a commit to a parent commit.
--- The run command is `git --no-pager diff SHA^! -- $CURRENT_FILE` @@ -288,19 +285,19 @@ previewers.git_commit_diff_to_parent = buffer_previewer.git_commit_diff_to_paren --- The run command is `git --no-pager diff --cached $SHA -- $CURRENT_FILE` --- --- The current file part is optional. So is only uses it with bcommits. -previewers.git_commit_diff_to_head = buffer_previewer.git_commit_diff_to_head +previewers.git_commit_diff_to_head = buffer_previewer.git_commit_diff_to_head --- A previewer that shows a diff of a commit as it was.
--- The run command is `git --no-pager show $SHA:$CURRENT_FILE` or `git --no-pager show $SHA` -previewers.git_commit_diff_as_was = buffer_previewer.git_commit_diff_as_was +previewers.git_commit_diff_as_was = buffer_previewer.git_commit_diff_as_was --- A previewer that shows the commit message of a diff.
--- The run command is `git --no-pager log -n 1 $SHA` -previewers.git_commit_message = buffer_previewer.git_commit_message +previewers.git_commit_message = buffer_previewer.git_commit_message --- A previewer that shows the current diff of a file. Used in git_status.
--- The run command is `git --no-pager diff $FILE` -previewers.git_file_diff = buffer_previewer.git_file_diff +previewers.git_file_diff = buffer_previewer.git_file_diff previewers.ctags = buffer_previewer.ctags previewers.builtin = buffer_previewer.builtin @@ -309,7 +306,6 @@ previewers.man = buffer_previewer.man previewers.autocommands = buffer_previewer.autocommands previewers.highlights = buffer_previewer.highlights - --- A deprecated way of displaying content more easily. Was written at a time, --- where the buffer_previewer interface wasn't present. Nowadays it's easier --- to just use this. We will keep it around for backwards compatibility diff --git a/lua/telescope/previewers/previewer.lua b/lua/telescope/previewers/previewer.lua index b4a3e47..dffa5de 100644 --- a/lua/telescope/previewers/previewer.lua +++ b/lua/telescope/previewers/previewer.lua @@ -56,7 +56,7 @@ function Previewer:send_input(input) if self._send_input then self:_send_input(input) else - vim.api.nvim_err_writeln("send_input is not defined for this previewer") + vim.api.nvim_err_writeln "send_input is not defined for this previewer" end end @@ -64,7 +64,7 @@ function Previewer:scroll_fn(direction) if self._scroll_fn then self:_scroll_fn(direction) else - vim.api.nvim_err_writeln("scroll_fn is not defined for this previewer") + vim.api.nvim_err_writeln "scroll_fn is not defined for this previewer" end end diff --git a/lua/telescope/previewers/term_previewer.lua b/lua/telescope/previewers/term_previewer.lua index a7a0f72..8d4219c 100644 --- a/lua/telescope/previewers/term_previewer.lua +++ b/lua/telescope/previewers/term_previewer.lua @@ -1,9 +1,9 @@ -local conf = require('telescope.config').values -local utils = require('telescope.utils') -local Path = require('plenary.path') -local putils = require('telescope.previewers.utils') -local from_entry = require('telescope.from_entry') -local Previewer = require('telescope.previewers.previewer') +local conf = require("telescope.config").values +local utils = require "telescope.utils" +local Path = require "plenary.path" +local putils = require "telescope.previewers.utils" +local from_entry = require "telescope.from_entry" +local Previewer = require "telescope.previewers.previewer" local flatten = vim.tbl_flatten local buf_delete = utils.buf_delete @@ -14,41 +14,41 @@ local defaulter = utils.make_default_callable local previewers = {} -- TODO: Should play with these some more, ty @clason -local bat_options = {"--style=plain", "--color=always", "--paging=always"} -local has_less = (vim.fn.executable('less') == 1) and conf.use_less +local bat_options = { "--style=plain", "--color=always", "--paging=always" } +local has_less = (vim.fn.executable "less" == 1) and conf.use_less local get_file_stat = function(filename) return vim.loop.fs_stat(vim.fn.expand(filename)) or {} end local list_dir = (function() - if vim.fn.has('win32') == 1 then + if vim.fn.has "win32" == 1 then return function(dirname) - return { 'cmd.exe', '/c', 'dir', vim.fn.expand(dirname) } + return { "cmd.exe", "/c", "dir", vim.fn.expand(dirname) } end else return function(dirname) - return { 'ls', '-la', vim.fn.expand(dirname) } + return { "ls", "-la", vim.fn.expand(dirname) } end end end)() local bat_maker = function(filename, lnum, start, finish) - if get_file_stat(filename).type == 'directory' then + if get_file_stat(filename).type == "directory" then return list_dir(filename) end - local command = {"bat"} + local command = { "bat" } if lnum then - table.insert(command, { "--highlight-line", lnum}) + table.insert(command, { "--highlight-line", lnum }) end if has_less then if start then - table.insert(command, {"--pager", string.format("less -RS +%s", start)}) + table.insert(command, { "--pager", string.format("less -RS +%s", start) }) else - table.insert(command, {"--pager", "less -RS"}) + table.insert(command, { "--pager", "less -RS" }) end else if start and finish then @@ -57,18 +57,21 @@ local bat_maker = function(filename, lnum, start, finish) end return flatten { - command, bat_options, "--", vim.fn.expand(filename) + command, + bat_options, + "--", + vim.fn.expand(filename), } end local cat_maker = function(filename, _, start, _) - if get_file_stat(filename).type == 'directory' then + if get_file_stat(filename).type == "directory" then return list_dir(filename) end - if 1 == vim.fn.executable('file') then - local output = utils.get_os_command_output{ 'file', '--mime-type', '-b', filename } - local mime_type = vim.split(output[1], '/')[1] + if 1 == vim.fn.executable "file" then + local output = utils.get_os_command_output { "file", "--mime-type", "-b", filename } + local mime_type = vim.split(output[1], "/")[1] if mime_type ~= "text" then return { "echo", "Binary file found. These files cannot be displayed!" } end @@ -76,27 +79,29 @@ local cat_maker = function(filename, _, start, _) if has_less then if start then - return { 'less', '-RS', string.format('+%s', start), vim.fn.expand(filename) } + return { "less", "-RS", string.format("+%s", start), vim.fn.expand(filename) } else - return { 'less', '-RS', vim.fn.expand(filename) } + return { "less", "-RS", vim.fn.expand(filename) } end else return { - "cat", "--", vim.fn.expand(filename) + "cat", + "--", + vim.fn.expand(filename), } end end local get_maker = function(opts) local maker = opts.maker - if not maker and 1 == vim.fn.executable("bat") then + if not maker and 1 == vim.fn.executable "bat" then maker = bat_maker - elseif not maker and 1 == vim.fn.executable("cat") then + elseif not maker and 1 == vim.fn.executable "cat" then maker = cat_maker end if not maker then - error("Needs maker") + error "Needs maker" end return maker @@ -119,28 +124,40 @@ previewers.new_termopen_previewer = function(opts) local old_bufs = {} local function get_term_id(self) - if not self.state then return nil end + if not self.state then + return nil + end return self.state.termopen_id end local function get_bufnr(self) - if not self.state then return nil end + if not self.state then + return nil + end return self.state.termopen_bufnr end local function set_term_id(self, value) - if job_is_running(get_term_id(self)) then vim.fn.jobstop(get_term_id(self)) end - if self.state then self.state.termopen_id = value end + if job_is_running(get_term_id(self)) then + vim.fn.jobstop(get_term_id(self)) + end + if self.state then + self.state.termopen_id = value + end end local function set_bufnr(self, value) - if get_bufnr(self) then table.insert(old_bufs, get_bufnr(self)) end - if self.state then self.state.termopen_bufnr = value end + if get_bufnr(self) then + table.insert(old_bufs, get_bufnr(self)) + end + if self.state then + self.state.termopen_bufnr = value + end end function opts.title(self) if opt_title then - if type(opt_title) == 'function' then + if type(opt_title) == "function" then return opt_title(self) else return opt_title @@ -158,7 +175,9 @@ previewers.new_termopen_previewer = function(opts) function opts.setup(self) local state = {} - if opt_setup then vim.tbl_deep_extend("force", state, opt_setup(self)) end + if opt_setup then + vim.tbl_deep_extend("force", state, opt_setup(self)) + end return state end @@ -192,12 +211,14 @@ previewers.new_termopen_previewer = function(opts) local term_opts = { cwd = opts.cwd or vim.fn.getcwd(), - env = conf.set_env + env = conf.set_env, } putils.with_preview_window(status, bufnr, function() local cmd = opts.get_command(entry, status) - if cmd then set_term_id(self, vim.fn.termopen(cmd, term_opts)) end + if cmd then + set_term_id(self, vim.fn.termopen(cmd, term_opts)) + end end) vim.api.nvim_buf_set_name(bufnr, tostring(bufnr)) @@ -223,7 +244,7 @@ previewers.new_termopen_previewer = function(opts) local input = direction > 0 and "d" or "u" local count = math.abs(direction) - self:send_input(count..input) + self:send_input(count .. input) end end @@ -244,10 +265,12 @@ previewers.cat = defaulter(function(opts) get_command = function(entry) local p = from_entry.path(entry, true) - if p == nil or p == '' then return end + if p == nil or p == "" then + return + end return maker(p) - end + end, } end, {}) @@ -268,8 +291,10 @@ previewers.vimgrep = defaulter(function(opts) local height = vim.api.nvim_win_get_height(win_id) local p = from_entry.path(entry, true) - if p == nil or p == '' then return end - if entry.bufnr and (p == '[No Name]' or vim.api.nvim_buf_get_option(entry.bufnr, 'buftype') ~= '') then + if p == nil or p == "" then + return + end + if entry.bufnr and (p == "[No Name]" or vim.api.nvim_buf_get_option(entry.bufnr, "buftype") ~= "") then return end @@ -301,7 +326,9 @@ previewers.qflist = defaulter(function(opts) local height = vim.api.nvim_win_get_height(win_id) local p = from_entry.path(entry, true) - if p == nil or p == '' then return end + if p == nil or p == "" then + return + end local lnum = entry.lnum local start, finish @@ -315,7 +342,7 @@ previewers.qflist = defaulter(function(opts) end return maker(p, lnum, start, finish) - end + end, } end, {}) diff --git a/lua/telescope/previewers/utils.lua b/lua/telescope/previewers/utils.lua index 5ede0e0..54435fd 100644 --- a/lua/telescope/previewers/utils.lua +++ b/lua/telescope/previewers/utils.lua @@ -1,10 +1,10 @@ -local context_manager = require('plenary.context_manager') +local context_manager = require "plenary.context_manager" -local has_ts, _ = pcall(require, 'nvim-treesitter') -local _, ts_configs = pcall(require, 'nvim-treesitter.configs') -local _, ts_parsers = pcall(require, 'nvim-treesitter.parsers') +local has_ts, _ = pcall(require, "nvim-treesitter") +local _, ts_configs = pcall(require, "nvim-treesitter.configs") +local _, ts_parsers = pcall(require, "nvim-treesitter.parsers") -local Job = require('plenary.job') +local Job = require "plenary.job" local utils = {} @@ -30,33 +30,41 @@ utils.job_maker = function(cmd, bufnr, opts) -- if any of them are missing, cache will be skipped if opts.bufname ~= opts.value or not opts.bufname or not opts.value then local command = table.remove(cmd, 1) - Job:new({ - command = command, - args = cmd, - env = opts.env, - cwd = opts.cwd, - on_exit = vim.schedule_wrap(function(j) - if not vim.api.nvim_buf_is_valid(bufnr) then return end - if opts.mode == "append" then - vim.api.nvim_buf_set_lines(bufnr, -1, -1, false, j:result()) - elseif opts.mode == "insert" then - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, j:result()) - end - if opts.callback then opts.callback(bufnr, j:result()) end - end) - }):start() + Job + :new({ + command = command, + args = cmd, + env = opts.env, + cwd = opts.cwd, + on_exit = vim.schedule_wrap(function(j) + if not vim.api.nvim_buf_is_valid(bufnr) then + return + end + if opts.mode == "append" then + vim.api.nvim_buf_set_lines(bufnr, -1, -1, false, j:result()) + elseif opts.mode == "insert" then + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, j:result()) + end + if opts.callback then + opts.callback(bufnr, j:result()) + end + end), + }) + :start() else - if opts.callback then opts.callback(bufnr) end + if opts.callback then + opts.callback(bufnr) + end end end local function has_filetype(ft) - return ft and ft ~= '' + return ft and ft ~= "" end --- Attach default highlighter which will choose between regex and ts utils.highlighter = function(bufnr, ft) - if not(utils.ts_highlighter(bufnr, ft)) then + if not (utils.ts_highlighter(bufnr, ft)) then utils.regex_highlighter(bufnr, ft) end end @@ -82,8 +90,10 @@ local treesitter_attach = function(bufnr, ft) end vim.treesitter.highlighter.new(ts_parsers.get_parser(bufnr, lang)) local is_table = type(config.additional_vim_regex_highlighting) == "table" - if config.additional_vim_regex_highlighting and - (not is_table or vim.tbl_contains(config.additional_vim_regex_highlighting, lang)) then + if + config.additional_vim_regex_highlighting + and (not is_table or vim.tbl_contains(config.additional_vim_regex_highlighting, lang)) + then vim.api.nvim_buf_set_option(bufnr, "syntax", ft) end return true @@ -94,10 +104,10 @@ end -- Attach ts highlighter utils.ts_highlighter = function(bufnr, ft) if not has_ts then - has_ts, _ = pcall(require, 'nvim-treesitter') + has_ts, _ = pcall(require, "nvim-treesitter") if has_ts then - _, ts_configs = pcall(require, 'nvim-treesitter.configs') - _, ts_parsers = pcall(require, 'nvim-treesitter.parsers') + _, ts_configs = pcall(require, "nvim-treesitter.configs") + _, ts_parsers = pcall(require, "nvim-treesitter.parsers") end end diff --git a/lua/telescope/sorters.lua b/lua/telescope/sorters.lua index 46a6cc8..8874287 100644 --- a/lua/telescope/sorters.lua +++ b/lua/telescope/sorters.lua @@ -1,5 +1,5 @@ -local log = require('telescope.log') -local util = require('telescope.utils') +local log = require "telescope.log" +local util = require "telescope.utils" local sorters = {} @@ -12,7 +12,7 @@ local ngram_highlighter = function(ngram_len, prompt, display) if prompt:find(char, 1, true) then table.insert(highlights, { start = disp_index, - finish = disp_index + ngram_len - 1 + finish = disp_index + ngram_len - 1, }) end end @@ -22,7 +22,6 @@ end local FILTERED = -1 - local Sorter = {} Sorter.__index = Sorter @@ -51,9 +50,9 @@ function Sorter:new(opts) tags = opts.tags, -- State management - init = opts.init, - start = opts.start, - finish = opts.finish, + init = opts.init, + start = opts.start, + finish = opts.finish, destroy = opts.destroy, filter_function = opts.filter_function, @@ -62,17 +61,21 @@ function Sorter:new(opts) discard = opts.discard, _discard_state = { filtered = {}, - prompt = '', + prompt = "", }, }, Sorter) end function Sorter:_init() - if self.init then self:init() end + if self.init then + self:init() + end end function Sorter:_destroy() - if self.destroy then self:destroy() end + if self.destroy then + self:destroy() + end end -- TODO: We could make this a bit smarter and cache results "as we go" and where they got filtered. @@ -81,7 +84,9 @@ end -- as he did in his example. -- Example can be found in ./scratch/prime_prompt_cache.lua function Sorter:_start(prompt) - if self.start then self:start(prompt) end + if self.start then + self:start(prompt) + end if not self.discard then return @@ -91,10 +96,10 @@ function Sorter:_start(prompt) local len_previous = #previous if #prompt < len_previous then - log.debug("Reset discard because shorter prompt") + log.debug "Reset discard because shorter prompt" self._discard_state.filtered = {} elseif string.sub(prompt, 1, len_previous) ~= previous then - log.debug("Reset discard no match") + log.debug "Reset discard no match" self._discard_state.filtered = {} end @@ -102,13 +107,17 @@ function Sorter:_start(prompt) end function Sorter:_finish(prompt) - if self.finish then self:finish(prompt) end + if self.finish then + self:finish(prompt) + end end -- TODO: Consider doing something that makes it so we can skip the filter checks -- if we're not discarding. Also, that means we don't have to check otherwise as well :) function Sorter:score(prompt, entry, cb_add, cb_filter) - if not entry or not entry.ordinal then return end + if not entry or not entry.ordinal then + return + end local ordinal = entry.ordinal if self:_was_discarded(prompt, ordinal) then @@ -117,7 +126,9 @@ function Sorter:score(prompt, entry, cb_add, cb_filter) local filter_score if self.filter_function ~= nil then - if self.tags then self.tags:insert(entry) end + if self.tags then + self.tags:insert(entry) + end filter_score, prompt = self:filter_function(prompt, entry) end @@ -159,7 +170,7 @@ sorters.Sorter = Sorter TelescopeCachedTails = TelescopeCachedTails or nil if not TelescopeCachedTails then local os_sep = util.get_separator() - local match_string = '[^' .. os_sep .. ']*$' + local match_string = "[^" .. os_sep .. "]*$" TelescopeCachedTails = setmetatable({}, { __index = function(t, k) local tail = string.match(k, match_string) @@ -170,20 +181,21 @@ if not TelescopeCachedTails then }) end -TelescopeCachedUppers = TelescopeCachedUppers or setmetatable({}, { - __index = function(t, k) - local obj = {} - for i = 1, #k do - local s_byte = k:byte(i, i) - if s_byte <= 90 and s_byte >= 65 then - obj[s_byte] = true +TelescopeCachedUppers = TelescopeCachedUppers + or setmetatable({}, { + __index = function(t, k) + local obj = {} + for i = 1, #k do + local s_byte = k:byte(i, i) + if s_byte <= 90 and s_byte >= 65 then + obj[s_byte] = true + end end - end - rawset(t, k, obj) - return obj - end -}) + rawset(t, k, obj) + return obj + end, + }) TelescopeCachedNgrams = TelescopeCachedNgrams or {} @@ -201,7 +213,7 @@ sorters.get_fuzzy_file = function(opts) local R = {} for i = 1, s:len() - n + 1 do - R[#R+1] = s:sub(i, i+n-1) + R[#R + 1] = s:sub(i, i + n - 1) end if not TelescopeCachedNgrams[s] then @@ -267,19 +279,17 @@ sorters.get_fuzzy_file = function(opts) end local denominator = ( - (10 * match_count / #prompt_lower_ngrams) - -- biases for shorter strings - + 3 * match_count * ngram_len / #line - + consecutive_matches - + N / (contains_string or (2 * #line)) - - -- + 30/(c1 or 2*N) - - -- TODO: It might be possible that this too strongly correlates, - -- but it's unlikely for people to type capital letters without actually - -- wanting to do something with a capital letter in it. - + uppers_matching - ) * tail_modifier + (10 * match_count / #prompt_lower_ngrams) + -- biases for shorter strings + + 3 * match_count * ngram_len / #line + + consecutive_matches + + N / (contains_string or (2 * #line)) + -- + 30/(c1 or 2*N) + -- TODO: It might be possible that this too strongly correlates, + -- but it's unlikely for people to type capital letters without actually + -- wanting to do something with a capital letter in it. + + uppers_matching + ) * tail_modifier if denominator == 0 or denominator ~= denominator then return -1 @@ -310,7 +320,7 @@ sorters.get_generic_fuzzy_sorter = function(opts) local R = {} for i = 1, s:len() - n + 1 do - R[#R+1] = s:sub(i, i+n-1) + R[#R + 1] = s:sub(i, i + n - 1) end if not TelescopeCachedNgrams[s] then @@ -359,15 +369,15 @@ sorters.get_generic_fuzzy_sorter = function(opts) -- TODO: Copied from ashkan. local denominator = ( - (10 * match_count / #prompt_ngrams) - -- biases for shorter strings - -- TODO(ashkan): this can bias towards repeated finds of the same - -- subpattern with overlapping_ngrams - + 3 * match_count * ngram_len / #line - + consecutive_matches - + N / (contains_string or (2 * #line)) - -- + 30/(c1 or 2*N) - ) + (10 * match_count / #prompt_ngrams) + -- biases for shorter strings + -- TODO(ashkan): this can bias towards repeated finds of the same + -- subpattern with overlapping_ngrams + + 3 * match_count * ngram_len / #line + + consecutive_matches + + N / (contains_string or (2 * #line)) -- + 30/(c1 or 2*N) + + ) if denominator == 0 or denominator ~= denominator then return -1 @@ -406,17 +416,17 @@ sorters.fuzzy_with_index_bias = function(opts) else return math.min(math.pow(entry.index, 0.25), 2) * base_score end - end + end, } end -- Sorter using the fzy algorithm sorters.get_fzy_sorter = function(opts) opts = opts or {} - local fzy = opts.fzy_mod or require('telescope.algos.fzy') + local fzy = opts.fzy_mod or require "telescope.algos.fzy" local OFFSET = -fzy.get_score_floor() - return sorters.Sorter:new{ + return sorters.Sorter:new { discard = true, scoring_function = function(_, prompt, line) @@ -454,10 +464,12 @@ end sorters.highlighter_only = function(opts) opts = opts or {} - local fzy = opts.fzy_mod or require('telescope.algos.fzy') + local fzy = opts.fzy_mod or require "telescope.algos.fzy" return Sorter:new { - scoring_function = function() return 0 end, + scoring_function = function() + return 0 + end, highlighter = function(_, prompt, display) return fzy.positions(prompt, display) @@ -467,7 +479,9 @@ end sorters.empty = function() return Sorter:new { - scoring_function = function() return 0 end, + scoring_function = function() + return 0 + end, } end @@ -475,8 +489,8 @@ end sorters.get_levenshtein_sorter = function() return Sorter:new { scoring_function = function(_, prompt, line) - return require('telescope.algos.string_distance')(prompt, line) - end + return require "telescope.algos.string_distance"(prompt, line) + end, } end @@ -490,7 +504,7 @@ local substr_highlighter = function(_, prompt, display) for _, word in pairs(search_terms) do hl_start, hl_end = display:find(word, 1, true) if hl_start then - table.insert(highlights, {start = hl_start, finish = hl_end}) + table.insert(highlights, { start = hl_start, finish = hl_end }) end end @@ -501,20 +515,20 @@ sorters.get_substr_matcher = function() return Sorter:new { highlighter = substr_highlighter, scoring_function = function(_, prompt, _, entry) - local display = entry.ordinal:lower() + local display = entry.ordinal:lower() - local search_terms = util.max_split(prompt, "%s") - local matched = 0 - local total_search_terms = 0 - for _, word in pairs(search_terms) do - total_search_terms = total_search_terms + 1 - if display:find(word, 1, true) then - matched = matched + 1 + local search_terms = util.max_split(prompt, "%s") + local matched = 0 + local total_search_terms = 0 + for _, word in pairs(search_terms) do + total_search_terms = total_search_terms + 1 + if display:find(word, 1, true) then + matched = matched + 1 + end end - end - return matched == total_search_terms and entry.index or -1 - end + return matched == total_search_terms and entry.index or -1 + end, } end @@ -552,25 +566,29 @@ local filter_function = function(opts) end local function create_tag_set(tag) - tag = vim.F.if_nil(tag, 'ordinal') + tag = vim.F.if_nil(tag, "ordinal") local set = {} return setmetatable(set, { __index = { insert = function(set_, entry) local value = entry[tag] - if not set_[value] then set_[value] = true end - end - } + if not set_[value] then + set_[value] = true + end + end, + }, }) end sorters.prefilter = function(opts) local sorter = opts.sorter - opts.delimiter = util.get_default(opts.delimiter, ':') + opts.delimiter = util.get_default(opts.delimiter, ":") sorter._delimiter = opts.delimiter sorter.tags = create_tag_set(opts.tag) sorter.filter_function = filter_function(opts) - sorter._was_discarded = function() return false end + sorter._was_discarded = function() + return false + end return sorter end diff --git a/lua/telescope/themes.lua b/lua/telescope/themes.lua index 3b2036b..1cd2efe 100644 --- a/lua/telescope/themes.lua +++ b/lua/telescope/themes.lua @@ -48,10 +48,10 @@ function themes.get_dropdown(opts) border = true, borderchars = { - { "─", "│", "─", "│", "╭", "╮", "╯", "╰"}, - prompt = {"─", "│", " ", "│", "╭", "╮", "│", "│"}, - results = {"─", "│", "─", "│", "├", "┤", "╯", "╰"}, - preview = { "─", "│", "─", "│", "╭", "╮", "╯", "╰"}, + { "─", "│", "─", "│", "╭", "╮", "╯", "╰" }, + prompt = { "─", "│", " ", "│", "╭", "╮", "│", "│" }, + results = { "─", "│", "─", "│", "├", "┤", "╯", "╰" }, + preview = { "─", "│", "─", "│", "╭", "╮", "╯", "╰" }, }, } @@ -71,11 +71,11 @@ function themes.get_cursor(opts) opts = opts or {} local theme_opts = { - theme = 'cursor', + theme = "cursor", - sorting_strategy = 'ascending', + sorting_strategy = "ascending", results_title = false, - layout_strategy = 'cursor', + layout_strategy = "cursor", layout_config = { width = function(_, _, _) return 80 @@ -86,14 +86,14 @@ function themes.get_cursor(opts) end, }, borderchars = { - { '─', '│', '─', '│', '╭', '╮', '╯', '╰'}, - prompt = {'─', '│', ' ', '│', '╭', '╮', '│', '│'}, - results = {'─', '│', '─', '│', '├', '┤', '╯', '╰'}, - preview = { '─', '│', '─', '│', '╭', '╮', '╯', '╰'}, + { "─", "│", "─", "│", "╭", "╮", "╯", "╰" }, + prompt = { "─", "│", " ", "│", "╭", "╮", "│", "│" }, + results = { "─", "│", "─", "│", "├", "┤", "╯", "╰" }, + preview = { "─", "│", "─", "│", "╭", "╮", "╯", "╰" }, }, } - return vim.tbl_deep_extend('force', theme_opts, opts) + return vim.tbl_deep_extend("force", theme_opts, opts) end --- Ivy style theme. @@ -126,7 +126,7 @@ function themes.get_ivy(opts) prompt = { "─", " ", " ", " ", "─", "─", " ", " " }, results = { " " }, -- results = { "a", "b", "c", "d", "e", "f", "g", "h" }, - preview = { "─", "│", "─", "│", "╭", "╮", "╯", "╰"}, + preview = { "─", "│", "─", "│", "╭", "╮", "╯", "╰" }, }, }, opts) end diff --git a/lua/telescope/utils.lua b/lua/telescope/utils.lua index eb59962..1735fa8 100644 --- a/lua/telescope/utils.lua +++ b/lua/telescope/utils.lua @@ -1,9 +1,9 @@ -local has_devicons, devicons = pcall(require, 'nvim-web-devicons') +local has_devicons, devicons = pcall(require, "nvim-web-devicons") -local Path = require('plenary.path') -local Job = require('plenary.job') +local Path = require "plenary.path" +local Job = require "plenary.job" -local log = require('telescope.log') +local log = require "telescope.log" local utils = {} @@ -47,7 +47,7 @@ utils.default_table_mt = { local obj = {} rawset(t, k, obj) return obj - end + end, } utils.repeated_table = function(n, val) @@ -62,13 +62,14 @@ utils.quickfix_items_to_entries = function(locations) local results = {} for _, entry in ipairs(locations) do - local vimgrep_str = entry.vimgrep_str or string.format( - "%s:%s:%s: %s", - vim.fn.fnamemodify(entry.display_filename or entry.filename, ":."), - entry.lnum, - entry.col, - entry.text - ) + local vimgrep_str = entry.vimgrep_str + or string.format( + "%s:%s:%s: %s", + vim.fn.fnamemodify(entry.display_filename or entry.filename, ":."), + entry.lnum, + entry.col, + entry.text + ) table.insert(results, { valid = true, @@ -119,7 +120,7 @@ utils.filter_symbols = function(results, opts) end end else - print("Please pass filtering symbols as either a string or a list of strings") + print "Please pass filtering symbols as either a string or a list of strings" return end @@ -131,7 +132,7 @@ utils.filter_symbols = function(results, opts) if filename_to_bufnr[symbol.filename] == nil then filename_to_bufnr[symbol.filename] = vim.uri_to_bufnr(vim.uri_from_fname(symbol.filename)) end - symbol['bufnr'] = filename_to_bufnr[symbol.filename] + symbol["bufnr"] = filename_to_bufnr[symbol.filename] end table.sort(filtered_symbols, function(a, b) if a.bufnr == b.bufnr then @@ -145,17 +146,17 @@ utils.filter_symbols = function(results, opts) end return a.bufnr < b.bufnr end) - return filtered_symbols + return filtered_symbols end -- only account for string|table as function otherwise already printed message and returned nil - local symbols = type(opts.symbols) == 'string' and opts.symbols or table.concat(opts.symbols, ', ') + local symbols = type(opts.symbols) == "string" and opts.symbols or table.concat(opts.symbols, ", ") print(string.format("%s symbol(s) were not part of the query results", symbols)) return end local convert_diagnostic_type = function(severity) -- convert from string to int - if type(severity) == 'string' then + if type(severity) == "string" then -- make sure that e.g. error is uppercased to Error return vim.lsp.protocol.DiagnosticSeverity[severity:gsub("^%l", string.upper)] end @@ -186,20 +187,20 @@ utils.diagnostics_to_tbl = function(opts) opts.severity_bound = convert_diagnostic_type(opts.severity_bound) local validate_severity = 0 - for _, v in ipairs({opts.severity, opts.severity_limit, opts.severity_bound}) do + for _, v in ipairs { opts.severity, opts.severity_limit, opts.severity_bound } do if v ~= nil then validate_severity = validate_severity + 1 end if validate_severity > 1 then - print('Please pass valid severity parameters') + print "Please pass valid severity parameters" return {} end end local preprocess_diag = function(diag, bufnr) local filename = vim.api.nvim_buf_get_name(bufnr) - local start = diag.range['start'] - local finish = diag.range['end'] + local start = diag.range["start"] + local finish = diag.range["end"] local row = start.line local col = start.character @@ -212,13 +213,13 @@ utils.diagnostics_to_tbl = function(opts) finish = finish, -- remove line break to avoid display issues text = vim.trim(diag.message:gsub("[\n]", "")), - type = lsp_type_diagnostic[diag.severity] or lsp_type_diagnostic[1] + type = lsp_type_diagnostic[diag.severity] or lsp_type_diagnostic[1], } return buffer_diag end - local buffer_diags = opts.get_all and vim.lsp.diagnostic.get_all() or - {[current_buf] = vim.lsp.diagnostic.get(current_buf, opts.client_id)} + local buffer_diags = opts.get_all and vim.lsp.diagnostic.get_all() + or { [current_buf] = vim.lsp.diagnostic.get(current_buf, opts.client_id) } for bufnr, diags in pairs(buffer_diags) do for _, diag in ipairs(diags) do -- workspace diagnostics may include empty tables for unused bufnr @@ -253,14 +254,14 @@ utils.diagnostics_to_tbl = function(opts) return items end -utils.path_shorten = function(filename,len) - log.warn("`utils.path_shorten` is deprecated. Use `require('plenary.path').shorten`.") +utils.path_shorten = function(filename, len) + log.warn "`utils.path_shorten` is deprecated. Use `require('plenary.path').shorten`." return Path:new(filename):shorten(len) end utils.path_tail = (function() local os_sep = utils.get_separator() - local match_string = '[^' .. os_sep .. ']*$' + local match_string = "[^" .. os_sep .. "]*$" return function(path) return string.match(path, match_string) @@ -268,25 +269,25 @@ utils.path_tail = (function() end)() utils.is_path_hidden = function(opts, path_display) - path_display = path_display or utils.get_default(opts.path_display, require('telescope.config').values.path_display) + path_display = path_display or utils.get_default(opts.path_display, require("telescope.config").values.path_display) - return path_display == nil or path_display == "hidden" or - type(path_display) ~= "table" or vim.tbl_contains(path_display, "hidden") or path_display.hidden + return path_display == nil + or path_display == "hidden" + or type(path_display) ~= "table" + or vim.tbl_contains(path_display, "hidden") + or path_display.hidden end utils.transform_path = function(opts, path) - local path_display = utils.get_default(opts.path_display, require('telescope.config').values.path_display) + local path_display = utils.get_default(opts.path_display, require("telescope.config").values.path_display) local transformed_path = path if type(path_display) == "function" then return path_display(opts, transformed_path) - elseif utils.is_path_hidden(nil, path_display) then - return '' - + return "" elseif type(path_display) == "table" then - if vim.tbl_contains(path_display, "tail") or path_display.tail then transformed_path = utils.path_tail(transformed_path) else @@ -298,7 +299,7 @@ utils.transform_path = function(opts, path) cwd = vim.fn.expand(opts.cwd) end else - cwd = vim.loop.cwd(); + cwd = vim.loop.cwd() end transformed_path = Path:new(transformed_path):make_relative(cwd) end @@ -310,8 +311,7 @@ utils.transform_path = function(opts, path) return transformed_path else - log.warn("`path_display` must be either a function or a table.", - "See `:help telescope.defaults.path_display.") + log.warn("`path_display` must be either a function or a table.", "See `:help telescope.defaults.path_display.") return transformed_path end end @@ -338,31 +338,39 @@ function utils.make_default_callable(f, default_opts) if not ok then error(debug.traceback(err)) end - end + end, }) end function utils.job_is_running(job_id) - if job_id == nil then return false end - return vim.fn.jobwait({job_id}, 0)[1] == -1 + if job_id == nil then + return false + end + return vim.fn.jobwait({ job_id }, 0)[1] == -1 end function utils.buf_delete(bufnr) - if bufnr == nil then return end + if bufnr == nil then + return + end -- Suppress the buffer deleted message for those with &report<2 local start_report = vim.o.report - if start_report < 2 then vim.o.report = 2 end + if start_report < 2 then + vim.o.report = 2 + end if vim.api.nvim_buf_is_valid(bufnr) and vim.api.nvim_buf_is_loaded(bufnr) then vim.api.nvim_buf_delete(bufnr, { force = true }) end - if start_report < 2 then vim.o.report = start_report end + if start_report < 2 then + vim.o.report = start_report + end end function utils.max_split(s, pattern, maxsplit) - pattern = pattern or ' ' + pattern = pattern or " " maxsplit = maxsplit or -1 local t = {} @@ -393,12 +401,11 @@ function utils.max_split(s, pattern, maxsplit) return t end - function utils.data_directory() - local sourced_file = require('plenary.debug_utils').sourced_filepath() + local sourced_file = require("plenary.debug_utils").sourced_filepath() local base_directory = vim.fn.fnamemodify(sourced_file, ":h:h:h") - return Path:new({base_directory, 'data'}):absolute() .. Path.path.sep + return Path:new({ base_directory, "data" }):absolute() .. Path.path.sep end function utils.display_termcodes(str) @@ -407,31 +414,38 @@ end function utils.get_os_command_output(cmd, cwd) if type(cmd) ~= "table" then - print('Telescope: [get_os_command_output]: cmd has to be a table') + print "Telescope: [get_os_command_output]: cmd has to be a table" return {} end local command = table.remove(cmd, 1) local stderr = {} - local stdout, ret = Job:new({ command = command, args = cmd, cwd = cwd, on_stderr = function(_, data) - table.insert(stderr, data) - end }):sync() + local stdout, ret = Job + :new({ + command = command, + args = cmd, + cwd = cwd, + on_stderr = function(_, data) + table.insert(stderr, data) + end, + }) + :sync() return stdout, ret, stderr end utils.strdisplaywidth = function() - error("strdisplaywidth deprecated. please use plenary.strings.strdisplaywidth") + error "strdisplaywidth deprecated. please use plenary.strings.strdisplaywidth" end utils.utf_ptr2len = function() - error("utf_ptr2len deprecated. please use plenary.strings.utf_ptr2len") + error "utf_ptr2len deprecated. please use plenary.strings.utf_ptr2len" end utils.strcharpart = function() - error("strcharpart deprecated. please use plenary.strings.strcharpart") + error "strcharpart deprecated. please use plenary.strings.strcharpart" end utils.align_str = function() - error("align_str deprecated. please use plenary.strings.align_str") + error "align_str deprecated. please use plenary.strings.align_str" end utils.transform_devicons = (function() @@ -441,13 +455,13 @@ utils.transform_devicons = (function() end return function(filename, display, disable_devicons) - local conf = require('telescope.config').values + local conf = require("telescope.config").values if disable_devicons or not filename then return display end - local icon, icon_highlight = devicons.get_icon(filename, string.match(filename, '%a+$'), { default = true }) - local icon_display = (icon or ' ') .. ' ' .. (display or '') + local icon, icon_highlight = devicons.get_icon(filename, string.match(filename, "%a+$"), { default = true }) + local icon_display = (icon or " ") .. " " .. (display or "") if conf.color_devicons then return icon_display, icon_highlight @@ -469,12 +483,12 @@ utils.get_devicons = (function() end return function(filename, disable_devicons) - local conf = require('telescope.config').values + local conf = require("telescope.config").values if disable_devicons or not filename then - return '' + return "" end - local icon, icon_highlight = devicons.get_icon(filename, string.match(filename, '%a+$'), { default = true }) + local icon, icon_highlight = devicons.get_icon(filename, string.match(filename, "%a+$"), { default = true }) if conf.color_devicons then return icon, icon_highlight else @@ -483,7 +497,7 @@ utils.get_devicons = (function() end else return function(_, _) - return '' + return "" end end end)() diff --git a/lua/tests/automated/action_spec.lua b/lua/tests/automated/action_spec.lua index 771ee50..752ed53 100644 --- a/lua/tests/automated/action_spec.lua +++ b/lua/tests/automated/action_spec.lua @@ -1,70 +1,92 @@ -local actions = require('telescope.actions') -local action_set = require('telescope.actions.set') +local actions = require "telescope.actions" +local action_set = require "telescope.actions.set" -local transform_mod = require('telescope.actions.mt').transform_mod +local transform_mod = require("telescope.actions.mt").transform_mod local eq = function(a, b) assert.are.same(a, b) end -describe('actions', function() - it('should allow creating custom actions', function() +describe("actions", function() + it("should allow creating custom actions", function() local a = transform_mod { - x = function() return 5 end, + x = function() + return 5 + end, } - eq(5, a.x()) end) - it('allows adding actions', function() + it("allows adding actions", function() local a = transform_mod { - x = function() return "x" end, - y = function() return "y" end, + x = function() + return "x" + end, + y = function() + return "y" + end, } local x_plus_y = a.x + a.y - eq({"x", "y"}, {x_plus_y()}) + eq({ "x", "y" }, { x_plus_y() }) end) - it('ignores nils from added actions', function() + it("ignores nils from added actions", function() local a = transform_mod { - x = function() return "x" end, - y = function() return "y" end, - nil_maker = function() return nil end, + x = function() + return "x" + end, + y = function() + return "y" + end, + nil_maker = function() + return nil + end, } local x_plus_y = a.x + a.nil_maker + a.y - eq({"x", "y"}, {x_plus_y()}) + eq({ "x", "y" }, { x_plus_y() }) end) - it('allows overriding an action', function() + it("allows overriding an action", function() local a = transform_mod { - x = function() return "x" end, - y = function() return "y" end, + x = function() + return "x" + end, + y = function() + return "y" + end, } -- actions.file_goto_selection_edit:replace(...) - a.x:replace(function() return "foo" end) + a.x:replace(function() + return "foo" + end) eq("foo", a.x()) a._clear() eq("x", a.x()) end) - it('allows overriding an action only in specific cases with if', function() + it("allows overriding an action only in specific cases with if", function() local a = transform_mod { - x = function(e) return e * 10 end, - y = function() return "y" end, + x = function(e) + return e * 10 + end, + y = function() + return "y" + end, } -- actions.file_goto_selection_edit:replace(...) - a.x:replace_if( - function(e) return e > 0 end, - function(e) return (e / 10) end - ) + a.x:replace_if(function(e) + return e > 0 + end, function(e) + return (e / 10) + end) eq(-100, a.x(-10)) eq(10, a.x(100)) eq(1, a.x(10)) @@ -73,16 +95,28 @@ describe('actions', function() eq(100, a.x(10)) end) - it('allows overriding an action only in specific cases with mod', function() + it("allows overriding an action only in specific cases with mod", function() local a = transform_mod { - x = function(e) return e * 10 end, - y = function() return "y" end, + x = function(e) + return e * 10 + end, + y = function() + return "y" + end, } -- actions.file_goto_selection_edit:replace(...) a.x:replace_map { - [function(e) return e > 0 end] = function(e) return (e / 10) end, - [function(e) return e == 0 end] = function(e) return (e + 10) end, + [function(e) + return e > 0 + end] = function(e) + return (e / 10) + end, + [function(e) + return e == 0 + end] = function(e) + return (e + 10) + end, } eq(-100, a.x(-10)) @@ -94,33 +128,51 @@ describe('actions', function() eq(100, a.x(10)) end) - it('continuous replacement', function() + it("continuous replacement", function() local a = transform_mod { - x = function() return "cleared" end, - y = function() return "y" end, + x = function() + return "cleared" + end, + y = function() + return "y" + end, } -- Replace original, which becomes new fallback - a.x:replace(function() return "negative" end) + a.x:replace(function() + return "negative" + end) -- actions.file_goto_selection_edit:replace(...) a.x:replace_map { - [function(e) return e > 0 end] = function(e) return "positive" end, - [function(e) return e == 0 end] = function(e) return "zero" end, + [function(e) + return e > 0 + end] = function(e) + return "positive" + end, + [function(e) + return e == 0 + end] = function(e) + return "zero" + end, } eq("positive", a.x(10)) - eq("zero" , a.x(0)) + eq("zero", a.x(0)) eq("negative", a.x(-10)) a._clear() eq("cleared", a.x(10)) end) - it('enhance.pre', function() + it("enhance.pre", function() local a = transform_mod { - x = function() return "x" end, - y = function() return "y" end, + x = function() + return "x" + end, + y = function() + return "y" + end, } local called_pre = false @@ -134,10 +186,14 @@ describe('actions', function() eq(true, called_pre) end) - it('enhance.post', function() + it("enhance.post", function() local a = transform_mod { - x = function() return "x" end, - y = function() return "y" end, + x = function() + return "x" + end, + y = function() + return "y" + end, } local called_post = false @@ -151,10 +207,14 @@ describe('actions', function() eq(true, called_post) end) - it('can call both', function() + it("can call both", function() local a = transform_mod { - x = function() return "x" end, - y = function() return "y" end, + x = function() + return "x" + end, + y = function() + return "y" + end, } local called_count = 0 @@ -171,10 +231,14 @@ describe('actions', function() eq(2, called_count) end) - it('can call both even when combined', function() + it("can call both even when combined", function() local a = transform_mod { - x = function() return "x" end, - y = function() return "y" end, + x = function() + return "x" + end, + y = function() + return "y" + end, } local called_count = 0 @@ -188,7 +252,7 @@ describe('actions', function() } a.x:enhance { - post = count_inc + post = count_inc, } local x_plus_y = a.x + a.y @@ -197,10 +261,14 @@ describe('actions', function() eq(3, called_count) end) - it('clears enhance', function() + it("clears enhance", function() local a = transform_mod { - x = function() return "x" end, - y = function() return "y" end, + x = function() + return "x" + end, + y = function() + return "y" + end, } local called_post = false @@ -217,31 +285,41 @@ describe('actions', function() eq(false, called_post) end) - it('handles passing arguments', function() + it("handles passing arguments", function() local a = transform_mod { - x = function(bufnr) return string.format("bufnr: %s") end, + x = function(bufnr) + return string.format "bufnr: %s" + end, } - a.x:replace(function(bufnr) return string.format("modified: %s", bufnr) end) + a.x:replace(function(bufnr) + return string.format("modified: %s", bufnr) + end) eq("modified: 5", a.x(5)) end) - describe('action_set', function() - it('can replace `action_set.edit`', function() - action_set.edit:replace(function(_, arg) return "replaced:" .. arg end) + describe("action_set", function() + it("can replace `action_set.edit`", function() + action_set.edit:replace(function(_, arg) + return "replaced:" .. arg + end) eq("replaced:edit", actions.file_edit()) eq("replaced:vnew", actions.file_vsplit()) end) - it('handles backwards compat with select and edit files', function() + it("handles backwards compat with select and edit files", function() -- Reproduce steps: -- In config, we have { [""] = actions.select, ... } -- In caller, we have actions._goto:replace(...) -- Person calls `select`, does not see update - action_set.edit:replace(function(_, arg) return "default_to_edit:" .. arg end) + action_set.edit:replace(function(_, arg) + return "default_to_edit:" .. arg + end) eq("default_to_edit:edit", actions.select_default()) - action_set.select:replace(function(_, arg) return "override_with_select:" .. arg end) + action_set.select:replace(function(_, arg) + return "override_with_select:" .. arg + end) eq("override_with_select:default", actions.select_default()) -- Sometimes you might want to change the default selection... diff --git a/lua/tests/automated/entry_display_spec.lua b/lua/tests/automated/entry_display_spec.lua index fff78cd..a09ccae 100644 --- a/lua/tests/automated/entry_display_spec.lua +++ b/lua/tests/automated/entry_display_spec.lua @@ -1,30 +1,32 @@ -local entry_display = require('telescope.pickers.entry_display') +local entry_display = require "telescope.pickers.entry_display" -describe('truncate', function() - for _, ambiwidth in ipairs{'single', 'double'} do - for _, case in ipairs{ - {args = {'abcde', 6}, expected = {single = 'abcde', double = 'abcde'}}, - {args = {'abcde', 5}, expected = {single = 'abcde', double = 'abcde'}}, - {args = {'abcde', 4}, expected = {single = 'abc…', double = 'ab…'}}, - {args = {'アイウエオ', 11}, expected = {single = 'アイウエオ', double = 'アイウエオ'}}, - {args = {'アイウエオ', 10}, expected = {single = 'アイウエオ', double = 'アイウエオ'}}, - {args = {'アイウエオ', 9}, expected = {single = 'アイウエ…', double = 'アイウ…'}}, - {args = {'アイウエオ', 8}, expected = {single = 'アイウ…', double = 'アイウ…'}}, - {args = {'├─┤', 7}, expected = {single = '├─┤', double = '├─┤'}}, - {args = {'├─┤', 6}, expected = {single = '├─┤', double = '├─┤'}}, - {args = {'├─┤', 5}, expected = {single = '├─┤', double = '├…'}}, - {args = {'├─┤', 4}, expected = {single = '├─┤', double = '├…'}}, - {args = {'├─┤', 3}, expected = {single = '├─┤', double = '…'}}, - {args = {'├─┤', 2}, expected = {single = '├…', double = '…'}}, +describe("truncate", function() + for _, ambiwidth in ipairs { "single", "double" } do + for _, case in ipairs { + { args = { "abcde", 6 }, expected = { single = "abcde", double = "abcde" } }, + { args = { "abcde", 5 }, expected = { single = "abcde", double = "abcde" } }, + { args = { "abcde", 4 }, expected = { single = "abc…", double = "ab…" } }, + { args = { "アイウエオ", 11 }, expected = { single = "アイウエオ", double = "アイウエオ" } }, + { args = { "アイウエオ", 10 }, expected = { single = "アイウエオ", double = "アイウエオ" } }, + { args = { "アイウエオ", 9 }, expected = { single = "アイウエ…", double = "アイウ…" } }, + { args = { "アイウエオ", 8 }, expected = { single = "アイウ…", double = "アイウ…" } }, + { args = { "├─┤", 7 }, expected = { single = "├─┤", double = "├─┤" } }, + { args = { "├─┤", 6 }, expected = { single = "├─┤", double = "├─┤" } }, + { args = { "├─┤", 5 }, expected = { single = "├─┤", double = "├…" } }, + { args = { "├─┤", 4 }, expected = { single = "├─┤", double = "├…" } }, + { args = { "├─┤", 3 }, expected = { single = "├─┤", double = "…" } }, + { args = { "├─┤", 2 }, expected = { single = "├…", double = "…" } }, } do - local msg = ('can truncate: ambiwidth = %s, [%s, %d] -> %s'):format(ambiwidth, case.args[1], case.args[2], case.expected[ambiwidth]) + local msg = ("can truncate: ambiwidth = %s, [%s, %d] -> %s"):format( + ambiwidth, + case.args[1], + case.args[2], + case.expected[ambiwidth] + ) it(msg, function() local original = vim.o.ambiwidth vim.o.ambiwidth = ambiwidth - assert.are.same( - case.expected[ambiwidth], - entry_display.truncate(case.args[1], case.args[2]) - ) + assert.are.same(case.expected[ambiwidth], entry_display.truncate(case.args[1], case.args[2])) vim.o.ambiwidth = original end) end diff --git a/lua/tests/automated/entry_manager_spec.lua b/lua/tests/automated/entry_manager_spec.lua index cc59ebd..bae23bc 100644 --- a/lua/tests/automated/entry_manager_spec.lua +++ b/lua/tests/automated/entry_manager_spec.lua @@ -1,9 +1,9 @@ -local EntryManager = require('telescope.entry_manager') +local EntryManager = require "telescope.entry_manager" local eq = assert.are.same -describe('process_result', function() - it('works with one entry', function() +describe("process_result", function() + it("works with one entry", function() local manager = EntryManager:new(5, nil) manager:add_entry(nil, 1, "hello") @@ -11,7 +11,7 @@ describe('process_result', function() eq(1, manager:get_score(1)) end) - it('works with two entries', function() + it("works with two entries", function() local manager = EntryManager:new(5, nil) manager:add_entry(nil, 1, "hello") @@ -23,18 +23,22 @@ describe('process_result', function() eq("later", manager:get_entry(2)) end) - it('calls functions when inserting', function() + it("calls functions when inserting", function() local called_count = 0 - local manager = EntryManager:new(5, function() called_count = called_count + 1 end) + local manager = EntryManager:new(5, function() + called_count = called_count + 1 + end) assert(called_count == 0) manager:add_entry(nil, 1, "hello") assert(called_count == 1) end) - it('calls functions when inserting twice', function() + it("calls functions when inserting twice", function() local called_count = 0 - local manager = EntryManager:new(5, function() called_count = called_count + 1 end) + local manager = EntryManager:new(5, function() + called_count = called_count + 1 + end) assert(called_count == 0) manager:add_entry(nil, 1, "hello") @@ -42,9 +46,11 @@ describe('process_result', function() assert(called_count == 2) end) - it('correctly sorts lower scores', function() + it("correctly sorts lower scores", function() local called_count = 0 - local manager = EntryManager:new(5, function() called_count = called_count + 1 end) + local manager = EntryManager:new(5, function() + called_count = called_count + 1 + end) manager:add_entry(nil, 5, "worse result") manager:add_entry(nil, 2, "better result") @@ -54,9 +60,11 @@ describe('process_result', function() eq(2, called_count) end) - it('respects max results', function() + it("respects max results", function() local called_count = 0 - local manager = EntryManager:new(1, function() called_count = called_count + 1 end) + local manager = EntryManager:new(1, function() + called_count = called_count + 1 + end) manager:add_entry(nil, 2, "better result") manager:add_entry(nil, 5, "worse result") @@ -64,24 +72,28 @@ describe('process_result', function() eq(1, called_count) end) - it('should allow simple entries', function() + it("should allow simple entries", function() local manager = EntryManager:new(5) local counts_executed = 0 - manager:add_entry(nil, 1, setmetatable({}, { - __index = function(t, k) - local val = nil - if k == "ordinal" then - counts_executed = counts_executed + 1 + manager:add_entry( + nil, + 1, + setmetatable({}, { + __index = function(t, k) + local val = nil + if k == "ordinal" then + counts_executed = counts_executed + 1 - -- This could be expensive, only call later - val = "wow" - end + -- This could be expensive, only call later + val = "wow" + end - rawset(t, k, val) - return val - end, - })) + rawset(t, k, val) + return val + end, + }) + ) eq("wow", manager:get_ordinal(1)) eq("wow", manager:get_ordinal(1)) @@ -90,7 +102,7 @@ describe('process_result', function() eq(1, counts_executed) end) - it('should not loop a bunch', function() + it("should not loop a bunch", function() local info = {} local manager = EntryManager:new(5, nil, info) manager:add_entry(nil, 4, "better result") @@ -102,7 +114,7 @@ describe('process_result', function() eq(2, info.looped) end) - it('should not loop a bunch, part 2', function() + it("should not loop a bunch, part 2", function() local info = {} local manager = EntryManager:new(5, nil, info) manager:add_entry(nil, 4, "better result") @@ -115,7 +127,7 @@ describe('process_result', function() eq(3, info.looped) end) - it('should update worst score in all append case', function() + it("should update worst score in all append case", function() local manager = EntryManager:new(2, nil) manager:add_entry(nil, 2, "result 2") manager:add_entry(nil, 3, "result 3") @@ -124,9 +136,11 @@ describe('process_result', function() eq(3, manager.worst_acceptable_score) end) - it('should update worst score in all prepend case', function() + it("should update worst score in all prepend case", function() local called_count = 0 - local manager = EntryManager:new(2, function() called_count = called_count + 1 end) + local manager = EntryManager:new(2, function() + called_count = called_count + 1 + end) manager:add_entry(nil, 5, "worse result") manager:add_entry(nil, 4, "less worse result") manager:add_entry(nil, 2, "better result") diff --git a/lua/tests/automated/layout_strategies_spec.lua b/lua/tests/automated/layout_strategies_spec.lua index f8f8b02..8b5af48 100644 --- a/lua/tests/automated/layout_strategies_spec.lua +++ b/lua/tests/automated/layout_strategies_spec.lua @@ -1,14 +1,14 @@ -- local tester = require('telescope.pickers._test') -local config = require('telescope.config') -local resolve = require('telescope.config.resolve') -local layout_strats = require('telescope.pickers.layout_strategies') +local config = require "telescope.config" +local resolve = require "telescope.config.resolve" +local layout_strats = require "telescope.pickers.layout_strategies" local validate_layout_config = layout_strats._validate_layout_config local eq = assert.are.same -describe('layout_strategies', function() - it('should have validator', function() +describe("layout_strategies", function() + it("should have validator", function() assert(validate_layout_config, "Has validator") end) @@ -23,13 +23,19 @@ describe('layout_strategies', function() end) end - test_height('should handle numbers', 10, 10) + test_height("should handle numbers", 10, 10) - test_height('should handle percentage: 100', 10, 0.1, { max_lines = 100 }) - test_height('should handle percentage: 110', 11, 0.1, { max_lines = 110 }) + test_height("should handle percentage: 100", 10, 0.1, { max_lines = 100 }) + test_height("should handle percentage: 110", 11, 0.1, { max_lines = 110 }) - test_height('should call functions: simple', 5, function() return 5 end) - test_height('should call functions: percentage', 15, function(_, _, lines) return 0.1 * lines end, { max_lines = 150 }) + test_height("should call functions: simple", 5, function() + return 5 + end) + test_height("should call functions: percentage", 15, function(_, _, lines) + return 0.1 * lines + end, { + max_lines = 150, + }) local test_defaults_key = function(should, key, strat, output, ours, theirs, override) ours = ours or {} @@ -38,65 +44,119 @@ describe('layout_strategies', function() it(should, function() config.clear_defaults() - config.set_defaults({layout_config=theirs}, {layout_config={ours,'description'}}) + config.set_defaults({ layout_config = theirs }, { layout_config = { ours, "description" } }) local layout_config = validate_layout_config(strat, layout_strats._configurations[strat], override) eq(output, layout_config[key]) end) end - test_defaults_key("should use ours if theirs and override don't give the key", - 'height','horizontal',50, - {height=50}, {width=100}, {width=120} + test_defaults_key( + "should use ours if theirs and override don't give the key", + "height", + "horizontal", + 50, + { height = 50 }, + { width = 100 }, + { width = 120 } ) - test_defaults_key("should use ours if theirs and override don't give the key for this strategy", - 'height','horizontal',50, - {height=50}, {vertical={height=100}}, {vertical={height=120}} + test_defaults_key( + "should use ours if theirs and override don't give the key for this strategy", + "height", + "horizontal", + 50, + { height = 50 }, + { vertical = { height = 100 } }, + { vertical = { height = 120 } } ) - test_defaults_key("should use theirs if override doesn't give the key", - 'height','horizontal',100, - {height=50}, {height=100}, {width=120} + test_defaults_key( + "should use theirs if override doesn't give the key", + "height", + "horizontal", + 100, + { height = 50 }, + { height = 100 }, + { width = 120 } ) - test_defaults_key("should use override if key given", - 'height','horizontal',120, - {height=50}, {height=100}, {height=120} + test_defaults_key( + "should use override if key given", + "height", + "horizontal", + 120, + { height = 50 }, + { height = 100 }, + { height = 120 } ) - test_defaults_key("should use override if key given for this strategy", - 'height','horizontal',120, - {height=50}, {height=100}, {horizontal={height=120}} + test_defaults_key( + "should use override if key given for this strategy", + "height", + "horizontal", + 120, + { height = 50 }, + { height = 100 }, + { horizontal = { height = 120 } } ) - test_defaults_key("should use theirs if override doesn't give key (even if ours has strategy specific)", - 'height','horizontal',100, - {horizontal={height=50}}, {height=100}, {width=120} + test_defaults_key( + "should use theirs if override doesn't give key (even if ours has strategy specific)", + "height", + "horizontal", + 100, + { horizontal = { height = 50 } }, + { height = 100 }, + { width = 120 } ) - test_defaults_key("should use override (even if ours has strategy specific)", - 'height','horizontal',120, - {horizontal={height=50}}, {height=100}, {height=120} + test_defaults_key( + "should use override (even if ours has strategy specific)", + "height", + "horizontal", + 120, + { horizontal = { height = 50 } }, + { height = 100 }, + { height = 120 } ) - test_defaults_key("should use override (even if theirs has strategy specific)", - 'height','horizontal',120, - {height=50}, {horizontal={height=100}}, {height=120} + test_defaults_key( + "should use override (even if theirs has strategy specific)", + "height", + "horizontal", + 120, + { height = 50 }, + { horizontal = { height = 100 } }, + { height = 120 } ) - test_defaults_key("should use override (even if ours and theirs have strategy specific)", - 'height','horizontal',120, - {horizontal={height=50}}, {horizontal={height=100}}, {height=120} + test_defaults_key( + "should use override (even if ours and theirs have strategy specific)", + "height", + "horizontal", + 120, + { horizontal = { height = 50 } }, + { horizontal = { height = 100 } }, + { height = 120 } ) - test_defaults_key("should handle user config overriding a table with a number", - 'height','horizontal',120, - {height={padding=5}},{height=120},{} + test_defaults_key( + "should handle user config overriding a table with a number", + "height", + "horizontal", + 120, + { height = { padding = 5 } }, + { height = 120 }, + {} ) - test_defaults_key("should handle user oneshot overriding a table with a number", - 'height','horizontal',120, - {},{height={padding=5}},{height=120} + test_defaults_key( + "should handle user oneshot overriding a table with a number", + "height", + "horizontal", + 120, + {}, + { height = { padding = 5 } }, + { height = 120 } ) - end) diff --git a/lua/tests/automated/linked_list_spec.lua b/lua/tests/automated/linked_list_spec.lua index 49c035a..bc17ba1 100644 --- a/lua/tests/automated/linked_list_spec.lua +++ b/lua/tests/automated/linked_list_spec.lua @@ -1,131 +1,131 @@ -local LinkedList = require('telescope.algos.linked_list') +local LinkedList = require "telescope.algos.linked_list" -describe('LinkedList', function() - it('can create a list', function() +describe("LinkedList", function() + it("can create a list", function() local l = LinkedList:new() assert.are.same(0, l.size) end) - it('can add a single entry to the list', function() + it("can add a single entry to the list", function() local l = LinkedList:new() - l:append('hello') + l:append "hello" assert.are.same(1, l.size) end) - it('can iterate over one item', function() + it("can iterate over one item", function() local l = LinkedList:new() - l:append('hello') + l:append "hello" for val in l:iter() do - assert.are.same('hello', val) + assert.are.same("hello", val) end end) - it('iterates in order', function() + it("iterates in order", function() local l = LinkedList:new() - l:append('hello') - l:append('world') + l:append "hello" + l:append "world" local x = {} for val in l:iter() do table.insert(x, val) end - assert.are.same({'hello', 'world'}, x) + assert.are.same({ "hello", "world" }, x) end) - it('iterates in order, for prepend', function() + it("iterates in order, for prepend", function() local l = LinkedList:new() - l:prepend('world') - l:prepend('hello') + l:prepend "world" + l:prepend "hello" local x = {} for val in l:iter() do table.insert(x, val) end - assert.are.same({'hello', 'world'}, x) + assert.are.same({ "hello", "world" }, x) end) - it('iterates in order, for combo', function() + it("iterates in order, for combo", function() local l = LinkedList:new() - l:prepend('world') - l:prepend('hello') - l:append('last') - l:prepend('first') + l:prepend "world" + l:prepend "hello" + l:append "last" + l:prepend "first" local x = {} for val in l:iter() do table.insert(x, val) end - assert.are.same({'first', 'hello', 'world', 'last'}, x) + assert.are.same({ "first", "hello", "world", "last" }, x) assert.are.same(#x, l.size) end) - it('has ipairs', function() + it("has ipairs", function() local l = LinkedList:new() - l:prepend('world') - l:prepend('hello') - l:append('last') - l:prepend('first') + l:prepend "world" + l:prepend "hello" + l:append "last" + l:prepend "first" local x = {} for v in l:iter() do table.insert(x, v) end - assert.are.same({'first', 'hello', 'world', 'last'}, x) + assert.are.same({ "first", "hello", "world", "last" }, x) local expected = {} for i, v in ipairs(x) do - table.insert(expected, {i, v}) + table.insert(expected, { i, v }) end local actual = {} for i, v in l:ipairs() do - table.insert(actual, {i, v}) + table.insert(actual, { i, v }) end assert.are.same(expected, actual) end) - describe('track_at', function() - it('should update tracked when only appending', function() + describe("track_at", function() + it("should update tracked when only appending", function() local l = LinkedList:new { track_at = 2 } - l:append("first") - l:append("second") - l:append("third") + l:append "first" + l:append "second" + l:append "third" assert.are.same("second", l.tracked) end) - it('should update tracked when first some prepend and then append', function() + it("should update tracked when first some prepend and then append", function() local l = LinkedList:new { track_at = 2 } - l:prepend("first") - l:append("second") - l:append("third") + l:prepend "first" + l:append "second" + l:append "third" assert.are.same("second", l.tracked) end) - it('should update when only prepending', function() + it("should update when only prepending", function() local l = LinkedList:new { track_at = 2 } - l:prepend("third") - l:prepend("second") - l:prepend("first") + l:prepend "third" + l:prepend "second" + l:prepend "first" assert.are.same("second", l.tracked) end) - it('should update when lots of prepend and append', function() + it("should update when lots of prepend and append", function() local l = LinkedList:new { track_at = 2 } - l:prepend("third") - l:prepend("second") - l:prepend("first") - l:append("fourth") - l:prepend("zeroth") + l:prepend "third" + l:prepend "second" + l:prepend "first" + l:append "fourth" + l:prepend "zeroth" assert.are.same("first", l.tracked) end) diff --git a/lua/tests/automated/pickers/find_files_spec.lua b/lua/tests/automated/pickers/find_files_spec.lua index b01dc51..ba1c21b 100644 --- a/lua/tests/automated/pickers/find_files_spec.lua +++ b/lua/tests/automated/pickers/find_files_spec.lua @@ -1,26 +1,27 @@ -require('plenary.reload').reload_module('telescope') +require("plenary.reload").reload_module "telescope" -local tester = require('telescope.pickers._test') +local tester = require "telescope.pickers._test" local disp = function(val) return vim.inspect(val, { newline = " ", indent = "" }) end -describe('builtin.find_files', function() - it('should find the readme', function() - tester.run_file('find_files__readme') +describe("builtin.find_files", function() + it("should find the readme", function() + tester.run_file "find_files__readme" end) - it('should be able to move selections', function() - tester.run_file('find_files__with_ctrl_n') + it("should be able to move selections", function() + tester.run_file "find_files__with_ctrl_n" end) for _, configuration in ipairs { - { sorting_strategy = 'descending', }, - { sorting_strategy = 'ascending', }, + { sorting_strategy = "descending" }, + { sorting_strategy = "ascending" }, } do - it('should not display devicons when disabled: ' .. disp(configuration), function() - tester.run_string(string.format([[ + it("should not display devicons when disabled: " .. disp(configuration), function() + tester.run_string(string.format( + [[ local max_results = 5 tester.builtin_picker('find_files', 'README.md', { @@ -41,18 +42,21 @@ describe('builtin.find_files', function() width = 0.9, }, }, vim.fn.json_decode([==[%s]==]))) - ]], vim.fn.json_encode(configuration))) + ]], + vim.fn.json_encode(configuration) + )) end) - it('should only save one line for ascending, but many for descending', function() + it("should only save one line for ascending, but many for descending", function() local expected - if configuration.sorting_strategy == 'descending' then + if configuration.sorting_strategy == "descending" then expected = 5 else expected = 1 end - tester.run_string(string.format([[ + tester.run_string(string.format( + [[ tester.builtin_picker('find_files', 'README.md', { post_typed = { { %s, function() return #GetResults() end }, @@ -66,15 +70,19 @@ describe('builtin.find_files', function() width = 0.9, }, }, vim.fn.json_decode([==[%s]==]))) - ]], expected, vim.fn.json_encode(configuration))) + ]], + expected, + vim.fn.json_encode(configuration) + )) end) - it('use devicons, if it has it when enabled', function() - if not pcall(require, 'nvim-web-devicons') then + it("use devicons, if it has it when enabled", function() + if not pcall(require, "nvim-web-devicons") then return end - tester.run_string(string.format([[ + tester.run_string(string.format( + [[ tester.builtin_picker('find_files', 'README.md', { post_typed = { { "> README.md", GetPrompt }, @@ -88,11 +96,13 @@ describe('builtin.find_files', function() disable_devicons = false, sorter = require('telescope.sorters').get_fzy_sorter(), }, vim.fn.json_decode([==[%s]==]))) - ]], vim.fn.json_encode(configuration))) + ]], + vim.fn.json_encode(configuration) + )) end) end - it('should find the readme, using lowercase', function() + it("should find the readme, using lowercase", function() tester.run_string [[ tester.builtin_picker('find_files', 'readme.md', { post_close = { @@ -102,7 +112,7 @@ describe('builtin.find_files', function() ]] end) - it('should find the pickers.lua, using lowercase', function() + it("should find the pickers.lua, using lowercase", function() tester.run_string [[ tester.builtin_picker('find_files', 'pickers.lua', { post_close = { @@ -112,7 +122,7 @@ describe('builtin.find_files', function() ]] end) - it('should find the pickers.lua', function() + it("should find the pickers.lua", function() tester.run_string [[ tester.builtin_picker('find_files', 'pickers.lua', { post_close = { @@ -123,7 +133,7 @@ describe('builtin.find_files', function() ]] end) - it('should be able to c-n the items', function() + it("should be able to c-n the items", function() tester.run_string [[ tester.builtin_picker('find_files', 'fixtures/file', { post_typed = { @@ -151,7 +161,7 @@ describe('builtin.find_files', function() ]] end) - it('should be able to get the current selection', function() + it("should be able to get the current selection", function() tester.run_string [[ tester.builtin_picker('find_files', 'fixtures/file_abc', { post_typed = { diff --git a/lua/tests/automated/pickers/scrolling_spec.lua b/lua/tests/automated/pickers/scrolling_spec.lua index 1a86822..760d2b9 100644 --- a/lua/tests/automated/pickers/scrolling_spec.lua +++ b/lua/tests/automated/pickers/scrolling_spec.lua @@ -1,12 +1,12 @@ -require('plenary.reload').reload_module('telescope') +require("plenary.reload").reload_module "telescope" -local tester = require('telescope.pickers._test') +local tester = require "telescope.pickers._test" -local log = require('telescope.log') +local log = require "telescope.log" log.use_console = false -describe('scrolling strategies', function() - it('should handle cycling for full list', function() +describe("scrolling strategies", function() + it("should handle cycling for full list", function() tester.run_file [[find_files__scrolling_descending_cycle]] end) end) diff --git a/lua/tests/automated/resolver_spec.lua b/lua/tests/automated/resolver_spec.lua index b26a9a1..534af7b 100644 --- a/lua/tests/automated/resolver_spec.lua +++ b/lua/tests/automated/resolver_spec.lua @@ -2,12 +2,11 @@ local eq = function(a, b) assert.are.same(a, b) end -local resolve = require('telescope.config.resolve') +local resolve = require "telescope.config.resolve" - -describe('telescope.config.resolve', function() - describe('win_option', function() - it('should resolve for percentages', function() +describe("telescope.config.resolve", function() + describe("win_option", function() + it("should resolve for percentages", function() local height_config = 0.8 local opt = resolve.win_option(height_config) @@ -16,7 +15,7 @@ describe('telescope.config.resolve', function() eq(height_config, opt.results) end) - it('should resolve for percetnages with default', function() + it("should resolve for percetnages with default", function() local height_config = 0.8 local opt = resolve.win_option(nil, height_config) @@ -25,8 +24,8 @@ describe('telescope.config.resolve', function() eq(height_config, opt.results) end) - it('should resolve table values', function() - local table_val = {'a'} + it("should resolve table values", function() + local table_val = { "a" } local opt = resolve.win_option(nil, table_val) eq(table_val, opt.preview) @@ -34,32 +33,32 @@ describe('telescope.config.resolve', function() eq(table_val, opt.results) end) - it('should allow overrides for different wins', function() - local prompt_override = {'a', prompt = 'b'} + it("should allow overrides for different wins", function() + local prompt_override = { "a", prompt = "b" } local opt = resolve.win_option(prompt_override) - eq('a', opt.preview) - eq('a', opt.results) - eq('b', opt.prompt) + eq("a", opt.preview) + eq("a", opt.results) + eq("b", opt.prompt) end) - it('should allow overrides for all wins', function() - local all_specified = {preview = 'a', prompt = 'b', results = 'c'} + it("should allow overrides for all wins", function() + local all_specified = { preview = "a", prompt = "b", results = "c" } local opt = resolve.win_option(all_specified) - eq('a', opt.preview) - eq('b', opt.prompt) - eq('c', opt.results) + eq("a", opt.preview) + eq("b", opt.prompt) + eq("c", opt.results) end) - it('should allow some specified with a simple default', function() - local some_specified = {prompt = 'b', results = 'c'} - local opt = resolve.win_option(some_specified, 'a') - eq('a', opt.preview) - eq('b', opt.prompt) - eq('c', opt.results) + it("should allow some specified with a simple default", function() + local some_specified = { prompt = "b", results = "c" } + local opt = resolve.win_option(some_specified, "a") + eq("a", opt.preview) + eq("b", opt.prompt) + eq("c", opt.results) end) end) - describe('resolve_height/width', function() + describe("resolve_height/width", function() eq(10, resolve.resolve_height(0.1)(nil, 24, 100)) eq(2, resolve.resolve_width(0.1)(nil, 24, 100)) diff --git a/lua/tests/automated/scroller_spec.lua b/lua/tests/automated/scroller_spec.lua index 7c2a557..96d64af 100644 --- a/lua/tests/automated/scroller_spec.lua +++ b/lua/tests/automated/scroller_spec.lua @@ -1,144 +1,143 @@ -local p_scroller = require('telescope.pickers.scroller') +local p_scroller = require "telescope.pickers.scroller" -local log = require('telescope.log') +local log = require "telescope.log" log.use_console = false local eq = assert.are.same -describe('scroller', function() +describe("scroller", function() local max_results = 10 - describe('ascending cycle', function() - local cycle_scroller = p_scroller.create('cycle', 'ascending') + describe("ascending cycle", function() + local cycle_scroller = p_scroller.create("cycle", "ascending") - it('should return values within the max results', function() + it("should return values within the max results", function() eq(5, cycle_scroller(max_results, max_results, 5)) end) - it('should return 0 at 0', function() + it("should return 0 at 0", function() eq(0, cycle_scroller(max_results, max_results, 0)) end) - it('should cycle you to the top when you go below 0', function() + it("should cycle you to the top when you go below 0", function() eq(max_results - 1, cycle_scroller(max_results, max_results, -1)) end) - it('should cycle you to 0 when you go past the results', function() + it("should cycle you to 0 when you go past the results", function() eq(0, cycle_scroller(max_results, max_results, max_results + 1)) end) - it('should cycle when current results is less than max_results', function() + it("should cycle when current results is less than max_results", function() eq(0, cycle_scroller(max_results, 5, 7)) end) end) - describe('ascending limit', function() - local limit_scroller = p_scroller.create('limit', 'ascending') + describe("ascending limit", function() + local limit_scroller = p_scroller.create("limit", "ascending") - it('should return values within the max results', function() + it("should return values within the max results", function() eq(5, limit_scroller(max_results, max_results, 5)) end) - it('should return 0 at 0', function() + it("should return 0 at 0", function() eq(0, limit_scroller(max_results, max_results, 0)) end) - it('should not cycle', function() + it("should not cycle", function() eq(0, limit_scroller(max_results, max_results, -1)) end) - it('should not cycle you to 0 when you go past the results', function() + it("should not cycle you to 0 when you go past the results", function() eq(max_results - 1, limit_scroller(max_results, max_results, max_results + 1)) end) - it('should stay at current results when current results is less than max_results', function() + it("should stay at current results when current results is less than max_results", function() local current = 5 eq(current - 1, limit_scroller(max_results, current, 7)) end) end) - describe('descending cycle', function() - local cycle_scroller = p_scroller.create('cycle', 'descending') + describe("descending cycle", function() + local cycle_scroller = p_scroller.create("cycle", "descending") - it('should return values within the max results', function() + it("should return values within the max results", function() eq(5, cycle_scroller(max_results, max_results, 5)) end) - it('should return max_results - 1 at 0', function() + it("should return max_results - 1 at 0", function() eq(0, cycle_scroller(max_results, max_results, 0)) end) - it('should cycle you to the bot when you go below 0', function() + it("should cycle you to the bot when you go below 0", function() eq(max_results - 1, cycle_scroller(max_results, max_results, -1)) end) - it('should cycle you to 0 when you go past the results', function() + it("should cycle you to 0 when you go past the results", function() eq(0, cycle_scroller(max_results, max_results, max_results + 1)) end) - it('should cycle when current results is less than max_results', function() + it("should cycle when current results is less than max_results", function() eq(9, cycle_scroller(max_results, 5, 4)) end) end) - describe('descending limit', function() - local limit_scroller = p_scroller.create('limit', 'descending') + describe("descending limit", function() + local limit_scroller = p_scroller.create("limit", "descending") - it('should return values within the max results', function() + it("should return values within the max results", function() eq(5, limit_scroller(max_results, max_results, 5)) end) - it('should return 0 at 0', function() + it("should return 0 at 0", function() eq(0, limit_scroller(max_results, max_results, 0)) end) - it('should not cycle', function() + it("should not cycle", function() eq(0, limit_scroller(max_results, max_results, -1)) end) - it('should not cycle you to 0 when you go past the results', function() + it("should not cycle you to 0 when you go past the results", function() eq(max_results - 1, limit_scroller(max_results, max_results, max_results + 1)) end) - it('should stay at current results when current results is less than max_results', function() + it("should stay at current results when current results is less than max_results", function() local current = 5 eq(max_results - current, limit_scroller(max_results, current, 4)) end) end) - describe('https://github.com/nvim-telescope/telescope.nvim/pull/293#issuecomment-751463224', function() - it('should handle having many more results than necessary', function() - local scroller = p_scroller.create('cycle', 'descending') + describe("https://github.com/nvim-telescope/telescope.nvim/pull/293#issuecomment-751463224", function() + it("should handle having many more results than necessary", function() + local scroller = p_scroller.create("cycle", "descending") -- 23 112 23 eq(0, scroller(23, 112, 23)) end) end) + describe("should give top, middle and bottom index", function() + it("should handle ascending", function() + eq(0, p_scroller.top("ascending", 20, 1000)) + eq(19, p_scroller.bottom("ascending", 20, 1000)) - describe('should give top, middle and bottom index', function() - it('should handle ascending', function() - eq(0, p_scroller.top('ascending', 20, 1000)) - eq(19, p_scroller.bottom('ascending', 20, 1000)) + eq(0, p_scroller.top("ascending", 20, 10)) + eq(9, p_scroller.bottom("ascending", 20, 10)) - eq(0, p_scroller.top('ascending', 20, 10)) - eq(9, p_scroller.bottom('ascending', 20, 10)) - - eq(5, p_scroller.middle('ascending', 11, 100)) - eq(10, p_scroller.middle('ascending', 20, 100)) - eq(12, p_scroller.middle('ascending', 25, 100)) + eq(5, p_scroller.middle("ascending", 11, 100)) + eq(10, p_scroller.middle("ascending", 20, 100)) + eq(12, p_scroller.middle("ascending", 25, 100)) end) - it('should handle descending', function() - eq(0, p_scroller.top('descending', 20, 1000)) - eq(19, p_scroller.bottom('descending', 20, 1000)) + it("should handle descending", function() + eq(0, p_scroller.top("descending", 20, 1000)) + eq(19, p_scroller.bottom("descending", 20, 1000)) - eq(10, p_scroller.top('descending', 20, 10)) - eq(19, p_scroller.bottom('descending', 20, 10)) + eq(10, p_scroller.top("descending", 20, 10)) + eq(19, p_scroller.bottom("descending", 20, 10)) - eq(25, p_scroller.middle('descending', 30, 10)) - eq(50, p_scroller.middle('descending', 60, 20)) - eq(105, p_scroller.middle('descending', 120, 30)) + eq(25, p_scroller.middle("descending", 30, 10)) + eq(50, p_scroller.middle("descending", 60, 20)) + eq(105, p_scroller.middle("descending", 120, 30)) end) end) end) diff --git a/lua/tests/automated/telescope_spec.lua b/lua/tests/automated/telescope_spec.lua index 6ad09d7..9b4cd5e 100644 --- a/lua/tests/automated/telescope_spec.lua +++ b/lua/tests/automated/telescope_spec.lua @@ -1,111 +1,108 @@ -local picker = require('telescope.pickers') +local picker = require "telescope.pickers" local eq = assert.are.same -describe('telescope', function() - describe('Picker', function() - describe('window_dimensions', function() - it('', function() +describe("telescope", function() + describe("Picker", function() + describe("window_dimensions", function() + it("", function() assert(true) end) end) - describe('attach_mappings', function() - it('should allow for passing in a function', function() - local p = picker.new({}, { attach_mappings = function() return 1 end }) + describe("attach_mappings", function() + it("should allow for passing in a function", function() + local p = picker.new({}, { + attach_mappings = function() + return 1 + end, + }) eq(1, p.attach_mappings()) end) - it('should override an attach mappings passed in by opts', function() + it("should override an attach mappings passed in by opts", function() local called_order = {} local p = picker.new({ attach_mappings = function() - table.insert(called_order, 'opts') + table.insert(called_order, "opts") end, }, { attach_mappings = function() - table.insert(called_order, 'default') - end + table.insert(called_order, "default") + end, }) p.attach_mappings() - eq({'default', 'opts'}, called_order) + eq({ "default", "opts" }, called_order) end) end) end) - describe('Sorters', function() - describe('generic_fuzzy_sorter', function() - it('sort matches well', function() - local sorter = require('telescope.sorters').get_generic_fuzzy_sorter() + describe("Sorters", function() + describe("generic_fuzzy_sorter", function() + it("sort matches well", function() + local sorter = require("telescope.sorters").get_generic_fuzzy_sorter() - local exact_match = sorter:score('hello', {ordinal = 'hello'}) - local no_match = sorter:score('abcdef', {ordinal = 'ghijkl'}) - local ok_match = sorter:score('abcdef', {ordinal = 'ab'}) + local exact_match = sorter:score("hello", { ordinal = "hello" }) + local no_match = sorter:score("abcdef", { ordinal = "ghijkl" }) + local ok_match = sorter:score("abcdef", { ordinal = "ab" }) assert(exact_match < no_match, "exact match better than no match") assert(exact_match < ok_match, "exact match better than ok match") assert(ok_match < no_match, "ok match better than no match") end) - it('sorts multiple finds better', function() - local sorter = require('telescope.sorters').get_generic_fuzzy_sorter() + it("sorts multiple finds better", function() + local sorter = require("telescope.sorters").get_generic_fuzzy_sorter() - local multi_match = sorter:score('generics', 'exercises/generics/generics2.rs') - local one_match = sorter:score('abcdef', 'exercises/generics/README.md') + local multi_match = sorter:score("generics", "exercises/generics/generics2.rs") + local one_match = sorter:score("abcdef", "exercises/generics/README.md") -- assert(multi_match < one_match) end) end) - describe('fuzzy_file', function() - it('sort matches well', function() - local sorter = require('telescope.sorters').get_fuzzy_file() + describe("fuzzy_file", function() + it("sort matches well", function() + local sorter = require("telescope.sorters").get_fuzzy_file() - local exact_match = sorter:score('abcdef', {ordinal = 'abcdef'}) - local no_match = sorter:score('abcdef', {ordinal = 'ghijkl'}) - local ok_match = sorter:score('abcdef', {ordinal = 'ab'}) + local exact_match = sorter:score("abcdef", { ordinal = "abcdef" }) + local no_match = sorter:score("abcdef", { ordinal = "ghijkl" }) + local ok_match = sorter:score("abcdef", { ordinal = "ab" }) - assert( - exact_match < no_match, - string.format("Exact match better than no match: %s %s", exact_match, no_match) - ) - assert( - exact_match < ok_match, - string.format("Exact match better than OK match: %s %s", exact_match, ok_match) - ) + assert(exact_match < no_match, string.format("Exact match better than no match: %s %s", exact_match, no_match)) + assert(exact_match < ok_match, string.format("Exact match better than OK match: %s %s", exact_match, ok_match)) assert(ok_match < no_match, "OK match better than no match") end) - it('sorts matches after last os sep better', function() - local sorter = require('telescope.sorters').get_fuzzy_file() + it("sorts matches after last os sep better", function() + local sorter = require("telescope.sorters").get_fuzzy_file() - local better_match = sorter:score('aaa', {ordinal = 'bbb/aaa'}) - local worse_match = sorter:score('aaa', {ordinal = 'aaa/bbb'}) + local better_match = sorter:score("aaa", { ordinal = "bbb/aaa" }) + local worse_match = sorter:score("aaa", { ordinal = "aaa/bbb" }) assert(better_match < worse_match, "Final match should be stronger") end) - pending('sorts multiple finds better', function() - local sorter = require('telescope.sorters').get_fuzzy_file() + pending("sorts multiple finds better", function() + local sorter = require("telescope.sorters").get_fuzzy_file() - local multi_match = sorter:score('generics', {ordinal = 'exercises/generics/generics2.rs'}) - local one_match = sorter:score('abcdef', {ordinal = 'exercises/generics/README.md'}) + local multi_match = sorter:score("generics", { ordinal = "exercises/generics/generics2.rs" }) + local one_match = sorter:score("abcdef", { ordinal = "exercises/generics/README.md" }) assert(multi_match < one_match) end) end) - describe('fzy', function() - local sorter = require'telescope.sorters'.get_fzy_sorter() + describe("fzy", function() + local sorter = require("telescope.sorters").get_fzy_sorter() local function score(prompt, line) - return sorter:score( - prompt, - {ordinal = line}, - function(val) return val end, - function() return -1 end - ) + return sorter:score(prompt, { ordinal = line }, function(val) + return val + end, function() + return -1 + end) end describe("matches", function() @@ -150,9 +147,9 @@ describe('telescope', function() assert.True(score("gemfil", "Gemfile") < score("gemfil", "Gemfile.lock")) end) it("prefers shorter matches", function() - assert.True(score("abce", "abcdef") < score("abce", "abc de")); - assert.True(score("abc", " a b c ") < score("abc", " a b c ")); - assert.True(score("abc", " a b c ") < score("abc", " a b c ")); + assert.True(score("abce", "abcdef") < score("abce", "abc de")) + assert.True(score("abc", " a b c ") < score("abc", " a b c ")) + assert.True(score("abc", " a b c ") < score("abc", " a b c ")) end) it("prefers shorter candidates", function() assert.True(score("test", "tests") < score("test", "testing")) @@ -174,21 +171,21 @@ describe('telescope', function() describe("positioning", function() it("favors consecutive positions", function() - assert.same({1, 5, 6}, positions("amo", "app/models/foo")) + assert.same({ 1, 5, 6 }, positions("amo", "app/models/foo")) end) it("favors word beginnings", function() - assert.same({1, 5, 12, 13}, positions("amor", "app/models/order")) + assert.same({ 1, 5, 12, 13 }, positions("amor", "app/models/order")) end) it("works when there are no bonuses", function() - assert.same({2, 4}, positions("as", "tags")) - assert.same({3, 8}, positions("as", "examples.txt")) + assert.same({ 2, 4 }, positions("as", "tags")) + assert.same({ 3, 8 }, positions("as", "examples.txt")) end) it("favors smaller groupings of positions", function() - assert.same({3, 5, 7}, positions("abc", "a/a/b/c/c")) - assert.same({3, 5}, positions("ab", "caacbbc")) + assert.same({ 3, 5, 7 }, positions("abc", "a/a/b/c/c")) + assert.same({ 3, 5 }, positions("ab", "caacbbc")) end) it("handles exact matches", function() - assert.same({1, 2, 3}, positions("foo", "foo")) + assert.same({ 1, 2, 3 }, positions("foo", "foo")) end) it("ignores empty requests", function() assert.same({}, positions("", "")) @@ -198,9 +195,9 @@ describe('telescope', function() end) end) - describe('layout_strategies', function() - describe('center', function() - it('should handle large terminals', function() + describe("layout_strategies", function() + describe("center", function() + it("should handle large terminals", function() -- TODO: This could call layout_strategies.center w/ some weird edge case. -- and then assert stuff about the dimensions. end) diff --git a/lua/tests/helpers.lua b/lua/tests/helpers.lua index 728aefb..bdb5f17 100644 --- a/lua/tests/helpers.lua +++ b/lua/tests/helpers.lua @@ -1,25 +1,25 @@ -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local previewers = require('telescope.previewers') -local pickers = require('telescope.pickers') -local sorters = require('telescope.sorters') +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local previewers = require "telescope.previewers" +local pickers = require "telescope.pickers" +local sorters = require "telescope.sorters" local helpers = {} -- TODO: We should do something with builtins to get those easily. helpers.auto_find_files = function(opts) opts = opts or {} - opts.prompt_prefix = '' + opts.prompt_prefix = "" local find_command = opts.find_command if not find_command then - if 1 == vim.fn.executable("fd") then - find_command = { 'fd', '--type', 'f' } - elseif 1 == vim.fn.executable("fdfind") then - find_command = { 'fdfind', '--type', 'f' } - elseif 1 == vim.fn.executable("rg") then - find_command = { 'rg', '--files' } + if 1 == vim.fn.executable "fd" then + find_command = { "fd", "--type", "f" } + elseif 1 == vim.fn.executable "fdfind" then + find_command = { "fdfind", "--type", "f" } + elseif 1 == vim.fn.executable "rg" then + find_command = { "rg", "--files" } end end @@ -30,11 +30,8 @@ helpers.auto_find_files = function(opts) opts.entry_maker = opts.entry_maker or make_entry.gen_from_file(opts) local p = pickers.new(opts, { - prompt = 'Find Files', - finder = finders.new_oneshot_job( - find_command, - opts - ), + prompt = "Find Files", + finder = finders.new_oneshot_job(find_command, opts), previewer = previewers.cat.new(opts), sorter = sorters.get_fuzzy_file(), @@ -43,21 +40,24 @@ helpers.auto_find_files = function(opts) local count = 0 p:register_completion_callback(function(s) - print(count, vim.inspect(s.stats, { - process = function(item) - if type(item) == 'string' and item:sub(1, 1) == '_' then - return nil - end + print( + count, + vim.inspect(s.stats, { + process = function(item) + if type(item) == "string" and item:sub(1, 1) == "_" then + return nil + end - return item - end, - })) + return item + end, + }) + ) count = count + 1 end) local feed = function(text, feed_opts) - feed_opts = feed_opts or 'n' + feed_opts = feed_opts or "n" vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(text, true, false, true), feed_opts, true) end @@ -70,7 +70,7 @@ helpers.auto_find_files = function(opts) end vim.wait(300, function() end) - feed("", '') + feed("", "") vim.defer_fn(function() PASSED = opts.condition() diff --git a/lua/tests/manual/all_defaults.lua b/lua/tests/manual/all_defaults.lua index 6aea199..4d39a05 100644 --- a/lua/tests/manual/all_defaults.lua +++ b/lua/tests/manual/all_defaults.lua @@ -2,19 +2,21 @@ vim.api.nvim_buf_set_lines(0, 4, -1, false, vim.tbl_keys(require('telescope.builtin'))) --]] -require('telescope.builtin').git_files() -RELOAD('telescope'); require('telescope.builtin').oldfiles() -require('telescope.builtin').grep_string() -require('telescope.builtin').lsp_document_symbols() -RELOAD('telescope'); require('telescope.builtin').lsp_workspace_symbols() -require('telescope.builtin').lsp_references() -require('telescope.builtin').builtin() -require('telescope.builtin').fd() -require('telescope.builtin').command_history() -require('telescope.builtin').search_history() -require('telescope.builtin').live_grep() -require('telescope.builtin').loclist() +require("telescope.builtin").git_files() +RELOAD "telescope" +require("telescope.builtin").oldfiles() +require("telescope.builtin").grep_string() +require("telescope.builtin").lsp_document_symbols() +RELOAD "telescope" +require("telescope.builtin").lsp_workspace_symbols() +require("telescope.builtin").lsp_references() +require("telescope.builtin").builtin() +require("telescope.builtin").fd() +require("telescope.builtin").command_history() +require("telescope.builtin").search_history() +require("telescope.builtin").live_grep() +require("telescope.builtin").loclist() -- TODO: make a function that puts stuff into quickfix. -- that way we can test this better. -require('telescope.builtin').quickfix() +require("telescope.builtin").quickfix() diff --git a/lua/tests/manual/auto_picker.lua b/lua/tests/manual/auto_picker.lua index e33edee..5189ba7 100644 --- a/lua/tests/manual/auto_picker.lua +++ b/lua/tests/manual/auto_picker.lua @@ -1,24 +1,24 @@ -RELOAD('telescope') +RELOAD "telescope" -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local previewers = require('telescope.previewers') -local pickers = require('telescope.pickers') -local sorters = require('telescope.sorters') +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local previewers = require "telescope.previewers" +local pickers = require "telescope.pickers" +local sorters = require "telescope.sorters" local find_files = function(opts) opts = opts or {} - opts.prompt_prefix = '' + opts.prompt_prefix = "" local find_command = opts.find_command if not find_command then - if 1 == vim.fn.executable("fd") then - find_command = { 'fd', '--type', 'f' } - elseif 1 == vim.fn.executable("fdfind") then - find_command = { 'fdfind', '--type', 'f' } - elseif 1 == vim.fn.executable("rg") then - find_command = { 'rg', '--files' } + if 1 == vim.fn.executable "fd" then + find_command = { "fd", "--type", "f" } + elseif 1 == vim.fn.executable "fdfind" then + find_command = { "fdfind", "--type", "f" } + elseif 1 == vim.fn.executable "rg" then + find_command = { "rg", "--files" } end end @@ -29,11 +29,8 @@ local find_files = function(opts) opts.entry_maker = opts.entry_maker or make_entry.gen_from_file(opts) local p = pickers.new(opts, { - prompt = 'Find Files', - finder = finders.new_oneshot_job( - find_command, - opts - ), + prompt = "Find Files", + finder = finders.new_oneshot_job(find_command, opts), previewer = previewers.cat.new(opts), sorter = sorters.get_fuzzy_file(), @@ -42,21 +39,24 @@ local find_files = function(opts) local count = 0 p:register_completion_callback(function(s) - print(count, vim.inspect(s.stats, { - process = function(item) - if type(item) == 'string' and item:sub(1, 1) == '_' then - return nil - end + print( + count, + vim.inspect(s.stats, { + process = function(item) + if type(item) == "string" and item:sub(1, 1) == "_" then + return nil + end - return item - end, - })) + return item + end, + }) + ) count = count + 1 end) local feed = function(text, feed_opts) - feed_opts = feed_opts or 'n' + feed_opts = feed_opts or "n" vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(text, true, false, true), feed_opts, true) end @@ -68,10 +68,10 @@ local find_files = function(opts) end vim.wait(300, function() end) - feed("", '') + feed("", "") coroutine.yield() - print("STILL CALLED?") + print "STILL CALLED?" end)) p:find() diff --git a/lua/tests/manual/find_and_sort_spec.lua b/lua/tests/manual/find_and_sort_spec.lua index 841399f..eec44b6 100644 --- a/lua/tests/manual/find_and_sort_spec.lua +++ b/lua/tests/manual/find_and_sort_spec.lua @@ -1,5 +1,5 @@ -require('plenary.reload').reload_module('plenary') -require('plenary.reload').reload_module('telescope') +require("plenary.reload").reload_module "plenary" +require("plenary.reload").reload_module "telescope" --[[ @@ -8,11 +8,11 @@ Goals: --]] -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local pickers = require('telescope.pickers') -local sorters = require('telescope.sorters') -local EntryManager = require('telescope.entry_manager') +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local pickers = require "telescope.pickers" +local sorters = require "telescope.sorters" +local EntryManager = require "telescope.entry_manager" local find_and_sort_test = function(prompt, f, s) local info = {} @@ -42,10 +42,7 @@ local find_and_sort_test = function(prompt, f, s) end info.added = info.added + 1 - entry_manager:add_entry( - s:score(prompt, entry), - entry - ) + entry_manager:add_entry(s:score(prompt, entry), entry) end local process_complete = function() @@ -58,7 +55,9 @@ local find_and_sort_test = function(prompt, f, s) f(prompt, process_result, process_complete) -- Wait until we're done to return - vim.wait(5000, function() return completed end, 10) + vim.wait(5000, function() + return completed + end, 10) return entry_manager, info end @@ -74,42 +73,33 @@ local info_to_csv = function(info, filename) writer:write(info.inserted .. "\t") writer:write(info.total .. "\t") writer:write(info.set_entry .. "\t") - writer:write(string.format("%.0f", collectgarbage("count")) .. "\t") - writer:write("\n") + writer:write(string.format("%.0f", collectgarbage "count") .. "\t") + writer:write "\n" writer:close() end +local cwd = vim.fn.expand "~/build/neovim" -local cwd = vim.fn.expand("~/build/neovim") - -collectgarbage("collect") +collectgarbage "collect" for _ = 1, 1 do - -- local s = sorters.get_fuzzy_file() local s = sorters.get_generic_fuzzy_sorter() - local finder = finders.new_oneshot_job( - {"fdfind"}, - { - cwd = cwd, - entry_maker = make_entry.gen_from_file {cwd = cwd}, - -- disable_devicons = true, - -- maximum_results = 1000, - } - ) + local finder = finders.new_oneshot_job({ "fdfind" }, { + cwd = cwd, + entry_maker = make_entry.gen_from_file { cwd = cwd }, + -- disable_devicons = true, + -- maximum_results = 1000, + }) - local res, info = find_and_sort_test( - "pickers.lua", - finder, - s - ) + local res, info = find_and_sort_test("pickers.lua", finder, s) -- print(vim.inspect(res:get_entry(1))) -- print(vim.inspect(info)) info_to_csv(info, "/home/tj/tmp/profile.csv") - collectgarbage("collect") + collectgarbage "collect" end -- No skip: 2,206,186 -- Ya skip: 2,133 diff --git a/lua/tests/manual/large_search.lua b/lua/tests/manual/large_search.lua index eda5f16..2685214 100644 --- a/lua/tests/manual/large_search.lua +++ b/lua/tests/manual/large_search.lua @@ -1,29 +1,25 @@ -RELOAD('plenary') -RELOAD('telescope') +RELOAD "plenary" +RELOAD "telescope" -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local previewers = require('telescope.previewers') -local pickers = require('telescope.pickers') -local sorters = require('telescope.sorters') +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local previewers = require "telescope.previewers" +local pickers = require "telescope.pickers" +local sorters = require "telescope.sorters" -local cwd = vim.fn.expand("~/build/neovim") +local cwd = vim.fn.expand "~/build/neovim" -pickers.new { - prompt = 'Large search', - finder = finders.new_oneshot_job( - {"fdfind"}, - { - cwd = cwd, - entry_maker = make_entry.gen_from_file {cwd = cwd}, - -- disable_devicons = true, - -- maximum_results = 1000, - } - ), +pickers.new({ + prompt = "Large search", + finder = finders.new_oneshot_job({ "fdfind" }, { + cwd = cwd, + entry_maker = make_entry.gen_from_file { cwd = cwd }, + -- disable_devicons = true, + -- maximum_results = 1000, + }), sorter = sorters.get_fuzzy_file(), - previewer = previewers.cat.new{cwd = cwd}, -}:find() - + previewer = previewers.cat.new { cwd = cwd }, +}):find() -- vim.wait(3000, function() -- vim.cmd [[redraw!]] diff --git a/lua/tests/manual/newline_tables.lua b/lua/tests/manual/newline_tables.lua index ec4988e..3be57a9 100644 --- a/lua/tests/manual/newline_tables.lua +++ b/lua/tests/manual/newline_tables.lua @@ -1,24 +1,24 @@ -require('plenary.reload').reload_module('telescope') +require("plenary.reload").reload_module "telescope" -local finders = require('telescope.finders') -local pickers = require('telescope.pickers') -local sorters = require('telescope.sorters') -local previewers = require('telescope.previewers') -local make_entry = require('telescope.make_entry') +local finders = require "telescope.finders" +local pickers = require "telescope.pickers" +local sorters = require "telescope.sorters" +local previewers = require "telescope.previewers" +local make_entry = require "telescope.make_entry" local my_list = { - 'lua/telescope/WIP.lua', - 'lua/telescope/actions.lua', - 'lua/telescope/builtin.lua', + "lua/telescope/WIP.lua", + "lua/telescope/actions.lua", + "lua/telescope/builtin.lua", } local opts = {} pickers.new(opts, { - prompt = 'Telescope Builtin', - finder = finders.new_table { + prompt = "Telescope Builtin", + finder = finders.new_table { results = my_list, }, - sorter = sorters.get_generic_fuzzy_sorter(), + sorter = sorters.get_generic_fuzzy_sorter(), previewer = previewers.cat.new(opts), }):find() diff --git a/lua/tests/manual/profile_for_sorters.lua b/lua/tests/manual/profile_for_sorters.lua index b5c7cd4..05a657a 100644 --- a/lua/tests/manual/profile_for_sorters.lua +++ b/lua/tests/manual/profile_for_sorters.lua @@ -1,18 +1,18 @@ -- TODO: Add a ladder test. -- 1, 2, 4, 8, 16, 32 attempts -RELOAD('plenary') +RELOAD "plenary" -- RELOAD('telescope') -local profiler = require('plenary.profile.lua_profiler') -local Job = require('plenary.job') +local profiler = require "plenary.profile.lua_profiler" +local Job = require "plenary.job" BIG_LIST = nil -BIG_LIST = BIG_LIST or Job:new { command = 'fdfind', cwd = '~/build/' }:sync() +BIG_LIST = BIG_LIST or Job:new({ command = "fdfind", cwd = "~/build/" }):sync() print(#BIG_LIST) local do_profile = true -local sorter_to_test = require('telescope.sorters').get_fuzzy_file() +local sorter_to_test = require("telescope.sorters").get_fuzzy_file() local strings_to_test = { "", "ev", "eval.c", "neovim/eval.c" } @@ -25,7 +25,7 @@ local first_results = setmetatable({}, { local obj = {} rawset(t, k, obj) return obj - end + end, }) local second_results = {} @@ -66,6 +66,5 @@ print(vim.inspect(first_results)) if do_profile then profiler.stop() - profiler.report('/home/tj/tmp/profiler_score.txt') + profiler.report "/home/tj/tmp/profiler_score.txt" end - diff --git a/lua/tests/manual/reference_tracker.lua b/lua/tests/manual/reference_tracker.lua index dc90671..f9e04c9 100644 --- a/lua/tests/manual/reference_tracker.lua +++ b/lua/tests/manual/reference_tracker.lua @@ -1,19 +1,24 @@ - -- local actions = require('telescope.actions') -- local utils = require('telescope.utils') -require('telescope') -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local previewers = require('telescope.previewers') -local pickers = require('telescope.pickers') -local sorters = require('telescope.sorters') +require "telescope" +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local previewers = require "telescope.previewers" +local pickers = require "telescope.pickers" +local sorters = require "telescope.sorters" -local log = require('telescope.log') +local log = require "telescope.log" -local real_opts = setmetatable({}, { __mode = 'v' }) -local opts = setmetatable({}, { - __index = function(t, k) log.debug("accessing:", k); return real_opts[k] end, - __newindex = function(t, k, v) log.debug("setting:", k, v); real_opts[k] = v end +local real_opts = setmetatable({}, { __mode = "v" }) +local opts = setmetatable({}, { + __index = function(t, k) + log.debug("accessing:", k) + return real_opts[k] + end, + __newindex = function(t, k, v) + log.debug("setting:", k, v) + real_opts[k] = v + end, }) opts.entry_maker = opts.entry_maker or make_entry.gen_from_file() @@ -31,17 +36,14 @@ end -- assert(not opts.entry_maker) local picker_config = { - prompt = 'Git File', - finder = finders.new_oneshot_job( - { "git", "ls-files", "-o", "--exclude-standard", "-c" } - , opts - ), + prompt = "Git File", + finder = finders.new_oneshot_job({ "git", "ls-files", "-o", "--exclude-standard", "-c" }, opts), -- previewer = previewers.cat.new(opts), -- sorter = sorters.get_fuzzy_file(opts), -- sorter = sorters.get_fuzzy_file(), } -log.debug("Done with config") +log.debug "Done with config" local x = pickers.new(picker_config) x:find() diff --git a/lua/tests/manual/resolver_spec.lua b/lua/tests/manual/resolver_spec.lua index 24f62cf..a03bfea 100644 --- a/lua/tests/manual/resolver_spec.lua +++ b/lua/tests/manual/resolver_spec.lua @@ -1,12 +1,10 @@ -RELOAD('telescope') +RELOAD "telescope" -local resolve = require('telescope.config.resolve') +local resolve = require "telescope.config.resolve" local eq = function(a, b) if a ~= b then - error(string.format( - "Expected a == b, got: %s and %s", vim.inspect(a), vim.inspect(b) - )) + error(string.format("Expected a == b, got: %s and %s", vim.inspect(a), vim.inspect(b))) end end @@ -25,30 +23,29 @@ eq(height_config, opt.preview) eq(height_config, opt.prompt) eq(height_config, opt.results) -local table_val = {'a'} +local table_val = { "a" } opt = resolve.win_option(nil, table_val) eq(table_val, opt.preview) eq(table_val, opt.prompt) eq(table_val, opt.results) -local prompt_override = {'a', prompt = 'b'} +local prompt_override = { "a", prompt = "b" } opt = resolve.win_option(prompt_override) -eq('a', opt.preview) -eq('a', opt.results) -eq('b', opt.prompt) +eq("a", opt.preview) +eq("a", opt.results) +eq("b", opt.prompt) -local all_specified = {preview = 'a', prompt = 'b', results = 'c'} +local all_specified = { preview = "a", prompt = "b", results = "c" } opt = resolve.win_option(all_specified) -eq('a', opt.preview) -eq('b', opt.prompt) -eq('c', opt.results) - -local some_specified = {prompt = 'b', results = 'c'} -opt = resolve.win_option(some_specified, 'a') -eq('a', opt.preview) -eq('b', opt.prompt) -eq('c', opt.results) +eq("a", opt.preview) +eq("b", opt.prompt) +eq("c", opt.results) +local some_specified = { prompt = "b", results = "c" } +opt = resolve.win_option(some_specified, "a") +eq("a", opt.preview) +eq("b", opt.prompt) +eq("c", opt.results) eq(10, resolve.resolve_height(0.1)(nil, 24, 100)) eq(2, resolve.resolve_width(0.1)(nil, 24, 100)) @@ -62,4 +59,4 @@ eq(24, resolve.resolve_width(50)(nil, 24, 100)) -- eq('b', opt.prompt) -- eq('c', opt.results) -print("DONE!") +print "DONE!" diff --git a/lua/tests/manual/slow_oneshot.lua b/lua/tests/manual/slow_oneshot.lua index f97c098..e16b3e1 100644 --- a/lua/tests/manual/slow_oneshot.lua +++ b/lua/tests/manual/slow_oneshot.lua @@ -1,12 +1,12 @@ -RELOAD('telescope') +RELOAD "telescope" -local actions = require('telescope.actions') -local finders = require('telescope.finders') -local make_entry = require('telescope.make_entry') -local previewers = require('telescope.previewers') -local pickers = require('telescope.pickers') -local sorters = require('telescope.sorters') -local utils = require('telescope.utils') +local actions = require "telescope.actions" +local finders = require "telescope.finders" +local make_entry = require "telescope.make_entry" +local previewers = require "telescope.previewers" +local pickers = require "telescope.pickers" +local sorters = require "telescope.sorters" +local utils = require "telescope.utils" local slow_proc = function(opts) opts = opts or {} @@ -18,11 +18,8 @@ local slow_proc = function(opts) opts.entry_maker = opts.entry_maker or make_entry.gen_from_file(opts) local p = pickers.new(opts, { - prompt = 'Slow Proc', - finder = finders.new_oneshot_job( - {"./scratch/slow_proc.sh"}, - opts - ), + prompt = "Slow Proc", + finder = finders.new_oneshot_job({ "./scratch/slow_proc.sh" }, opts), previewer = previewers.cat.new(opts), sorter = sorters.get_fuzzy_file(), @@ -31,21 +28,24 @@ local slow_proc = function(opts) local count = 0 p:register_completion_callback(function(s) - print(count, vim.inspect(s.stats, { - process = function(item) - if type(item) == 'string' and item:sub(1, 1) == '_' then - return nil - end + print( + count, + vim.inspect(s.stats, { + process = function(item) + if type(item) == "string" and item:sub(1, 1) == "_" then + return nil + end - return item - end, - })) + return item + end, + }) + ) count = count + 1 end) local feed = function(text) - vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(text, true, false, true), 'n', true) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(text, true, false, true), "n", true) end if false then @@ -64,7 +64,6 @@ local slow_proc = function(opts) end)) end - p:find() end diff --git a/lua/tests/pickers/find_files__readme.lua b/lua/tests/pickers/find_files__readme.lua index 534ee3e..7ec8bcc 100644 --- a/lua/tests/pickers/find_files__readme.lua +++ b/lua/tests/pickers/find_files__readme.lua @@ -1,8 +1,8 @@ -local tester = require('telescope.pickers._test') -local helper = require('telescope.pickers._test_helpers') +local tester = require "telescope.pickers._test" +local helper = require "telescope.pickers._test_helpers" -tester.builtin_picker('find_files', 'README.md', { +tester.builtin_picker("find_files", "README.md", { post_close = { - {'README.md', helper.get_file }, - } + { "README.md", helper.get_file }, + }, }) diff --git a/lua/tests/pickers/find_files__scrolling_descending_cycle.lua b/lua/tests/pickers/find_files__scrolling_descending_cycle.lua index 7740003..4f8a3f2 100644 --- a/lua/tests/pickers/find_files__scrolling_descending_cycle.lua +++ b/lua/tests/pickers/find_files__scrolling_descending_cycle.lua @@ -1,12 +1,12 @@ -require('plenary.reload').reload_module('plenary') -require('plenary.reload').reload_module('telescope') +require("plenary.reload").reload_module "plenary" +require("plenary.reload").reload_module "telescope" -local tester = require('telescope.pickers._test') -local helper = require('telescope.pickers._test_helpers') +local tester = require "telescope.pickers._test" +local helper = require "telescope.pickers._test_helpers" -tester.builtin_picker('find_files', 'telescope', { +tester.builtin_picker("find_files", "telescope", { post_close = { - tester.not_ { 'plugin/telescope.vim', helper.get_file }, + tester.not_ { "plugin/telescope.vim", helper.get_file }, }, }, { sorting_strategy = "descending", diff --git a/lua/tests/pickers/find_files__with_ctrl_n.lua b/lua/tests/pickers/find_files__with_ctrl_n.lua index 5d93f60..4820f34 100644 --- a/lua/tests/pickers/find_files__with_ctrl_n.lua +++ b/lua/tests/pickers/find_files__with_ctrl_n.lua @@ -1,9 +1,8 @@ -local tester = require('telescope.pickers._test') -local helper = require('telescope.pickers._test_helpers') +local tester = require "telescope.pickers._test" +local helper = require "telescope.pickers._test_helpers" -tester.builtin_picker('find_files', 'fixtures/file', { +tester.builtin_picker("find_files", "fixtures/file", { post_close = { - { 'lua/tests/fixtures/file_abc.txt', helper.get_selection_value }, + { "lua/tests/fixtures/file_abc.txt", helper.get_selection_value }, }, }) -