regexnotepad++

How do I wrap lines in Notepad++ before N symbols?


How can I use a regex find/replace to wrap to new lines so I'll never have more than 20 symbols per line?

I found this:

Find: \s(?<=.{20})
Replace: $0\r\n

It would be perfect, but it leaves words in line bigger than 20 symbols if they started before 20 symbols.

I need a similar expression, but if the last item makes the line bigger it should also go to the new line, so the final line would have always have <20 symbols.

I know I have done it before long ago, perhaps with some plugin, but I can't make it work now. How can I do this?


Solution

  • For word wrap it's kind of subjective where to put the line breaks.

    For N characters, single pass regex it might be :

        (?:
           (?:
              (?>
                 ( .{1,N} )                   # (1)
                 (?:                           #  break types:                                                            
                    $                             # EOS                                                                 
                  | (?<= [^\S\r\n] )              # 1. - Behind a non-linebreak whitespace                           
                    [^\S\r\n]?                    #      ( optionally accept an extra non-linebreak whitespace )     
                  | (?<= [!,./:;?] )              # 2. - Behind sepcial punctuation breaks                              
                    [^\S\r\n]?                    #      ( optionally accept an extra non-linebreak whitespace )     
                  | (?=                           # 3. - Ahead a linebreak or special punctuation breaks                
                       \r? \n                                                                                 
                     | [#%&*\-@_]                                                                                
                    )
                  | [^\S\r\n]                     # 4. - Accept an extra non-linebreak whitespace                    
                 )
              )
            | ( .{1,N} )                   # (2)
           )
           (?: \r? \n )?
         | (?: \r? \n )
        )
    
    (?:(?:(?>(.{1,N})(?:$|(?<=[^\S\r\n])[^\S\r\n]?|(?<=[!,./:;?])[^\S\r\n]?|(?=\r?\n|[#%&*\-@_])|[^\S\r\n]))|(.{1,N}))(?:\r?\n)?|(?:\r?\n))
    

    Replace $1$2\r\n