Today I Learned

A Hashrocket project

297 posts about #vim

fill your quickfix window with lint

File names I can’t jump to frustrate me. Today I ran $ npx eslint and my computer said “I looked at a file, and found a problem on this line, in this column. Do you want to see it? Good for you. Go type out the file name in your editor then.”

ButI wanted a jump list of all the eslint errors in my project. Eslint is a kind of compiler, right? Vim knows compilers.

:set makeprg=npx\ eslint\ -f\ unix

Now I can

:make

and behold!

:cw

I can now see all of the errors and warnings for the project, and nimbly jump betwixt.

Vim Tags in Visual Mode 🏷

This is my 400th TIL! 🎉

I’ll file this under ‘Vim is endlessly composable’. Today I learned that Vim tags can be used to define a range in visual mode. Here’s how you’d fold your code between two Vim tags.

Go to the first tag. If you marked it 1, here’s how you’d do that:

m1

Enter visual mode and extend to your second tag 2:

m2

Enter command mode and fold the range:

:fold

Which automatically extends to:

:'<,'>fold

I use this in big markdown files to hide all but the thing I’m currently working on. Enjoy.

Vim Reverse Sort

I use Vim’s :sort all the time. If I can’t have a more meaningful algorithm than alphabetical, at least my lists are in some kind of order.

This function comes in surprisingly useful while writing GitHub-style checkbox lists.

- [x] Check mail
- [ ] Play guitar
- [x] Write TIL

Sorting this list alphabeticaly puts the undone items at the top.

- [ ] Play guitar
- [x] Check mail
- [x] Write TIL

Reverse the order (in classic Vim style) with a bang:

:sort!

Pretty-Print JSON in NeoVim/Vim using jq

I’ve written here before about how to pretty-print JSON in Vim but since then I have found an even easier method using jq.

jq is an amazing command line utility for processing, querying and formatting JSON. I use it all the time when I get a response from an API request and I want to extract information or simply to pretty-print it with colors. All you have to do is pipe the curl results into jq:

curl https://til.hashrocket.com/api/developer_posts.json?username=doriankarter | jq

image

You can also use jq inside of NeoVim to pretty print a JSON string, right in your buffer using this command:

:%!jq

demo

Open the Vim Quickfix

Today I learned a new Vim command, :copen or :cope. The headline for this command is that it “open[s] a window to show the current list of errors”. The side benefit is that if you already have quickfix window in your buffers, like you would after greping the codebase, it will open or reopen that quickfix buffer.

See :help :copen for more info.

Reset a Vim Split

When I make a Vim horizontal split, the two panes are evenly sized. I then often use :resize n to make one pane larger or smaller. To restore the panes to their evenly sized split, use <vim-leader> =. In the Hashrocket dotfiles, this translates to CTRL + W =.

Send a Command's Output to Vim (Part II) ↪️

In a Hashrocket blog post, 10 Vim Commands for a Better Workflow, I wrote about :.! <command>, which replaces the output of <command> with your current line.

Today I learned what this technique is called: filtering. From the docs:

filter is a program that accepts text at standard input, changes it in some way, and sends it to standard output. You can use the commands below to send some text through a filter, so that it is replaced by the filter output.

An even shorter version is just !!<command> in normal mode. A use case for this would be writing docs, where command-line output (ls, curl, etc.) can help demonstrate an idea.

Check out :help !! to see all the permutations of this interesting command.

Go to next ALE error

Has ALE overtaken your vim setup like it has mine? It constantly runs linters, compilers and formatters, just waiting for you to slip up so that it can put an X in the gutter.

Those X’s are really quite handy. They generally point me to the next place in the code that I need to make a change.

To get there quickly you can goto the next ALE error with:

:ALENext

This will stop at the last error in the file though. To have it wrap around use:

:ALENextWrap

I really enjoy vim-unimpaired’s handy bracket mappings, but I don’t use ]a that move between args (because I don’t use args very often).

To setup my own handy bracket mappings for ALE:

:nmap ]a :ALENextWrap<CR>
:nmap [a :ALEPreviousWrap<CR>
:nmap ]A :ALELast
:nmap [A :ALEFirst

Open FZF Result In A Split In Vim

The fzf.vim plugin allows you to do speedy fuzzy searches for filenames and line-by-line content.

Once you’ve narrowed down the results and found what you’re interested in, you can hit <enter> and a new buffer will open over what was already in the window. You can also open that file as a split.

Hitting Ctrl-x will open the file under the cursor as a horizontal split.

Hitting Ctrl-v will alternatively open that file as a vertical split.

Edit A File Starting On The Last Line

Generally when you start editing a file whether as a new Vim session (vim file.txt) or in an existing Vim session (:e file.txt), your cursor will be positioned at the beginning of the file.

You can start editing a file with the cursor positioned at the end of a file using an edit command — include + with no line number. This may be useful for a large file or even if you just know that you’ll be adding content directly to the bottom of the file.

If you are starting a new Vim session:

$ vim + file.txt

or if you are already in a Vim session:

:e + file.txt

See man vim or :h +cmd for more details.

Edit A File At A Specific Line Number In Vim

I use long-running Vim sessions where I constantly open files as new buffers with the :edit (or :e) command. Generally, when I open a new file I end up with the cursor at the top of the buffer and go from there. But what if I have a specific line number in mind and I want the cursor to start there?

The :edit command can receive arguments, including a line number argument. To open up to line 159, I can include the +159 argument in the command.

:edit +159 path/to/the/file.txt

See :h :edit and :h +cmd for more details about how :edit works and what the different arguments can do.

Search Backward Through A File

There are a number of ways to search for a match in a file. One I use quite often is hitting * while the cursor is over the word I want to find matches for. It searches forward jumping to the next occurrence of that word.

It turns out there is a way of doing the same thing, but searching backward to the previous occurrence of the word. If you hit # with the cursor over a word, it will jump backward through the file until it finds an occurrence of that word. Keep hitting # to keep searching backward.

See :h # for more details.

Clear Out The Jump List In Vim

Vim uses a jump list to track all they jumps you’ve made during a session. Vim can even be configured to keep a record of those jumps between sessions. This is really handy for a long-lived project, but what if you want those jumps cleared out?

You can clear them out for the current and subsequent windows using :clearjumps. The jump list for existing windows will be unchanged and once you start a new session, the full jump list will be restored.

See :h :clearjumps for more details.

Navigate To The Nth Column On A Line In Vim

You can navigate the cursor to a specific column of the current line using the | character. For instance typing

45|

will navigate your cursor to the 45th column of the current line. If you type a number that exceeds the number of columns on the line, your cursor will be placed on the last column.

Here is what the help files have to say about |:

|           To screen column [count] in the current line.
            |exclusive| motion.  Ceci n'est pas une pipe.

Change DOS to Unix text file format in VIM

The last few times I had to use a .txt file as an input, I’ve run into difficult-to-troubleshoot parsing errors. What could be wrong? I check and re-check the text file, and I can’t find any mistakes!

If the text file came from a Windows machine, this may due to a difference in line-ending between DOS and Unix text files. You can check and change this file format in Vim.

Open your file in Vim and, in normal mode, type :set ff? to see what the file format is. If it is DOS, then type :set ff=unix to change it to Unix.

Quit When There Is An Argument List

To start a Vim session with multiple files in the argument list, name multiple files when invoking Vim:

$ vim README.md LICENSE

The first file in the argument list, and the current buffer, is README.md. The last file in the argument list is LICENSE.

At this point if you try to quit, Vim will prevent you saying 1 more file to edit. If we look at the docs for :q and :wq, we see something along the lines of:

This fails when the last file in the argument list has not been edited.

Vim wants to ensure that you’ve paid attention to every file that you loaded up into your argument list. If you’d like to quit regardless. then this is where the :q! and :wq! variants come in handy. This commands will skip the argument list check.

Set Vim Filetype or Syntax with Modeline

Here’s a problem I faced today: I’m writing a Thor CLI. The convention for that project is a file called cli, written in Ruby but with no .rb extension. Vim highlights it and otherwise treats it like a conf file, but it’s Ruby. I want my editor to progamatically recognize that and act accordingly.

One solution is Vim’s modeline. With modeline enabled, either of these settings will enable syntax highlighting on buffer read. They can both be used at the same time as shown.

# vi: syntax=ruby
# vi: filetype=ruby

def ruby_here
end

Using vim-surround With A Visual Selection

The vim-surround plugin allows you to do a variety of actions that have to do with the surrounding characters of text objects.

The S keystroke allows you to surround a visual selection with the following character.

First, make a visual selection. Then hit S. Then hit a surround character such as ( or [ and the area of text that has been visually selected will be wrapped with the respective surround characters.

Jump Back To The Latest Jump Position In Vim

Any sort of jump motion, such as gg or 121G, will be recorded in your Vim session’s jump list. If you’d like to return to the latest position in your jump list, you can tap '' within normal mode.

You can then tap '' again and you’ll be returned to the position you were just at. This is great if you want to toggle back and forth between your current position and the previous position.

If the latest jump position is not within the current buffer, then you will be jumped to the initial cursor position at the top of the file.

You can learn more about this by reference :help jump-motions, :help jumplist, and :help ''.

h/t Jake Worth

Jump Back 🐇

A Vim motion I’ve really been loving lately is '' or ``, which returns you to the previous jump position. It references the previous jump, so using it twice in a row will toggle you back and forth between two locations.

I use this a lot after jumping to the next occurance of a word with *, and then changing that word in some way so I can’t return with *. If you’re using normal mode most of the time, this command can help you walk back through your thought process.

For more info:

:help ''

Restore from Diff in Vim

I often use diffs in Vim to compare my current file with the previous Git commit. vim-fugitive is one way to do this, via commands like :Gdiff or :Gvdiff (vertical option).

From this diff state, we can restore the code from one pane to the other using the command :diffput. This is useful for restoring one line, or a range, from the previous commit to my working copy.

Using vimscript lambdas with map

Vimscript has lambda functions, check them out with :help lambda.

You don’t have to reference an argument with the a: prefix and returns are implicit.

Generally they take the form of:

:let Add = {a, b -> a + b}
:echo Add(1, 2)
 3

You can also pass a lambda to the map func:

:let fruits = ['apple', 'orange', 'banana']
:echo map(fruits, {key, val -> "key: " . key . " val: " . val})
['key: 0 val: apple', 'key: 1 val: orange', 'key: 2 val: banana']

Alwyas be careful with vim’s map() though. It Mutates

To make sure you don’t mutate the list you are mapping over, use copy().

:echo map(copy(fruits), {key, val -> "key: " . key . " val: " . val})

What is that chäräcter ?

If you are in vim and you encounter a weird looking unicode character, and you want to know what the codepoint(s) for that character is/are you can use ga

If my cursor is over ä and I use ga I get output:

<ä> 228, Hex 00e4, Octal 344

If my cursor is over and I use ga I get output:

<a>  97,  Hex 61,  Octal 141 < ̈> 776, Hex 0308, Octal 1410

The first character is a precombined Unicode character, the a with the umlaut already has its own unicode character.

The second character is an a combined with a diacrital mark, and the output of ga reflects that by listing each utf codepoint that composes the character.

The five values that define cursor position in vim

We generally think of a cursor having two coordinates, x and y, row and column, but when I call getcurpos() I get a list with 5 values in it.

:help getcurpos()
:echo getcurpos()
[0, 4124, 8, 0, 57]

Here are the definitions of those numbers:

bufnum - the number of the buffer when calling getpos("'A") to get the position with a mark. Always 0 with getcurpos()

lnum - The line number

col - The number of chars used to go this far to the right. is 2. 10 spaces is 10.

off - Is the number of chars past the end of the line. 0 unless using virtualedit.

curswant - Is the column you started on when starting to navigate with j and k. You might start on col 20, and go down to a line with only 10 columns in which case the cursor would be on col 10, but curswant would still 20. The next navigation to a line with more than 20 characters would put you back on col 20.

With virtualedit turned on curswant will always be the column position of the cursor.

Sort numerically

The sort command :sort in vim sorts by the string representation by default. For numbers this is weird. If you have 2, 12, and 1 on separate lines they end up sorted like this:

1
12
2

To sort them numerically you can pass the n argument to the sort command, like this :sort n which gives you what you want:

1
2
12

Making virtualedit a local option

virtualedit is a global option. This means that when you call setlocal virtualedit it’s not set just for this buffer but for all windows and all buffers. This is confusing, but only options labeled local to buffer in help can be set to the local buffer. virtualedit is labeled as global.

However there is a hack. You can simulate this as a buffer local option by setting it on BufEnter and unsetting it on BufLeave.

In my .vimrc.local I have

autocmd BufNewFile,BufRead,BufEnter *.part setlocal virtualedit+=all
autocmd BufLeave *.part setlocal virtualedit-=all

Set it when you enter, unset it when you leave, and now the setting is confined to the buffer you’d like to use it in.

Print The Relative Path Of The Current File

As a project grows and there are many directories and long path names, Vim will not always have enough room to display the full relative path of the current file. It may have to cut off the initial directories which can make it hard to know where you are.

You can hit Ctrl-g to quickly display the relative path of the current file below the status bar.

example of using ctrl-g

See :help Ctrl-g for more details.

Aborting Git Commits And Rebases Within Vim

When you are amending a commit or doing an interactive rebase of a series of commits, Vim will be open to a buffer full of content related to the respective action. Normally, you’ll make some changes, save the buffer, and then quit — Git will take over from there by processing the commit or rebase.

What if you find yourself in this situation and you want to cancel the commit or rebase? Simply quitting with text already in the buffer will be interpreted by Git as a signal to go ahead and process the commit/rebase.

So, how do we quit without confirming the action?

Vim allows you to quit with an error code.

:cq

This means that irrespective of the content of the buffer, Vim will signal to Git with an error code to not process the commit or rebase, effectively aborting the action.

See :help cq for more details.

Preserve whitespace while joining in Vim

I have this text:

abc
   def

There are 3 spaces on the line before “def” and I want to make sure that space is preserved.

I usually join with J in normal mode. There is, however, a :join command that behaves the same way except you can follow it with an optional !.

By using the abbreviation it is shortened to:

:j!

And the result I get is:

abc   def

Space preserved!

See :help :join for more information.

For When That Escape Key Is Hard To Reach

Using Vim to its full potential requires using just about every key on the keyboard. Of all those keys, the escape key is particularly important. It’s how you get back to normal node.

If you find the escape key hard to reach or your laptop vendor decided you don’t need it anymore, what’s the alternative?

There is a built-in alternative:

Ctrl-[

Note: If your <Esc> key is hard to hit on your keyboard, train yourself to use CTRL-[.

See :help Ctrl-[ for more details.

source

Vim: Peek horizontally without moving the cursor

Some people like wordwrapping in Vim. Personally I find it annoying for code because it can destroy the meaning of the code in the context that it was formatted in by the original author, making it hard to understand where one line begins and ends.

Turning wordwrap off though, can put you in a situation where you have a line of text slightly longer than the screen can show, and you may want to scroll a bit to the right/left for reference but not move your cursor and lose your position with ^ or $.

Vim allows you to do that with zs and ze mappings.

DEMO demo

Learn more with :h zs or :h ze.

Execute command from register

Here’s a cool command

:nmap <leader>s :smile<CR>

If you read the above in vim, how would you execute it? You can use the system buffer or tmux copy+paste and paste it to the command line, but that seems very not-vim.

Vim has a :@ command that will execute registry contents. Just put the line into your registry with yy and then call:

:@"

This executes the contents of the default register

`yo` has been replaced by `]op`

vim-unimpaired is a fantastic vim plugin full of utility mappings, many to do with toggling. I have relied heavily on yo to enter insert mode with the paste option set when I want to use the system buffer for pasting.

Recently, the yo mapping has been repurposed. Read the github issue here.

Instead, ]op is the new mapping to put you in insert mode with the paste option set.

The documentation now looks like this:

                                                *[op* *]op* *yop*
A toggle has not been provided for 'paste' because the typical use case of
wrapping of a solitary insertion is inefficient:  You toggle twice, but
you only paste once (YOPO).  Instead, press [op, ]op, or yop to invoke |o|,
|O|, or |0||C| with 'paste' already set.  Leaving insert mode sets 'nopaste'
automatically.

Vim Verbose Map

Do you have a Vim mapping you’d like to know more about? One technique to explore a mapping is map. Here’s what my machine knows about gcc:

:map gcc
n  gcc           <Plug>CommentaryLine
o  gc            <Plug>Commentary
n  gc            <Plug>Commentary
x  gc            <Plug>Commentary

Need more information? Add verbose, which will also display where it was last set.

:verbose map gcc
n  gcc           <Plug>CommentaryLine
        Last set from ~/hashrocket/dotmatrix/.vim/bundle/vim-commentary/plugin/commentary.vim
o  gc            <Plug>Commentary
        Last set from ~/hashrocket/dotmatrix/.vim/bundle/vim-commentary/plugin/commentary.vim
n  gc            <Plug>Commentary
        Last set from ~/hashrocket/dotmatrix/.vim/bundle/vim-commentary/plugin/commentary.vim
x  gc            <Plug>Commentary
        Last set from ~/hashrocket/dotmatrix/.vim/bundle/vim-commentary/plugin/commentary.vim

Now we know which modes support gcc (normal, plus operator-pending, normal, and ex-mode as gc), what happens when the command is used, and who set it last.

h/t Chris Erin

Python and Neovim

Some Vim plugins require Python, and if you’re using NeoVim, you’ll need to do a bit of extra work to get them working. An error message like this, seen when Python is definitely installed on your machine, is a hint you’re in this predicament:

$ vim
MatchTagAlways unavailable: requires python

Neovim needs its own Python support. Solve the problem with this library, specifically one of the following commands depending on your Python version:

$ pip2 install neovim
$ pip3 install neovim

Escaping Terminal Mode In An Nvim Terminal

A recent TIL by Chris Erin showed how to split open a terminal in a Neovim session — :sp term://zsh.

The terminal is emulated into a Vim buffer which means that you can treat it sort of like any other Vim buffer. You start in Normal mode. Once you use any mapping that would transition you into Insert mode, you’ll instead find yourself in Terminal mode. Terminal mode works just like any zsh session (give ls a try).

Try hitting <Esc> though and you’ll see that you stay in Terminal mode instead of being transitioned back to Normal mode.

So how do you get back to Normal mode?

Hit <Ctrl-\><Ctrl-n>.

This is a pretty awkward key mapping though, so follow the Nvim Terminal docs and bring back the Escape key.

:tnoremap <Esc> <C-\><C-n>

Open a zsh terminal in a split window in Neovim

Opening a terminal in Neovim is one of the more eye opening features of the vim fork. To open a terminal in vim use the :terminal command.

:te
:term
:terminal

Those commands though will use your entire current window for the terminal and by default it opons in bash even though my shell is configured to be zsh

To open a terminal in zsh use:

:te zsh

This still takes up the entire window. Lets now use the split command and the terminal protocol syntax to open a split window with zsh.

:sp term://zsh
:split term://zsh

Pipe text into Vim from stdin

You can pipe text into vim directly from stdin. This can be helpful if you want to edit the output of a long bash command, or if you want to see what an installation script contains before piping it into bash.

curl -fsSL https://raw.github.com/cknadler/vim-anywhere/master/install | vim -

The key is to use the - after the vim command to make it read from stdin. This will open a new buffer with the output of the previous command.

autocmd on a List of Extensions

Yesterday I was VimScripting and learned that the autocmd function can execute against multiple file extensions in a single line of setup. Here’s a contrived example:

" ~/.vimrc
autocmd BufWritePost *.exs,*.ex :! git add %

In this code, after every buffer write on files matching .ex and .exs, add the current buffer to our Git staging area. Learning this helped me reduce duplication in my configuration.

Netrw header toggling with vim-vinegar

vim-vinegar is a vim plugin that “cleans up” Netrw as-

an attempt to mitigate the need for more disruptive “project drawer” style plugins

but it turns off the Netrw header, which, while unnecessary is the second most charming feature of vim.

To reclaim your Netrw header, use I while in Netrw.

As a vim-vinegar bonus, use - while in a buffer to open Netrw in the directory of the current buffer.

Having rapid directory access available changes everything

All quotes are from the the vim-vinegar README. Thank you to Vidal for the hat tip about I.

Fold A Visual Selection And Expand It Back

If I visually select a series of lines — say the open and close tags of a large div in an HTML file I am reading through — and then hit zf, it will be folded into a single line. That line will list how many lines are included in the fold as well as the content of the first line of the fold.

If I later come back to that fold and want to expand it again, I can hit zd to delete (or undo) the fold.

To do this, you’ll want to make sure your foldmethod is set to manual. This can be done by running the following command:

:set foldmethod=manual

See the vim helpfiles (:h fold) for more details.

Vi + Imitation

It’s understood in the Vim community that the name ‘Vim’ stands for ‘Vi + Improved’, because this tool improves upon the classic Vi text editor.

Last night at the Vim Chicago Meetup, I learned that ‘Vim’ once stood for ‘Vi + Imitation.’ Bram Moolenaar, the creator of Vim, changed the name when the feature surpassed the tool it was originally built to imitate.

This was one of many facts I learned during from a fantastic lightning talk on the history of Vim. We recorded it and plan to post it online soon.

Treat words with dash as a word in Vim

By default vim treats two words connected with an underscore e.g. search_tag as a vim word text-object.

This is very useful because you can then use motions and commands on them such as daw to delete a word, or ciw to change inside the word.

That is not the case for dash separated words e.g. search-tag. These types of words are very common in CSS class names and HTML IDs.

To make vim treat dash separated words as a word text-object simply add the following to your .vimrc:

set iskeyword+=-

And source it again.

Jump between #git hunks in Vim with vim-gitgutter

One of my favorite Vim plugins is vim-gitgutter - it shows gutter markings for changes in the current buffer when that file is tracked by git.

It looks like this:

+ = new lines - = deleted line ~ = changed line

It also comes with a few very useful commands for working with hunks, sections of changed code in your file.

To jump between hunks you can use ]c and [c. Since I don’t really use the return and backspace keys in normal mode I have mapped those instead:

nnoremap <silent> <cr> :GitGutterNextHunk<cr>
nnoremap <silent> <backspace> :GitGutterPrevHunk<cr>

This is especially useful on big files (more than a bufferful) with scattered changes.