Is there a way (or package) to search and replace code like:

class Account
  def list_accounts


class Company
  def list_companies

Basically I want to replace account(s) with compan(y/ies)

Vim does this with Subvert

  • 1
    The "case" part of your question should be the default behaviour of query-replace. That is, if you ask to replace "account" with "company", then "Account" will be replaced with "Company". Is that not what happens for you?
    – Malabarba
    Commented Sep 29, 2014 at 16:57

1 Answer 1


Retaining the cases on replacing

By default, emacs retains the cases when replacing.

From the emacs manual,

When the newstring argument is all or partly lower case, replacement commands try to preserve the case pattern of each occurrence. Thus, the command

M-x replace-string <RET> foo <RET> bar <RET>

replaces a lower case foo with a lower case bar, an all-caps FOO with BAR, and a capitalized Foo with Bar. (These three alternatives—lower case, all caps, and capitalized, are the only ones that replace-string can distinguish.)

Ensure that the case-replace variable is t (which it is, by default).

Replacing with plurals

You can try query-replace-regexp (C-M-%) then replace



compan\,(if (string= \1 "s") "ies" "y)
  • 1
    I wonder if this could be combined with emacswiki.org/emacs/plural.el to come up with replace-string-with-plural or equivalent.
    – b4hand
    Commented Sep 29, 2014 at 20:05
  • "y should be "y"
    – user64953
    Commented Aug 19, 2021 at 13:21

Your Answer

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

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