Emacs 配置 :使用快捷鍵格式化程式碼
阿新 • • 發佈:2019-01-10
前言
眾所周知,emacs十分自由,可以新增很多的配置。
作為程式設計師,想必都不會想讓自己的程式碼縮排的亂七八糟,但是有時候敲幾個tab還是挺煩人的,那麼,可不可以配置Emacs,讓我們可以用快捷鍵自動格式化程式碼呢?
當然可以
準備工作
- Emacs,版本高於22.0
- Astyle,並且已經將可執行檔案所在目錄加入到壞境變數中,以便Emacs呼叫
Astyle介紹
Emacs本身的程式碼縮排功能不是很理想,我們就藉助第三方的Astyle來格式化程式碼。
Astyle是一個開源程式。可以使用astyle <file name>
並且Atyle還有很多可選項,包括但不限於--style=<java,google,etc>
,具體幫助選項使用astyle -h
檢視
原理
使用Lisp函式獲取當前正在編輯的檔案的名稱。呼叫Astyle格式化程式碼。
程式碼實現
(let ((style "google"))
(setq format-command (format "astyle --style=%s" style)))
(global-auto-revert-mode t)
(defun format-code ()
"Format current buffer"
(interactive)
(let ((file (buffer-file-name)))
(save-excursion
(shell-command-to-string (format "%s %s" format-command file))
(message "Code formatted"))))
(global-set-key "\C-f" 'format-code)
(provide 'init-astyle)
程式碼解釋
format-command
包括Astyle的選項。
(global-auto-revert-mode t)
模式可以令Emacs在磁碟檔案改變之後自動更新快取區,不然還會詢問你要不要修改,比較麻煩。
format-code
是格式化函式,(interactive)
選項是為了使函式可以繫結到按鍵上,(buffer-file-name)
返回當前快取區所編輯檔案的檔名,shell-command-to-string
函式可以執行shell指令。
(global-set-key)
用於繫結按鍵。
宣告
不反對引用轉載,但請註明出處。程式碼可以拷貝到自己的emacs配置中去。