Close netrw explorer after opening a new file - vim

I'd like the netrw explorer to automatically close after opening a file.
For example:
:Lex to open file explorer
Open file
Upon open, the file explorer automatically closes.
I've tried setting:
autocmd FileType netrw setl bufhidden=wipe
But it doesn't work.
Rest of relevant .vimrc settings:
let g:netrw_banner = 0
let g:netrw_liststyle = 3
let g:netrw_altv = 1
let g:netrw_winsize = 25
noremap <C-x> :Lex<CR>
autocmd FileType netrw setl bufhidden=wipe

I took this snippet from another Stack Overflow answer (linked below) and added it to the BufWinEnter event to solve this problem.
" Close after opening a file (which gets opened in another window):
let g:netrw_fastbrowse = 0
autocmd FileType netrw setl bufhidden=wipe
function! CloseNetrw() abort
for bufn in range(1, bufnr('$'))
if bufexists(bufn) && getbufvar(bufn, '&filetype') ==# 'netrw'
silent! execute 'bwipeout ' . bufn
if getline(2) =~# '^" Netrw '
silent! bwipeout
endif
return
endif
endfor
endfunction
augroup closeOnOpen
autocmd!
autocmd BufWinEnter * if getbufvar(winbufnr(winnr()), "&filetype") != "netrw"|call CloseNetrw()|endif
aug END
Original answer here:
https://vi.stackexchange.com/questions/14622/how-can-i-close-the-netrw-buffer
This one in particular https://vi.stackexchange.com/a/29004

Try using :Explore, :Sexplore, :Hexplore, or :Vexplore instead of :Lexplore. The primary reason for :Lexplore is to have a persistent explorer on one side or the other; the others already go away when you select a file with <cr>.

Related

Using template files in Vim

I am trying to use a template for Ruby files, by adding this to my .vimrc:
function! RubyTemplate()
" Add pragma comment
call setline(1, '# frozen_string_literal: true')
" Add two empty lines
call append(1, repeat([''], 2))
" Place cursor on line number 3
call cursor(3, 0)
endfunction
autocmd BufNewFile *.rb :call RubyTemplate()
However, this doesn't work and when I open a new Ruby file, it's empty.
Everything works as expected if I issue an :e! afterwards. However, this doesn't work if I add e! to the function, so I have to manually fire it every time.
What am I doing wrong?
You can use a static template file instead of invoking a function.
For instance, you can create a template file for your ruby scripts in your vim directory as ~/.vim/skeletons/ruby.skel, with the desired contents.
1 # frozen_string_literal: true
2
3
Then in your vimrc you should add the following code:
" Skeleton for .rb files
augroup ruby
" Remove all existing autocommands in the group
au!
au BufNewFile *.rb 0r ~/.vim/skeletons/ruby.skel
augroup end
Noah Frederick has an elegant solution that allows us to insert snippets manually or automatically.
It uses ultisnips plugin and two files
" after/plugin/ultisnips_custom.vim
if !exists('g:did_UltiSnips_plugin')
finish
endif
augroup ultisnips_custom
autocmd!
autocmd BufNewFile * silent! call snippet#InsertSkeleton()
augroup END
and
" autoload/snippet.vim
function! s:try_insert(skel)
execute "normal! i_" . a:skel . "\<C-r>=UltiSnips#ExpandSnippet()\<CR>"
if g:ulti_expand_res == 0
silent! undo
endif
return g:ulti_expand_res
endfunction
function! snippet#InsertSkeleton() abort
let filename = expand('%')
" Abort on non-empty buffer or extant file
if !(line('$') == 1 && getline('$') == '') || filereadable(filename)
return
endif
call s:try_insert('skel')
endfunction
In my case, I have done some changes but now if I create an empty python file, for example, I end up with:
An important note: In my case, if vim or neovim is not detecting the filetype correctly, and it can be done with auto commands, your automatic snippet insertion will not work.

Can an autocmd be turned on/off?

I have follwing in my .vimrc to hightlight all words that matches the one on current cursor
autocmd CursorMoved * silent! exe printf('match Search /\<%s\>/', expand('<cword>'))
But sometimes it is a little annoying, so I'd like to map a key to turn on or off it, e.g. <F10>
How can I do this?
Clear the autocommand and remove highlight:
nmap <f8> :autocmd! CursorMoved<cr> :call clearmatches()<cr>
and to turn it back on using a different key:
nmap <f9> :autocmd CursorMoved * silent! exe printf('match Search /\<%s\>/', expand('<cword>'))<cr>
Put the following in your .vimrc:
let g:toggleHighlight = 0
function! ToggleHighlight(...)
if a:0 == 1 "toggle behaviour
let g:toggleHighlight = 1 - g:toggleHighlight
endif
if g:toggleHighlight == 0 "normal action, do the hi
silent! exe printf('match Search /\<%s\>/', expand('<cword>'))
else
"do whatever you need to clear the matches
"or nothing at all, since you are not printing the matches
endif
endfunction
autocmd CursorMoved * call ToggleHighlight()
map <F8> :call ToggleHighlight(1)<CR>
The idea is, if you call the function with an argument it changes the behavior to print/no print.
The autocommand just uses the last setting because the function there is called without an argument.

NerdTree - Reveal file in tree

Is there a shortcut which reveal the current file in the NerdTree directory panel.
Like TextMate 'Reveal file in Drawer' - Ctrl+Command+R
in :h NERDTree:
:NERDTreeFind :NERDTreeFind
Find the current file in the tree. If no tree exists for the current tab,
or the file is not under the current root, then initialize a new tree where
the root is the directory of the current file.
I don't think it's bound to anything by default, so you have to do a keybind yourself.
nmap ,n :NERDTreeFind<CR>
is what appears in my .vimrc, along with
nmap ,m :NERDTreeToggle<CR>
Check this out, it automates the sync operation, whenever you change buffer, the nerdtree will automatically refreshed itself (I copied from here with tiny modifications)
" Check if NERDTree is open or active
function! IsNERDTreeOpen()
return exists("t:NERDTreeBufName") && (bufwinnr(t:NERDTreeBufName) != -1)
endfunction
" Call NERDTreeFind iff NERDTree is active, current window contains a modifiable
" file, and we're not in vimdiff
function! SyncTree()
if &modifiable && IsNERDTreeOpen() && strlen(expand('%')) > 0 && !&diff
NERDTreeFind
wincmd p
endif
endfunction
" Highlight currently open buffer in NERDTree
autocmd BufEnter * call SyncTree()
This should also probably be just a comment. With the current version toggling NerdTree and using SyncTree causes NERDTree to be invoked twice. This modification seems to fix that problem:
" Check if NERDTree is open or active
function! IsNERDTreeOpen()
return exists("t:NERDTreeBufName") && (bufwinnr(t:NERDTreeBufName) != -1)
endfunction
" Call NERDTreeFind iff NERDTree is active, current window contains a modifiable
" file, and we're not in vimdiff
function! SyncTree()
if &modifiable && IsNERDTreeOpen() && strlen(expand('%')) > 0 && !&diff
NERDTreeFind
wincmd p
endif
endfunction
" Highlight currently open buffer in NERDTree
autocmd BufEnter * call SyncTree()
function! ToggleNerdTree()
set eventignore=BufEnter
NERDTreeToggle
set eventignore=
endfunction
nmap <C-n> :call ToggleNerdTree()<CR>
Chen Rushan's answer + the comment worked perfectly well for me, except when the tree is open. With this setting, the current file in the tree will be revealed when the tree is opened.
" Check if NERDTree is open or active
function! IsNERDTreeOpen()
return exists("t:NERDTreeBufName") && (bufwinnr(t:NERDTreeBufName) != -1)
endfunction
function! CheckIfCurrentBufferIsFile()
return strlen(expand('%')) > 0
endfunction
" Call NERDTreeFind iff NERDTree is active, current window contains a modifiable
" file, and we're not in vimdiff
function! SyncTree()
if &modifiable && IsNERDTreeOpen() && CheckIfCurrentBufferIsFile() && !&diff
NERDTreeFind
wincmd p
endif
endfunction
" Highlight currently open buffer in NERDTree
autocmd BufRead * call SyncTree()
function! ToggleTree()
if CheckIfCurrentBufferIsFile()
if IsNERDTreeOpen()
NERDTreeClose
else
NERDTreeFind
endif
else
NERDTree
endif
endfunction
" open NERDTree with ctrl + n
nmap <C-n> :call ToggleTree()<CR>
To go along with Chen Rushan's post, the
autocmd BufEnter * call SyncTree()
won't let NERDTree close. I couldn't find a solution (other than below) that would highlight the current open buffer in NERDTree while allowing NERDTree to Toggle.
Below is what I scraped together to be able to toggle NERDTree and have files highlighted while using Ctrl + ] for my next buffer mapping.
Hopefully others can improve this.
"Buffers
set hidden
function! IsNERDTreeOpen()
return exists("t:NERDTreeBufName") && (bufwinnr(t:NERDTreeBufName) != -1)
endfunction
function! NextBuffer()
bnext
if IsNERDTreeOpen()
NERDTreeFind
wincmd p
endif
endfunction
nnoremap <c-]> <Esc>:call NextBuffer()<CR>
function! PrevBuffer()
bprev
if IsNERDTreeOpen()
NERDTreeFind
wincmd p
endif
endfunction
nnoremap <c-[> <Esc>:call PrevBuffer()<CR>
function! ToggleNT()
NERDTreeToggle
endfunction
map <c-u> <Esc>:call ToggleNT()<cr>
function! NerdTreeToggleFind()
if exists("g:NERDTree") && g:NERDTree.IsOpen()
NERDTreeClose
elseif filereadable(expand('%'))
NERDTreeFind
else
NERDTree
endif
endfunction
nnoremap <C-n> :call NerdTreeToggleFind()<CR>

How to open or close NERDTree and Tagbar with <leader>\?

I want <leader>\ to open or close NERDTree and Tagbar, under the following conditions:
Only close both if NERDTree and Tagbar are both opened
Open both if NERDTree and Tagbar are closed OR if one is already opened
So far, in VIMRC, I have:
nmap <leader>\ :NERDTreeToggle<CR> :TagbarToggle<CR>
Which doesn't exactly work, since if one is opened, and the other closed. It would open the one that was closed and close the one that was opened.
How can this be achieved?
You need to use a function that checks whether the plugin windows are open or not and then acts accordingly. This should work and will also jump back to the window that you started in:
function! ToggleNERDTreeAndTagbar()
let w:jumpbacktohere = 1
" Detect which plugins are open
if exists('t:NERDTreeBufName')
let nerdtree_open = bufwinnr(t:NERDTreeBufName) != -1
else
let nerdtree_open = 0
endif
let tagbar_open = bufwinnr('__Tagbar__') != -1
" Perform the appropriate action
if nerdtree_open && tagbar_open
NERDTreeClose
TagbarClose
elseif nerdtree_open
TagbarOpen
elseif tagbar_open
NERDTree
else
NERDTree
TagbarOpen
endif
" Jump back to the original window
for window in range(1, winnr('$'))
execute window . 'wincmd w'
if exists('w:jumpbacktohere')
unlet w:jumpbacktohere
break
endif
endfor
endfunction
nnoremap <leader>\ :call ToggleNERDTreeAndTagbar()<CR>
hmm... this works for me in vimrc
The toggle option checks if the window already exists, so no custom function needed (#JanLarres or one of the contributors) must have added it to TagBar :D
" NERDTree
map <leader>n :NERDTreeToggle<CR>
" TagBar
map <leader>t :TagbarToggle<CR>

Setting netrw like NERDTree

I used nmap <silent> <f2> :NERDTreeToggle<cr> to toggle nerdtree window. How can I do the same with netrw?
nerdtree window is not shown in the buffer list(:ls). netrw is listed in the buffer list. How can I make it not listed?
:bn command works but :bp command does not work in the netrw window. Is this a bug?
The 'Vexplore' command opens a vertical directory browser. You can build on this by adding the following code to your .vimrc file to toggle the vertical browser with Ctrl-E (for example):
" Toggle Vexplore with Ctrl-E
function! ToggleVExplorer()
if exists("t:expl_buf_num")
let expl_win_num = bufwinnr(t:expl_buf_num)
if expl_win_num != -1
let cur_win_nr = winnr()
exec expl_win_num . 'wincmd w'
close
exec cur_win_nr . 'wincmd w'
unlet t:expl_buf_num
else
unlet t:expl_buf_num
endif
else
exec '1wincmd w'
Vexplore
let t:expl_buf_num = bufnr("%")
endif
endfunction
map <silent> <C-E> :call ToggleVExplorer()<CR>
The code above tries to open the Explorer window on the left hand side of the screen at all times; I use it with multiple split vertical windows open.
[OPTIONAL] You might like to add the following lines to your .vimrc to improve the browsing experience:
" Hit enter in the file browser to open the selected
" file with :vsplit to the right of the browser.
let g:netrw_browse_split = 4
let g:netrw_altv = 1
" Change directory to the current buffer when opening files.
set autochdir
Starting with netrw v150, there's :Lexplore, which will toggle a netrw window on the left-hand side.
I just did some improvements on Nick's solution which fixes:
opens 100% high window (independent from window splits)
:Lexplore opens it on left side, :Lexplore! on the right
listing the directory of the current file (even on remote directories)
Put these lines to the end of your .vimrc:
com! -nargs=* -bar -bang -complete=dir Lexplore call netrw#Lexplore(<q-args>, <bang>0)
fun! Lexplore(dir, right)
if exists("t:netrw_lexbufnr")
" close down netrw explorer window
let lexwinnr = bufwinnr(t:netrw_lexbufnr)
if lexwinnr != -1
let curwin = winnr()
exe lexwinnr."wincmd w"
close
exe curwin."wincmd w"
endif
unlet t:netrw_lexbufnr
else
" open netrw explorer window in the dir of current file
" (even on remote files)
let path = substitute(exists("b:netrw_curdir")? b:netrw_curdir : expand("%:p"), '^\(.*[/\\]\)[^/\\]*$','\1','e')
exe (a:right? "botright" : "topleft")." vertical ".((g:netrw_winsize > 0)? (g:netrw_winsize*winwidth(0))/100 : -g:netrw_winsize) . " new"
if a:dir != ""
exe "Explore ".a:dir
else
exe "Explore ".path
endif
setlocal winfixwidth
let t:netrw_lexbufnr = bufnr("%")
endif
endfun
Suggested options to behave like NERDTree:
" absolute width of netrw window
let g:netrw_winsize = -28
" do not display info on the top of window
let g:netrw_banner = 0
" tree-view
let g:netrw_liststyle = 3
" sort is affecting only: directories on the top, files below
let g:netrw_sort_sequence = '[\/]$,*'
" use the previous window to open file
let g:netrw_browse_split = 4
Toggle function
Here is my version of toggle function, based on Nick's answer. Now you can use hotkey from any pane, not only from netrw's pane. In Nick's version it causes an error, also I did some code cleanup and remap it to Ctrl-O, because Ctrl-E is used by default to scroll down by one line.
" Toggle Vexplore with Ctrl-O
function! ToggleVExplorer()
if exists("t:expl_buf_num")
let expl_win_num = bufwinnr(t:expl_buf_num)
let cur_win_num = winnr()
if expl_win_num != -1
while expl_win_num != cur_win_num
exec "wincmd w"
let cur_win_num = winnr()
endwhile
close
endif
unlet t:expl_buf_num
else
Vexplore
let t:expl_buf_num = bufnr("%")
endif
endfunction
map <silent> <C-O> :call ToggleVExplorer()<CR>
Variable "t:expl_buf_num" is global for current tab, so you can have one Explorer per tab. You can change it to "w:expl_buf_num" if you want to be able to open Explorer in every window.
Keep focus in Explorer
Also I like to have this at my .vimrc:
" Open file, but keep focus in Explorer
autocmd filetype netrw nmap <c-a> <cr>:wincmd W<cr>
Actually,
let g:netrw_browse_split = 4
let g:netrw_altv = 1
works best for me.
*g:netrw_browse_split* when browsing, <cr> will open the file by:
=0: re-using the same window
=1: horizontally splitting the window first
=2: vertically splitting the window first
=3: open file in new tab
=4: act like "P" (ie. open previous window)
Note that |g:netrw_preview| may be used
to get vertical splitting instead of
horizontal splitting.
I think the best behavior is described by option 4. By pressing enter, file is opened on the other split, avoiding an overpopulation of splits.
" Toggle Vexplore with Ctrl-E
function! ToggleVExplorer()
Lexplore
vertical resize 30
endfunction
map <silent> <C-E> :call ToggleVExplorer()<CR>
Simplify
As a similar and simpler aprroach to Nick's, you could make it toggleable (and very NERDTree-like) with F9 with this in your .vimrc:
" ---------------------------------------------------------------
" File Explorer start
let g:netrw_banner = 0
let g:netrw_liststyle = 3
let g:netrw_browse_split = 4
let g:netrw_altv = 1
let g:netrw_winsize = 15
" Toggle Vexplore with F9
map <silent> <F9> :Lexplore<CR>
" File Explorer end
" ---------------------------------------------------------------

Resources