Nir
Nir

Reputation: 1426

goto-file in Emacs

Is there a substitute in emacs for the vi gf command? I mean to open the file which is under the cursor right now, if a real file name is in fact there.

Upvotes: 56

Views: 16012

Answers (3)

Mehrad
Mehrad

Reputation: 3829

There is a built-in command in Emacs for this called find-file-at-point which is part of ffap.el (you don't need to install it as it is shipped with emacs (at least from Emacs 28.1). You can try it out with M-x find-file-at-point and see how it looks like.

You can also replace it with the default find-file as it behaves like find-file if your point is not on a filepath:

(global-set-key (kbd "C-x C-f") 'find-file-at-point)

Although I suggest against it. You can map it safely to:

(global-set-key (kbd "C-c C-f") 'find-file-at-point)

Upvotes: 0

Nir
Nir

Reputation: 1426

Thanks, it works quite well but somehow the vi (gf) version is still somewhat smarter. I think it looks at some path variable for search paths.

I made something which is needlessly complicated but works for me (only in linux). It uses the "locate" command to search for the path under the cursor. I guess it could be made smarter by searching the relative path to the current file first. sorry for my bad elisp skills...It can probably be achieved in a much nicer way.

put in your .emacs, then use with M-x goto-file

(defun shell-command-to-string (command)
  "Execute shell command COMMAND and return its output as a string."
  (with-output-to-string
    (with-current-buffer standard-output
      (call-process shell-file-name nil t nil shell-command-switch command))))

(defun goto-file ()
  "open file under cursor"
  (interactive)
  (find-file (shell-command-to-string (concat "locate " (current-word) "|head -c -1" )) ))

Upvotes: 8

cjm
cjm

Reputation: 62099

You want the find-file-at-point function (which is also aliased to ffap). It's not bound to a key by default, but you can use

M-x ffap

Or, you can put in your .emacs file:

(ffap-bindings)

This will replace many of the normal find-file key bindings (like C-x C-f) with ffap-based versions. See the commentary in ffap.el for details.

Upvotes: 79

Related Questions