[小函数分享]我再也不想手动输入` = `了

有天突然发现自己会写很多很多很多的赋值语句,于是会输入很多很多=,要按三个键,而且其中等号还不是很好按。为什么不用个按键一下子insert它们呢?

简单写了个函数,根据光标所在位置猜测用户想把当前内容作为left value还是right value。另有js版本会在a = b const a = b let a = b之间切换。js版本的效果:assignment

代码如下:
普通版:

(defun jester/make-simple-assignment ()
  "Make a assignment statement,
using things left of point as left value, things right as right value.

If nothing is at left, move point to the left value's position,
otherwise move to before semicolon."
  (interactive)
  (let ((need-signs (save-excursion (beginning-of-line-text) (not (looking-at ".*=.*$"))))
        (something-left-p (not (looking-back "^\s*"))))
    (save-excursion
      (when need-signs
          (progn (insert " = "))))
    (when (and need-signs something-left-p) (move-end-of-line 1))))

js版:

(defun jester/make-javascript-assignment ()
  "Make a javascript assignment statement,
using things left of point as left value, things right as right value.

If nothing is at left, move point to the left value's position,
otherwise move to before semicolon.

If this line is already an assignment (has a \"=\"), cycle through styles in this order:
  an assignment without \"const\" or \"let\",
  a \"const\" assignment,
  a \"let\" assignment."
  (interactive)
  (let ((need-signs (save-excursion (beginning-of-line-text) (not (looking-at ".*=.*$"))))
        (something-left-p (not (looking-back "^\s*"))))
    (save-excursion
      (if need-signs
          (progn (insert " = ") (move-end-of-line 1)
                 (unless (looking-back ";") (insert ";")))
        (beginning-of-line-text)
        (cond
         ((looking-at "const ") (kill-word 1) (insert "let"))
         ((looking-at "let ") (kill-word 1) (delete-char 1))
         (t (insert "const ")))))
    (when (and need-signs something-left-p) (move-end-of-line 1) (left-char))))

bonus: 一开始用yas写出$1 ? $2 : $0,后来发现有点不对劲,总是第一个单词写完了才想用这个snippet。后来发现了yas-expand-snippet,世界又美好了:

(defun jester/expand-to-ternary ()
  "Add a ternary expression, using the symbol before point as the first field."
  (interactive)
  (yas-expand-snippet " ? $1 : $0"))

bonus’: 又发现key: val,出现的频率很高,回想了一下,以前都是copy这一行后粘贴好多份,然后一个个改key和val。为什么不一键输入: ,呢?

(defun jester/make-key-value-pair ()
  "Make a key-value pair, by inserting \": ,\" at point.
Effectively using symbol before point as the key."
  (interactive)
  (insert ": ,") (backward-char))

类似帖子:

6 个赞

emacs使人变懒,哈哈