Telescope.nvim: Find files in specific directory

· wordCount · 2 minute read

I like being able to browse files in certain directories from anywhere. Telescope.nvim already has a feature that allows you to browse files in the cwd; with this guide, we’ll extend that feature to only display files in a specific directory.

A quick start guide for neovim lua can be found here: nvim-lua-guide.

Preview
Preview
  1. File structure

    ├── init.lua
    ├── lua
    │   └── plugins
    │       ├── telescope.lua
    │       └── config
    │           ├── telescope.lua
    
  2. Configuring the ‘find files’ builtin

    File: plugins/config/telescope.lua

    local M = {}
    
    -- Configure find files builtin with custom opts
    -- For neovim's config directory
    function M.dir_nvim()
        local opts = {
            prompt_title = "Neovim", -- Title for the picker
            shorten_path = false, -- Display full paths, short paths are ugly
            cwd = "~/Appdata/Local/nvim", -- Set path to directory whose files should be shown
            file_ignore_patterns = { ".git", ".png", "tags" }, -- Folder/files to be ignored
            initial_mode = "insert", -- Start in insert mode
            selection_strategy = "reset", -- Start selection from top when list changes
            theme = require("telescope.themes").get_dropdown({}), -- Theme to be used, can be omitted to use defaults
            previewer = false, -- Disable previewer
        }
    
        -- Pass opts to find_files
        require("telescope.builtin").find_files(opts)
    end
    
    return M
    

    When called, this will open a picker that will list all files in ~/Appdata/Local/nvim, excluding the ones listed in file_ignore_patterns.

  3. Configure mappings

    File: plugins/telescope.lua

    local opts = { noremap = true, silent = true }
    vim.api.nvim_set_keymap("n", "<Leader>tn", "<cmd>lua require('plugins.config.telescope').dir_nvim()<CR>", opts)
    

    Now, after restarting or reloading neovim, we can use <Leader>tn to browse files in neovim’s config directory. Find more examples at config/telescope.lua.