0

I use vim as a note-taking app by editing a text file and appending notes to it.

I have written a simple function to insert a block of text as follows:

function! AddBlock2(...) range
    let l:hdr = strftime("_%d%b%y_%H-%M-%S")
    let l:b = repeat("-", 20)
    call append(line('$'), ['',l:b,'MEETING TIME : ' . l:hdr,'KEYWORDS : ',l:b, ''])
    execute "normal! G$o"
endfunction

I have mapped it so that it is easy to add a new header at the beginning of a meeting:

" append header to existing buffer
:nnoremap <C-b> :call AddBlock2() <CR>
:inoremap <C-b> :call AddBlock2() <CR>

This has the effect of inserting a block like this at the end of the file:

enter image description here

Currently the code puts the cursor at the end of the block of inserted text because of execute "normal! G$o".

Ideally I would like to cursor to be placed in insert mode after "KEYWORD: " once the text has been inserted

How could I change the code to achieve this ? I have tried replacing the last line with execute "normal! G?:a " but it does not work at all

1

? needn't be called with :norm. Just use ?: alone.

With your :norm calls there's no need to wrap in :execute since there are no variables being used.

And need to start insert with, well, :startinsert.

That gives...

function! AddBlock2(...) range
    let l:hdr = strftime("_%d%b%y_%H-%M-%S")
    let l:b = repeat("-", 20)
    call append(line('$'), ['',l:b,'MEETING TIME : ' . l:hdr,'KEYWORDS : ',l:b, ''])
    norm! G$o
    ?:
    norm! A<space>
    startinsert
endfunction

Replace the <space> after norm! A with an actual space.

You could alternatively place the cursor with movement commands (e.g. 2k$) or function call(s) but this works just fine.

BTW, your Insert mode mapping won't work. You need to exit Insert mode before you can get to the command line...

:inoremap <c-b> <Esc>:call AddBlock2()<CR>
4
  • for whatever reason, this does not work for me - <C-b> now inserts ":call AddBlock2".literally in the buffer. I am using neovim so maybe that is the reason. I will try your suggestion 2k$ Dec 21 '20 at 8:50
  • See my updated answer w/r/t the last norm! command and your insert mode mapping.
    – B Layer
    Dec 21 '20 at 9:07
  • That now works perfectly ! Many thanks ! Dec 21 '20 at 9:12
  • Great. You're welcome.
    – B Layer
    Dec 21 '20 at 9:14

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.