How to set gvim’s window width to 80 columns of text, plus the ones needed to show the line number


I use gvim with

set number

in my .vimrc so it shows the linenumber, plus a space, before every line.

If the document has less than 10 lines, this takes 2 columns, If it has more than 10, 3 columns and so on.

If I put

set lines=40 columns=80

in .gvimrc, it will show 78 columns of code and 2 for the linenumber plus pace, or 77 + 3 and so on.

I'd like the window width to be set to 80 columns + whatever number of columns are necessary to show the linenumber.

It doesn't need to be dynamic, but I'd like to be able to read the number of lines of a given file and set columns according. (Of course, a dynamic solution would be really neat, but not essential)

Best Answer

Try this in your ~/.vimrc:

au BufRead * let &numberwidth = float2nr(log10(line("$"))) + 2
          \| let &columns = &numberwidth + 80

Every time you load a buffer (i.e., open a file), that will determine the number of columns required to show the largest line number, set the 'numberwidth' option accordingly, and set 'columns' to that number plus 80 for your text.