reddit / emacs

Elisp: Format string where resulting string contains format characters

pragmat1c1 · 2022-05-10 11:49
I am processing a list of URLs where spaces have been replaced by "%2F". For example: "https://example.com/query=aasfasdf%2Fapp%2Fuser=test" Now I try to create new strings that contain those URLs. `(format "Name: %s URL: %s" name url)` and get an error: `(error "Not enough arguments for format string")` Apparently the resulting string contains those "%2F" strings, and `format` cannot fill them. Is there a way to provide literal strings to `format` function and prevent it from trying to interpolate the resulting string? ## Edit: Here is a code fragment that demonstrates it ``` (let ((name "Test URL") (url "https://firebasestorage.googleapis.com/v0/b/firescript-577a2.appspot.com/o/imgs%2Fapp%2FJames%1Qr5z3L.png?alt=media&token=3571-455b-960f-b68acc31faf0")) (message (format "%s %s" name url))) ``` ## Solved https://www.gnu.org/software/emacs/manual/html_node/elisp/Displaying-Messages.html ``` Warning: If you want to use your own string as a message verbatim, don’t just write (message string). If string contains ‘%’, ‘`’, or ‘'’ it may be reformatted, with undesirable results. Instead, use (message "%s" string). ``` So this does the trick: ``` (let ((name "Test URL") (url "https://firebasestorage.googleapis.com/v0/b/firescript-577a2.appspot.com/o/imgs%2Fapp%2FJames%1Qr5z3L.png?alt=media&token=3571-455b-960f-b68acc31faf0")) (message "%s" (format "%s %s" name url))) ```
usaoc · 2022-05-10 12:55
[`message` accepts a format string as the first argument](https://www.gnu.org/software/emacs/manual/html_node/elisp/Displaying-Messages.html). [It uses `format-message` under the hood](https://github.com/emacs-mirror/emacs/blob/145727df29d2e067b062cb44548dd97b076567fa/src/editfns.c#L2849), [which see](https://www.gnu.org/software/emacs/manual/html_node/elisp/Formatting-Strings.html). Therefore, `(message "%s %s" name url)` is enough.
pragmat1c1 · 2022-05-10 18:29
Excellent! Thank you.