How can I save a text block in visual mode to a file in Vim?

后端 未结 8 2134
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 18:54

The title is very descriptive. Just in case, I will give an example:

START BLOCK1
something
END BLOCK1

START BLOCK2
something
somenthing...
END BLOCK2
         


        
8条回答
  •  伪装坚强ぢ
    2020-12-23 19:08

    Vim get the visual selection and save to a file:

    function! Get_visual_selection()
        #Get the position of left start visual selection
        let [line_start, column_start] = getpos("'<")[1:2]
        #Get the position of right end visual selection
        let [line_end, column_end] = getpos("'>")[1:2]
        #gotta catch them all.
        let lines = getline(line_start, line_end)
        if len(lines) == 0
            return ''
        endif
        #edge cases and cleanup.
        let lines[-1] = lines[-1][: column_end - 2]
        let lines[0] = lines[0][column_start - 1:]
        return join(lines, "\n")
    endfunction
    
    function Save_visually_selected_text_to_file()
        let selected_text = Get_visual_selection()
        call writefile(split(selected_text, "\n"), "/tmp/something.txt")
    endfunction
    
    #the c-u does a union of all lines in visual selection.
    #this goes in the vimrc
    vnoremap  :call Save_visually_selected_text_to_file()
    

提交回复
热议问题