Search code examples
emacsglobalyasnippet

emacs autoload modes


I am a newbie. Now I want to

auto start yasnippet auto-complete gtags flymake modes

when I opening a (php/java/el/...) file.

What Should I put in my emacs config file ?


Solution

  • As liu says, you use add-hook to specify that an action be run when a particular mode is started. Documentation here. Hooks are analogous to events in C#, or the observer pattern in OOP.

    Every mode should define a hook that is run when that mode is started, eg. for a mode named java-mode there is a corresponding hook called java-mode-hook. add-hook lets you wire an action to this hook:

    (add-hook 'java-mode-hook 'my-action)
    

    You can use anonymous lambda functions to define the action in-place, like so:

    (add-hook 'java-mode-hook (lambda () (message "hello from java-mode")))
    

    This will print a message whenever you start up java mode.

    It is usually better to define a named function for the purpose. If you use named functions, add-hook will ensure the same function is not called multiple times.

      (defun hello () 
        (message "hello from java-mode"))
    
      (add-hook 'java-mode-hook 'hello)
    

    Language editing modes are derived from prog-mode. If you want to run an action when you start up any programming language mode, you add your function to prog-mode-hook.


    You need to manually configure autocomplete mode for each mode you want to use it in. For each mode, add that mode to the ac-modes list:

    (add-to-list 'ac-modes 'java-mode)
    

    As a side note, you will want to use flyspell-prog-mode for programming language modes, so you only receive spelling suggestions in comments and string literals.

    (defun on-prog-mode ()
      (flyspell-prog-mode t))
    
    (add-hook 'prog-mode-hook 'on-prog-mode)
    

    And you will probably want to use flycheck instead of the older flymake. Flycheck is under active development and has checkers for php.