2023-03-30

Netrw Vim's Builtin File Explorer Filetype Plugin

Netrw is Vim's file explorer, a built-in plugin for reading/writing files, and browsing local and over-network directories.

The video below shows how to change the listing format, some useful keyboard shortcuts, and how to save bookmarks and use the directory history list.

The command :Lexplore opens the file explorer in a sidebar, this netrw window has its own filetype and therefore it's possible to have a dedicated filetype plugin.

The filetype plugin should be located in a directory called ftplugin (~/.vim/ftplugin) included in the runtime path and named netrw.vim.

If you have a recent Vim version (8.2 or above), vim9script can also be used as shown below.


    vim9script
    # filename: ~/.vim/ftplugin/netrw.vim

    if v:version < 900
        finish
    endif

    command -nargs=0 W3mMarkFiles W3mMarkFiles()
    nnoremap <buffer> ~ :edit ~/<CR>
    nnoremap <buffer> @ :echo expand("<cfile>")<CR>
    nnoremap <buffer> <silent><space> :W3mMarkFiles<CR>

    def W3mMarkFiles(): void
        var mfl = netrw#Expose("netrwmarkfilelist")
        var markedfilelist = ''
        if type(mfl) != 1
           markedfilelist = "'" .. join(mfl, "' '") .. "'"
        endif
        exec ":FloatermNew --disposable --name=preview C:\\path\\to\\w3m.exe -o confirm_qq=false -M -B " .. markedfilelist 
    enddef

This plugin allows displaying marked files with W3M text browser in a terminal window, and moving to the user's home directory with the keyboard shortcut %, as shown in the video below.