1

I'm writing a little cleanup function that will search for the word 'let' in a case insensitive manner then replace it with the lowercase 'let'. It works in all my test cases, except for when the first letter is capitalized:

leT x=1
Let y=2
let z=3
lEt a=3

In the output, the second line is wrong:

let x=1
Let y=2
let z=3
let a=3

Here's the elisp:

(defun let-cmd()
  (goto-char (point-min))
  (while (search-forward-regexp "Let" nil t) 
    (replace-match "let" (match-string 1)) t nil))

(defun cleanup()
  (interactive)
  (let-cmd))

How do I fix this one example?

1 Answer 1

2

You can pass a non-nil value as the FIXEDCASE parameter. From the built-in help:

(replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING SUBEXP)

Replace text matched by last search with NEWTEXT. Leave point at the end of the replacement text.

If optional second arg FIXEDCASE is non-nil, do not alter the case of the replacement text. Otherwise, maybe capitalize the whole text, or maybe just word initials, based on the replaced text. If the replaced text has only capital letters and has at least one multiletter word, convert NEWTEXT to all caps. Otherwise if all words are capitalized in the replaced text, capitalize each word in NEWTEXT.

4
  • That's (match-string 1). I have 1 optional parameter. I've tried make it nil and it didn't help: (replace-match "let" nil)
    – h4labs
    Mar 26, 2015 at 21:09
  • 1
    (replace-match "let" t);; Works. I thought (match 1) was non-nil. Guess not.
    – h4labs
    Mar 26, 2015 at 21:16
  • 1
    @h4labs Your usage of match-string was wrong. (replace-match "let" t) is indeed the correct way here.
    – Malabarba
    Mar 26, 2015 at 21:24
  • @h4labs, (match-string 1) is nil in this example since it refers to the first parenthesized regexp group, and you don't have in your regexp. However, it's irrelevant since the parameter is a simple bool value, and there is no point in passing (parts of) the matched string to it. (I think you confused it with the case where you replace one string with another.) Anyway, I'm glad that you got it working. Mar 27, 2015 at 7:42

Your Answer

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

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