It seems subr-x's string-trim-right only operates on the last line.

How to strip trailing spaces on all lines in a variable?

  • ITYM it operates on a string, not lines inside a string. By that definition it does indeed "trim whitespace from the end of a multi-line string". I'd be surprised if it trimmed it in the middle of it, just because there happened to be a newline at that place.
    – wasamasa
    Jul 29, 2017 at 19:59

1 Answer 1


This can be done by splitting and joining strings:

(require 'subr-x)
(defun string-trim-right-multiline (str)
  (mapconcat 'string-trim-right
   (split-string str "\n") "\n"))

Note that if you want to perform other operations on the string you can define a function:

(require 'subr-x)
(defun string-trim-right-multiline (str)
  (mapconcat (function (lambda (s) (string-trim-right s)))
   (split-string str "\n") "\n"))
  • 1
    You can replace (function (lambda (s) (string-trim-right s))) with just 'string-trim-right.
    – wvxvw
    Jul 30, 2017 at 6:00
  • Done, but included previous since it can be handy to make other edits.
    – ideasman42
    Jul 30, 2017 at 13:58

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.