Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NERDTree live-preview (like sublime sidebar)

Sublime's sidebar has a cool feature, where I can just press the arrow keys and get a quick glance of what each file looks like in the editor pane. It doesn't actually open the file -- just shows it in the editor pane.

I want to do the same thing with NERDTree in Vim (or Vinegar/netrw, doesn't really matter). I know NERDTree lets me use go to open the file under the cursor while keeping the tree in focus, but (a) that requires two keystrokes, and (b) it creates a new buffer for every file I "preview" like this, so... not much of a preview really.

Is there a way to make NERDTree or Vim emulate this Sublime feature?

like image 944
ezuk Avatar asked Feb 08 '15 16:02

ezuk


1 Answers

Yes, there is. Vim has a feature called "preview window". You can open a file in the preview window with :pedit <filename>. If you want to plug this into NERDTree, you could create a file in the ~/.vim/nerdtree_plugin/ directory, for example "live_preview_mapping.vim", with the following contents:

if exists("g:loaded_nerdree_live_preview_mapping")
  finish
endif
let g:loaded_nerdree_live_preview_mapping = 1

call NERDTreeAddKeyMap({
      \ 'key':           '<up>',
      \ 'callback':      'NERDTreeLivePreview',
      \ 'quickhelpText': 'preview',
      \ })

function! NERDTreeLivePreview()
  " Get the path of the item under the cursor if possible:
  let current_file = g:NERDTreeFileNode.GetSelected()

  if current_file == {}
    return
  else
    exe 'pedit '.current_file.path.str()
  endif
endfunction

The first part is simply a load guard, so the file is sourced only once, just boilerplate. The second part adds a keymap using the NERDTree API for the <up> key that calls the given callback function.

The callback function is the meat of the code, but it should be fairly easy to understand -- it takes the node under the cursor, if there is one, and executes a :pedit with the filename.

You can even do this more easily with a simple filetype-specific mapping, something like this:

autocmd FileType nerdtree nnoremap <buffer> <up> :call NERDTreeLivePreview()<cr>

But the former is the approach recommended by the plugin (see :help NERDTreeAPI). If nothing else, this adds a help entry to the ? key for it, and it keeps nerdtree extensions in one place.

For more info on what you can do with the preview window, try :help preview-window. For instance, you can close it with <c-w>z, but you can map that to whatever you'd like, that's not really related to the NERDTree anymore. If you're unhappy with where the window shows up, consider changing the "pedit" to "botright pedit" or "leftabove pedit" or whatever you want. Check the help for :leftabove and take a look at the related commands below.

like image 154
Andrew Radev Avatar answered Nov 09 '22 06:11

Andrew Radev