Function: s-format

s-format is a byte-compiled function defined in s.el.

Signature

(s-format TEMPLATE REPLACER &optional EXTRA)

Documentation

Format TEMPLATE with the function REPLACER.

REPLACER takes an argument of the format variable and optionally an extra argument which is the EXTRA value from the call to s-format.

Several standard s-format helper functions are recognized and adapted for this:

    (s-format "${name}" 'gethash hash-table)
    (s-format "${name}" 'aget alist)
    (s-format "$0" 'elt sequence)

The REPLACER function may be used to do any other kind of transformation.

Source Code

;; Defined in ~/.emacs.d/elpa/s-20220902.1511/s.el
(defun s-format (template replacer &optional extra)
  "Format TEMPLATE with the function REPLACER.

REPLACER takes an argument of the format variable and optionally
an extra argument which is the EXTRA value from the call to
`s-format'.

Several standard `s-format' helper functions are recognized and
adapted for this:

    (s-format \"${name}\" \\='gethash hash-table)
    (s-format \"${name}\" \\='aget alist)
    (s-format \"$0\" \\='elt sequence)

The REPLACER function may be used to do any other kind of
transformation."
  (let ((saved-match-data (match-data)))
    (unwind-protect
        (replace-regexp-in-string
         "\\$\\({\\([^}]+\\)}\\|[0-9]+\\)"
         (lambda (md)
           (let ((var
                  (let ((m (match-string 2 md)))
                    (if m m
                      (string-to-number (match-string 1 md)))))
                 (replacer-match-data (match-data)))
             (unwind-protect
                 (let ((v
                        (cond
                         ((eq replacer 'gethash)
                          (funcall replacer var extra))
                         ((eq replacer 'aget)
                          (funcall 's--aget extra var))
                         ((eq replacer 'elt)
                          (funcall replacer extra var))
                         ((eq replacer 'oref)
                          (funcall #'slot-value extra (intern var)))
                         (t
                          (set-match-data saved-match-data)
                          (if extra
                              (funcall replacer var extra)
                            (funcall replacer var))))))
                   (if v (format "%s" v) (signal 's-format-resolve md)))
               (set-match-data replacer-match-data))))
         template
         ;; Need literal to make sure it works
         t t)
      (set-match-data saved-match-data))))