29

I notice that the current auto-mode-alist entries all end with a single quote, for example

 ("\\.java\\'" . java-mode)

What is the purpose of the single quote. I would have expected to see

 ("\\.java$" . java-mode)

The reason I ask is that I am trying to get files with names matching regexp

^twiki\.corp.* 

to open in org-mode. I have tried the following without success:

(add-to-list 'auto-mode-alist '("^twiki\\.corp" . org-mode))
(add-to-list 'auto-mode-alist '("\\'twiki\\.corp" . org-mode))

The following works:

(add-to-list 'auto-mode-alist '("twiki\\.corp" . org-mode))

but is not quite what I want since file names with twiki.corp embedded in them will be opened in org-mode.

chris
  • 2,473
  • 1
  • 29
  • 28

1 Answers1

30

\\' matches the empty string at the end of the string/buffer:

http://www.gnu.org/software/emacs/manual/html_node/emacs/Regexp-Backslash.html e l

$ will match the end of the line: If you have newlines in your filename (very uncommon) $ will match the newline and not the end of the string.

The regex is matched against the whole filename, so you need include "/" to match the directory seperator:

(add-to-list 'auto-mode-alist '("/twiki\\.corp" . org-mode))
Jürgen Hötzel
  • 18,997
  • 3
  • 42
  • 58
  • Thx! What is the purpose of matching an empty string at the end of the string in this case? Is it to ensure that there are no spaces after ".java"? How is it better than using $? – chris Aug 16 '10 at 15:56
  • 3
    It is to ensure that you have nothing after the '.java'. Otherwise soemthing like 'somefile.java.not.really' would also match. It's better than '$' if you have a newline in your filename which is unusual but possible. For example a file name like 'bob.java\nsomething else' might be the vector for some malicious attack (though I have no idea what the attack would be). – Ivan Andrus Aug 17 '10 at 13:59
  • 5
    I would use the lovely `rx` form, which saves you from having to remember that awful regexp syntax. (You instead have to remember rx's own syntax, but it's lots more readable.) `(rx "/twiki.corp" eos)` – offby1 Aug 17 '10 at 16:28
  • 4
    If you've got a newline in your filename, you deserve whatever weird errors you get. – Cheeso Apr 28 '11 at 21:04
  • If someone reading this still is confused, "matches the empty string, but only at the end of the string" is a convoluted but strictly correct way of saying what most of us would call "matches the end of the string". So `\'` in elisp is like `\z` in Ruby. The great thing about regexps is that almost everywhere you find it, it's a slightly different dialect from what you've learned before. – clacke Apr 22 '12 at 08:30