Say I want to begin letters like this:

Dear world,

What's the simplest way to define a mapping that opens a new line preserving the cursor's horizontal position?

  • And perhaps next you will ask, "And the most correct way?" :) – VanLaser Mar 26 '16 at 0:19
  • Not really a vi/Vim answer, but you may want to learn about vertical tabs. For terminal-specific files they can be handy. – Wildcard Mar 26 '16 at 1:19
  • @Wildcard, what are they? – Toothrot Mar 26 '16 at 1:33
  • See for yourself: printf '%s\v%s\n' hello there (at a command prompt). – Wildcard Mar 26 '16 at 1:37

An easy way to achieve this using no vimscript is the following:

nnoremap <leader>o yyp^v$r A

This assumes you want to start the mapping in normal mode (otherwise just add <Esc> to the beginning of your insert mode mapping). It copies the current line with yy, pastes it on the line below (p), selects the pasted text in visual mode (^v$), replaces the selection with whitespaces (r followed by a space) and jumps to the end, putting you in insert mode (A).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.