Smart Wrap in Vim

后端 未结 8 1478
离开以前
离开以前 2020-12-02 06:28

I have been wondering if Vim has the capability to smart wrap lines of code, so that it keeps the same indentation as the line that it is indenting. I have noticed it on som

8条回答
  •  一向
    一向 (楼主)
    2020-12-02 07:00

    A Macro Solution:


    Edit:

    The operate gq{motion} auto-formats to whatever the variable "textwidth" is set to. This is easier/better than using the 80lBi^M I have for my macro.


    If you have autoindent enabled

    :set autoindent
    

    Then entering a return at the end of a line will indent the next line the same amount. You can use this to hard enter in linewraps if you'd like. The following macro takes advantage of this to automatically indent your text:

    set register z to:

    gg/\v^.{80,}$^M@x (change 80 to whatever length you want your text to be)
    

    and set register x to:

    80lBi^M^[n@x (change 80 to whatever length you want your text to be)
    

    Then do

    @x   
    

    to activate the macros. After a few seconds you're text will all be in properly indented lines of 80 characters or less.

    Explanation:

    Here's a dissection of the macros:

    Part 1 (macro z):

    gg/\v^.{80,}$^M@x
    
    gg - start at the top of the file (this avoids some formatting issues)
    /  - begin search
    \v - switch search mode to use a more generic regex input style - no weird vim 'magic'
    ^.{80,}$ - regex for lines that contain 80 or more characters
    ^M - enter - do the search (don't type this, you can enter it with ctrl+v then enter)
    @x - do macro x
    

    Part 2 (macro x):

    80lBi^M^[n@x
    
    80l - move right 80 characters
    B   - move back one WORD (WORDS include characters like "[];:" etc.)
    i^M - enter insert mode and then add a return (again don't type this, use ctrl+v)
    ^[  - escape out of insert mode (enter this with ctrl+v then escape)
    @x  - repeat the macro (macro will run until there are no more lines of 80 characters or more)
    

    Caveats:

    • This macro will break if the there's a WORD that is 80 characters or longer.

    • This macro will not do smart things like indent lines past tags.

    • Use the lazyredraw setting (:set lazyredraw) to speed this up

提交回复
热议问题