Searching case-sensitivity is governed by the variable
case-fold-search: nil means case-sensitive; non-nil means case-insensitive (the case is “folded”).
case-fold-search also affects how lots of programs work. For example MailSplitting? in Gnus.
The default behaviour is to make searches case insensitive, unless you are searching for a mixed case word.
See also: IncrementalSearch
‘isearch-toggle-case-fold’ toggles case-folding in searching on and off. The tip is to bind this command to
‘C-s C-c’, so you can toggle on the fly, while searching.
This code does that:
(add-hook 'isearch-mode-hook (function (lambda () (define-key isearch-mode-map "\C-h" 'isearch-mode-help) (define-key isearch-mode-map "\C-t" 'isearch-toggle-regexp) (define-key isearch-mode-map "\C-c" 'isearch-toggle-case-fold) (define-key isearch-mode-map "\C-j" 'isearch-edit-string))))
Actually, it also adds some other
isearch-mode-help– Provides help on incremental searching. Defined in library Lisp:isearch+.el.
isearch-toggle-regexp– Toggles regexp searching on and off.
isearch-edit-string– Edit the search string in the MiniBuffer. This also provides other isearch options, including word searches (C-w).
To indicate the current state of
case-fold-search in your ModeLine, add the following to your ~/.emacs:
From: KalleOlaviNiemitalo Subject: Re: case-fold-search indicator Newsgroups: gnu.emacs.help Date: 21 Jun 2001 18:06:42 +0300
(add-to-list 'minor-mode-alist '(case-fold-search " CFS"))
This then displays CFS when the searching is case-insensitive, otherwise it shows nothing.
In Lisp programs, be sure to set the case-fold-search variable to nil with regular expressions that desire to be case-sensitive. To do this in your Lisp program set the case-fold-search variable to false (nil) temporarily with the let syntax:
(define mytext-find-heading () "Finds text heading by finding a line whose letters are uppercase." (interactive) (message "Finding text headings ...") (push-mark) (let ((case-fold-search nil)) ;; case-sensitive!! (if (re-search-forward "^[^a-z\n]+$" nil 'move) (message "Found text heading.") (message "End of buffer"))))
The term “case-fold” might appear strange to an emacs newbie. Is there any reason, “historical” or other, for it? – PhilHudson
I’ve got the same question as PhilHudson. More precisely I’ve trapped when trying to find capitalize word in a text with regular expression. The regexp-builder as well as the re-search-forward was actually returning every single word, capitalized or not. Until I dive into the source and understood. Once known it’s ok, but IMHO it must not be the default behavior? Well … hard to change the behavior once it has been the case so much time. Too much code out there expect it to be … a feature now.