简体   繁体   中英

emacs: open all .txt files in a specific directory in a specific major mode

EDIT: It turns out that the second edit to my .emacs file actually works. (See the comments below this entry.)

I tried a couple of addition to the .emacs to make all txt files opened in emacs use orgmode. They did not work. How can I make it happen?

;;SET EMACS AS DEFAULT MAJOR MODE TO FOR ALL FILES WITH AN UNSPECIFIED MODE
(setq default-major-mode 'org-mode)

;;OPEN ALL TXT FILES IN ORGMODE
(add-to-list 'auto-mode-alist '("\\.txt$" . org-mode))

Additionally:

It would be even better to open only txt files in a certain directory orgmode. Any hint as to how that could be done would also be appreciated.

Another way to do this is using directory-local variables. This is nice because you can put a file in any directory where you want this behavior to engage, and it works recursively in any subdirectories.

Create a file called .dir-locals.el in the desired directory.

Here are the contents:

((nil (eval . (if (string-match ".txt$" (buffer-file-name))(org-mode)))))

Read this like so: for any major-mode ( nil ), eval uate the following form:

(if ....  (org-mode))

auto-mode-alist的正则表达式可能更复杂,例如"^/path/to/.*\\\\.txt$"

You can implement a hook which verifies the file directory and modifies the buffer mode:

(add-hook 'find-file-hooks 
          (lambda ()
            (let ((file (buffer-file-name)))
              (when (and file (equal (file-name-directory file) "c:/temp/"))
                (org-mode)))))

As an alternative you can add the mode line in the beginning of your text file. In this case emacs will set the specified mode.

; -*- mode: org;-*-
* header 1
** header 2

I glued together some code from Oleg Pavliv's answer here, and from yibe's at elisp - File extension hook in Emacs - Stack Overflow

(defun use-org-mode-for-dot-txt-files-in-owncloud ()
  (when (and (string-match owncloud buffer-file-name)
             (string-match "\\.txt\\'" buffer-file-name))
    (org-mode)))
(add-hook 'find-file-hook 'use-org-mode-for-dot-txt-files-in-owncloud)

This way, though ownCloud Web and phone apps are currently friendly only with .txt files, from my PC I can use Emacs' Org-mode for them.

(If I set all .txt files to use Org-mode, it breaks todotxt-mode .)

(Note that owncloud is a string variable equal to my ownCloud path.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM