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

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.

  • 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 '15 at 21:09
  • (replace-match "let" t);; Works. I thought (match 1) was non-nil. Guess not. – h4labs Mar 26 '15 at 21:16
  • @h4labs Your usage of match-string was wrong. (replace-match "let" t) is indeed the correct way here. – Malabarba Mar 26 '15 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. – Lindydancer Mar 27 '15 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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