Previous: Full Source, Up: Quick Start [Contents][Index]
Let’s examine this program step-by-step now.
First, we put ourselves in the Common Lisp user package, and load FoCus
from its ASDF system ‘net.didierverna.focus’. FoCus lives in a
package also named ‘net.didierverna.focus’, that we nickname to
just focus
immediately, thanks to the function
nickname-package
.
(in-package :cl-user) (require "asdf") (asdf:load-system :net.didierverna.focus) (net.didierverna.focus:nickname-package) |
Next, we create our own :quotation
package (don’t do that for
real!), and provide a quotation-formatter
function that will
write its string argument between a pair of (back)quotes. Note that this
is the kind of function that you would use in the standard ~/
format directive.
(defpackage :quotation (:use :cl) (:export :quotation)) (in-package :quotation) (defun quotation-formatter (stream argument colonp atsignp &rest arguments) (declare (ignore colonp atsignp arguments)) (write-char #\` stream) (write-string argument stream) (write-char #\' stream)) |
The interesting part comes now. FoCus uses so-called format
tables to store the mappings between directive characters and their
behavior. Much like what a readtable does with macro characters. So
let’s create a new format table. This is done with the function
make-format-table
.
(let ((table (focus:make-format-table))) |
By default, new format tables inherit the standard format
behavior (that
is, all standard directives are recognized). Let’s add a new directive
character, `
(backquote) to our new format table, and map it to
the quotation-formatter
function. This is done with the function
set-format-directive
. By default, FoCus works with the
so-called current format table. One way of making sure that the
current format table is the appropriate one is to use the macro
with-format-table
.
(focus:with-format-table table (focus:set-format-directive #\` :function 'quotation-formatter)) |
Now, let’s create a silly quotation
function for printing
someone’s quote. FoCus provides its own format
function which wraps
around the standard one. This function works exactly like the original
format
, except that it uses the current format table to interpret your
custom format string, so again, we need to make sure that the proper
table is used when the function is called.
(defun quotation (who quotation) (focus:with-format-table table (focus:format t "As ~A would say: ~`.~%" who quotation)))) |
Finally, let’s try it!
(in-package :cl-user) (quotation:quotation "Bugs Bunny" "What's Up Doc?") |
Previous: Full Source, Up: Quick Start [Contents][Index]