title: Control padding programmatically in Clojure format (java.util.Formatter), cl-format (Common Lisp format)?
body: <p>Is there a way to use Clojure <code>forrmat</code> (based on <code>java.util.Formatter</code>) or <code>cl-format</code> (based on Common Lisp's <code>format</code>) to set space padding programmatically?  If you know the desired width in advance these both return <code>"   foo"</code>:</p>
  
  <pre><code>(format "%6s" "foo")
  (clojure.pprint/cl-format nil "~6d" "foo")
  </code></pre>
  
  <p>But what if I want the program to decide how wide the returned string should be?  Obviously I can construct the format string by hand, e.g.:</p>
  
  <pre><code>(def width 6)
  (format (str "%" width "s") "foo")
  </code></pre>
  
  <p>But I thought I remembered that there was a Common Lisp <code>format</code> directive that could simply insert the value of a format argument into a format directive, and then use the resulting constructed directive to process the next argument.  However, I haven't yet found such a directive in the <a href="http://www.lispworks.com/documentation/HyperSpec/Front/" rel="nofollow">CL Hyperspec</a> or <a href="http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node200.html#SECTION002633000000000000000" rel="nofollow">CLTL2</a> (which doesn't mean that the information is not there).  Nor have I discovered such a directive in the <code>java.util.Formatter</code> documentation, so far.  Is there a way to control directives with directives in any of these formatting functions/classes?</p>
  
  <p>(I'm not sure whether my <code>cl-format</code> example is supposed to work, since <code>d</code> is a number-formatting directive.  It does work in Clojure 1.5.1.  The same trick works in CLISP with <code>format</code>, but not in SBCL, ABCL, CCL, or ECL.)</p>
  
  <p>Edit:
  (I've discovered that the correct way to left-pad a string is by adding <code>@</code> to the <code>a</code> directive, rather than by using <code>d</code>:</p>
  
  <pre><code>(clojure.pprint/cl-format nil "~6@a" "foo")
  </code></pre>
  
  <p>This method should always work in Common Lisp, and by using <code>@a</code> rather than <code>d</code> in Clojure, one avoids the risk that a future implementation of <code>cl-format</code> will change the behavior of <code>d</code> with strings, which is an unintended use.)</p>