在emacs中实现kill word或line函数

时间:2013-06-04 10:40:00

标签: emacs elisp

如何在emacs中实现一个杀死一个单词的函数,然后如果立即再次调用它会杀死整行,可能称为kill-word-or-line。我有点像一个elisp n00b,但如果有人能指出一个行为类似的函数,即连续两次调用时有不同的行为,我自己也可以这样做。

如果杀死线版本被调用,那么杀戮戒指包含整行将是好的,即我想在杀死该行之前需要再次插入被杀死的单词。这是一个例子:('|'表示点位置)

This is an exam|ple line.

第一次打电话kill-word-or-line得到类似的东西......

This is an | line.

再次致电kill-word-or-line以获得......

|

杀戮戒指应包含exampleThis is an example line.

2 个答案:

答案 0 :(得分:4)

last-command变量包含交互式执行的最后一个命令,您可以使用它来测试是否连续两次调用相同的命令:

(defun kill-word-or-line ()
  (interactive)
  (if (eq last-command 'kill-word-or-line)
      (message "kill line")
    (message "kill word")))

此机制用于undo

的实现中

答案 1 :(得分:2)

您可以在kill-region上使用以下建议来杀死所选区域,或者首先杀死该点,然后杀死整行。

杀死单词或行
(defadvice kill-region (before slick-cut-line first activate compile)
  "When called interactively kill the current word or line.

Calling it once without a region will kill the current word.
Calling it a second time will kill the current line."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
    (if (eq last-command 'kill-region)
        (progn
          ;; Return the previous kill to rebuild the line
          (yank)
          ;; Add a blank kill, otherwise the word gets appended.
          ;; Change to (kill-new "" t) to remove the word and only
          ;; keep the whole line.
          (kill-new "")
          (message "Killed Line")
          (list (line-beginning-position)
                (line-beginning-position 2)))
      (save-excursion
        (forward-char)
        (backward-word)
        (mark-word)
        (message "Killed Word")
        (list (mark) (point)))))))

这是一样的,但是复制而不是杀戮。

复制单词或行
(defadvice kill-ring-save (before slick-copy-line activate compile)
  "When called interactively with no region, copy the word or line

Calling it once without a region will copy the current word.
Calling it a second time will copy the current line."
    (interactive
     (if mark-active (list (region-beginning) (region-end))
       (if (eq last-command 'kill-ring-save)
           (progn
             ;; Uncomment to only keep the line in the kill ring
             ;; (kill-new "" t)
             (message "Copied line")
             (list (line-beginning-position)
                   (line-beginning-position 2)))
         (save-excursion
           (forward-char)
           (backward-word)
           (mark-word)
           (message "Copied word")
           (list (mark) (point)))))))

两者都改编自this blog post中的命令。