最近在大量写 vue 的单文件组件,而 vue 一个文件有三种模式:html,javascript 和 css 。原来写的少,每次写不同的代码是手动切换,现在终于无法忍受了,于是写了一个简单的小模式,只要在当前行按下 Ctrl+回车键 就可以正常切换到相应的模式,这只是针对我自己的代码,不同编码习惯的代码可能并不适用。
这是在 .emacs
里面增加的代码
;;
;; vue-mode
;;
(define-minor-mode vue-mode
"Toggle Vue mode.
Interactively with no argument, this command toggles the mode.
A positive prefix argument enables the mode, any other prefix
argument disables it. From Lisp, argument omitted or nil enables
the mode, `toggle' toggles the state."
;; The initial value.
nil
;; The indicator for the mode line.
" Vue"
;; The minor mode bindings.
'(([C-return] . vue-smart-set-mode))
:group 'vue)
(defun vue-smart-set-mode ()
(interactive)
(progn
(setq line (buffer-substring (line-beginning-position)
(line-end-position)))
;; If line start with ".", or end with ";"
;; then css-mode
(if (string-match "\\(^ *\\.\\|; *$\\)" line)
(css-mode)
(progn
;; if line start with "<" or end with ">"
;; or start with "xxxx=", no space before "="
;; then html-mode
(if (or
(string-match "\\(^ *<\\|> *$\\)" line)
(string-match "^ *[a-zA-Z:@0-9]+=" line))
(html-mode)
(javascript-mode))))))
(setq auto-mode-alist
(append
'(("\\.vue\\'" . vue-mode))
auto-mode-alist))
(add-hook 'css-mode-hook 'vue-mode)
(add-hook 'html-mode-hook 'vue-mode)
(add-hook 'js-mode-hook 'vue-mode)
基本工作原理就是
- 定义一个小模式 (minor mode)vue-mode ,绑定 Ctrl+回车键 到自定义模式设置函数
- 定义模式设置函数,根据当前行的内容进行设置
- 如果是以
.
开头或者;
结束的行,那么就设置为css-mode
- 如果是以
<
开头或者>
结束的行,那么就设置为html-mode
- 其他情况都设置为
javascript-mode
- 如果是以
- 设置
auto-mode-alist
,打开.vue
文件自动进入vue-mode
- 设置主模式钩子函数,让主模式切换之后自动也打开
vue-mode
这样,就可以随时使用 Ctrl+回车键 快速切换不同的语言模式了。