0

So I wanted to basically copy the current selection, then yanking it into find-file, as when using:

  • C-SPC: set-mark-command
  • M-w: kill-ring-save
  • C-x C-f: find-file
  • C-y: yank

While that works great, I wanted to make it into a command if possible, so I tried and came up with this so far:

(define-advice kill-ring-save (:around (old-fun &rest args) highlight)
  "Save the text selection and keep the selection highlight."
  (let (deactivate-mark)
    (apply old-fun args)))

(defun find-file-region () (interactive) (execute-extended-command nil "kill-ring-save" nil) (call-interactively 'find-file) (yank nil))

Now, I'm using this particular kill-ring-save function, mostly because I found it work better than the default one, but that's just what I noticed in my workflow. And also because i didn't know how to use the default one in this particular endeavor

So this doesn't obviously work, my guess being is that it doesn't run yank after running (call-interactively 'find-file)

I've tried:

  • using default find-file but since it require a filename and doesn't just "open with current directory of the buffer/file" like it usually do if used in the keybinding, that didn't work either.

  • was replacing (call-interactively 'find-file) with (execute-extended-command nil "find-file" nil) but it did the same thing as far as I'm aware (that is, it didn't work either).

Question

How could I pass the current selection/region (from C-SPC) to find-file and open the file whether it exists or not? (since usually, I recall find-file creates the file if it doesn't exist, which is what I want too).

Don't really care if it's done interactively or in the background, as I just did that to tinker around and see if it'll work.

Nordine Lotfi
  • 357
  • 2
  • 13

1 Answers1

1

The main problem lies in yanking nowhere useful because it'll yank after call-interactively returns, not inside its execution.

Basically you don't need anything else than calling this if you already have done M-w on region, as it actually adds it to kill-ring.

(defun find-file-region()
 (interactive)
 (find-file (substring-no-properties (car kill-ring))))

The idea is passing the equivalent of pop'ing the kill-ring without discarding it.

Or you can skip the kill-ring steps using region's content making use of a similar approach.

(defun find-file-region()
  (interactive)
  (if (region-active-p)
    (let ((str (buffer-substring (region-beginning) (region-end))))
      (find-file str))
    (message "No region active")))
Muihlinn
  • 2,614
  • 1
  • 15
  • 22