Emacs

如何在正在執行的 emacs 中打開特定行的文件?

  • March 15, 2022

可以從命令行執行 emacs 以在第 n 行打開文件,並使用+n如下命令行參數:

$ emacs +n file

我想通過find-file或其他方式從正在執行的 emacs 實例做同樣的事情。那可能嗎 ?

在 emacs wiki 上找到了一個解決方案,該解決方案將增強 ffap 以選擇行號並在找到文件後轉到該文件號。

; 
; have ffap pick up line number and goto-line
; found on emacswiki : https://www.emacswiki.org/emacs/FindFileAtPoint#h5o-6
; 

(defvar ffap-file-at-point-line-number nil
 "Variable to hold line number from the last `ffap-file-at-point' call.")

(defadvice ffap-file-at-point (after ffap-store-line-number activate)
 "Search `ffap-string-at-point' for a line number pattern and
save it in `ffap-file-at-point-line-number' variable."
 (let* ((string (ffap-string-at-point)) ;; string/name definition copied from `ffap-string-at-point'
        (name
         (or (condition-case nil
                 (and (not (string-match "//" string)) ; foo.com://bar
                      (substitute-in-file-name string))
               (error nil))
             string))
        (line-number-string 
         (and (string-match ":[0-9]+" name)
              (substring name (1+ (match-beginning 0)) (match-end 0))))
        (line-number
         (and line-number-string
              (string-to-number line-number-string))))
   (if (and line-number (> line-number 0)) 
       (setq ffap-file-at-point-line-number line-number)
     (setq ffap-file-at-point-line-number nil))))

(defadvice find-file-at-point (after ffap-goto-line-number activate)
 "If `ffap-file-at-point-line-number' is non-nil goto this line."
 (when ffap-file-at-point-line-number
   (goto-line ffap-file-at-point-line-number)
   (setq ffap-file-at-point-line-number nil)))

您可以編寫自己的函式:

(defun find-file-at-line (file line)
 "Open FILE on LINE."
 (interactive "fFile: \nNLine: \n")
 (find-file file)
 (goto-line line))

引用自:https://unix.stackexchange.com/questions/691444