在函数的交互列表中添加file-exists-p条件

时间:2013-06-13 00:15:21

标签: emacs

我在尝试在此print-to-pdf函数的交互列表中添加if file-exists-p条件时遇到困难。错误消息为:file-name-sans-extension: Wrong type argument: stringp, t。我已经注释掉了有效的部分,但是它却覆盖了现有文件而没有提示是或否。我已尝试将hello-world替换为pdf-file-name,但这并未解决错误。

Emacs Trunk开发人员使用ns-read-file-name在OSX上构建--with-ns,喜欢在没有提示的情况下覆盖文件,除非函数中包含额外的file-exists-p

(defun print-to-pdf (pdf-file-name)
  "Print the current file to the given file."

;; (interactive (list (ns-read-file-name "Write PDF file: " "~/" nil ".pdf")

(interactive (list 

 (let ((hello-world (ns-read-file-name "Write PDF file: " "~/" nil ".pdf")))
            (if (file-exists-p hello-world)
                (or (yes-or-no-p (format "File %s exists. Save anyway? " hello-world))
                (error ""))))

))


  (let (
    (ps-file-name (concat (file-name-sans-extension pdf-file-name) ".ps"))
    (wbuf (generate-new-buffer "*Wrapped*"))
    (sbuf (current-buffer)))
    (jit-lock-fontify-now)
    (save-current-buffer
    (set-buffer wbuf)
    (insert-buffer sbuf)
    (longlines-mode t)
    (harden-newlines)
    (message (buffer-name sbuf))
    (spool-buffer-given-name (buffer-name sbuf))
    (kill-buffer wbuf)
    (switch-to-buffer "*PostScript*")
    (write-file ps-file-name)
    (kill-buffer (current-buffer)))
    (call-process "/usr/local/bin/ps2pdf14" nil nil nil ps-file-name pdf-file-name)
    (delete-file ps-file-name)
    (message "PDF saved to %s" pdf-file-name))
)

1 个答案:

答案 0 :(得分:4)

为什么要首先将其添加到interactive?这样的东西不适合你吗?

(defun print-to-pdf (pdf-file-name)
  "Print the current buffer to the given file as PDF."
  (interactive (list (ns-read-file-name "Write PDF file: " "~/" nil ".pdf")))
  (when (and pdf-file-name
             (or (not (file-exists-p pdf-file-name))
                 (yes-or-no-p "File exists. Overwrite? ")))
    (let ((ps-file-name (concat (file-name-sans-extension pdf-file-name) ".ps"))
          (wbuf (generate-new-buffer "*Wrapped*"))
          (sbuf (current-buffer)))
      (jit-lock-fontify-now)
      (save-current-buffer
        (set-buffer wbuf)
        (insert-buffer sbuf)
        (longlines-mode t)
        (harden-newlines)
        (message (buffer-name sbuf))
        (spool-buffer-given-name (buffer-name sbuf))
        (kill-buffer wbuf)
        (switch-to-buffer "*PostScript*")
        (write-file ps-file-name)
        (kill-buffer (current-buffer)))
      (call-process "/usr/local/bin/ps2pdf14" nil nil nil ps-file-name pdf-file-name)
      (delete-file ps-file-name)
      (message "PDF saved to %s" pdf-file-name))))