1

Having some text selected in visual mode, I need some way of turning it into a string that can be used in an expression.

I have tried this

function! VisualSelection()
    normal! `<""y`>
    return @"
endfunction

and it works by itself, but when I want to use it in a mapping vim complains because of the normal command, which, guess what, can't be used in mappings with <expr>, so I need some different way of doing this.

I've found out that it is possible to find mark positions with regex like \%'< and \%'> but I don't know how to find regex in the file in an expression (match wants a string, and I haven't found any similar function that searches in the file itself)

  • pd: stack exchange markup is weird; kinda like markdown yet not really. I miss my ```<language> ... ``` for multiline code :'( – DarkWiiPlayer Oct 31 '17 at 10:00
  • 1
    Just FYI, fenced code blocks aren't part of Markdown; they were added by later variants. (I think first by MultiMarkdown?) StackExchange's markdown dialect is pretty close to the original. – Rich Oct 31 '17 at 11:42
3

Your question is a duplicate of https://stackoverflow.com/questions/1533565/how-to-get-visually-selected-text-in-vimscript on SO.

Two solutions, plus many variations, have been provided and discussed.

  • One based on manual decoding on text in between getpos() results,
  • and the traditional one based on normal! gv"ay, with restoration of register and so on.

    function! lh#visual#selection() abort
      try
        let a_save = @a
        silent! normal! gv"ay
        return @a
      finally
        let @a = a_save
      endtry
    endfunction
    
  • Thanks a lot for that link, I tried one of the solutions and it works. As for the second solution you mention, that one doesn't work (sadly) because vim doesn't like it and throws an error (E523), as I mentioned in my question. – DarkWiiPlayer Oct 31 '17 at 11:53
  • Should probably use getreg/getregtype in this case, if writing a plugin – Mass Oct 31 '17 at 12:27
  • @DarkWiiPlayer, Sorry, I didn't think your code will work, and it does. As such I dismissed the <expr> part of your question. My mistake. – Luc Hermitte Oct 31 '17 at 13:35
  • @Mass, the thing is the code as been working for quite sometime now, long before getreg() and all. So far I haven't been in a use case where I need more precision. I'll need to investigate further. – Luc Hermitte Oct 31 '17 at 13:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.