Home > Software design >  Breaking long lines at ~80 characters and prepending characters to each new line
Breaking long lines at ~80 characters and prepending characters to each new line

Time:11-20

I have a few really long lines of text that I'd basically like to hard wrap (break) at word boundaries before or on the 80 character mark. However, I also need to prepend characters to each newly broken line, like so:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque viverra euismod pulvinar. Fusce quis nibh commodo, commodo massa eu, ultricies nisi. Phasellus ac nulla odio.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque viverra
    \ euismod pulvinar. Fusce quis nibh commodo, commodo massa eu, ultricies
    \ nisi. Phasellus ac nulla odio.

I've found many methods to break long lines, but none that I've been able to modify to generate output like the above, and I can't simply tack it on after the fact because that would expand the lines beyond 80 characters again.

Can anyone recommend a Vim-compatible regex or native commands to do the above formatting? Something using sed or fmt or other external tools also welcome, but something I can use within Vim would be preferred in this case.

What I've found and tried so far:

I'm sure there's something fairly simple I'm missing, but stuck on how to do that conditional format to break at essentially the last space before 80 characters. Any suggestions would be very much appreciated. Thanks.

CodePudding user response:

You need to amend two things:

  • Replace the exactly 80 quantifier with zero to 80 quantifier, \{0,80} (or \{0,78}as it seems you want to have 80-2=78 limit since \t\\ will be two additional chars that you want to insert)
  • Add a trailing word boundary at the end, \>
  • Add \t\\ to the replacement pattern to insert a TAB char and \ in the created lines.

You can use

:%s/.\{0,78}\>/&\r\t\\/g

CodePudding user response:

A verbose awk command may also do the job well:

awk -v n=76 '
{
   len = 0
   for (i=1; i<=NF;   i) {
      len  = 1   length($i)
      printf "%s", $i
      if (len > n && i < NF) {
         printf "%s\t\\ ", ORS
         len = 6
      }
      else
         printf "%s", OFS
    }
    print ""
}' file

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque viverra
    \ euismod pulvinar. Fusce quis nibh commodo, commodo massa eu, ultricies
    \ nisi. Phasellus ac nulla odio.

For the 2nd sample provided below I get this output:

_Array1DToHistogram _ArrayAdd _ArrayBinarySearch _ArrayColDelete _ArrayColInsert
    \ _ArrayCombinations _ArrayConcatenate _ArrayDelete _ArrayDisplay _ArrayExtract
    \ _ArrayFindAll _ArrayInsert _ArrayMax _ArrayMaxIndex _ArrayMin _ArrayMinIndex
    \ _ArrayPermute _ArrayPop _ArrayPush _ArrayReverse _ArraySearch _ArrayShuffle

and length of each line is:

80
80
79
79
  • Related