Emacs Lisp: Open File Path Under Cursor Fast

Master emacs+lisp, benefit for life. Testimonials. Thank you for support.
, ,

Emacs has a command ffap. When your cursor is on a file path or URL, it'll open the file. This is extremely useful in shell output or in HTML file.

One problem is that it'll prompt to confirm. This is annoying. Also, the command itself doesn't have a key.

You can write a similar command that doesn't need confirmation. Here's the code.

(defun open-file-at-cursor ()
  "Open the file path under cursor.
If there is text selection, uses the text selection for path.
If the path is starts with “http://”, open the URL in browser.
Input path can be {relative, full path, URL}.
This command is similar to `find-file-at-point' but without prompting for confirmation.
  (let ( (path (if (use-region-p)
                   (buffer-substring-no-properties (region-beginning) (region-end))
                 (thing-at-point 'filename) ) ))
    (if (string-match-p "\\`https?://" path)
        (browse-url path)
      (progn ; not starting “http://”
        (if (file-exists-p path)
            (find-file path)
          (if (file-exists-p (concat path ".el"))
              (find-file (concat path ".el"))
            (when (y-or-n-p (format "file doesn't exist: 「%s」. Create?" path) )
              (find-file path )) ) ) ) ) ))

Be sure to give it a easy key. 〔☛ Emacs: How to Define Keys

Like what you read?
Buy Xah Emacs Tutorial
or share some
blog comments powered by Disqus