<ESC>:w !sudo tee %
Pipes the content of the file to a tee process as root and lets tee save it under the current file name. Vim will tell you the file has changed on disk and ask if it should reload it afterwards.
IMO, it's better not to do that in the first place (which, of course, only makes your tip all the more useful!)
nmap gz :term zsh<CR>
Same number of keystrokes, and does not override any existing normal-mode command from what I can see. :nnoremap <C-z> :term<Return>
works for me (tmux in urxvt).Ctrl-Z only gets converted to SIGTSTP if the terminal has ISIG set. For example, try `stty -isig; sleep 5` and try to suspend or interrupt the sleep command.
:sh ENTER
or for more control over which shell, or to run a shell with any arguments, or even to run any command w/ or w/o args:
:!bash
:!bash -o vi
:!bash some_script.sh
:!some_command some args
and after any of those, just press Ctrl-D or type exit ENTER to return to the vim session.
Very fast and easy to do. I use it all the time.
To do something like scan through a JSON or XML document and split a 'name' field/tag into 'firstName'/'lastName', Vim is the tool I'd reach for.
I think of it as 'cursor-oriented programming', but what I do with it isn't really programming, it's generally of the pattern of 1. Find start of pattern 2. Transform pattern 3. GOTO 1
Or at worst, the decorate/sort/undecorate pattern.
But it boils down to repeatedly applying a macro.
<li class="wrong">first</li>
<li class="wrong">second</li>
<li class="wrong">third</li>
You want to change all the instances of "wrong" to "right". So you put the cursor on the first "w", then `Ctrl-V` to enter blockwise visual mode, then `e2j` to select the "wrong" words, then `c` to remove all of them and enter insert mode to type a replacement. The replacement text is then applied to each line separately. Full series of keystrokes (starting with the cursor on the "w" in the first line) if you want to follow along: <Ctrl-V>e2jcright<ESC>Example:
(1) Select block with `C-v`
(2) Hit colon `:`
(3) Write norm and enter any sequence as you would be in normal mode: `norm I# ` (prepend selection with a comment sign)
(4) Admire the result.
gd" go to definition of variable
:%s/" beginning of a replace...
Ctrl-r /" inserts the last word searched into the command, so what "gd" found
/newname/gc" finish the replace command, g=global replace, c=confirm each replace
Save a character going to a line:
instead of using :42<enter> to go to line 42, can use 42GAuto-indent: =
Go to last file: Ctrl-^
Abbreviations: put this in your ~/.vimrc
iab cmain int main() {
\<CR> return 0;
\<CR>}
Insert the contents of a file:
:r <filename>I like to have a ~/gitmessage.txt which has a template I like, then when I do git commit all I have to do is:
:r ~/gitmessage.txt
Vim + Ctags:Ctags link usages and definitions so you can navigate through code like in an IDE without the bloat of an IDE. Works best with C, but works pretty well with any language with C-like syntax (and more).
Goto tag (definition) of what's under cursor: Ctrl-]
Go back: Ctrl-t
Open tag in a preview: Ctrl-w
:tag <tag> " go to tag, like:
:tag someFunction
:tag SOME_CONSTANTThe file name can be a pipe instead.
Let’s say you have a Makefile based project and the dependencies aren’t as complete as they ought to be. With your cursor on this line in the Makefile:
SOURCES = \
You can say :r !ls src/*.c
That will put the complete list of extant C source files into the file at that position, complete with the “src/“ path prefix. Then to format the list properly for “make” syntax, use Shift-V to select the list, hit the right angle bracket (“>”) once to indent it a level, then say: :s/$/ \/
This trick of replacing the start (“^”) or end (“$”) of a line is very often helpful. Here I’ve used it to ask Vim to put a space and backslash after every line to allow the SOURCES variable definition to continue from one line to the next.(This will look like “:’<,’>s...” in your editor, with the bit between the colon and s being inserted by Vim; it means “front the start of the selection to the end.”)
Remove the final backslash and it’s done.
The advantage of working this way is that you aren’t manually transcribing things the computer already knows and can report on command.
The possibilities here are vast. For instance, if your C source files are buried under subdirectories of `src`, say this instead:
:r !find src -name \*.cThere's also `vt` + some character to select text from the cursor to the next occurrence of that character.
`=` for re-indenting a selection to your current shift-width settings etc. (or `gg=G` to just do the whole file)
https://www.gnu.org/software/coreutils/manual/coreutils.html#fmt-invocation
http://www.nicemice.net/par/
These formatters will do nice things like choose line breaks intelligently to reduce the raggedness of the right edge. I just tested `gqip` on a paragraph in a Markdown document here that was formatted with `fmt`: the `fmt` output put breaks in such that all but the last line was within one character of equal, whereas `gqip` had line lengths varying as much as 5 characters on a 72 character line length.A quicker alternative to Shift-V, arrows, then `=` to reformat a paragraph with `fmt` is this:
:map <F2> !}fmt -w72<CR>
That works anywhere inside the paragraph like with your `gqip`, but it uses the smarter `fmt` paragraph formatter.Select your keystroke to taste. I chose F2 so long ago that I forget why that was a good idea at the time.
I figured this out today. And I submitted this Ask HN to find out more such things.
Even better: Map "jk" to Escape. Enter normal mode without even leaving the home keys; so much easier.
.vimrc:
inoremap jk <Esc>For instance:
Delele first 20 lines:
<ESC>:0,20d
Delete lines from current location to end of file:
<ESC>:,$d
Search and replace from regrex:
<ESC>:0,$s/regex/replacement/g
(from cursor next 20 lines) <ESC> d20d
When deleted is on your copy buffer, just prest p tu paste it from cursor.
Delete from the current line to a line with a particular line number you already see on the left if you have line numbering enabled.
dG
is a lot faster.
Copy lines 0 through 20 to the current line:
<ESC>:0,20t.
I end up using variants of this and the above multiple times every work day.
Just '*' does this, no need for alt.
* ctrl+z; kill %1
* Open a new terminal and ignore the one with vim running.
* ZZ
* Pull the power cord, erasing any sign of it running.
* ESC :q!
* ESC :wq
* ESC :exit
* ESC :quit
Of course ESC and :q usually works too ;)In Unix vi(m), you use Ctrl-V to quote a special character to actually insert it into the text (or into a last line mode command; see example below).
So in Unix if you want to insert a carriage return (Ctrl-M) into a file or a command, you do Ctrl-V Ctrl-M. That does not work in Windows with gVim because Ctrl-V means paste from clipboard. So you use Ctrl-Q instead of Ctrl-V, like in this example, where you want to use vim to remove all the carriage returns (CRs) from the file (say if you were going to use the file on Unix later [1]):
:%s/Ctrl-QEnter//g
where instead of typing the letters Enter, you hit the Enter key.The %s means do the command for all lines in the file (% for all lines, s for substitute), the command is search-and-replace (old pattern with new pattern, here Ctrl-M with nothing), and the g(lobal) at the end means do it for all occurrences in the line (otherwise it does it only for the first occurrence on the line).
This will show on your screen as:
:%s/^M//g (the Ctrl-Q does not show on screen)
where the ^M represents the CR or Enter.The same command on Unix would be:
:%s/Ctrl-VEnter//g
This will show on your screen as: :%s/^M//g (the Ctrl-V does not show on screen)
[1] Of course there are other ways to remove the CRs from the file, like a) using a dos2unix utility, a) many modern editors will do it for you (via a setting or a menu option), c) push it to Git from Windows and then pull it from Unix (with appropriate Git settings for line-ending handling), etc. " Use Unix line feeds.
:set fileformat=unix
" Use Windows line feeds.
:set fileformat=dos
" Shortcut
:set ff=unix
" See the current format
:set ff>a) many modern editors will do it for you
although I tend not to use those particular vim options much.
And for anyone else who does not know, many other vim set commands also have shortcuts, like:
:se ai (for :set autoindent)
and ts for tabstop, sw for shiftwidth, ic for ignorecase, wm for wrapmargin and many others, probably.
I tend to do this in my .vimrc or .exrc as soon as I start using any new instance (on a new machine) of vi/vim:
:se ai ts=4 sw=4 showmode showmatch ignorecase expandtab report=0
Also, like:
>" See the current format
> :set ff
you can do this for any boolean setting, like readonly, ignorecase, etc.:
:se readonly?
:se ic?
to query their values.
:tabe newfile to open a new file.
Then, add the following to your ~/.vimrc (on MacOS)
map <Esc>f <Esc>:tabn<cr> map <Esc>b <Esc>:tabp<cr>
Now you can switch between tabs using option + arrow keys
Assigning different functions to the arrow keys helps when learning vim navigation
That pastes the contents of the 0 register into the buffer. Very useful. That'll work for all registers too.
nmap <C-j> 3j3<C-e>
nmap <C-k> 3k3<C-y>
This maps the <C-j> and <C-k> keys to a scroll action similar to mouse scrolling: the cursors stays in a fixed position while the whole screen moves up or down 3 rows.
Vimgrep and the quickfix window are also pretty cool.
Any tips on how to just rip recoding mode completely out of my vim?
removes the recording mode and throws a simple error when you use :Q instead of :q
will make :Q behave like :q
to open file called "filename" in a vertical split of the console window. Also
:split filename
will open it in a horizontal split
You can do :wq return, or the abbreviated form of :x return, or as you say, ZZ
- ctrl+p plugin to find files in project.
- :bn / :bp / :b<number> to switch between files (buffers)
- :bd to close file
I've mapped 11 to go to previous file, 22 to go to next file, 33 to close file.
zt - scroll the line with the cursor to the top
zb - scroll the line with the cursor to the bottom
also:
Ctrl-O - jump to last (think "o"lder) cursor positions
Ctrl-I - jump to next cursor positions (after using Ctrl-O)
git grep -n foo | vim - -c 'cbuf!' killall vim
There you go. :)The text can be anything from a single line, some arbitrary range of lines (defined via vim marks like a and b or other letters, some paragraphs (see example below), to the entire file - and the filter command can be anything at all, too. The Cartesian product of those two things makes it a very powerful technique.
An example is this key mapping of the character v to a command that format paragraphs of text using the fmt command [1]:
map v !}fmt -w 64<CR>
This says: map the letter v to the command following it (after the space), which is:
!}fmt -w 64<CR>
which runs/pipes (!) the current paragraph (when at top of a para, the cursor movement } defines a para) through the fmt -w 64 command, which formats its input text into lines of not more than 64 characters each.(I just used v because it was one of the characters that Vim does not already assign a command to - any other available character will work.)
I have the mapping in my _vimrc on Windows and .vimrc on Unix.
With that mapping, I can reformat any paragraph (where paragraphs in vim are defined by a blank line either above and below them or both), just by going to the top of the paragraph (with { ) and typing v (no Enter needed).
For example, if I have this (single) line in a file in vim:
the quick brown fox jumped the quick brown fox jumped the quick brown fox jumped the quick brown fox jumped the quick brown fox jumped
and I press v when at the start of that line, it gets reformatted into this para: the quick brown fox jumped the quick
brown fox jumped the quick brown fox
jumped the quick brown fox jumped the
quick brown fox jumped
I typically use this technique when writing text content (non-programming content, such as documentation, tech articles, blog posts, etc.) or sometimes even for block comments of text in programs.You can also create a different version of that formatting command to filter the entire text file through fmt in one shot (that would be "!Gfmt -w 64" when at top of file, where G moves to the last line), but I tend not to use that approach much, because it sometimes messes up some paragraphs which should not be reformatted. So I do it a para at a time.
If you use the sort command instead of fmt, that will sort the range of lines you select, and the sorted lines replace the original lines. This is of course useful in text files and (text format) data files, but is also sometimes useful in source code, e.g. to sort lines of import statements (say in Python or Go - although Go has commands for that), ranges of variable declarations into alphabetical order, array literals, etc.).
[1] (Fmt is a Unix command, but you can probably get it in many of the Unix subsystems that run on Windows too, like Cygwin, UWin, Windows Subsystem for Linux too). c The command that you run the selected text through, can also be a Unix or Windows pipeline, which makes the technique even more powerful.