Vim Auto Indent with newline

前端 未结 6 1107
礼貌的吻别
礼貌的吻别 2021-02-01 13:18

How do I get vim to place the cursor within the braces starting on a new line, ie with | denoting the cursor position :

class {
  |
}

right now

相关标签:
6条回答
  • 2021-02-01 13:55

    I have Ubuntu 12.04 and I found no vimrc file in home directory. Global vimrc file was in /etc/vim/vimrc.
    There was almost nothing in this file. So for me it worked to add this 3 lines to the end of /etc/vim/vimrc

    set autoindent
    set cindent
    inoremap { {<CR>}<up><end><CR>
    

    When you will type { next time it will be changed by combination {, Enter, }, up, end, Enter. cindent and autoindent will add required amount of Tab's.
    P.S. I'm not good in tuning up vim so some explanations may be not so accurate. It's how I think it works.

    0 讨论(0)
  • 2021-02-01 14:04

    I found that delimitMate does exactly what you describe and more (that is, automatically inserting the ending }). Note you have to tell delimitMate to expand carriage returns by adding let delimitMate_expand_cr=1 to your config.

    From my observation, this is exactly the behaviour found in TextMate and SublimeText.

    0 讨论(0)
  • 2021-02-01 14:08

    autoindent refers to it carrying over the current indentation level onto subsequent lines. To get it to indent according to syntax, you need to specify a flag like smartindent or cindent as well.

    0 讨论(0)
  • 2021-02-01 14:16

    I wrote this in my .vimrc

    inoremap <expr> <CR> InsertMapForEnter()
    function! InsertMapForEnter()
        if pumvisible()
            return "\<C-y>"
        elseif strcharpart(getline('.'),getpos('.')[2]-1,1) == '}'
            return "\<CR>\<Esc>O"
        elseif strcharpart(getline('.'),getpos('.')[2]-1,2) == '</'
            return "\<CR>\<Esc>O"
        else
            return "\<CR>"
        endif
    endfunction
    

    The code above first check if you are using Enter to do confirm a code completion, if not it will indent the {|} when you type Enter. Also, it provides html tags auto indent.

    For your problem:

    class {|}
    

    press Enter and you will get

    class {
        |
    }
    
    <html>|<html>
    

    press Enter and you will get

    <html>
        |
    </html>
    
    0 讨论(0)
  • 2021-02-01 14:19

    Put this in your .vimrc :

    imap <C-Return> <CR><CR><C-o>k<Tab>
    

    Assuming autoindent and smartindent are set correctly, typing Ctrl + Return between braces will put your cursor where you want it to be.

    0 讨论(0)
  • 2021-02-01 14:20

    At bottom of the file, I'm using:

    # vim: ts=2 sw=2 sts=2 sr noet st ai si
    

    For example Dockerfile:

    FROM centos-7
    RUN ...
    CMD ...
    
    # vim: ts=2 sw=2 sts=2 sr noet st ai si
    

    If you want keep the indentation only, use # vim: st ai si

    0 讨论(0)
提交回复
热议问题