In a fortran code, I have lines like

c    write(6,*) "something"
     write(6,*) "something_else"

I would like to insert the first character of the previous line when I open a new line with o in normal mode or enter in insert mode.
In the example given, if I open a new line under the 1st line, the line should open with a c and when I open new line under the 2nd, the new line should start with a whitespace. How would I do that in vim?

P.S. Kindly add appropriate tags if you find any. I could only find vimscript and vimrc which might even be not so appropriate.

  • 2
    something like this perhaps: nnoremap o o<c-y> – Christian Brabandt Feb 3 '17 at 10:56
  • 1
    Also, it might be worth saying that in this context, c is the character for commenting. – nobe4 Feb 3 '17 at 11:04
  • 1
    @ChristianBrabandt That doesn't work for lines beginning with whitespace since it also prints the first non-whitespace character along with the whitespace – user41805 Feb 3 '17 at 11:26
  • @KritixiLithos That's why it is only a comment and no real solution. However I think this one does really what the OP wants: nnoremap o o<c-u><c-y> – Christian Brabandt Feb 3 '17 at 15:36

One possible approach is to use custom function:

function! MyFunction()
  let curline = getline(line('.'))
  let char = " "
  if len(curline)
    let char = curline[0]
  let l:r = append(line('.'), char)
  let l:r = setpos('.', [0, line('.')+1, 3, 1])

nnoremap o :call MyFunction()<CR>A
inoremap <CR> <Esc>:call MyFunction()<CR>A

Using above mapping will make it work both in normal and insert mode.

  • Works perfectly! Mecri! – Sathyam Feb 3 '17 at 11:54

Try adding this to your vimrc:

nnoremap o 0ylo^OP

where ^O is the character literal for <C-o>

The first thing that happens in the mapping is that you go to the beginning of the line 0 and yank the first character yl. Then you go ahead and create a newline below the current line o. All that's left now is to paste that character, so we execute <C-o> (which allows us to execute one normal mode command while in insert mode) and we paste that register to the left of our cursor P.

  • When I do 'o', A new line starts with the character ^OP. – Sathyam Feb 3 '17 at 11:58
  • @Sathyam You have to type <C-v><C-o> in insert mode to print the literal ^O – user41805 Feb 3 '17 at 14:22

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.