Emacs 之迷你 Vue 模式

最近在大量写 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+回车键 快速切换不同的语言模式了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值