oil.nvim

repository·master·Indexed 27 days ago

https://github.com/stevearc/oil.nvim

A file explorer for Neovim (0.10+) that allows users to manipulate the filesystem by editing a buffer like a normal text file. It supports standard buffer edits for renaming, deleting, and creating files, and includes adapters for browsing remote files via SSH and AWS S3. The plugin provides a comprehensive API for buffer management, entry manipulation, and view configuration.

Tokens
7.9K
Snippets
10
Records
23
Agent score
91%

What's inside oil.nvim

  1. Quick start with oil.nvim

    master

    To get started, initialize the plugin in your init.lua:

    require("oil").setup()

    Usage

    • Open a directory: Run nvim . in your terminal, or use :edit <path> or :Oil <path> within Neovim.
    • Open in floating window: Use :Oil --float <path>.
    • Navigate: Use <CR> to open a file or directory, and - to go up a directory.
    • Edit filesystem: Treat the oil buffer like a normal text buffer. Make your changes (rename, delete, add files) and save the buffer with :w to apply the changes to the actual filesystem.

    To mimic vim-vinegar behavior for navigating to the parent directory of a file, add this to your configuration:

    vim.keymap.set("n", "-", "<CMD>Oil<CR>", { desc = "Open parent directory" })
  2. Install oil.nvim

    master

    oil.nvim requires Neovim 0.10+. You can install it using any major Neovim plugin manager. It is recommended to disable lazy loading to ensure it works correctly in all situations. Optional icon providers like mini.icons or nvim-web-devicons can be used for file and folder icons.

    -- lazy.nvim
    {
      'stevearc/oil.nvim',
      ---@module 'oil'
      ---@type oil.SetupOpts
      opts = {},
      -- Optional dependencies
      dependencies = { { "nvim-mini/mini.icons", opts = {} } },
      -- dependencies = { "nvim-tree/nvim-web-devicons" }, -- use if you prefer nvim-web-devicons
      lazy = false,
    }
  3. Use the SSH adapter to browse remote files

    master

    You can browse files over SSH using the same URL format as netrw. This allows you to perform file operations (like copying) between local and remote filesystems.

    Requirements:

    • The remote server must have /bin/sh and standard Unix commands installed (ls, rm, mv, mkdir, chmod, cp, touch, ln, echo).
    • This adapter does not currently support Windows machines.
    nvim oil-ssh://[username@]hostname[:port]/[path]
  4. Use the S3 adapter to browse AWS S3 buckets

    master

    You can browse files stored in AWS S3 by using the oil-s3:// URL scheme.

    Requirements:

    • The aws CLI must be correctly configured on your system.

    Note on Neovim Versions:

    • For Neovim 0.11 and older, use the prefix oil-sss:// because older versions of Neovim do not support numbers in the URL.
    • For newer versions, use oil-s3://.
  5. Configure oil.nvim options

    master

    The require("oil").setup() function accepts a configuration object to customize behavior. Key configuration groups include:

    • default_file_explorer: Set to true to let Oil take over directory buffers (e.g., vim .).
    • columns: Define columns to display (e.g., "icon", "permissions", "size", "mtime").
    • view_options: Control visibility and sorting. Includes show_hidden (boolean), natural_order ("fast", true, or false), and sort (array of { "type", "asc" | "desc" }).
    • keymaps: Define custom keybindings for oil buffers. You can use strings matching "actions.<name>" to map to built-in actions.
    • float: Configure the floating window used by oil.open_float, including padding, max_width, max_height, and border.
    • preview_win: Configure the file preview window, including update_on_cursor_moved and preview_method ("load" | "scratch" | "fast_scratch").
    • delete_to_trash: If true, deleted files are sent to the trash instead of being permanently deleted.
    require("oil").setup({
      -- Example configuration
      default_file_explorer = true,
      columns = {
        "icon",
      },
      view_options = {
        show_hidden = false,
        natural_order = "fast",
      },
      keymaps = {
        ["<CR>"] = "actions.select",
        ["-"] = { "actions.parent", mode = "n" },
      },
    })
  6. Show CWD in the oil.nvim winbar

    master

    To display the current working directory (CWD) in the Neovim winbar while using oil.nvim, define a global function that uses require("oil").get_current_dir(bufnr) and then configure win_options.winbar in your oil setup.

    -- Declare a global function to retrieve the current directory
    function _G.get_oil_winbar()
      local bufnr = vim.api.nvim_win_get_buf(vim.g.statusline_winid)
      local dir = require("oil").get_current_dir(bufnr)
      if dir then
        return vim.fn.fnamemodify(dir, ":~")
      else
        -- If there is no current directory (e.g. over ssh), just show the buffer name
        return vim.api.nvim_buf_get_name(0)
      end
    end
    
    require("oil").setup({
      win_options = {
        winbar = "%!v:lua.get_oil_winbar()",
      },
    })
  7. Hide gitignored files and show git tracked hidden files

    master

    You can customize file visibility by using the is_hidden_file function within view_options. This recipe allows you to hide files that are ignored by git while ensuring that hidden files (dotfiles) that are actually tracked by git remain visible.

    -- helper function to parse output
    local function parse_output(proc)
      local result = proc:wait()
      local ret = {}
      if result.code == 0 then
        for line in vim.gsplit(result.stdout, "\n", { plain = true, trimempty = true }) do
          -- Remove trailing slash
          line = line:gsub("/$", "")
          ret[line] = true
        end
      end
      return ret
    end
    
    -- build git status cache
    local function new_git_status()
      return setmetatable({}, {
        __index = function(self, key)
          local ignore_proc = vim.system(
            { "git", "ls-files", "--ignored", "--exclude-standard", "--others", "--directory" },
            {
              cwd = key,
              text = true,
            }
          )
          local tracked_proc = vim.system({ "git", "ls-tree", "HEAD", "--name-only" }, { 
            cwd = key,
            text = true,
          })
          local ret = {
            ignored = parse_output(ignore_proc),
            tracked = parse_output(tracked_proc),
          }
    
          rawset(self, key, ret)
          return ret
        end,
      })
    end
    local git_status = new_git_status()
    
    -- Clear git status cache on refresh
    local refresh = require("oil.actions").refresh
    local orig_refresh = refresh.callback
    refresh.callback = function(...) 
      git_status = new_git_status()
      orig_refresh(...)
    end
    
    require("oil").setup({
      view_options = {
        is_hidden_file = function(name, bufnr)
          local dir = require("oil").get_current_dir(bufnr)
          local is_dotfile = vim.startswith(name, ".") and name ~= ".."
          -- if no local directory (e.g. for ssh connections), just hide dotfiles
          if not dir then
            return is_dotfile
          end
          -- dotfiles are considered hidden unless tracked
          if is_dotfile then
            return not git_status[dir].tracked[name]
          else
            -- Check if file is gitignored
            return git_status[dir].ignored[name]
          end
        end,
      },
    })
  8. Toggle file detail view in oil.nvim

    master

    You can create a custom keymap to toggle between a minimal view (showing only icons) and a detailed view (showing icons, permissions, size, and modification time) using require("oil").set_columns().

    local detail = false
    require("oil").setup({
      keymaps = {
        ["gd"] = {
          desc = "Toggle file detail view",
          callback = function()
            detail = not detail
            if detail then
              require("oil").set_columns({ "icon", "permissions", "size", "mtime" })
            else
              require("oil").set_columns({ "icon" })
            end
          end,
        },
      },
    })
  9. Use FreeDesktop trash on MacOS

    master

    To use the FreeDesktop trash implementation on MacOS (which allows oil.nvim's trash features to work but prevents files from appearing in the standard system trash), override the oil.adapters.trash.mac module.

    package.loaded["oil.adapters.trash.mac"] = require("oil.adapters.trash.freedesktop")
  10. Explore oil.nvim API functions

    master

    The oil.nvim API provides methods for controlling directory buffers and filesystem interactions. Key functional groups include:

    • Buffer/Directory Management: open(dir, opts, cb), open_float(dir, opts, cb), toggle_float(dir, opts, cb), close(opts), get_current_dir(bufnr).
    • Entry Manipulation: get_cursor_entry(), get_entry_on_line(bufnr, lnum).
    • View Configuration: set_columns(cols), set_sort(sort), set_is_hidden_file(is_hidden_file), toggle_hidden().
    • Changes: save(opts, cb), discard_all_changes().
    • Selection/Preview: select(opts, callback), open_preview(opts, callback).
    • Setup: setup(opts).
  11. Close oil with close(opts)

    master

    Use close(opts) to close the oil buffer and restore the buffer that was active before oil was opened.

    opts properties:

    • exit_if_last_buf: boolean (if true, exits Vim if this oil buffer is the last open buffer).