2

Why does this not work as expected?

function! MyO()
     normal! o
endfunction
nnoremap TT :call MyO()<cr>i

If this is the situation:

 |   an indented text
 ^ (normal mode)

typing o gives:

    an indented text
    |
    ^ (insert mode)

but typing TT gives:

    an indented text
|
^ (insert mode)

Why can't I enjoy automatic indentation with normal ?

3
  • 1
    Why execute "normal! o" and not normal! o?
    – romainl
    Aug 18 '15 at 22:37
  • @romainl Just a habit as it allows use of special characters (see :help normal and answer below).
    – iago-lito
    Aug 19 '15 at 5:51
  • Well it's useless here, you might as well make your script simpler.
    – romainl
    Aug 19 '15 at 7:11
5

As explained in help :normal, if an argument to :normal is not a complete normal-mode command, it will be aborted as if <Esc> or Ctrl-C was typed. "This implies that an insert command [such as o] must be completed (to start Insert mode, see :startinsert)."

So your TT command is effectively executing o<esc>i, which is not the same as just typing o--it removes the indent.

To do what you want to do, try the following.

execute "normal o\<Space>\<BS>\<Esc>"
startinsert!

That opens a new line with the cursor at the indented position, inserts a space and backspaces over the space to preserve the indent, then escapes back to normal mode. The :startinsert! command then puts you in insert mode after the indent.

0

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.