如何获取绝对文件名的非目录部分?

How to get nondirectory part of absolute file name?

我想问一下如何从lisp中的交互式命令中获取文件名。

顺便说一句,这是取自另一个 Whosebug 线程。

Paste an image on clipboard to Emacs Org mode file without saving it

(defun markdown-insert-clipboard-image (&optional file)
  (interactive "G")
  (shell-command (concat "pngpaste " file))
  (insert (concat "![" file "](" file ")")))

我的问题是文件使用绝对路径而不仅仅是文件名导致文件在推送到服务器时出现错误。

而不是仅 yahoocom.png, 我得到

/Users/test/test/test/test/yahoocom.png

我只想得到

yahoocom.png

我是否可以修改代码,使其仅使用文件名。

我想你要找的是file-name-nondirectory:

Return file name FILENAME sans its directory. For example, in a Unix-syntax file name, this is everything after the last slash, or the entire name if it contains no slash.

请注意,您可能 而不是 想要将基本名称传递给 shell-command(使用原始绝对路径或 file-relative-name)

PS。我建议您在 interactive 表单中将 "G" 替换为 "fImage file name: ",因为如果 file 不存在,您的函数将失败。

虽然 sds 的回答确实给出了您直接要求的内容,但我认为您真正想要的可能是拥有文件的相对名称(如果文件在当前工作中,这将是相同的)目录)。如果是这样,请尝试 file-relative-name:

Convert FILENAME to be relative to DIRECTORY (default: default-directory).
This function returns a relative file name that is equivalent to FILENAME when used with that default directory as the default.
If FILENAME is a relative file name, it will be interpreted as existing in default-directory.
If FILENAME and DIRECTORY lie on different machines or on different drives on a DOS/Windows machine, it returns FILENAME in expanded form.