Usando el método en la respuesta proporcionada por Steve Moyer, pude producir la siguiente solución. Es un truco bastante poco elegante, me temo, y creo que debe haber una solución más ordenada, pero funciona, y es mucho más rápido que simplemente contar todas las palabras en un buffer cada vez que se actualiza la línea de estado. También debo señalar que esta solución es independiente de la plataforma y no supone que un sistema tenga 'wc' o algo similar.
Mi solución no actualiza periódicamente el búfer, pero la respuesta proporcionada por Mikael Jansson podría proporcionar esta funcionalidad. Hasta el momento, no he encontrado una instancia en la que mi solución no esté sincronizada. Sin embargo, solo he probado esto brevemente, ya que un conteo exacto de palabras en vivo no es esencial para mis necesidades. El patrón que uso para emparejar palabras también es simple y está destinado a documentos de texto simples. Si alguien tiene una mejor idea para un patrón o cualquier otra sugerencia, no dude en publicar una respuesta o editar esta publicación.
Mi solución:
"returns the count of how many words are in the entire file excluding the current line
"updates the buffer variable Global_Word_Count to reflect this
fu! OtherLineWordCount()
let data = []
"get lines above and below current line unless current line is first or last
if line(".") > 1
let data = getline(1, line(".")-1)
endif
if line(".") < line("$")
let data = data + getline(line(".")+1, "$")
endif
let count_words = 0
let pattern = "\\<\\(\\w\\|-\\|'\\)\\+\\>"
for str in data
let count_words = count_words + NumPatternsInString(str, pattern)
endfor
let b:Global_Word_Count = count_words
return count_words
endf
"returns the word count for the current line
"updates the buffer variable Current_Line_Number
"updates the buffer variable Current_Line_Word_Count
fu! CurrentLineWordCount()
if b:Current_Line_Number != line(".") "if the line number has changed then add old count
let b:Global_Word_Count = b:Global_Word_Count + b:Current_Line_Word_Count
endif
"calculate number of words on current line
let line = getline(".")
let pattern = "\\<\\(\\w\\|-\\|'\\)\\+\\>"
let count_words = NumPatternsInString(line, pattern)
let b:Current_Line_Word_Count = count_words "update buffer variable with current line count
if b:Current_Line_Number != line(".") "if the line number has changed then subtract current line count
let b:Global_Word_Count = b:Global_Word_Count - b:Current_Line_Word_Count
endif
let b:Current_Line_Number = line(".") "update buffer variable with current line number
return count_words
endf
"returns the word count for the entire file using variables defined in other procedures
"this is the function that is called repeatedly and controls the other word
"count functions.
fu! WordCount()
if exists("b:Global_Word_Count") == 0
let b:Global_Word_Count = 0
let b:Current_Line_Word_Count = 0
let b:Current_Line_Number = line(".")
call OtherLineWordCount()
endif
call CurrentLineWordCount()
return b:Global_Word_Count + b:Current_Line_Word_Count
endf
"returns the number of patterns found in a string
fu! NumPatternsInString(str, pat)
let i = 0
let num = -1
while i != -1
let num = num + 1
let i = matchend(a:str, a:pat, i)
endwhile
return num
endf
Esto se añade a la línea de estado por:
:set statusline=wc:%{WordCount()}
espero que esto ayude a cualquiera que busque un recuento de palabras en vivo en Vim. Aunque uno que no siempre es exacto.¡Alternativamente, por supuesto, g ctrl-g le proporcionará el recuento de palabras de Vim!
¿Cuál es su función actual? –
Para otros que vienen aquí para un conteo general de palabras, use 'g Ctrl-g'. – naught101