Emacs Lisp

Table of Contents

参考:




判断「相等」

数字比较 (= 1 1)
字符串比较 (equal “abc” “abc”)
数组比较(比较内部元素) (equal [1 2 3] [1 2 3])
列表比较(比较内部元素) (equal ’(a b c) ’(a b c))
对象比较(比较地址) (eq ’a ’a)

网络请求

;; 同步网络请求
(with-current-buffer
    (url-retrieve-synchronously "http://www.baidu.com")
  (let ((data (buffer-string)))
    (message "%s" data)))

;; 异步网络请求
(url-retrieve "http://www.baidu.com"
              (lambda(status) (message "%s" (buffer-string))))

创建进程

(with-current-buffer (get-buffer-create "*baidu.com*")
  (erase-buffer)
  (make-process
   :name "baidu"
   :buffer (current-buffer)
   :command '("curl" "-s" "www.baidu.com")
   :connection-type 'pipe)
  (switch-to-buffer-other-window "*baidu.com*"))

Lisp 的引号使用

`' 类似,但 ` 可以和 ,@ 配合展开部分内部宏

' 用来表示后面跟着符号(symbol)
参考 https://emacs-china.org/t/namespace/8402
` 其实是一个宏 backquote 的别名 (backquote.el)
(defalias '\` (symbol-function 'backquote))
比如 `(1 2 3) 其实就是 (backquote (1 2 3))

For example:

b              => (ba bb bc)		; assume b has this value
`(a b c)       => (a b c)		; backquote acts like quote
`(a ,b c)      => (a (ba bb bc) c)	; insert the value of b
`(a ,@b c)     => (a ba bb bc c)	; splice in the value of b

Vectors work just like lists.  Nested backquotes are permitted.
(apply #'+ `(1 ,@(number-sequence 2 4) 5))
`(a (+ 3 4) ,(+ 3 4))

#’foo 函数声明

下列三种写法功能相同

(lambda (x) (* x x))
(function (lambda (x) (* x x)))
#'(lambda (x) (* x x))

#' 是 function 宏的简写,用于引用一个函数对象, #'lambda 会创建一个函数对象。

(defvar square #'(lambda (x) (* x x)))
(funcall square 3) ;; 返回 9

(defvar square '(lambda (x) (* x x)))
(funcall square 3) ;; 会导致错误,因为 square 不是一个函数对象

在需要引用函数的地方使用 #'

编写一个 major mode

(define-derived-mode new-plugin-mode text-mode "new-plugin"
  (interactive)
  (kill-all-local-variables)                  ; 删除 buffer 下所有的局部变量, 避免其他 mode 的干扰
  (setq major-mode 'new-plugin-mode)          ; 设置当前的 mode 为 new-plugin-mode
  (setq mode-name "new-plugin")               ; 设置 mode 的名称
  (new-plugin-highlight-keywords)             ; 根据正则表达式提供语法高亮
  (use-local-map new-plugin-mode-map)         ; 加载 mode 对应的快捷键
  (run-hooks 'new-plugin-mode-hook))          ; 加载 mode 对应的 hook, 注意 new-plugin-mode-hook 会自动生成

(defvar new-plugin-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map (kbd "M-m") #'new-plugin-function)   ; 绑定 new-plugin-function 函数到快捷键 Alt-m 上
    map)
  "Keymap used by `new-plugin-mode'.")

(defun new-plugin-highlight-keywords ()
  "Highlight keywords."
  ;; Add keywords for highlight.
  (font-lock-add-keywords
   nil
   '(
     ("regexp-string" . 'font-lock-constant-face)   ; 当 buffer 内容匹配正则, 就会自动按照 font-lock-constant-face 提供颜色高亮
     ))
  ;; Enable font lock.
  (font-lock-mode 1))                               ; 开启语法高亮