1

I have configured a keyboard shortcut using xbindkeys to run a python script.

Now, while editing any vim file if that user press that keyboard shortcut-

  • I want my python script to run this command to paste the path and line no to the system clipboard-

    :let @+=expand("%") . ':' . line(".")

  • Then I want my script to copy that path from the system clipboard and process it further

Can you please suggest me a good solution for this. Thanks In advance

3
  • 1
    If you want copy to the system clipboard then you could use this command os.system("echo 'hello world' | pbcopy") Commented Jul 6, 2013 at 5:08
  • @kylek Thanks for replying, any idea about the first part, that is more important to me. Commented Jul 6, 2013 at 5:29
  • @kylek i am on linux and this worked for me link Commented Jul 6, 2013 at 5:33

2 Answers 2

1

This works on my machine (OSX):

function! CopyToClipboard()
    py << EOF
import vim, os
# evaluate a vim expression and save its value to a variable
path_line = vim.eval('expand("%") . ":" . line(".")')
# copy the string to the clipboard
os.system("echo '%s' | pbcopy" % path_line)

# do additional stuff with path_line here

EOF
endfunction

An example keybinding:

nnoremap ,c :call CopyToClipboard()<CR>

Have a look at this link for further information on the python/vim interface: http://vimdoc.sourceforge.net/htmldoc/if_pyth.html and, of course, :h python.

If your script is quite long, I would recommend putting everything in separate python-only files.

:h pyfile

Should help in this case.

Sign up to request clarification or add additional context in comments.

2 Comments

Can I invoke this script using a keyboard shortcut say using ctrl + shift + e or i can invoke it from vim only. And where did you place this file and what extension did you used .py ?
You can invoke it with a keybinding from within vim. You could place the function (and the keybinding) in your .vimrc. If you place it in a file with file extension .vim, you just have to make sure vim reads (sources) the file on startup. See :h source. As I said, you can put the python only code inside a .py file and load it with pyfile.
1

You should be using Vim's Python API, not an external Python script. see :h python. You can access all that info directly through its functions. You can evaluate a vim command with vim.command() to interface with the clipboard.

There are other ways to get at the clipboard using e.g. PyGTK, or perhaps more directly through python-xlib, but would probably be more difficult.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.