sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #347: Format paragraph without changing the cursor position

 tip karma   Rating 17/10, Viewed by 2132 

created:   October 18, 2002 21:02      complexity:   intermediate
author:   Kartik Agaram      as of Vim:   6.0

map <silent> <C-j> :let line=line(".")<CR>:let col=col(".")<CR>gqap:exec ":".line<CR>:exec "normal " . col . "\|"<CR>
imap <silent> <C-j> <Esc>:let line=line(".")<CR>:let col=col(".")<CR>gqap:exec ":".line<CR>:exec "normal " . col . "\|"<CR>a

 rate this tip  Life Changing Helpful Unfulfilling 

<<Wrap text in HTML/XML tags after prompting for the tag name | Quickly insert a single word >>

Additional Notes

Anonymous, October 23, 2002 1:20
Why not simply use <C-O> after gq command?
Kartik, October 23, 2002 17:52
Hmm... let me try to describe a case. Let's say you open a text file and start inserting text somewhere in between without ever adding to the jump list (just arrow keys, '{}'). Now typing <Esc> gqap <C-o> doesn't restore cursor position. At least for me.
Anonymous, October 24, 2002 6:33
Ok, mea culpa - I always used gq}, and it worked. The gqap is different.
[email protected] (Dorai Sitaram), March 13, 2003 11:47
It may be more desirable to preserve the cursor's logical position (i.e., which word it
is currently on), rather than its line/col position.

The following nmap does this by inserting a small and unusual bogus text at the current
cursor position; formatting the paragraph; using search to get to the bogus word;
and then deleting it.

nmap gb i<zqfm><esc>gqip?<zqfm><cr>df>

Kartik, October 23, 2003 19:07
Absolutely outstanding. Thanks, Dorai!
[email protected], November 23, 2003 12:56
Is there a way to make "gqap" use filling spaces to have
block alignment instead of left alignment in the lines?
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
    stats
Sponsored by Web Concept Group Inc. SourceForge.net Logo