Trim trailing spaces in MS Word and LibreOffice

Let’s do some cleaning.
 3 min. to read
 No comment yet
  (last mod.: 2021-03-21)

If you like to deliver clean documents, you probably sometimes display invisible characters in Word. In such occasions, you may have seen lines or paragraphs ending with ·¶. Yes, because a document is not only written but also manipulated and changed a number of times, having trailing spaces is not a rare thing. One of my development reflexes is to trim those, but Word does not provide any tool to do that automatically. Or does it?

The (almost) useless advice #

A quick search yesterday gave me things that seemed clueless to me:

  • “Align to the right, trailing spaces will be visible and you’ll be able to remove them by hand.”
  • “Display invisible characters, trailing spaces will be visible and you’ll be able to remove them by hand.”

In a summary, “make the trailing spaces visible and remove them by hand.” That may be tolerable for a two-page document, but is not acceptable for a three-hundred-page one. If you see those advices for your large document, forget them (the first one especially, as it may wreak havoc in your layout).

My solution for MS Word #

Word allows to search and replace special charcters (see here to discover how and have application examples). Knowing this, removing trailing spaces becomes a problem of determining the correct search pattern. You can bring up the Replace window with the Ctrl + H shortcut.

To remove all your trailing spaces in MS Word, search and replace all ^w^p with ^p. Execute Replace All several times (until Word says nothing was changed; each execution will remove one trailing space at the end of all lines).

  • ^w is a whitespace (normal, non-breaking…).
  • ^p is the paragraph mark (the ).

You can also replace all ^w^l with ^l, though this has a higher risk of breaking your layout, espacially if your text is justified (^l is the carriage return ).

What about LibreOffice Writer? #

The solution is even easier for LibreOffice Writer. That is, if you’re familiar with regular expressions. There again, we’ll use the Replace tool (same Ctrl + H shortcut as before).

In Other options, check Regular expressions.

In LibreOffice Writer, you can replace \s+(\r?(\n|$)) with $1 to remove all trailing spaces. A single execution should be efficient this time.

The expression can be decomposed this way:

  • \s+ matches one or more whitespaces;
  • (\r?(\n|$)) matches a carriage return (\r?\n) or the end of a paragraph (\r?$); \r? is there only to be compatible with Windows carriage return format;
  • $1 is the first captured group ((\r?(\n|$))) as it was found in the text (we put back what was found).

Regular expressions are a vast topic I won’t go furhter into here, but don’t hesitate to ask questions I may answer.

I hope this post will help you.