2

With plaintext files, when I reopen them in Vim to add content, I want to go to the end of the last line of content and get to insert mode. In ideal circumstances, a simple GA after opening the file would take care of this. Unfortunately, I have the habit of adding a few extra newlines at the end of the file, and it's proving a hard habit to get rid of.

Given this, what is the simplest way in Vim of saying "go to the last line in the file that has content in it, go to the end of that line and get into insert mode"? I guess the crux of my question is, how do I express the concept of "last line that has content in it" to Vim?

Sundar R
  • 1,539

3 Answers3

1

You could use ?\w enter followed by A

  • ?\w searches backwards for the first word
  • A puts you into insert mode on the last line containing content
1

If you wish to always go to the last non-whitespace line of a file, or a given sort of file, you can insert an autocmd in your ~/.vimrc. For example:

:autocmd BufRead *.txt :$;?\S?

This automatically goes to end of file, and searches back for a non-whitespace char, on any file matching the glob pattern *.txt. You then type o for example to add stuff.

The same technique can be used to remove blank lines you leave at the end of buffers when you write them back to the file, hence avoiding the problem in the first place. For example:

:autocmd FileType python autocmd BufWritePre <buffer> :%s/\(\n\s*\)\+\%$//e

This example does so only for files recognised as filetype python (eg suffix .py).

meuh
  • 6,624
0

I have never worked in Vim, but I will propose some logic:

  • Go to end-of-file
  • Back up one character
  • Replace newline with null string -- if successful, repeat; if not, we're done.