Suppose I select some text in an emacs buffer using point and mark. How do I tell emacs to replace each non-whitespace character with x, say? For concreteness, that I select the text using point and mark. Also, for clarity, I consider newlines to be whitespace for the purpose of this question.

The idea is to keep the structure of the text intact, but remove all information. My current use case is a LaTeX MWE document.

  • I take it you know about ipsum, a LaTeX package for generating lines of example text? – wvxvw Apr 30 '15 at 6:26
  • @wvxvw Yes, I do. – Faheem Mitha Apr 30 '15 at 7:48

Use M-x replace-regexp to replace all non-whitespace characters by x. You can use C-M-% to run query-replace-regexp and, once a match is found, press ! to replace all matches.

Now for a regexp that matches non-whitespace characters. You'd think that the character class [:space:] would match whitespace characters, and so you'd use [^[:space:]] as the regexp to mean “any non-whitespace character”. But in LaTeX mode, newlines have the “comment end” syntax instead of the “whitespace” syntax, so they don't count as whitespace for the purpose of [:space:]. So you need to use the regexp


To enter a newline in the regexp, press C-q C-j: the command C-q means to enter the next character literally instead of interpreting it as a command, and C-j (not the C-m character that the Enter key sends) is the newline character.

That is, you type:

M-x replace-regexp RET
[^[:space:] C-q C-j ] RET

Note that this replaces all non-whitespace, including LaTeX commands, comments, etc.

Why not use lipsum instead?

  • That works. Thank you. I notice that capital letters are replaced by a capital X, but that does not matter for my purposes. Can one use lipsum to replace a block of text exactly? – Faheem Mitha Apr 29 '15 at 21:37
  • @FaheemMitha M-x set-variable RET case-fold-search RET nil RET to make it all x, or untick “Ignore Case for Search” in the Options menu. You can use lipsum to generate blocks of text. You aren't replacing text “exactly” anyway, since x doesn't have the same metrics as other characters: replacing mmmmmm by xxxxxx leads to different line breaks etc. – Gilles Apr 29 '15 at 21:47

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.