Vim: Get the Text from Visual Selection

Edit

Published on March 05, 2022

Author: Meet Rajesh Gor

#vim

Using Registers

We can get the selected text in a variable in Vim Script using registers.


vimscript
normal gv"xy
let context = getreg("x")

Lets break down the command


normal mode -> gv -> (y)ank text -> to the "x" register
               |                  |
               |               Copy the contents into x register(or any register you like)    
               |                  
            Select the previously selected text   

Here, we are entering normal mode and selecting text which was previously selected and yank the contents into a register in this case we are using (x) register, it can be any register. Now to get the contents of that register we can use the function getreg("register_name") or use "xp" to paste the contents of the x register or more generally for any register("<register-name>p).

Hence we can store the contents of the selected text in a variable for further processing or manipulation.

To quickly test this snippet from command mode, you can try the following steps:

Select a text and press Escape, we just want the gv command to refresh and get it's contents to the latest visual selection.


vimscript
:normal! gv"xy

vimscript
:let foo = getreg("x")

vimscript
:echo foo

The echo command will simply print the text which we have selected in the file.

Visual Select Text

<a class='prev' href='/python-dict-to-csv-table'>

    <svg width="50px" height="50px" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M13.5 8.25L9.75 12L13.5 15.75" stroke="var(--prevnext-color-angle)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> </path>
    </svg>
    <div class='prevnext-text'>
        <p class='prevnext-subtitle'>prev</p>
        <p class='prevnext-title'>Turn Python dictionary into a neat CSV table</p>
    </div>
</a>

<a class='next' href='/django-app-from-scratch'>

    <div class='prevnext-text'>
        <p class='prevnext-subtitle'>next</p>
        <p class='prevnext-title'>Django App from Scratch Using Docker with Debian Base Image</p>
    </div>
    <svg width="50px" height="50px" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M10.5 15.75L14.25 12L10.5 8.25" stroke="var(--prevnext-color-angle)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
    </svg>
</a>