はじめに
先日の記事ではEmacsのcompany-modeの設定をしましたが、 CまたはC++を使う場合のプロジェクト内のヘッダファイルを検索対象にするために、ひと手間必要でした。 ここではそれを自動化するための設定をしてみます。
設定
プロジェクトルートを見つけるため、最初にProjectileをインストールします。
M-x package-install [Enter] projectile [Enter]次に、~/.emacs.d/init.elに以下の内容を記載します。
(require 'company)
(global-company-mode t)
(define-key global-map (kbd "C-f") 'company-complete)
(setq company-backends '((company-clang company-dabbrev-code company-gtags)))
(require 'projectile)
(define-key projectile-mode-map (kbd "C-c p") 'projectile-command-map)
(projectile-mode +1)
;; Return a project root if it is found else a current directory
(defun pproot () (let ((d (projectile-project-root))) (unless d (setq d ".")) d))
;; Find all include paths and set them to clang include path
(defun set-company-clang-include-path ()
(interactive)
(setq company-clang-arguments
(mapcar (lambda (x) (concat "-I" x)) ;; Make clang options to set include path
(seq-uniq (mapcar (lambda (x) (replace-regexp-in-string "/[^\/]*$" "" x)) ;; Extract directories
(directory-files-recursively (pproot) ".*\.\\(h\\|hpp\\)$")))))) ;; Find all header files
(defun set-company-clang-include-path-if-empty ()
(unless company-clang-arguments (set-company-clang-include-path)))
(add-hook 'c++-mode-hook 'set-company-clang-include-path-if-empty)
(add-hook 'c-mode-hook 'set-company-clang-include-path-if-empty)
プロジェクトルート以下の.h/.hppをすべて検索するため、大きめのプロジェクトでは、
c-modeまたはc++-modeでファイルを開くと最初は時間がかかるかもしれません。
company-clang-argumentsを更新する場合は、M-x set-company-clang-include-pathを実行します。