4

By default, occur uses the passed regexp to match lines in a case-insensitive way. Is there a way to make this matching case-sensitive?

For example, if I run M-x occur ^function RET, occur will match lines that start with both function and Function. I want it to only match function.

For reference, this is how I am currently using occur to generate a "table of contents" for Perl and other languages:

(defun toc ()
  "Show a 'Table of Contents' for the current file using occur"
  (interactive)
  (let (regexp)
    (if (derived-mode-p 'cperl-mode)  ;; for perl
        (setq regexp "^\\(sub\\|has\\|=head1\\|requires\\) ")
      (setq regexp "^function "))     ;; for everything else
    (occur regexp)))
Ben
  • 587
  • 4
  • 11

2 Answers2

4

By default occur searches are case-insensitive. To force them to be case sensitive, you need to set the variable case-fold-search to nil. Note that this is a buffer-local variable. If you set it for one buffer, it won't change it's value for other buffers.

In your function, adding the form (case-fold-search nil) to your let statement should work:

(defun toc ()
  "Show a 'Table of Contents' for the current file using occur"
  (interactive)
  (let (regexp
        (case-fold-search nil))
    (if (derived-mode-p 'cperl-mode)  ;; for perl
        (setq regexp "^\\(sub\\|has\\|=head1\\|requires\\) ")
      (setq regexp "^function "))     ;; for everything else
    (occur regexp)))
Tyler
  • 21,719
  • 1
  • 52
  • 92
2

You may (globally) toggle the behaviour with M-x toggle-case-fold-search. For more information see http://ergoemacs.org/emacs/elisp_list_matching_lines.html (dunno why the emacs wiki is less comprehensive on this topic).

JeanPierre
  • 7,323
  • 1
  • 18
  • 37
StefanQ
  • 141
  • 2