Vim: how to create key mapping to :edit and jump to last line?
-
19-02-2021 - |
Question
I mapped key F2 to refresh (:edit
) currently opened file. I'm using this when watching a log file to update the screen when file has been updated outside (new lines added at the end of a log file).
nnoremap <silent> <F2> :edit<CR>
I would like to jump to the end of the file after it has been refreshed.
How do I create key mapping which does :edit
and jump to end of the file (shortcut G
) at the same time?
Solution
An idiomatic way to position the cursor in the just opened (or reopened) file
is to use the +
-argument of the :edit
command (see :help +cmd
).
Although the general syntax allows to execute any command, there are special
cases for navigating to a certain line by a pattern matching text on that line
(+/
followed by the pattern), or by a line number (+
followed by the
number). If the number is omitted in the latter form, it is assumed to be the
last line of the file.
In such a way, to reload the current file positioning the cursor on the last line, one can use the command
:edit +$
or
:edit + %
It is possible to shorten these commands by using :e
instead of :edit
and
leaving out an optional space before the +
-argument.
:e+$
or
:e+ %
The corresponding mappings would take the form
:nnoremap <silent> <F2> :edit +$<CR>
and
:nnoremap <silent> <F2> :edit + %<CR>
Note that this +
-argument syntax is also valid for opening a file from the
command line, so
$ vim + filename
works as well.
OTHER TIPS
This is what I'd use:
nnoremap <silent><F2> :edit<bar>$<CR>
You can chain commands in a map by using <bar>
. This mapping does what you want:
:nnoremap <silent> <F2> :edit <bar> :normal! G<enter>
It's important to use normal!
instead of normal
in mappings/scripts because the prior will not take user defined mappings into account. Even if there is a mapping for G
in this case, vim will treat G
as if it were not mapped at all.
In Vim '|'
can be used to separate commands, much like many flavors of Linux/Unix. For more information about the use of the bar check out :help bar
Example:
:edit | normal! G
If you wish to use this in a key mapping You may find that your ~/.vimrc
doesn't like maps utilizing |
, or \|
. In order to make this work use the equivalent <bar>
instead.