Say I have a symbolic link .emacs link to emacs.link,so when I open emacs.link,the associated buffer's major mode is Fundamental mode. I want emacs.link's major mode Emacs-Lisp.

Another example is: for a symbolic link .bashrc link to bashrc.link,I want bashrc.link opened in sh-mode.

  • Please provide a step-by-step recipe to reproduce what you see, preferably from emacs -Q (no init file).
    – Drew
    Aug 8, 2017 at 16:59
  • I don't think it's possible to do this reliably. If you created a link called .bashrc to your .emacs, how would Emacs know which major mode to use? You could of course do something like (add-to-list 'auto-mode-alist '("emacs\\.link" . emacs-lisp-mode))
    – Nova
    Aug 11, 2017 at 13:35
  • @Erik,the link has a pattern,.bashrc will be link bashrc.link,.emacs` link emacs.link. I have fix the problem but forget to self answer it.
    – Vacker
    Aug 14, 2017 at 2:39

1 Answer 1


After digging files.el in emacs src code,I got the solution.

The procedure:

  1. once the file.link file opened,figure out .file name by buffer-file-name.

  2. find .file major mode by search auto-mode-alist

  3. call set-auto-mode-0

The code:

(defun zil/link-file-open-hook ()                                                                                                                                       
 "for link files' major-mode in dot-file"                                                                                                                              
 (let* ((bn (buffer-file-name))                                                                                                                                        
        (dot-name (concat "." (file-name-base bn)))                                                                                                                    
        (mode (assoc-default dot-name auto-mode-alist 'string-match)))                                                                                                 
    (if (and (string= "link" (file-name-extension bn)))                                                                                                                 
         (string-match-p "dot" bn))                                                                                                                                 
    (and mode (set-auto-mode-0 mode t))))                                                                                                                           

 (add-hook 'find-file-hook 'zil/link-file-open-hook)                                                                                                                     

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.