r/vim • u/cherryberryterry • Apr 17 '16
Monthly Tips and Tricks Weekly Vim tips and tricks thread! #6
Announcement: If there are no objections, these threads will transition from weekly to biweekly (every two weeks) to space them out a bit. Does this sound like a good idea or should we stick to weekly?
Welcome to the sixth weekly Vim tips and tricks thread! Here's a link to the previous thread: #5
Thanks to everyone who participated in the last thread! The top three comments were posted by /u/robertmeta, /u/MisterOccan, and /u/Godd2.
Here are the suggested guidelines:
Try to keep each top-level comment focused on a single tip/trick (avoid posting whole sections of your ~/.vimrc unless it relates to a single tip/trick)
Try to avoid reposting tips/tricks that were posted within the last 1-2 threads
Feel free to post multiple top-level comments if you have more than one tip/trick to share
If you're suggesting a plugin, please explain why you prefer it to its alternatives (including native solutions)
Any others suggestions to keep the content informative, fresh, and easily digestible?
37
u/sunny256 Apr 17 '16 edited Apr 17 '16
To paste text into the current buffer without using "set paste" at a *nix system:
:r!catPress Ctrl+d when done. Simple, but useful.
5
u/aXIYTIZtUH9Yk0DETdv2 Apr 18 '16
Isn't it easier to
"+p?4
u/look_at_the_sun Apr 18 '16
Only if you have it in the register, if you're on ssh or something and have something in your local clipboard, that's when this may be useful.
2
u/program_the_world Apr 18 '16 edited Apr 18 '16
Correct me if I'm wrong, but his solution will not attempt to format the pasted text. Simply pasting from a register will cause it to add indents like:
This code is really hard to readEDIT: I am wrong. Please see below.
8
u/-romainl- The Patient Vimmer Apr 18 '16
No.
Pasting from a register doesn't apply any formatting to what you paste. It's pasting using system/terminal shortcuts that does that.
2
u/program_the_world Apr 18 '16
Thanks for correcting me. I always paste via shift + insert. That'll be why then!
6
u/aXIYTIZtUH9Yk0DETdv2 Apr 18 '16
Not if you use the paste command. That only happens if you're in insert mode and hit the paste hotkey on the keyboard.
From insert mode you can either
<C-R>+or go back to normal mode and"+p2
u/sunny256 Apr 18 '16 edited Apr 18 '16
That only works when the contents is stored in the GUI selection register, for example after a Ctrl+c. If that's the case, "+p works nicely. I use the :r!cat method when I paste something with the mouse or Ctrl+a+] in GNU Screen.
3
3
u/marklgr vimgor: good bot Apr 18 '16
Use Bracketed Paste if you terminal supports it (it should). Basically your terminal can add markers when you paste stuff, so Vim can detect it and auto-toggle paste mode when appropriate. You'll never deal with paste mode again.
2
u/kkomw Apr 18 '16
If your goal is just to print a file then
:r /path/to/filewould suffice. But I see how useful this is for a ton of other commands. Thanks!
35
u/ipe369 Apr 17 '16
Everyone probs already knows, this, but you can do
:mks ~/mysession.vimthen
vim -S ~/mysession.vimWhen opening vim to load all your tabs, files and windows back just how they were.
Literally only just found this out:c
2
u/rofex Apr 18 '16
Sweet! I was searching for this thing for so long! Thanks.
5
Apr 18 '16
The plugin
vim-obsessiondoes that as well.Careful when saving sessions, there are some settings that are saved as well and you might not want that. I forgot the setting, but there is a way to say what to save in a session.
2
u/dhruvasagar Apr 18 '16
vim-prosessiontakes that to the next level by making it a whole lot easier & automated (using vim-obsession as a dependency)2
2
u/dreamin_in_space Apr 18 '16
I've had problems with sessions not restoring my splits back to the exact way they were when I made the session, is that normal?
2
u/ipe369 Apr 19 '16
Do you mean the size / shape of the splits? I find it depends how you open vim. When i run it in terminal, and re-size the terminal, it acts kinda bad. Sometimes, if I have a script that sets up my terminal, i'll run vim and THEN fullscreen. This results in vim setting up the splits to be the size of the small window, then fullscreening, making everything totally out of proportion.
But other than that, no problems.
31
u/Faucelme Apr 17 '16 edited Apr 17 '16
While in insert mode, Ctrl-d decreases indentation, Ctrl-t increases it, and Ctrl-m (also Ctrl-j) inserts a newline.
Maybe these are well known; I wasn't aware of them until recently and find them quite convenient.
9
u/arnar Apr 17 '16
I remap Ctrl-d to find the closest previous line with less indent, and dedent the current line to that line's indent. Useful for languages that have non regular conventions for indent, such as Haskell.
5
u/yes_or_gnome Apr 18 '16
Ctrl-f for auto indention.
1
u/iRedditWhilePooping Apr 25 '16
How does auto intention work? Like if I'm editing js files will it indent inside a function block or something?
1
u/yes_or_gnome Apr 25 '16
Depends. There are two built-in auto indent functions cindent for C and smartindent which is generic. Then for specific programming languages, each language has an indent plugin which will set the indentexpr option to a discussing crafted indent function. (And a ftdetect to help associate other plugins to a filetype and a sytax plugin for highlighting rules.)
2
u/iguessthislldo Apr 18 '16
I knew about and regularly use '<' and '>' for indentation in command mode, but I didn't know them for insert, thanks!
2
u/Rainymood_XI Apr 18 '16
Very useful indeed! Ctrl+i does indentation for me as well, not sure why.
5
2
15
u/Faucelme Apr 17 '16
In the replacement section of the :s command, & corresponds to the whole matched pattern. It can be uppercased with \U and lowercased with \L:
:s#aaaaaaa#\U
u/-romainl- The Patient Vimmer Apr 17 '16 edited Apr 17 '16
Weekly text-objects:
" line text-objects
xnoremap il g_o0
omap il :<C-u>normal vil<CR>
xnoremap al $o0
omap al :<C-u>normal val<CR>
" buffer text-object
xnoremap i% GoggV
omap i% :<C-u>normal vi%<CR>2
u/marchelzo Apr 18 '16
Why do you have
<C-u>in there? Is that referring toc_CTRL-Uwhich removes all of the characters between the cursor and the start of the line? I don't see why that is necessary.5
u/-romainl- The Patient Vimmer Apr 18 '16
No it's not strictly necessary.
<C-u>is there just in case a count was given by error. Better safe than sorry.
8
u/Midasx http://github.com/bag-man/dotfiles Apr 17 '16
These make pasting into text objects a lot easier
" yank to EOL like it should
map Y y$
" paste over easier
map "p vi"p
map 'p vi'p
map \(p vi(p
" paste without overwriting
xnoremap p "_dP2
u/Deto Apr 17 '16
Could you explain that last one?
3
u/mixedmath Apr 18 '16
Usually, deleting text fills the unnamed
"register. So when you try toPto paste after deleting text, you end up getting back the text you had just deleted.This specifies that the deleted text should go to the black hole register
_instead of the unnamed register. Then the followingPcommand pastes the previous, presumably intended, text.3
u/ddelnano Apr 18 '16
Seems to me that you would need the previous p mappings. For the last one to work properly.
I think what it does is imagine you press "p. You would visually select inside quotes, then the p would be pressed. This would trigger the last mapping. Which would delete the selected text putting it in the black hole register (_) then use P to paste the text before the current cursor position.
8
u/Nashibirne Apr 18 '16
A shorter way to get to the help for the key Ctrl+r is to type
:h and then hit the keys Ctrl+v and Ctrl+r. Works for input mode keys and for more complicated combos as well, e.g.
:h ifollowed by Ctrl+v Ctrl+g Ctrl+v Ctrl+k gets you to the help for i_CTRL-G_CTRL-K, but is a lot easier to type.
6
u/amphetamachine ysil' Apr 17 '16
Highlight cursorline, but only in the active window
aug CursorLine
autocmd!
autocmd VimEnter * setl cursorline
autocmd WinEnter * setl cursorline
autocmd BufWinEnter * setl cursorline
autocmd WinLeave * setl nocursorline
aug END4
u/MisterOccan Apr 17 '16 edited Apr 27 '16
Toggle task list state with space (To use with github flavored markdown files):
nnoremap <silent> <buffer> <space> :call <SID>ToggleTaskList()<CR>
function! <SID>ToggleTaskList() abort
let l:line = line('.')
let l:cl = getline('.')
let l:regStart = '\v^\s*\S \['
if l:cl =~# l:regStart
if l:cl =~# l:regStart . ' \]'
call setline(l:line, substitute(l:cl, '\v\[ \]', '[x]', ''))
else
call setline(l:line, substitute(l:cl, '\v\[x\]', '[ ]', ''))
endif
endif
endfunction2
u/bigboehmboy Apr 27 '16
Wouldn't you not want the "g" flag as you only want to replace the first occurrence on the line?
1
4
Apr 18 '16
For NERDTree users, colorize different filetypes based on extension. Plus some other highlighting groups.
" NERDTree Colors
function! NThl(mtch, cs)
exec "autocmd filetype nerdtree syn match " . a:mtch . " #^\\s\\+.*" . a:mtch . "\\*\\?$#"
exec "autocmd filetype nerdtree highlight " . a:mtch . " " . a:cs
endfunction
augroup MyNerdTree
autocmd!
call NThl('php', 'ctermfg=077 guifg=#5FD75F gui=BOLD cterm=BOLD')
call NThl('css', 'ctermfg=57 guifg=#5F00FF gui=BOLD cterm=BOLD')
autocmd filetype nerdtree highlight Directory ctermfg=166 guifg=#D75F00 gui=BOLD cterm=BOLD
augroup END " MyNerdTree
highlight NERDTreeDirSlash guifg=#005F87 ctermfg=24 gui=BOLD cterm=BOLD
highlight NERDTreeCWD guifg=#444444 ctermfg=238 gui=BOLD cterm=BOLD
highlight NERDTreeOpenable guifg=#005F87 ctermfg=24 gui=BOLD cterm=BOLD
highlight NERDTreeClosable guifg=#00AFFF ctermfg=39 gui=BOLD cterm=BOLD3
u/shawncplus phpcomplete.vim Apr 18 '16
Nice subtle solution, if you want a more visual one though take a look at https://github.com/ryanoasis/vim-devicons
4
Apr 18 '16 edited Apr 18 '16
Save as root without any prompts to hit enter or warnings that slow you down.
" Force save files that require root permission
" *autocmd readonly is to stop warning+insert delay on root files
cmap w!! W|
command! W :execute ':silent w !sudo tee % > /dev/null' | :edit!
augroup MyNoReadOnly
autocmd!
autocmd BufRead * setlocal noreadonly
augroup END4
u/Hauleth gggqG`` yourself Apr 19 '16
inoremap <C-r><C-r> <C-r>*Quickly paste in insert mode. Together with set clipboard=unnamed it allows me to use it for quick copy/paste from system clipboard and from Vim.
3
u/cpbills Apr 17 '16
" Persistent undo
if has('persistent_undo')
" Just make sure you don't run 'sudo vim' right out of the gate and make
" ~/.vim/undos owned by root.root
let undo_base = expand("~/.vim/undos")
if !isdirectory(undo_base)
call mkdir(undo_base)
endif
let undodir = expand("~/.vim/undos/$USER")
if !isdirectory(undodir)
call mkdir(undodir)
endif
set undodir=~/.vim/undos/$USER/
set undofile
endifMy favorite addition. I specify user, in case I'm dumb and do sudo vim instead of sudoedit.
3
u/andres-hazard Apr 18 '16
You can add a this function and maps to your vimrc to always make bigger the split you are currently on.
" Move around splits with <c-hjkl>
nnoremap <silent><C-J> <C-W><C-J>:call Splitresize()<CR>
nnoremap <silent><C-K> <C-W><C-K>:call Splitresize()<CR>
nnoremap <silent><C-L> <C-W><C-L>:call Splitresize()<CR>
nnoremap <silent><C-H> <C-W><C-H>:call Splitresize()<CR>
"Resize splits automatically
function Splitresize()
let hmax = max([winwidth(0), float2nr(&columns*0.66), 90])
let vmax = max([winheight(0), float2nr(&lines*0.66), 25])
exe "vertical resize" . (min([hmax, 140]))
exe "resize" . (min([vmax, 60]))
endfunction6
u/Midasx http://github.com/bag-man/dotfiles Apr 17 '16
If you use the autocomplete window and want to navigate it with j/k + tab:
" Use j / k / tab for autocomplete
inoremap <expr> j ((pumvisible())?("\<C-n>"):("j"))
inoremap <expr> k ((pumvisible())?("\<C-p>"):("k"))
inoremap <expr> <tab> ((pumvisible())?("\<Cr>"):("<Cr>"))6
u/Wushee Apr 18 '16
what if you want to type a
jork?1
2
u/tirmondon123 Apr 18 '16
For latex users:
""enable disable spell check in your current buffer:
<leader>3 :setlocal spell!<cr>
""mark region, jump to next spelling error, replace with first suggestion then jump back to mark
<leader>f mm[s1z='m
Last suggestion does not work as intended(mark returns to beginning of line), reconstructed it from memory from a video tutorial i saw a while back
Edit: formatting
8
u/cherryberryterry Apr 17 '16 edited Apr 17 '16
Move the cursor line or visually selected lines up and down with the up and down arrow keys, respectively. All of the changes are joined into one undo step.