scheme shell
about
download
support
resources
docu
links
 
scsh.net

Format Spec

The procedure `format-spec' bellow allows to format strings using arbitrary user-defined escape sequences. This can be useful when generating text from a template, as in the following example:

 (format-spec
  "From: me <me@localhost>
 To: \"%n\" <%a>
 Subject: Hello

Dear %n,

..." `((#\n . ,(customer-name cust)) (#\a . ,(customer-address cust))))

Here is the code:

 ;;; formatting arbitrary formatting strings
 ;; Emilio Lopes <eclig@gmx.net>, 2006-04-17

;; Based on the Emacs library `format-spec' by Lars Magne Ingebrigtsen.

;; THIS FILE IS IN THE PUBLIC DOMAIN. USE AT YOUR OWN RISK!

(define-structure format-spec (export format-spec)

(open let-opt srfi-13 scheme-with-scsh) (begin " For the sake of Emacs' indentation ("

(define *escape-char* #\%)

(define (format-spec fmt specification) ;; Return a string based on FMT and SPECIFICATION. ;; FMT is a string containing `format'-like specs like \"bash %u %k\", ;; while SPECIFICATION is an alist mapping from format spec characters ;; to values. (define esc (string *escape-char*)) (define (match-handler m) (let-match m (#f spec) (cond ((string-null? spec) (error 'format-spec (format #f "Invalid format string at char ~a." (match:start m 0)))) ((string=? spec esc) esc) ((assq (string-ref spec 0) specification) => cdr) (else (error 'format-spec (format #f "Unknown format specifier `~a' at char ~a." spec (match:start m 0))))))) (regexp-substitute/global #f (rx ,esc (submatch (? (| ,esc alphabetic)))) fmt 'pre match-handler 'post)) ))

;; (format-spec "%a %%xy %z %c %a" ;; '((#\a . "foo") (#\c . "bar") (#\z . "baz")))


FormatSpec - raw wiki source | code snippets archive