在Emacs中替换指定位置的文件

3
我在这里找到了替换文件位置的函数,但似乎无法正常工作:http://www.emacswiki.org/emacs/InsertFileName。它能够正确找到指定位置的文件,但从我看来,它似乎使用了你输入的文件而不是最初检测到的文件。我不确定如何解决这个问题。
如果我在 /home/testfile 上运行该函数,
首先,它会说要替换的文件,例如:/home/secondfile 然后它会说:用'/home/secondfile'替换:/home/secondfile 然后它会说:没有在指定位置找到文件
有什么想法吗?
下面是这个函数:
(autoload 'ffap-guesser "ffap")
(autoload 'ffap-read-file-or-url "ffap")

(defun my-replace-file-at-point (currfile newfile)
"Replace CURRFILE at point with NEWFILE.

  When interactive, CURRFILE will need to be confirmed by user
  and will need to exist on the file system to be recognized,
  unless it is a URL.

  NEWFILE does not need to exist.  However, Emacs's minibuffer
  completion can help if it needs to be.
  " 

(interactive
 (let ((currfile (ffap-read-file-or-url "Replace filename: "
                                        (ffap-guesser))))
   (list currfile
         (ffap-read-file-or-url (format "Replace `%s' with: "
                                        currfile) currfile))))
(save-match-data
  (if (or (looking-at (regexp-quote currfile))
          (let ((filelen (length currfile))
                (opoint (point))
                (limit (+ (point) (length currfile))))
            (save-excursion
              (goto-char (1- filelen))
              (and (search-forward currfile limit
                                   'noerror)
                   (< (match-beginning 0) opoint))
                   (>= (match-end 0) opoint))))
      (replace-match newfile)
    (error "No file at point to replace"))))
2个回答

1

这里可能有几个问题。首先,当您执行此操作时,您的点位置可能不正确。其次,如果您使用/home/user/something,那么/home/user/something和~/something之间可能存在不匹配(ffap返回后者,而在该点上您可能已经写了前者)。

第一点:

使用带引号的正则表达式文件名的looking-at期望点位于开头:例如|/home/user/something

它的伴侣looking-back期望/home/user/something|。 在中间某个地方会引发此错误。

解决此问题的快速方法是将looking-at更改为thing-at-point-looking-at

第二点:

如果您已经编写了/home/user/something,ffap函数(在我的情况下)会使用~进行缩短。可能有一些设置来管理此操作,但我知道的最简单、快速的修复方法是使用expand-file-name。这将处理第一种情况,如果它被写成~/something,save-excursion体将在备用情况下替换它。
我唯一看到的负面结果是,有时您可能会将/home/user/something替换为~/somethingelse。
但无论如何,这两个快速修复只会导致完全更改: (thing-at-point-looking-at (regexp-quote (expand-file-name currfile)))

谢谢!没错,问题就在于如果不使用expand-file-name,它无法正确处理完整路径名。但正如你所说,使用该函数会将其替换为缩短版本。有没有什么简单的方法可以强制它展开已经展开的路径,或者更好的方式是,如果传递给函数的前缀参数(C-u)则只展开文件名呢? - J Spen

0

看不到“ffap-guesser”定义在哪里。看起来像是一个错误。

也许可以尝试使用

“find-file-at-point”


抱歉,我忘记添加自动加载。它在“ffap.el”中定义,但似乎我的问题不在那里。据我所知,它正确地识别了文件指针,但似乎是在替换内容的函数中出现了问题。替换似乎会取代我想要替换的文件而不是原始函数,因此当搜索发生时,它找不到应该替换的内容。我可能对此有所误解。 - J Spen
还添加了一个确切步骤的示例,如果我使用find-file-at-point,我是否可以将其替换为ffap-guesser? - J Spen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接