Skip to content

Instantly share code, notes, and snippets.

@atripes
Created May 19, 2017 16:35
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save atripes/15372281209daf5678cded1d410e6c16 to your computer and use it in GitHub Desktop.
Save atripes/15372281209daf5678cded1d410e6c16 to your computer and use it in GitHub Desktop.
URL encode/decode vim selection.
" URL encode/decode selection
vnoremap <leader>en :!python -c 'import sys,urllib;print urllib.quote(sys.stdin.read().strip())'<cr>
vnoremap <leader>de :!python -c 'import sys,urllib;print urllib.unquote(sys.stdin.read().strip())'<cr>
@Bhupesh-V
Copy link

Clever trick 👌
If someone ends up here looking for a native Vimscript solution

function! UrlEncode(mystring)
let urlsafe = ""
for char in split(join(lines, "\n"), '.\zs')
    if matchend(char, '[-_.~a-zA-Z0-9]') >= 0
        let urlsafe = urlsafe . char
    else
        let decimal = char2nr(char)
        let urlsafe = urlsafe . "%" . printf("%02x", decimal)
    endif
endfor
echo urlsafe
" return urlsafe
endfunction

@brianlehrer-nbcuni
Copy link

I ran into some issues with running the leader commands above with Python 3. These work though:

" URL encode/decode selection
vnoremap <leader>en :!python3 -c 'import sys; from urllib import parse; print(parse.quote_plus(sys.stdin.read().strip()))'<cr>
vnoremap <leader>de :!python3 -c 'import sys; from urllib import parse; print(parse.unquote_plus(sys.stdin.read().strip()))'<cr>

@bennypowers
Copy link

bennypowers commented Nov 13, 2022

if you have nodejs installed

:'<,'>!node -e 'console.log(decodeURIComponent(process.argv[1])))' -- `cat`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment