Open a file at line with "filename:line" syntax

Very often, compilations errors are displayed with the file:line syntax.

It would be nice to copy-paste this directly to open the file at the right line.

Emacs already has some mode to handle this in buffers (compile-mode, iirc), but I would like to have this available from the shell command line, since I use the standard shell most of the time outside of emacs.

Any idea how to tweak emacs to learn file:line syntax to open file at line line? (obviously, if file:line really exists on disk, it should be opened preferably)


You can do this using emacsclient. e.g. to open FILE at line 4, column 3 in a new frame:

emacsclient +4:3 FILE

Leave off the :3 to simply open the file at line 4.


I have the following in my .emacs, but I haven't found it as useful as I thought it would be.

;; Open files and goto lines like we see from g++ etc. i.e. file:line#
;; (to-do "make `find-file-line-number' work for emacsclient as well")
;; (to-do "make `find-file-line-number' check if the file exists")
(defadvice find-file (around find-file-line-number
                             (filename &optional wildcards)
                             activate)
  "Turn files like file.cpp:14 into file.cpp and going to the 14-th line."
  (save-match-data
    (let* ((matched (string-match "^\\(.*\\):\\([0-9]+\\):?$" filename))
           (line-number (and matched
                             (match-string 2 filename)
                             (string-to-number (match-string 2 filename))))
           (filename (if matched (match-string 1 filename) filename)))
      ad-do-it
      (when line-number
        ;; goto-line is for interactive use
        (goto-char (point-min))
        (forward-line (1- line-number))))))