Search code examples
searchemacsselectioncopy-paste

In emacs incremental search, how can I cut the highlighted selection to the kill ring?


In Emacs's incremental search (C-s), C-w will append the next word to the search. I can then copy the highlighted text to the kill ring using M-w, but because C-w is in incremental-search mode and appending the next word, I can't use it to cut the highlighted selection to the kill ring.

Is there a quick way to exit incremental search but keep the search text highlighted at point so I can use C-w to kill it? Or an incremental search command I missed that will do this?

--- Update: From the comments I think my question wasn't totally clear. I'd like to be able to cut from the buffer any particular instance of the search string while doing an incremental search. So, C-s, C-w C-w to append words, C-s C-s to find an occurrence, then cut that instance. Or, just C-s C-w C-w, and then cut, to use isearch as a shortcut to highlight the text at point that I'd like to cut. Regarding the comments about M-e, that doesn't cut the text from the buffer, which was the heart of my original question - how to cut as opposed to copy.


Solution

  • (define-key isearch-mode-map (kbd "M-s M-w") #'my-isearch-copy-match)
    (define-key isearch-mode-map (kbd "M-s C-w") #'my-isearch-kill-match)
    
    (defun my-isearch-copy-match ()
      "Copy the currently-matched text to the kill ring."
      (interactive)
      (kill-new (buffer-substring (min (point) isearch-other-end)
                                  (max (point) isearch-other-end))))
    
    (defun my-isearch-kill-match ()
      "Kill the currently-matched text."
      (interactive)
      (kill-region (min (point) isearch-other-end)
                   (max (point) isearch-other-end)))
    

    If you want these commands to automatically drop out of the isearch, then add a call to (isearch-exit) at the end of each function.

    The M-sM-w key binding shadows eww-search-words in the global keymap, but it just seems like the correct binding for this command (and it's easy enough to drop out of isearch normally with RET if you ever want to call the eww command whilst isearching).