I am adding divider lines to certain sections of the reports generated by the binary ledger [ https://www.ledger-cli.org/ ] through the function ledger-do-report in the ledger-mode Lisp library [ https://github.com/ledger/ledger-mode]. To accomplish this goal, I have chosen replace-regexp-in-string. I wish to prepend the divider line followed by a new line; i.e., "======\n".

Q:  Is there a built-in way to prepend the additional string without the need to create an empty substring at the beginning of the REGEXP; i.e., \\(\\)?

In the following example, I have begun my REGEXP with ^\\(\\) so that I can replace that number 1 subsexpression with the new string. However, I have a feeling that there is a more correct approach to simply prepend a string without using an empty placeholder in the REGEXP.

NOTE: The ^[ is defined by Emacs as: old-name: ESCAPE; general-category: Cc (Other, Control); decomposition: (27) ('^[')

;;;           $ 98,477.47  ASSETS
;;;  =>
;;;           $ 98,477.47  ^[[34mASSETS^[[0m
(setq report (replace-regexp-in-string
               (concat (make-string (- (window-width) 1) ?=)" \n")
               report nil nil 1))
  • 1
    Note that you can use "\e" for the ESCAPE char, and then people can copy/paste the code.
    – phils
    Dec 2, 2020 at 21:23

1 Answer 1


If LITERAL is nil then you can use "\\&" in the replacement to represent the entire matched string, and so your replacement text could be "PREFIX\\&".

Refer to C-h f replace-match for the behaviour of LITERAL.

(And if you didn't want special characters in the replacement text to be processed, you would generally want LITERAL to be non-nil, for safety.)

  • Thank you. I used your answer; and I removed the empty REGEXP subexpression of \\(\\); and I changed SUBEXP so that it is now nil; and I added a START of 0.
    – lawlist
    Dec 2, 2020 at 22:22

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.