emacs terminal mode: how to copy and paste efficiently

前端 未结 2 1468
臣服心动
臣服心动 2021-02-13 21:09

I\'m having a hard time making this emacs -nw work effectively under the terminal mode (emacs -nw). Some setup information: The working server is connected via SSH, and emacs i

相关标签:
2条回答
  • 2021-02-13 21:38

    You can accomplish this by using a terminal escape code! There is a unique category of terminal escape codes called "Operating System Controls" (OSC) and one of these sequences (\033]52) is meant for interacting with the system clipboard. The great thing is that your terminal doesn't care where the code came from so it will work in remote sessions as well.

    Most terminal emulators support it (iTerm2, OS X Terminal, and I think all Linux terminals besides GNOME). You can test if your terminal supports this sequence by simply running:

    $ printf "\033]52;c;$(printf "Hello, world" | base64)\a"
    

    Then paste from your system clipboard. If it pastes "Hello, world" then your terminal supports it!

    I have this function in my init.el so when I call yank-to-clipboard Emacs will yank the value from my kill ring into the system clipboard:

    (defun yank-to-clipboard ()
    "Use ANSI OSC 52 escape sequence to attempt clipboard copy"
      (interactive)
      (send-string-to-terminal
        (format "\033]52;c;%s\a"
          (base64-encode-string 
            (encode-coding-string 
              (substring-no-properties 
                (nth 0 kill-ring)) 'utf-8) t))))
    

    As I type this, I stumbled upon an almost-identical script supported by Chromium community: https://chromium.googlesource.com/apps/libapps/+/master/hterm/etc/osc52.el

    For those running Emacs inside Tmux: Tmux consumes the sequence, so you'll need to pipe the sequence to the Tmux active tty for this to work. For more information on how this might work, see: https://sunaku.github.io/tmux-yank-osc52.html

    0 讨论(0)
  • 2021-02-13 22:04

    This is not an ideal solution per se, but i figured out a way that I feel better than the previous one.

    The idea is to get rid of X which causes heavy latency issues, i.e. keep only the following:

    ;; enable clipboard in emacs
    (setq x-select-enable-clipboard t)
    

    The results are:

    1. copy/paste within Emacs is straightforward and fast.

    2. copy from other apps to Emacs: Ctrl+Shift+v

    3. copy from Emacs to other apps: mouse selection is now on X Selection, so right-click and copy shall copy the text into the Selection. Note that 'M-w" now won't copy anything into Selection or system clipboard.

    This is again a compromise rather than a solution, but considering the fact that i copy/paste more often than inter-app operations, this is acceptable at the moment.

    Still looking forward to a good solution!

    0 讨论(0)
提交回复
热议问题