Search code examples
vimword-wrap

Word wrapping a txt file in vim not working as expected


I am trying to edit a file on vim. You can download the txt file here.

I am following the instructions on this blog. I am also using what I read on StackOverflow.

First, I did this inside vim (command mode):

:set textwidth=80

Second, I used visual mode v to select all lines in the file. I started at the first line and the pressed G (goes to the last line). This made all the file selected.

Third, to reformat it, I did:

gq 

Ok, the text is close to what I want. However, when I do this:

:echo max(map(range(1, line('$')), "col([v:val, '$'])")) - 1

The output is:

90

The command above shows me the length in characters of the lengthiest line. The output should be 80, not 90!

What I set as the limit of the text wrap was: 80

What mistake am I making? How can I wrap the text to 80 columns?

I started to use Vim this week. I am sorry if this question is too naive.


Solution

  • Your text width and reformatting is working fine, but the expression col is actually counting the "byte index" of the column position at the end of each line (not the character position). See :help col for all the info you need on how col works.

    Instead, try using a character counting function like strchars: echo max(map(range(1, line('$')), "strchars(getline(v:val))"))

    On your example text I get an output of 83 because of the way the wrapping works on whitespace which count as characters. To take care of that, you could trim trailing whitespace with something like :%s/\s*$//, and now my example expression above using strchars returns 80 as expected.