Search code examples
emacsrequiremode

How can load a .el configure file with a specified mode in emacs


Usually, I put the confugire .el files in src directory for all kinds of languages. Such as Go, the go-conf.el file:

(add-hook 'before-save-hook 'gofmt-before-save)
(add-hook 'go-mode-hook (lambda ()
                      (local-set-key (kbd "M-.") 'godef-jump)))
(add-hook 'go-mode-hook (lambda ()
                      (local-set-key (kbd "M-,") 'godef-jump-back)))
(add-to-list 'load-path "/usr/local/go/src/github.com/dougm/goflymake")
(add-hook 'after-init-hook #'global-flycheck-mode)
(require 'flycheck)
(require 'go-autocomplete)
(require 'auto-complete-config)
(ac-config-default)
)
(provide 'go-conf)

Then, in init.el, I write this line

(require 'go-conf)

Although go-conf can be loaded successfully, emacs launches slowly. It is because that emacs loads go-conf whatever files are opened. I can not tolerate it. It is better that only when Go file is opened, go-conf is loaded.

I modify the init.el as :

(add-hook 'go-mode-hook '(lambda ()
                      (require 'go-conf)
                       (go-conf)
                      ))

But it does not work!!

who can help me?


Solution

  • Your code seems to assume that the whole Emacs only has a single buffer and mode, whereas that is not the case. E.g. (add-hook 'before-save-hook 'gofmt-before-save) affects all buffers, whether they're using go-mode or not. Same for (add-hook 'after-init-hook #'global-flycheck-mode). Emacs is designed such that you can start it once and then edit hundreds of different files at the same time in that one Emacs session. So you should probably rewrite your code along the lines of:

    (defun my-go-lang-config ()
      (add-hook 'before-save-hook #'gofmt-before-save nil 'local)
      (local-set-key (kbd "M-.") 'godef-jump)
      (local-set-key (kbd "M-,") 'godef-jump-back)
      (add-to-list 'load-path "/usr/local/go/src/github.com/dougm/goflymake")
      (require 'go-autocomplete))
    (add-hook 'go-mode-hook #'my-go-lang-config)
    
    (require 'auto-complete-config)
    (ac-config-default)
    (global-flycheck-mode 1)
    

    where the last three lines are part of your "generic" config (not specific to support for the Go language), meaning that you want to use flycheck and auto-complete whenever it's available rather than only in go-mode.