Pressing “Home” in Vim on an Indented Line

前端 未结 5 1238
不知归路
不知归路 2021-02-07 07:36

I have a bad habit of using the \'home\' key to go back to the beginning of a line. As I recently started using vim I noticed that when I press the home key on a lined that is i

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-07 07:53

    You could remap Home to be the same as ^ (the docs say Home's default function is equivalent to the movement command 1|):

    :map  ^  
    :imap  ^i  
    

    Which should make the insert mode mapping be equivalent to escaping out of insert mode, pressing ^ and then returning to insert mode. I don't know about the best method of mapping a motion command for use inside insert mode, so this may break something, but it seems to work.

    As to your indentation settings, they shouldn't have an effect on movement controls, but I also think you probably would prefer to have them set differently. autoindent just keeps your current indentation for new lines (so if you place 4 spaces at the beginning of a line, after you press return your new line will also have 4 spaces placed in front of it). I don't know why you wouldn't want that, since it's pretty useful in pretty much any programming language, or even just freeform text. smartindent on the other hand implements a couple of hard-coded lightly C-ish indentation rules, like indenting after an opening {, and deindenting after a closing }, but doesn't automatically carry over indentation from previous lines. The docs recommend keeping autoindent on if you use smartindent.

    However, smartindent is useless for languages that don't meet its hard-coded rules, or even actively harmful (like when it automatically removes indentation from any line starting with a '#', which it thinks is a preprocessor directive but is wrong for python programmers trying to write an indented comment).

    So vim also includes a more advanced indentation mode, filetype indentation, which allows flexible indentation rules on a per-language/filetype basis and is the preferred indentation mode for most people (even for C-like languages). If you do use filetype indentation, it's best to turn off smartindent (otherwise it can interfere with the filetype indentation, like moving all comment lines to column 0 in python files).

    Personally, I always have autoindent on, use filetype when available, and never use smartindent. My .vimrc includes:

    set autoindent " doesn't interfere with filetype indents, and is useful for text  
    if has("autocmd")  
      " Enable file type detection and indentation  
      filetype plugin indent on  
      set nosmartindent  
    endif  
    

    I imagine there's something you could do to have smartindent turned on only when filetype indenting doesn't exist for a filetype, if you're editing that many different C-like languages with no filetype indentation available.

提交回复
热议问题