Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

command - longest line in vim?

Is there a command to determine length of a longest line in vim? And to append that length at the beginning of the file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Gnu's wc command has a -L --max-line-length option which prints out the max line length of the file. See the gnu man wc. The freebsd wc also has -L, but not --max-line-length, see freebsd man wc.

How to use these from vim? The command:

:%!wc -L

Will filter the open file through wc -L and make the file's contents the maximum line length.

To retain the file contents and put the maximum line length on the first line do:

:%yank
:%!wc -L
:put

Instead of using wc, Find length of longest line - awk bash describes how to use awk to find the length of the longest line.

Ok, now for a pure Vim solution. I'm somewhat new to scripting, but here goes. What follows is based on the FilterLongestLineLength function from textfilter.

function! PrependLongestLineLength ( )
  let maxlength   = 0
  let linenumber  = 1
  while linenumber <= line("$")
    exe ":".linenumber
    let linelength  = virtcol("$")
    if maxlength < linelength
      let maxlength = linelength
    endif
    let linenumber  = linenumber+1
  endwhile

  exe ':0'
  exe 'normal O'
  exe 'normal 0C'.maxlength
endfunction

command PrependLongestLineLength call PrependLongestLineLength()

Put this code in a .vim file (or your .vimrc) and :source the file. Then use the new command:

:PrependLongestLineLength

Thanks, figuring this out was fun.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...