2

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.

4
  • 2
    something like this perhaps: nnoremap o o<c-y> Commented Feb 3, 2017 at 10:56
  • 1
    Also, it might be worth saying that in this context, c is the character for commenting.
    – nobe4
    Commented Feb 3, 2017 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
    Commented Feb 3, 2017 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> Commented Feb 3, 2017 at 15:36

2 Answers 2

2

One possible approach is to use custom function:

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

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.

1
  • Works perfectly! Mecri!
    – Sathyam
    Commented Feb 3, 2017 at 11:54
1

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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