optional的prefix该怎么使用?

(defun my/format-region-or-buffer(&optional column)
  "Perform a bunch of operations on the whitespace content of a buffer.

 Indent region/buffer with COLUMN space(s).
 Including indent-buffer, which should not be called automatically on save."
  (interactive "p")
  (save-excursion
    (let ((column (prefix-numeric-value column)))
      (if (region-active-p)
          (progn
            (untabify (region-beginning) (region-end))
            (delete-trailing-whitespace (region-beginning) (region-end))
            (indent-region (region-beginning) (region-end) column)
            (message "Selected region formatted."))
        (progn
          (untabify (point-min) (point-max))
          (delete-trailing-whitespace)
          (indent-region (point-min) (point-max) column)
          (message "Buffer formatted."))))))

我想让这个函数在有C-u传入参数的时候按照传递的参数进行缩进,没有参数的时候就遵循默认缩进

但是在不输入参数的情况下prefix-numeric-value会返回1,也就导致了不输入参数时默认缩进到一个空格处,有什么办法可以解决这个问题🐎️?

使用 raw prefix argument (elisp) Prefix Command Arguments

(interactive "P")
;; => (nil)

(interactive "p")
;; => (1)

大写 P 是列表,小写 p 是数字。

你的 column 是数字形式的了,只有 raw 形式才需要这个函数。

2 个赞

谢谢

也就是说当使用interactive "P" 时才有使用这个函数的必要是吗?

嗯,小写的 p 得到的参数,应该就相当于把大写的 P 用这个函数转换得到的。

谢谢你的耐心解答 :ghost: