Compare commits

..

9 Commits

@ -1,43 +0,0 @@
name: CI
on: [push, pull_request]
jobs:
run:
name: "Build using Racket '${{ matrix.racket-version }}' (${{ matrix.racket-variant }})"
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
racket-version: ["6.6", "6.7", "6.8", "6.9", "6.10.1", "6.11", "6.12", "7.0", "7.1", "7.2", "7.3", "7.4", "7.5", "7.6", "7.7", "7.8", "7.9", "current"]
racket-variant: ["BC", "CS"]
# CS builds are only provided for versions 7.4 and up so avoid
# running the job for prior versions.
exclude:
- {racket-version: "6.6", racket-variant: "CS"}
- {racket-version: "6.7", racket-variant: "CS"}
- {racket-version: "6.8", racket-variant: "CS"}
- {racket-version: "6.9", racket-variant: "CS"}
- {racket-version: "6.10.1", racket-variant: "CS"}
- {racket-version: "6.11", racket-variant: "CS"}
- {racket-version: "6.12", racket-variant: "CS"}
- {racket-version: "7.0", racket-variant: "CS"}
- {racket-version: "7.1", racket-variant: "CS"}
- {racket-version: "7.2", racket-variant: "CS"}
- {racket-version: "7.3", racket-variant: "CS"}
steps:
- name: Checkout
uses: actions/checkout@master
- uses: Bogdanp/setup-racket@v0.11
with:
distribution: 'full'
version: ${{ matrix.racket-version }}
variant: ${{ matrix.racket-variant }}
- name: Install Pollen and its dependencies
run: raco pkg install --auto --batch
- name: Run the tests
run: xvfb-run raco test -j 4 -p pollen

@ -0,0 +1,46 @@
# adapted from
# https://github.com/greghendershott/travis-racket/blob/master/.travis.yml
# Thanks Greg!
dist: trusty
language: c
sudo: false
env:
global:
- RACKET_DIR=~/racket
matrix:
- RACKET_VERSION=6.3
- RACKET_VERSION=6.6
- RACKET_VERSION=6.9
- RACKET_VERSION=6.12
- RACKET_VERSION=7.0
- RACKET_VERSION=7.3
- RACKET_VERSION=7.4
- RACKET_VERSION=7.5
- RACKET_VERSION=7.6
- RACKET_VERSION=HEAD
- RACKET_VERSION=HEADCS
# You may want to test against certain versions of Racket, without
# having them count against the overall success/failure.
matrix:
allow_failures:
- env: RACKET_VERSION=HEAD
- env: RACKET_VERSION=HEADCS
# Fast finish: Overall build result is determined as soon as any of
# its rows have failed, or, all of its rows that aren't allowed to
# fail have succeeded.
fast_finish: true
before_install:
- "export DISPLAY=:99.0" # needed for testing with `racket/gui`
- "sh -e /etc/init.d/xvfb start" # needed for testing with `racket/gui`
- git clone https://github.com/mbutterick/travis-racket.git
- cat travis-racket/install-racket.sh | bash # pipe to bash not sh!
- export PATH="${RACKET_DIR}/bin:${PATH}" #install-racket.sh can't set for us
script:
- cd .. # Travis did a cd into the dir. Back up, for the next:
- travis_retry raco pkg install --deps search-auto https://github.com/mbutterick/pollen.git
- raco test -p pollen

@ -1,134 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
mb@mbtype.com (= Matthew Butterick).
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
[https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0].
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available
at [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

@ -4,13 +4,13 @@ I welcome pull requests. But accepting a PR obligates me to maintain that code f
* Theres plenty of room for improvement in the Pollen code, because every line of it has been written against the backdrop of ignorance and fallibility, mostly my own. (= Principle of Prior Ignorance)
* PRs for simple documentation fixes (e.g., spelling and grammar corrections) are always welcome. For more substantial changes, I dont necessarily prefer PRs to issues or feature requests. A good description of the problem with a working example is better than a half-baked PR. I can often fix it in less time than it would take to review the PR. (= Principle of Efficiency)
* I dont necessarily prefer PRs to issues or feature requests. A good description of the problem with a working example is better than a half-baked PR. I can often fix it in less time than it would take to review the PR. (= Principle of Efficiency)
* If you want feedback on a potential PR, I recommend posting to the [Pollen forum](https://forums.matthewbutterick.com/c/typesetting/) rather than here. Because more people will see it. (= Principle of Exposure)
* If you want feedback on a potential PR, I recommend posting to the [Pollen mailing list](http://groups.google.com/forum/#!forum/pollenpub) rather than here. Because more people will see it. (= Principle of Exposure)
* Small PRs are easier to accept than large ones. Large PRs should have a benefit worthy of their complexity. PRs that want to amend Pollens public interface receive the highest scrutiny. (= Principle of Proportionality)
* I consider every PR, but I cant promise detailed code reviews or comments. Helpful Racketeers can be found on the [Pollen forum](https://forums.matthewbutterick.com/c/pollen/), the [Racket mailing list](https://lists.racket-lang.org/), and the Racket [Slack channel](https://racket.slack.com/). (= Principle of Specialization)
* I consider every PR, but I cant promise detailed code reviews or comments. Helpful Racketeers can be found on the [Pollen mailing list](http://groups.google.com/forum/#!forum/pollenpub), the [Racket mailing list](https://lists.racket-lang.org/), and the Racket [Slack channel](https://racket.slack.com/). (= Principle of Specialization)
* PRs should be necessary, in the sense that the proposed change can only be accomplished by patching this repo. (Corollary: features that can live in a separate [package](https://pkgs.racket-lang.org/) probably should.) (= Principle of Necessity)

@ -1,4 +1,4 @@
## Pollen: the book is a program [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](CODE_OF_CONDUCT.md)
## Pollen: the book is a program [![Build Status](https://travis-ci.org/mbutterick/pollen.svg?branch=master)](https://travis-ci.org/mbutterick/pollen)
A book-publishing system written in [Racket](http://racket-lang.org). This is the software I use to publish & maintain my web-based books [Beautiful Racket](http://beautifulracket.com), [Practical Typography](http://practicaltypography.com), and [Typography for Lawyers](http://typographyforlawyers.com).
@ -23,12 +23,8 @@ And update like so:
raco pkg update --update-deps pollen
Official forum: https://forums.matthewbutterick.com/c/typesetting/
Official discussion area: https://github.com/mbutterick/pollen-users
## License
MIT
## Project status
Actively developed, though the pace has slowed now that Pollen is arguably feature complete and stable. I use it almost every day so it's not going anywhere. But I have no plans to substantially enlarge or extend it.

@ -1,7 +1,7 @@
#lang info
(define collection 'multi)
(define version "3.2")
(define version "2.2")
(define deps '(["base" #:version "6.3"]
["txexpr" #:version "0.2"]
["sugar" #:version "0.2"]
@ -15,8 +15,7 @@
"scribble-text-lib"
"rackunit-lib"
"gui-lib"
"string-constants-lib"
"net-lib"))
"string-constants-lib"))
(define build-deps '("plot-gui-lib"
"scribble-lib"
"racket-doc"

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 431 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@ -0,0 +1,180 @@
#lang debug racket/gui
(require pollen/private/log
pollen/private/command
pollen/setup
pollen/private/project-server
net/sendurl)
(define app-mono-fam
(for*/first ([preferred
'("Triplicate T4" "Menlo" "Consolas" "Andale Mono" "Courier")]
[mono-fam (in-list (get-face-list 'mono))]
#:when (equal? preferred mono-fam))
preferred))
(define app-font-size 14)
(define app-font (make-font #:face (send normal-control-font get-face) #:size app-font-size))
(define window (new frame% [label "Pollen Helper"]
[width 700]
[height 500]
[x 40]
[y 40]
[alignment '(left top)]
[spacing 6]
[border 6]))
(define (make-hpanel) (new horizontal-panel%
[parent window]
[alignment '(left top)]
[stretchable-height #false]))
(define hpanel-select (make-hpanel))
(define current-manager-directory (make-parameter #f))
(define current-server-stopper (make-parameter #f))
(define (set-current-manager-directory val)
(current-manager-directory val)
(send directory-msg set-label (if val (path->string val) "")))
(module+ main
(set-current-manager-directory (expand-user-path "~/git/bpt/")))
(define button-directory
(let ([str "Select project directory"])
(new button%
[label str]
[parent hpanel-select]
[callback (λ (button evt)
(define dir (get-directory str))
(when dir
(set-current-manager-directory dir)
(set-server-port (setup:project-server-port dir))))])))
(define directory-msg
(new message%
[label ""]
[parent hpanel-select]
[auto-resize #true]))
(define hpanel-server-options (make-hpanel))
(define server-option-port
(new text-field%
[parent hpanel-server-options]
[label "server port"]
[min-width 150]
[stretchable-width #false]
[init-value (number->string (setup:project-server-port))]
[callback (λ (tf evt)
(set-server-port (string->number (send tf get-value))))]))
(define (set-server-port num)
(when (number? num)
(current-server-port num)
(send server-option-port set-value (number->string num))))
(define server-option-local
(new check-box%
[parent hpanel-server-options]
[label "local only"]
[callback (λ (cb evt)
(current-server-listen-ip (and (send cb get-value) "127.0.0.1")))]))
(define hpanel-server-controls (make-hpanel))
(define dialog-alert (new dialog%
[label "Error"]
[border 6]
[spacing 6]
[parent #f]))
(define dialog-message (new message%
[parent dialog-alert]
[auto-resize #t]
[label ""]))
(define dialog-alert-button-pane
(new horizontal-pane%
[parent dialog-alert]
[alignment '(right bottom)]))
(define dialog-alert-button-ok
(new button%
[parent dialog-alert-button-pane]
[label "OK"]
[style '(border)]
[callback (λ (button evt)
(send dialog-alert show #f))]))
(define (make-alert str)
(send dialog-message set-label str)
(send dialog-alert show #t))
(define button-start
(new button%
[label "Start project server"]
[parent hpanel-server-controls]
[callback (λ (button evt)
(if (current-server-stopper)
(make-alert "Project server already running.")
(match (current-manager-directory)
[#false (make-alert "No project directory selected.")]
[dir
(message "starting project server")
;; stopper is a function that sends a break signal
;; to the web server thread, wherever it is
(define stopper
(parameterize ([current-project-root dir])
(start-server (setup:main-pagetree dir) #:return #true)))
(current-server-stopper stopper)])))]))
(define button-stop
(new button%
[label "Stop project server"]
[parent hpanel-server-controls]
[callback (λ (button evt)
(match (current-server-stopper)
[#false (make-alert "Project server not running.")]
[stopper-proc
(stopper-proc)
(current-server-stopper #false)
(message "project server stopped")]))]))
(define button-launch
(new button%
[label "Launch browser"]
[parent hpanel-server-controls]
[callback (λ (button evt)
(cond
[(current-server-stopper)
(send-url
(format "http://localhost:~a/~a"
(current-server-port)
(setup:main-pagetree (current-manager-directory)))
#false)]
[else (make-alert "Project server not running.")]))]))
(define status-box
(let* ([wb (new text-field%
[label #f]
[style '(multiple)]
[parent window]
[font (make-font #:face app-mono-fam #:size app-font-size)])]
[ed (send wb get-editor)])
(send ed set-line-spacing (* app-font-size 0.4))
(send ed set-padding 6 3 6 3)
wb))
(define status-box-ed (send status-box get-editor))
(define log-receiver-thread
(thread (λ ()
(define rcvr (make-log-receiver pollen-logger 'info 'pollen))
(for ([vec (in-producer (λ () (sync rcvr)))])
(match-define (vector _ msg _ _) vec)
(send status-box-ed insert msg)
(send status-box-ed insert "\n")))))
(send window show #t)

@ -0,0 +1,13 @@
#lang br
(require pict icns file/ico rsvg)
(define p (svg-file->pict "pollen-raw.svg"))
(send (pict->bitmap p) save-file "pollen.png" 'png)
(with-output-to-file "pollen.icns"
(λ () (void (write-bytes (pict->icns-bytes p))))
#:exists 'replace)
(write-icos (for/list ([size '(16 32 48 256)])
(argb->ico size size (pict->argb-pixels (scale p (/ size 720))))) "pollen.ico"
#:exists 'replace)

@ -0,0 +1,142 @@
#lang debug racket
(require racket/gui sugar/coerce sugar/debug)
(define current-cell-size (make-parameter 120))
(define current-dc (make-parameter #f))
(define current-target (make-parameter 'gui))
(define current-stroke-scale (make-parameter 1))
(define char-edge-size 6)
(define (pathify vs)
(define p (new dc-path%))
(define pts (map (λ (x) (list (* (current-cell-size) (sub1 (modulo x 10))) (* (current-cell-size) (- 4 (sub1 (floor (/ x 10))))) )) vs))
(send p move-to (first (car pts)) (second (car pts)))
(for-each (λ (pt) (send p line-to (first pt) (second pt))) (cdr pts))
(when (= (first vs) (last vs)) (send p close))
p)
(struct $glyph (name paths))
(define font-definition
'((a (51 54 45 15 12 21 31 33))
(b (11 51 55 25 14 13) (35 33))
(c (25 15 11 41 52 55 45))
(d (31 11 14 25 45 54 51))
(e (15 11 41 52 55 35 33))
(E (55 52 41 11 15) (31 35))
(f (11 41 52 55) (31 35))
(g (33 35 15 11 41 52 55))
(h (11 51) (15 55) (31 35))
(i (11 15) (51 55) (13 53))
(j (53 55 15 12 21 31))
(k (11 51) (11 21 54 55) (43 34 25 15))
(L (51 11 15) (53 33 35))
(l (25 15 11 41 52))
(m (11 51 54 45 15) (53 13))
(n (11 51 54 45 15))
(N (11 51 52 43 23 14 15 55))
(O (11 41 52 55 25 14 11))
(o (51 54 45 15 12 21 51))
(P (11 51 54 45 35 24 23))
(p (51 54 45 35 33 13 11 31))
(p0 (11 51 55 35 24 23))
(q (33 24 13 11 41 52 55 35 24))
(r (11 51 53 54 45 35 33 23 14 15))
(s (11 14 25 35 31 41 52 55))
(t (31 51 55 35) (53 13) (11 15))
(T (51 55) (53 13))
(u (51 21 12 15 55))
(v (55 35 13 11 51))
(w (51 21 12 15 55) (53 13))
(x (51 52 43 23 14 15) (11 12 23 43 54 55))
(X (51 41 32 34 25 15) (11 21 32 34 45 55))
(y (51 31 35)(55 25 14 11))
(z (51 55 45 34 32 21 11 15))
( (12 21 41 52 43 54 45 25 14 12))
(0 (51 54 45 15 12 21 31 51))
(1 (51 53 13) (11 15))
(2 (51 54 45 35 31 11 15))
(3 (51 54 45 15 11) (31 35))
(4 (41 21 25) (54 14))
(5 (55 51 31 35 25 14 11))
(6 (31 35 25 14 11 41 52 55))
(7 (51 55 45 22 12))
(8 (12 21 51 54 45 15 12) (31 35))
(9 (11 14 25 55 52 41 31 35))
(λ (51 52 25 15) (11 21 43))
(> (51 52 25 15))
(% (11 51) (12 52) (13 53) (14 54) (15 55))
(^ (11 51) (12 42) (13 33) (14 24))
(< (11 21 43))
(|(| (55 54 43 23 14 15))
(|)| (51 52 43 23 12 11))))
(define (type str [xoffset 0] [yoffset 0] #:color color-proc #:width width)
(define glyphs (map (λ (i) ($glyph (->string (car i)) (map pathify (cdr i)))) font-definition))
(cond
[(equal? str "") (void)]
[else
(define gname (substring str 0 1))
(define g (findf (λ (g) (equal? ($glyph-name g) gname)) glyphs))
(when g
(define pen (make-pen #:color (->string (color-proc)) #:width width #:style 'solid #:cap 'projecting #:join 'miter))
(send (current-dc) set-pen pen)
(send (current-dc) set-brush "white" 'transparent)
(for-each (λ (p) (send (current-dc) draw-path p (+ xoffset (current-cell-size)) (+ yoffset (current-cell-size)))) ($glyph-paths g)))
(type (substring str 1) (+ xoffset (* (current-cell-size) char-edge-size)) yoffset #:color color-proc #:width width)]))
(define (layer-type str #:xoffset [xoffset 0] #:yoffset [yoffset 0] . attrs)
(define layers (for/list ([i (in-range 0 (length attrs) 2)]) (list (list-ref attrs i) (list-ref attrs (add1 i)))))
(for-each (λ (layer) (type str xoffset yoffset #:color (first layer) #:width (* (current-cell-size) (current-stroke-scale) (second layer)))) layers))
(define (render text layers [stroke-scale 1] [name (gensym)])
(define lines (string-split text))
(define horiz (* (current-cell-size) (apply max (map string-length lines)) char-edge-size))
(define vert (* (current-cell-size) char-edge-size (length lines)))
(define target (make-bitmap horiz vert))
(parameterize ([current-dc (if (equal? 'svg (current-target))
(new svg-dc% [width horiz] [height vert] [output (format "/Users/MB/Desktop/~a.svg" name)] [exists 'replace])
(new bitmap-dc% [bitmap target]))]
[current-stroke-scale stroke-scale])
(when (eq? 'svg (current-target))
(send (current-dc) start-doc "start")
(send (current-dc) start-page))
(send (current-dc) set-smoothing 'smoothed)
(for* ([(line lineno) (in-indexed lines)]
[layer (in-list layers)])
(define layer-color (first layer))
(define layer-thickness (second layer))
(layer-type line #:xoffset 0 #:yoffset (* (current-cell-size) char-edge-size lineno) layer-color layer-thickness))
(make-object image-snip% target)
(when (eq? 'svg (current-target))
(send (current-dc) end-page)
(send (current-dc) end-doc))
(when (eq? 'png (current-target))
(send target save-file (format "/Users/MB/Desktop/~a.png" name) 'png))))
(define-syntax-rule (render-svg arg ...)
(parameterize ([current-target 'svg])
(render arg ...)))
(define-syntax-rule (render-png arg ...)
(parameterize ([current-target 'png])
(render arg ...)))
(define (random-select xs)
(list-ref xs (random (length xs))))
(module+ main
(current-target 'svg)
(define (do-it text name)
(render-svg text
(list (list (λ () 'Black) 11)
(list (λ () 'White) 9)
(list (λ () 'Black) 7)
(list (λ () 'White) 5)
(list (λ () 'Black) 3)
(list (λ () 'White) 1))
(/ 1 char-edge-size) name))
(do-it "P" 'pollen-raw))

@ -0,0 +1,145 @@
#lang debug racket
(require racket/gui sugar/coerce sugar/debug)
(define current-cell-size (make-parameter 30))
(define current-dc (make-parameter #f))
(define current-bitmap (make-parameter #f))
(define current-target (make-parameter 'gui))
(define current-stroke-scale (make-parameter 1))
(define char-edge-size 6)
(define (pathify vs)
(define p (new dc-path%))
(define pts
(for/list ([v (in-list vs)])
(list (* (current-cell-size) (sub1 (modulo v 10)))
(* (current-cell-size) (- 4 (sub1 (floor (/ v 10))))))))
(send/apply p move-to (car pts))
(for/last ([pt (in-list (cdr pts))])
(send/apply p line-to pt))
(when (= (first vs) (last vs)) (send p close))
p)
(struct $glyph (name paths))
(define font-definition
'((a (51 54 45 15 12 21 31 33))
(b (11 51 55 25 14 13) (35 33))
(c (25 15 11 41 52 55 45))
(d (31 11 14 25 45 54 51))
(e (15 11 41 52 55 35 33))
(E (55 52 41 11 15) (31 35))
(f (11 41 52 55) (31 35))
(g (33 35 15 11 41 52 55))
(h (11 51) (15 55) (31 35))
(i (11 15) (51 55) (13 53))
(j (53 55 15 12 21 31))
(k (11 51) (11 21 54 55) (43 34 25 15))
(L (51 11 15) (53 33 35))
(l (25 15 11 41 52))
(m (11 51 54 45 15) (53 13))
(n (11 51 54 45 15))
(N (11 51 52 43 23 14 15 55))
(O (11 41 52 55 25 14 11))
(o (51 54 45 15 12 21 51))
(P (11 51 54 45 35 24 23))
(p (51 54 45 35 33 13 11 31))
(p0 (11 51 55 35 24 23))
(q (33 24 13 11 41 52 55 35 24))
(r (11 51 53 54 45 35 33 23 14 15))
(s (11 14 25 35 31 41 52 55))
(t (31 51 55 35) (53 13) (11 15))
(T (51 55) (53 13))
(u (51 21 12 15 55))
(v (55 35 13 11 51))
(w (51 21 12 15 55) (53 13))
(x (51 52 43 23 14 15) (11 12 23 43 54 55))
(X (51 41 32 34 25 15) (11 21 32 34 45 55))
(y (51 31 35)(55 25 14 11))
(z (51 55 45 34 32 21 11 15))
( (12 21 41 52 43 54 45 25 14 12))
(0 (51 54 45 15 12 21 31 51))
(1 (51 53 13) (11 15))
(2 (51 54 45 35 31 11 15))
(3 (51 54 45 15 11) (31 35))
(4 (41 21 25) (54 14))
(5 (55 51 31 35 25 14 11))
(6 (31 35 25 14 11 41 52 55))
(7 (51 55 45 22 12))
(8 (12 21 51 54 45 15 12) (31 35))
(9 (11 14 25 55 52 41 31 35))
(λ (51 52 25 15) (11 21 43))
(> (51 52 25 15))
(% (11 51) (12 52) (13 53) (14 54) (15 55))
(^ (11 51) (12 42) (13 33) (14 24))
(< (11 21 43))
(|(| (55 54 43 23 14 15))
(|)| (51 52 43 23 12 11))))
(define glyphs (map (λ (i) ($glyph (->string (car i)) (map pathify (cdr i)))) font-definition))
(define (type str [xoffset 0] [yoffset 0] #:color color-proc #:width width)
(send* (current-dc)
[set-brush "white" 'transparent]
[set-pen (make-pen #:color (->string (if (procedure? color-proc) (color-proc) color-proc)) #:width width #:style 'solid #:cap 'projecting #:join 'miter)])
(for/fold ([xoffset xoffset]
[yoffset yoffset])
([c (in-list (string->list str))])
(define g (findf (λ (g) (equal? ($glyph-name g) (string c))) glyphs))
(when g
(for ([p (in-list ($glyph-paths g))])
(send (current-dc) draw-path p
(+ xoffset (current-cell-size))
(+ yoffset (current-cell-size)))))
(values (+ xoffset (* (current-cell-size) char-edge-size)) yoffset)))
(define (layer-type str #:xoffset [xoffset 0] #:yoffset [yoffset 0] . attrs)
(for ([layer (in-list (for/list ([i (in-range 0 (length attrs) 2)])
(list (list-ref attrs i) (list-ref attrs (add1 i)))))])
(type str xoffset yoffset #:color (first layer) #:width (* (current-cell-size) (current-stroke-scale) (second layer)))))
(define (render text layers [stroke-scale (/ 1 char-edge-size)] [name 'test])
(define lines (string-split text))
(define horiz (* (current-cell-size) (apply max (map string-length lines)) char-edge-size))
(define vert (* (current-cell-size) char-edge-size (length lines)))
(parameterize* ([current-bitmap (case (current-target)
[(svg) #false]
[else (make-bitmap horiz vert)])]
[current-dc
(case (current-target)
[(svg) (new svg-dc%
[width horiz]
[height vert]
[output (build-path
(find-system-path 'desk-dir)
(format "~a.svg" name))]
[exists 'replace])]
[else (new bitmap-dc% [bitmap (current-bitmap)])])]
[current-stroke-scale stroke-scale])
(case (current-target)
[(svg) (send* (current-dc) [start-doc ""][start-page])])
(send (current-dc) set-smoothing 'smoothed)
(for* ([(line lineidx) (in-indexed lines)]
[layer (in-list layers)])
(apply layer-type line
#:yoffset (* (current-cell-size) char-edge-size lineidx)
layer))
(case (current-target)
[(svg) (send* (current-dc) [end-page][end-doc])]
[(png) (send (current-bitmap) save-file (build-path
(find-system-path 'desk-dir)
(format "~a.png" name)) 'png)]
[(gui) (make-object image-snip% (current-bitmap))])))
(define (render-svg . args)
(parameterize ([current-target 'svg])
(apply render args)))
(define (render-png . args)
(parameterize ([current-target 'png])
(apply render args)))
(module+ main
(render "PoLEn" (for/list ([color (in-cycle '(Black White))]
[size (in-range 11 0 -2)])
(list color size))))

@ -39,7 +39,7 @@
(λ (path-or-path-string subkey caller-name)
(define path
(with-handlers ([exn:fail? (path-error-handler caller-name path-or-path-string)])
(simple-form-path (if (path? path-or-path-string)
(path->complete-path (if (path? path-or-path-string)
path-or-path-string
(string->path path-or-path-string)))))
(unless (file-exists? path)
@ -61,7 +61,7 @@
(cached-require-base path-string subkey 'cached-require))
(define+provide (cached-doc path-string)
(cached-require-base path-string pollen-main-export 'cached-doc))
(cached-require-base path-string (setup:main-export) 'cached-doc))
(define+provide (cached-metas path-string)
(cached-require-base path-string pollen-meta-export 'cached-metas))
(cached-require-base path-string (setup:meta-export) 'cached-metas))

@ -1,7 +1,7 @@
#lang racket/base
(require (for-syntax
racket/base
"private/constants.rkt")
"setup.rkt")
racket/match
txexpr/base
xml/path
@ -120,7 +120,7 @@
(define-syntax (when/splice stx)
(syntax-case stx ()
[(_ COND . BODY)
(with-syntax ([SPLICING-TAG (datum->syntax stx pollen-splicing-tag)])
(with-syntax ([SPLICING-TAG (datum->syntax stx (setup:splicing-tag))])
#'(if COND
(SPLICING-TAG . BODY)
(SPLICING-TAG)))]))
@ -130,7 +130,7 @@
(define-syntax (for/splice/base stx)
(syntax-case stx ()
[(_ ITERATORS . BODY)
(with-syntax ([SPLICING-TAG (datum->syntax stx pollen-splicing-tag)]
(with-syntax ([SPLICING-TAG (datum->syntax stx (setup:splicing-tag))]
[FORM (or (syntax-property stx 'form) #'for/list)])
#'(apply SPLICING-TAG (FORM ITERATORS
(SPLICING-TAG . BODY))))]))

@ -16,8 +16,8 @@
(check-equal? (->preproc-source-path "foo") (->path "foo.pp"))
(check-equal? (->preproc-source-path 'foo) (->path "foo.pp"))
(check-true (pagetree-source? (format "foo.~a" pollen-pagetree-source-ext)))
(check-false (pagetree-source? (format "~a.foo" pollen-pagetree-source-ext)))
(check-true (pagetree-source? (format "foo.~a" (setup:pagetree-source-ext))))
(check-false (pagetree-source? (format "~a.foo" (setup:pagetree-source-ext))))
(check-false (pagetree-source? #f))
(check-true (markup-source? "foo.pm"))

@ -4,6 +4,10 @@
(define raco-commands '(("pollen" (submod pollen/private/command raco) "issue Pollen command" #f)))
(define compile-omit-paths '("test" "tools" "server-extras" "scribblings/third-tutorial-files"))
;; it's redundant to test "pollen.scrbl" because it incorporates the other scribble sources by reference
(define test-omit-paths '("test/data" "tools" "server-extras" "scribblings/third-tutorial-files" "test/test-project-port.rkt"))
;; don't test app.rkt because it launches the gui
(define test-omit-paths '("test/data" "tools" "server-extras" "scribblings/third-tutorial-files" "scribblings/pollen.scrbl" "app"))
;; don't put #"p" in this list because it's not a #lang
(define module-suffixes '(#"pp" #"pm" #"pmd" #"ptree"))
(define gracket-launcher-names '("Pollen"))
(define gracket-launcher-libraries '("app/app.rkt"))

@ -1,29 +1,54 @@
#lang racket/base
#|
Implements the pollen/mode metalanguage. Certain values are hardcoded inside the Racket source, so we have to copy & paste, a little.
Implements the pollen/mode metalanguage.
Problem is that scribble/reader, and the at-exp metalanguage, changed after 6.1.
So this file
a) adapts the at-exp metalang from 6.2
b) incorporates the scribble/reader from 6.2
so that everything will work correctly in 6.0.
Note that pollen/mode uses a hardcoded #\◊, as the command char, NOT (setup:command-char),
because importing `pollen/setup` will create a loading loop
if pollen/mode were used in "pollen.rkt" (which is a likely place to use it)
Note that pollen/mode uses default-command-char, NOT (setup:command-char),
because doing so would create a loading loop if pollen/mode were used in "pollen.rkt" (which is a likely place to use it)
Intractable problem; unavoidable limitation.
|#
;; because the reader "boots" from `pollen/mode`,
;; Racket looks for the `language-info` submodule in `pollen/mode`
;; so we just re-export the default.
(module language-info racket/base
(require at-exp/lang/language-info)
(provide (all-from-out at-exp/lang/language-info)))
(module* runtime-config racket/base
(provide configure)
(require (only-in (submod ".." at-reader) make-at-readtable))
(define (configure data)
(define old-read (current-read-interaction))
(define (new-read src in)
(parameterize ([current-readtable (make-at-readtable #:readtable (current-readtable))])
(old-read src in)))
(current-read-interaction new-read)))
;; adapted from
;; https://github.com/racket/racket/blob/master/pkgs/at-exp-lib/at-exp/lang/reader.rkt
(module* language-info racket/base
(provide get-language-info)
(require racket/match)
(define (get-language-info data)
(define other-get-info
(match data
[(vector mod sym data2)
((dynamic-require mod sym) data2)]
[_ (λ (key default) default)]))
(λ (key default)
(case key
[(configure-runtime)
(define config-vec '#[(submod pollen/mode runtime-config) configure #f])
(define other-config (other-get-info key default))
(cond [(list? other-config) (cons config-vec other-config)]
[else (list config-vec)])]
[else (other-get-info key default)]))))
(module* reader racket/base
(require syntax/module-reader
(only-in scribble/reader make-at-readtable))
(only-in (submod ".." at-reader) make-at-readtable))
(provide (rename-out [at-read read]
[at-read-syntax read-syntax]
@ -33,7 +58,7 @@ Intractable problem; unavoidable limitation.
(λ args
(parameterize ([current-readtable (make-at-readtable #:datum-readtable 'dynamic
#:command-readtable 'dynamic
#:command-char #\◊)])
#:command-char (dynamic-require 'pollen/setup 'default-command-char))])
(apply p args))))
(define-values (at-read at-read-syntax at-get-info)
@ -55,7 +80,7 @@ Intractable problem; unavoidable limitation.
(λ args
(define stx (apply read-syntax args))
(define old-prop (syntax-property stx 'module-language))
(define new-prop `#(at-exp/lang/language-info get-language-info ,old-prop))
(define new-prop `#((submod pollen/mode language-info) get-language-info ,old-prop))
(syntax-property stx 'module-language new-prop)))
(λ (proc)
(λ (key defval)
@ -73,3 +98,675 @@ Intractable problem; unavoidable limitation.
[(drracket:indentation)
(dynamic-require 'pollen/private/external/mode-indentation 'determine-spaces)]
[else (fallback)]))))))
(module at-reader racket/base
;; ============================================================================
;; Implements the @-reader macro for embedding text in Racket code.
(require syntax/readerr)
;; ----------------------------------------------------------------------------
;; utilities for syntax specifications below
;; regexps
(define (px . args)
(let* ([args (let loop ([xs args])
(if (list? xs) (apply append (map loop xs)) (list xs)))]
[args (map (lambda (x)
(cond [(bytes? x) x]
[(string? x) (string->bytes/utf-8 x)]
[(char? x) (regexp-quote (string->bytes/utf-8 (string x)))]
[(not x) #""]
[else (internal-error 'px)]))
args)])
(byte-pregexp (apply bytes-append args))))
(define (^px . args) (px #"^" args))
;; reverses a byte string visually
(define reverse-bytes
(let ([pairs (let ([xs (bytes->list #"([{<")]
[ys (bytes->list #")]}>")])
(append (map cons xs ys) (map cons ys xs)))])
(define (rev-byte b)
(cond [(assq b pairs) => cdr]
[else b]))
(lambda (bs) (list->bytes (map rev-byte (reverse (bytes->list bs)))))))
;; ----------------------------------------------------------------------------
;; syntax
;; basic syntax customization
(define ch:command #\@)
(define ch:comment #\;)
(define ch:expr-escape #\|)
(define ch:datums-begin #\[)
(define ch:datums-end #\])
(define ch:lines-begin #\{)
(define ch:lines-end #\})
(define str:lines-begin* #"(\\|[^a-zA-Z0-9 \t\r\n\f@\\\177-\377{]*)\\{")
(define str:end-of-line "[ \t]*\r?\n[ \t]*") ; eat spaces on the next line
;; regexps based on the above (more in make-dispatcher)
(define re:whitespaces (^px "\\s+"))
(define re:comment-start (^px ch:comment))
(define re:comment-line (^px "[^\n]*(?:\n|$)[ \t]*")) ; like tex's `%'
(define re:expr-escape (^px ch:expr-escape))
(define re:datums-begin (^px ch:datums-begin))
(define re:datums-end (^px ch:datums-end))
(define re:lines-begin (^px ch:lines-begin))
(define re:lines-begin* (^px str:lines-begin*))
(define re:lines-end (^px ch:lines-end))
(define re:end-of-line (^px str:end-of-line))
;; ----------------------------------------------------------------------------
;; utilities
(define (internal-error label)
(error 'scribble-reader "internal error [~a]" label))
;; like `regexp-try-match', without extras; the regexp that is used
;; must be anchored -- nothing is dropped
(define (*regexp-match-peek-positions pattern input-port)
#; ; sanity checks, not needed unless this file is edited
(unless (and (byte-regexp? pattern)
(regexp-match? #rx#"^\\^" (object-name pattern)))
(internal-error 'invalid-bregexp))
(regexp-match-peek-positions pattern input-port))
;; the following doesn't work -- must peek first
;; (define (*regexp-match-positions pattern input-port)
;; #; ; sanity checks, not needed unless this file is edited
;; (unless (and (byte-regexp? pattern)
;; (regexp-match? #rx#"^\\^" (object-name pattern)))
;; (internal-error 'invalid-bregexp))
;; (regexp-match-peek-positions pattern input-port))
(define (*regexp-match pattern input-port)
(let ([m (*regexp-match-peek-positions pattern input-port)])
(and m (let ([s (read-bytes (cdar m) input-port)])
(cons s (map (lambda (p) (and p (subbytes s (car p) (cdr p))))
(cdr m)))))))
;; like regexp-match, but returns the whole match
(define (*regexp-match1 pattern input-port)
(let ([m (*regexp-match-peek-positions pattern input-port)])
(and m (read-bytes (cdar m) input-port))))
;; Utility for readtable-based caches
(define (readtable-cached fun)
(let ([cache (make-weak-hasheq)])
(letrec ([readtable-cached
(case-lambda
[(rt) (hash-ref cache rt
(lambda ()
(let ([r (fun rt)])
(hash-set! cache rt r)
r)))]
[() (readtable-cached (current-readtable))])])
readtable-cached)))
;; Skips whitespace characters, sensitive to the current readtable's
;; definition of whitespace; optimizes common spaces when possible
(define skip-whitespace
(let* ([plain-readtables (make-weak-hasheq)]
[plain-spaces " \t\n\r\f"]
[plain-spaces-list (string->list " \t\n\r\f")]
[plain-spaces-re (^px "[" plain-spaces "]*")])
(define (skip-plain-spaces port)
;; hack: according to the specs, this might consume more characters
;; than needed, but it works fine with a simple <ch>* regexp (because
;; it can always match an empty string)
(*regexp-match-peek-positions plain-spaces-re port))
(define (whitespace? ch rt)
(if rt
(let-values ([(like-ch/sym _1 _2) (readtable-mapping rt ch)])
;; if like-ch/sym is whitespace, then ch is whitespace
(and (char? like-ch/sym) (char-whitespace? like-ch/sym)))
;; `char-whitespace?' is fine for the default readtable
(char-whitespace? ch)))
(define plain-readtable?
(readtable-cached
(lambda (rt)
(andmap (lambda (ch) (whitespace? ch rt)) plain-spaces-list))))
(lambda (port)
(let* ([rt (current-readtable)] [plain? (plain-readtable? rt)])
(let loop ()
(when plain? (skip-plain-spaces port))
(let ([ch (peek-char port)])
(unless (eof-object? ch)
(when (whitespace? ch rt) (read-char port) (loop)))))))))
;; make n spaces, cached for n
(define make-spaces
(let ([t (make-hasheq)])
(lambda (n)
(hash-ref t n
(lambda ()
(let ([s (make-string n #\space)])
(hash-set! t n s) s))))))
(define (bytes-width bs start)
(let ([len (bytes-length bs)])
(if (regexp-match? #rx"^ *$" bs start)
(- (bytes-length bs) start)
(let loop ([i start] [w 0])
(if (= i len)
w
(loop (add1 i)
(+ w (if (eq? 9 (bytes-ref bs i)) (- 8 (modulo w 8)) 1))))))))
;; A syntax object that has the "original?" property:
(define orig-stx (read-syntax #f (open-input-string "dummy")))
;; ----------------------------------------------------------------------------
;; main reader function for @ constructs
(define (dispatcher char inp source-name line-num col-num position
start-inside? command-readtable ch:command
re:command re:line-item* re:line-item
re:line-item-no-nests datum-readtable
syntax-post-processor)
(define (read-error line col pos msg . xs)
(let* ([eof? (and (eq? 'eof msg) (pair? xs))]
[msg (apply format (if eof? xs (cons msg xs)))])
((if eof? raise-read-error raise-read-eof-error)
msg (or source-name (object-name inp)) line col pos (span-from pos))))
(define (read-error* . xs)
(apply read-error line-num col-num position xs))
(define (read-stx) (read-syntax/recursive source-name inp))
(define (read-stx/rt rt) (read-syntax/recursive source-name inp #f rt))
;; use this to avoid placeholders
(define (read-stx*)
;; (read-syntax/recursive source-name inp #f (current-readtable) #f)
(read-syntax source-name inp))
(define (*match rx) (*regexp-match rx inp))
(define (*match1 rx) (*regexp-match1 rx inp))
;; (define (*skip rx) (*regexp-match-positions rx inp)) ; <- see above
(define (*skip rx) (*regexp-match1 rx inp))
(define (*peek rx) (*regexp-match-peek-positions rx inp))
(define (span-from start)
(and start (let-values ([(line col pos) (port-next-location inp)])
(- pos start))))
(define (read-delimited-list begin-re end-re end-ch)
(let-values ([(line col pos) (port-next-location inp)])
(and (*skip begin-re)
(let loop ([r '()])
(skip-whitespace inp)
(if (*skip end-re)
(reverse r)
(let ([x (read-stx)])
(if (eof-object? x)
(read-error line col pos 'eof "expected a '~a'" end-ch)
(loop (if (special-comment? x) r (cons x r))))))))))
;; identifies newlines in text
(define (eol-syntax? x)
(let ([p (and (syntax? x) (syntax-property x 'scribble))])
(and (pair? p) (eq? 'newline (car p)))))
;; gets an accumulated (reversed) list of syntaxes and column markers, and
;; sorts things out (remove prefix and suffix newlines, adds indentation if
;; needed)
(define (done-items xs)
;; a column marker is either a non-negative integer N (saying the following
;; code came from at column N), or a negative integer -N (saying that the
;; following code came from column N but no need to add indentation at this
;; point because it is at the openning of a {...}); `get-lines*' is careful
;; not to include column markers before a newline or the end of the text,
;; and a -N marker can only come from the beginning of the text (and it's
;; never there if the text began with a newline)
(if (andmap eol-syntax? xs)
;; nothing to do
(reverse xs)
(let ([mincol (let loop ([xs xs] [m #f])
(if (null? xs)
m
(let ([x (car xs)])
(loop (cdr xs)
(if (integer? x)
(let ([x (abs x)]) (if (and m (< m x)) m x))
m)))))])
(let loop ([xs (if (and (not start-inside?) (eol-syntax? (car xs)))
(cdr xs) ; trim last eol
xs)]
[r '()])
(if (or (null? xs)
(and (not start-inside?)
;; trim first eol
(null? (cdr xs)) (eol-syntax? (car xs))))
r
(loop
(cdr xs)
(let ([x (car xs)])
(cond [(integer? x)
(if (or (< x 0) (= x mincol))
r ; no indentation marker, or zero indentation
(let ([eol (cadr xs)]
[spaces (make-spaces (- x mincol))])
;; markers always follow end-of-lines
(unless (eol-syntax? eol)
(internal-error 'done-items))
(cons (syntax-property
(datum->syntax eol spaces eol)
'scribble 'indentation)
r)))]
;; can have special comment values from "@||"
[(special-comment? x) r]
[else (cons x r)]))))))))
;; cons stx (new syntax) to the list of stxs, merging it if both are
;; strings, except for newline markers
(define (maybe-merge stx stxs)
(let* ([2nd (and (syntax? stx) (syntax-e stx))]
[stx0 (and (pair? stxs) (car stxs))]
[1st (and (syntax? stx0) (syntax-e stx0))])
(if (and (string? 1st) (not (eol-syntax? stx0))
(string? 2nd) (not (eol-syntax? stx)))
(cons (datum->syntax stx0
(string-append 1st 2nd)
(vector (syntax-source stx0)
(syntax-line stx0)
(syntax-column stx0)
(syntax-position stx0)
;; this is called right after reading stx
(span-from (syntax-position stx0)))
stx0)
(cdr stxs))
(cons stx stxs))))
;; helper for `get-lines*' drop a column marker if the previous item was also
;; a newline (or the beginning)
(define (maybe-drop-marker r)
(if (and (pair? r) (integer? (car r))
(or (null? (cdr r)) (eol-syntax? (cadr r))))
(cdr r)
r))
(define (get-lines* re:begin re:end re:cmd-pfx re:item end-token)
;; re:begin, re:end, end-token can be false if start-inside? is #t;
;; re:cmd-pfx is a regexp when we do sub-@-reads only after a prefix
(let loop ([lvl 0]
[r (let-values ([(l c p) (port-next-location inp)])
;; marker for the beginning of the text
(if c (list (- c)) '()))])
;; this loop collects lines etc for the body, and also puts in column
;; markers (integers) after newlines -- the result is handed off to
;; `done-items' to finish the job
(define-values (line col pos) (port-next-location inp))
(define (make-stx sexpr)
(datum->syntax #f
(if (bytes? sexpr) (bytes->string/utf-8 sexpr) sexpr)
(vector source-name line col pos (span-from pos))
orig-stx))
(cond
[(and re:begin (*match1 re:begin))
=> (lambda (m) (loop (add1 lvl) (maybe-merge (make-stx m) r)))]
[(and re:end (*match1 re:end))
=> (lambda (m)
(if (and (zero? lvl) (not start-inside?))
;; drop a marker if it's after a last eol item
(done-items (maybe-drop-marker r))
(loop (sub1 lvl) (maybe-merge (make-stx m) r))))]
[(*match1 re:end-of-line)
=> (lambda (m)
(let ([n (car (regexp-match-positions #rx#"\n" m))])
(loop lvl (list* ; no merge needed
(bytes-width m (cdr n))
(syntax-property
(make-stx "\n")
'scribble `(newline ,(bytes->string/utf-8 m)))
(maybe-drop-marker r)))))]
[(if re:cmd-pfx
(and (*skip re:cmd-pfx) (*peek re:command))
(*peek re:command))
;; read the next value
=> (lambda (m)
(define x (cond [(cadr m)
;; the command is a string escape, use
;; `read-stx*' to not get a placeholder, so we
;; can merge the string to others
(read-stx*)]
[(caddr m)
;; it's an expression escape, get multiple
;; expressions and put them all here
(read-bytes (caaddr m) inp)
(get-escape-expr #f)]
[else (read-stx)])) ; otherwise: a plain sub-read
(loop lvl (cond [(eof-object? x)
;; shouldn't happen -- the sub-read would
;; raise an error
(internal-error 'get-lines*-sub-read)]
;; throw away comments
[(special-comment? x) r]
;; escaped expressions: no merge, and add a
;; comment to prevent merges with later stuff
[(pair? x)
`(,(make-special-comment #f) ,@(reverse x) ,@r)]
[(null? x) (cons (make-special-comment #f) r)]
[else (maybe-merge x r)])))]
;; must be last, since it will always succeed with 1 char
[(*peek re:item) ; don't read: regexp grabs the following text
=> (lambda (m)
(loop lvl
(maybe-merge (make-stx (read-bytes (cdadr m) inp)) r)))]
[(*peek #rx#"^$")
(if end-token
(read-error* 'eof "missing closing `~a'" end-token)
(done-items r))]
[else (internal-error 'get-lines*)])))
(define (get-lines)
(cond [(*skip re:lines-begin) (get-lines* re:lines-begin re:lines-end #f
re:line-item ch:lines-end)]
[(*match re:lines-begin*)
=> (lambda (m)
(let* ([bgn (car m)]
[end (reverse-bytes bgn)]
[bgn* (regexp-quote bgn)]
[end* (regexp-quote end)]
[cmd-pfx* (regexp-quote (cadr m))])
(get-lines* (^px bgn*) (^px end*)
(^px cmd-pfx* "(?=" ch:command ")")
(re:line-item* bgn* end* cmd-pfx*)
end)))]
[else #f]))
(define (get-datums)
(parameterize ([current-readtable datum-readtable])
(read-delimited-list re:datums-begin re:datums-end ch:datums-end)))
(define (get-escape-expr single?)
;; single? means expect just one expression (or none, which is returned as
;; a special-comment)
(let ([get (lambda ()
(parameterize ([current-readtable command-readtable])
(read-delimited-list re:expr-escape re:expr-escape
ch:expr-escape)))])
(if single?
(let*-values ([(line col pos) (port-next-location inp)]
[(xs) (get)])
(cond [(not xs) xs]
[(or (null? xs) (not (null? (cdr xs))))
(read-error line col pos
"a ~a|...| form in Racket mode must have ~a"
ch:command
"exactly one escaped expression")]
[else (car xs)]))
(get))))
;; called only when we must see a command in the input
(define (get-command)
(let ([cmd (read-stx/rt command-readtable)])
(cond [(special-comment? cmd)
(read-error* "expecting a command expression, got a comment")]
[(eof-object? cmd)
(read-error* 'eof "missing command")]
;; we have a command: adjust its location to include the dispatch
;; character
[else
;; (datum->syntax #f (syntax-e cmd)
;; (vector (syntax-source cmd)
;; (syntax-line cmd)
;; (cond [(syntax-column cmd) => sub1] [else #f])
;; (cond [(syntax-position cmd) => sub1] [else #f])
;; (cond [(syntax-span cmd) => add1] [else #f]))
;; orig-stx)
;; The reasoning for the above is that in `@foo' the `@' is part
;; of the syntax of the identifier, in a similar way to including
;; the double quotes in the position information for a string
;; syntax or the backslash in a mzscheme \foo identifier. Another
;; feature of this is that there needs to be some way to know what
;; was the actual source of some syntax. However, this is
;; problematic in two ways: (a) it can be confusing that
;; highlighting an identifier highlights the `@' too, and more
;; importantly, it makes `@|foo|' be treated differently than
;; `@foo'. So we'll try to not do this adjusting.
cmd])))
(define (get-rprefixes) ; return punctuation prefixes in reverse
(let loop ([r '()])
(let-values ([(line col pos) (port-next-location inp)])
(cond [(*match1 #rx#"^#?(?:'|`|,@?)")
=> (lambda (m)
(let ([sym (cond [(assoc m '([#"'" quote]
[#"`" quasiquote]
[#"," unquote]
[#",@" unquote-splicing]
[#"#'" syntax]
[#"#`" quasisyntax]
[#"#," unsyntax]
[#"#,@" unsyntax-splicing]))
=> cadr]
[else (internal-error 'get-rprefixes)])])
(loop (cons (datum->syntax #f sym
(vector source-name line col
pos (span-from pos))
orig-stx)
r))))]
[(*skip re:whitespaces)
(read-error* "unexpected whitespace after ~a" ch:command)]
[else r]))))
(cond
[start-inside?
(datum->syntax #f (get-lines* #f #f #f re:line-item-no-nests #f)
(vector source-name line-num col-num position (span-from position))
orig-stx)]
[(*skip re:whitespaces)
(read-error* "unexpected whitespace after ~a" ch:command)]
[(*skip re:comment-start)
(unless (get-lines) (*skip re:comment-line))
(make-special-comment #f)]
[else
(let*-values
([(rpfxs) (get-rprefixes)]
[(cmd datums lines)
(cond [(get-lines)
;; try get-lines first -- so @|{...}| is not used as a simple
;; expression escape, same for get-datums
=> (lambda (lines) (values #f #f lines))]
[(get-datums)
=> (lambda (datums) (values #f datums (get-lines)))]
[(get-escape-expr #t) => (lambda (expr) (values expr #f #f))]
[else (values (get-command) (get-datums) (get-lines))])]
[(stx) (and (or datums lines)
(append (or datums '()) (or lines '())))]
[(stx) (or (and cmd stx (cons cmd stx)) ; all parts
stx ; no cmd part => just a parenthesized expression
cmd ; no datums/lines => simple expression (no parens)
;; impossible: either we saw []s or {}s, or we read a
;; racket expression
(internal-error 'dispatcher))]
[(stx) (let ([ds (and datums (length datums))]
[ls (and lines (length lines))])
(syntax-property
(if (syntax? stx)
stx
(datum->syntax #f stx
(vector source-name line-num col-num position
(span-from position))
orig-stx))
'scribble (list 'form ds ls)))]
[(stx) (syntax-post-processor stx)]
[(stx)
;; wrap the prefixes around the result
(let loop ([rpfxs rpfxs] [stx stx])
(if (null? rpfxs)
stx
(loop (cdr rpfxs) (list (car rpfxs) stx))))])
(datum->syntax #f stx (vector source-name line-num col-num position
(span-from position))
orig-stx))]))
(define (make-dispatcher start-inside? ch:command
get-command-readtable get-datum-readtable
syntax-post-processor)
(define re:command (^px ch:command
;; the following identifies string and expression
;; escapes, see how it is used above
"(?:(\")|("ch:expr-escape"))?"))
(define (re:line-item* bgn end cmd-prefix)
(^px "(.+?)(?:" (and bgn `(,bgn"|")) (and end `(,end"|"))
cmd-prefix ch:command"|"str:end-of-line"|$)"))
(define re:line-item (re:line-item* ch:lines-begin ch:lines-end #f))
(define re:line-item-no-nests (and start-inside? (re:line-item* #f #f #f)))
(lambda (char inp source-name line-num col-num position)
(dispatcher char inp source-name line-num col-num position
start-inside? (get-command-readtable) ch:command
re:command re:line-item* re:line-item re:line-item-no-nests
(get-datum-readtable) syntax-post-processor)))
;; ----------------------------------------------------------------------------
;; minor utilities for the below
(define default-src (gensym 'scribble-reader))
(define (src-name src port)
(if (eq? src default-src) (object-name port) src))
(define-syntax-rule (named-lambda (name . args) . body)
(let ([name (lambda args . body)]) name))
;; ----------------------------------------------------------------------------
;; readtable and reader
(provide make-at-readtable make-at-reader)
(define ((make-at-readtable-or-inside-reader inside-reader?)
readtable command-char command-readtable datum-readtable syntax-post-processor)
(define (get-cmd-rt)
(if (readtable? cmd-rt)
cmd-rt
(cmd-rt)))
(define (get-datum-rt)
(if (eq? datum-rt 'dynamic)
(current-readtable)
datum-rt))
(define dispatcher
(make-dispatcher #f command-char get-cmd-rt get-datum-rt
syntax-post-processor))
(define (make-inside-reader)
(define dispatcher
(make-dispatcher #t command-char get-cmd-rt get-datum-rt
syntax-post-processor))
;; use a name consistent with `make-at-reader'
(named-lambda (at-read-syntax/inside [src default-src]
[inp (current-input-port)])
(define-values [line col pos] (port-next-location inp))
(parameterize ([current-readtable at-rt])
(dispatcher #f inp (src-name src inp) line col pos))))
(define at-rt
(make-readtable readtable command-char 'non-terminating-macro dispatcher))
(define command-bar
(lambda (char inp source-name line-num col-num position)
(let ([m (*regexp-match #rx#"^([^|]*)\\|" inp)])
(unless m
(raise-read-error "unbalanced `|'" source-name
line-num col-num position #f))
(datum->syntax
#f (string->symbol (bytes->string/utf-8 (cadr m)))
(vector source-name line-num col-num position
(add1 (bytes-length (car m))))
orig-stx))))
(define (make-cmd-rt command-readtable)
;; similar to plain Racket (scribble, actually), but with `@' as usual and
;; and `|' as a terminating macro characters (otherwise it behaves the
;; same; the only difference is that `a|b|c' is three symbols)
(make-readtable command-readtable
command-char 'non-terminating-macro dispatcher
#\| 'terminating-macro command-bar))
(define cmd-rt
(if (eq? command-readtable 'dynamic)
(readtable-cached make-cmd-rt)
(make-cmd-rt command-readtable)))
(define datum-rt
(cond [(or (not datum-readtable) (readtable? datum-readtable))
datum-readtable]
[(eq? #t datum-readtable) at-rt]
[(procedure? datum-readtable) (datum-readtable at-rt)]
[(eq? datum-readtable 'dynamic) 'dynamic]
[else (error 'make-at-readtable
"bad datum-readtable: ~e" datum-readtable)]))
(if inside-reader? (make-inside-reader) at-rt))
(define (make-at-readtable
#:readtable [readtable (current-readtable)]
#:command-char [command-char ch:command]
#:command-readtable [command-readtable readtable]
#:datum-readtable [datum-readtable #t]
#:syntax-post-processor [syntax-post-processor values])
((make-at-readtable-or-inside-reader #f)
readtable command-char command-readtable datum-readtable syntax-post-processor))
(define (make-at-reader
#:readtable [readtable (current-readtable)]
#:command-char [command-char ch:command]
#:datum-readtable [datum-readtable #t]
#:command-readtable [command-readtable readtable]
#:syntax-post-processor [syntax-post-processor values]
#:syntax? [syntax-reader? #t]
#:inside? [inside-reader? #f])
(let ([r ((make-at-readtable-or-inside-reader inside-reader?)
readtable command-char command-readtable datum-readtable syntax-post-processor)])
;; the result can be a readtable or a syntax reader, depending on inside?,
;; convert it now to the appropriate reader
(if inside-reader?
;; if it's a function, then it already is a syntax reader, convert it to
;; a plain reader if needed (note: this only happens when r is a reader)
(if syntax-reader?
r
(named-lambda (at-read/inside [in (current-input-port)])
;; can't be eof, since it returns a list of expressions (as a syntax)
(syntax->datum (r (object-name in) in))))
;; if it's a readtable, then just wrap the standard functions
(if syntax-reader?
(named-lambda (at-read-syntax [src default-src]
[inp (current-input-port)])
(parameterize ([current-readtable r])
(read-syntax src inp)))
(named-lambda (at-read [inp (current-input-port)])
(parameterize ([current-readtable r])
(let ([r (read-syntax (object-name inp) inp)])
;; it might be eof
(if (syntax? r) (syntax->datum r) r))))))))
(provide use-at-readtable)
(define use-at-readtable
(make-keyword-procedure
(lambda (kws kw-args . rest)
(port-count-lines! (current-input-port))
(current-readtable
(keyword-apply make-at-readtable kws kw-args rest)))))
;; utilities for below
(define make-default-at-readtable
(readtable-cached (lambda (rt) (make-at-readtable #:readtable rt
#:command-readtable 'dynamic
#:datum-readtable 'dynamic))))
(define make-default-at-reader/inside
(readtable-cached
(lambda (rt) (make-at-reader #:inside? #t #:readtable rt
#:command-readtable 'dynamic
#:datum-readtable 'dynamic))))
;; ----------------------------------------------------------------------------
;; readers
(provide (rename-out [*read read] [*read-syntax read-syntax]))
(define (*read [inp (current-input-port)])
(parameterize ([current-readtable (make-default-at-readtable)])
(read inp)))
(define (*read-syntax [src default-src] [inp (current-input-port)])
(parameterize ([current-readtable (make-default-at-readtable)])
(read-syntax (src-name src inp) inp)))
(provide read-inside read-syntax-inside)
(define (read-inside [inp (current-input-port)])
(syntax->datum ((make-default-at-reader/inside) default-src inp)))
(define (read-syntax-inside [src default-src] [inp (current-input-port)]
#:command-char [command-char ch:command])
(((readtable-cached
(lambda (rt) (make-at-reader #:inside? #t #:command-char command-char #:readtable rt))))
src inp)))

@ -215,21 +215,9 @@
(define+provide/contract (pagetree->list pt-or-path)
((or/c pagetree? pathish?) . -> . pagenodes?)
; use rest to get rid of root tag at front
(pagetree-strict->list (get-pagetree pt-or-path)))
(pagetree-strict->list (get-pagetree pt-or-path)))
(define+provide/contract (pagetree->paths pt-or-path)
((or/c pagetree? pathish?) . -> . (listof complete-path?))
(define-values (dir-for-resolving-paths pt)
(match pt-or-path
[(? pagetree?) (values (current-project-root) pt-or-path)]
[_ (define dir (match (dirname (->path pt-or-path))
['relative (current-project-root)]
[dir dir]))
(values dir (cached-doc pt-or-path))]))
(parameterize ([current-directory dir-for-resolving-paths])
(map ->complete-path (pagetree->list pt))))
(module-test-external
(define test-pagetree `(pagetree-main foo bar (one (two three))))
(check-equal? (pagetree->list test-pagetree) '(foo bar one two three)))
@ -308,17 +296,7 @@
(define starting-dir (match starting-path
[(? directory-exists?) starting-path]
[_ (dirname starting-path)]))
(define relpath (if (eq? starting-dir 'relative)
path
(find-relative-path (->complete-path starting-dir) (->complete-path path))))
(->output-path relpath))
(module-test-external
(check-equal? (path->pagenode "/foo/bar/index.html" "/foo") 'foo/bar/index.html)
(check-equal? (path->pagenode "/foo/bar/index.html" "/foo/bar") 'bar/index.html)
(check-equal? (path->pagenode "/foo/bar/index.html" (string->path "/foo/bar")) 'bar/index.html)
(check-equal? (path->pagenode "/foo/bar/index.html" "/foo/bar/other.html") 'index.html)
(check-equal? (path->pagenode "assets" 'index.html) 'assets))
(->output-path (find-relative-path (->complete-path starting-dir) (->complete-path path))))
(define+provide/contract (in-pagetree? pnish [pt-or-path (current-pagetree)])

@ -7,12 +7,10 @@
racket/file
racket/path
racket/list
racket/port
racket/match
sugar/coerce
sugar/test
racket/fasl
racket/serialize
compiler/cm)
(provide (all-defined-out))
@ -36,7 +34,7 @@
;; user-designated files to track
(map ->string (setup:cache-watchlist source-path)))))
(define env-rec (for/list ([env-name (in-list (cons default-env-name (sort (setup:envvar-watchlist source-path) bytes<?)))])
(cons env-name (match (getenv (->string env-name))
(cons env-name (match (getenv (string-downcase (->string env-name)))
[#false #false]
[str (string-downcase (->string str))]))))
(define poly-flag (and (has-inner-poly-ext? source-path) (current-poly-target)))
@ -46,9 +44,9 @@
[(? symbol? sym) sym]
[#false #false]
[_ (define cp (->complete-path ps))
(unless (file-exists? cp)
(message (format "watchlist file /~a does not exist" (find-relative-path (current-project-root) cp))))
(cons (path->string cp) (file-or-directory-modify-seconds cp #false (λ () 0)))])))
(unless (file-exists? cp)
(message (format "watchlist file /~a does not exist" (find-relative-path (current-project-root) cp))))
(cons (path->string cp) (file-or-directory-modify-seconds cp #false (λ () 0)))])))
(list* cache-type env-rec poly-flag (and output-path (path->string output-path)) path+mod-time-pairs))
(define (key->source-path key) (car (fifth key)))
@ -61,40 +59,28 @@
(define-namespace-anchor cache-utils-module-ns)
;; faster than the usual `managed-compile-zo`
(define caching-zo-compiler (make-caching-managed-compile-zo))
(define (path->hash path)
(define compilation-namespace
(cond
[(current-session-interactive?)
;; in interactive mode, we need a fresh namespace every time
;; and can't use bytecode, because it's possible that path
;; or any dependency (say, "pollen.rkt") has changed
(define bns (make-base-namespace))
(define outer-ns (namespace-anchor->namespace cache-utils-module-ns))
;; bring in currently instantiated params (unlike namespace-require)
(namespace-attach-module outer-ns 'pollen/setup bns)
bns]
[else
;; make bytecode, because we know that in a non-interactive sesssion
;; the sources won't change in the midst
(for-each caching-zo-compiler (cons path (or (get-directory-require-files path) null)))
; recycle namespace
(current-namespace)]))
;; I monkeyed around with using the metas submodule to pull out the metas (for speed)
;; but in practice most files get their doc requested too.
;; so it's just simpler to get both at once and be done with it.
;; the savings of avoiding two cache fetches at the outset outweighs
;; the benefit of not reloading doc when you just need metas.
;; new namespace forces `dynamic-require` to re-instantiate `path`
;; otherwise it gets cached in current namespace.
(define doc-missing-thunk (λ () ""))
(define metas-missing-thunk (λ () (hasheq)))
(parameterize ([current-namespace compilation-namespace]
[current-directory (dirname path)])
(hasheq pollen-main-export (dynamic-require path pollen-main-export doc-missing-thunk)
pollen-meta-export (dynamic-require path pollen-meta-export metas-missing-thunk))))
(for-each managed-compile-zo (or (get-directory-require-files path) null))
(apply hasheq
(let ([doc-key (setup:main-export)] [meta-key (setup:meta-export)])
(unless (and (symbol? doc-key) (symbol? meta-key))
(raise-argument-error 'path->hash "symbols for doc and meta key" (cons doc-key meta-key)))
;; I monkeyed around with using the metas submodule to pull out the metas (for speed)
;; but in practice most files get their doc requested too.
;; so it's just simpler to get both at once and be done with it.
;; the savings of avoiding two cache fetches at the outset outweighs
;; the benefit of not reloading doc when you just need metas.
;; new namespace forces `dynamic-require` to re-instantiate `path`
;; otherwise it gets cached in current namespace.
(parameterize ([current-namespace (make-base-namespace)]
[current-directory (dirname path)])
;; brings in currently instantiated params (unlike namespace-require)
(define outer-ns (namespace-anchor->namespace cache-utils-module-ns))
(namespace-attach-module outer-ns 'pollen/setup)
(define doc-missing-thunk (λ () ""))
(define metas-missing-thunk (λ () (hasheq)))
(list doc-key (dynamic-require path doc-key doc-missing-thunk)
meta-key (dynamic-require path meta-key metas-missing-thunk))))))
(define (my-make-directory* dir)
(define base (dirname dir))
@ -106,7 +92,7 @@
(define (make-cache-dirs path)
(define path-dir (dirname path))
(define cache-dir (build-path path-dir pollen-cache-dir-name pollen-cache-subdir-name))
(define cache-dir (build-path path-dir (setup:cache-dir-name) (setup:cache-subdir-name)))
(define private-cache-dir (build-path cache-dir "private"))
(my-make-directory* private-cache-dir) ; will also make cache-dir, if needed
(values cache-dir private-cache-dir))
@ -123,13 +109,9 @@
(define dest-file (build-path cache-dir (format "~a.rktd" dest-path-filename)))
(define (generate-dest-file)
(message-debug (format "cache miss for ~a" dest-file))
#;(with-output-to-file dest-file
(λ ()
(define op (open-output-bytes))
(s-exp->fasl (path-hash-thunk) op)
(write-bytes (get-output-bytes op)))
#:exists 'replace)
(write-to-file (serialize (path-hash-thunk)) dest-file #:exists 'replace))
(with-output-to-file dest-file
(λ () (s-exp->fasl (path-hash-thunk) (current-output-port)))
#:exists 'replace))
;; `cache-file` looks for a file in private-cache-dir previously cached with key
;; (which in this case carries modification dates and POLLEN env).
@ -152,6 +134,5 @@
[(or "cache attempt failed: could not acquire exclusive lock"
"cache attempt failed: could not acquire shared lock") (void)]
[_ (log-pollen-error str)])))
#;(with-input-from-file dest-file
(λ () (fasl->s-exp (port->bytes))))
(deserialize (file->value dest-file)))
(with-input-from-file dest-file
(λ () (fasl->s-exp (current-input-port)))))

@ -7,8 +7,8 @@
sugar/coerce
"file-utils.rkt"
"log.rkt"
"../setup.rkt"
"../pagetree.rkt")
"../setup.rkt")
(provide start-project-server)
;; The use of dynamic-require throughout this file is intentional:
;; this way, low-dependency raco commands (like "version") are faster.
@ -45,14 +45,14 @@
[(let ([str (getenv "PLTSTDERR")])
(and str (regexp-match "@pollen" str))) (dispatch-thunk)]
[else (with-logging-to-port
(current-error-port)
dispatch-thunk
#:logger pollen-logger
'info
'pollen)]))
(current-error-port)
dispatch-thunk
#:logger pollen-logger
'info
'pollen)]))
(define (very-nice-path x)
(simple-form-path (cleanse-path (->path x))))
(path->complete-path (simplify-path (cleanse-path (->path x)))))
(define (handle-test)
(displayln "raco pollen is installed correctly"))
@ -105,7 +105,6 @@ version print the version" (current-server-port) (make-publish-di
(define render-with-subdirs? (make-parameter #f))
(define render-parallel? (make-parameter #f))
(define special-output? (make-parameter #f))
(define force-render? (make-parameter #f))
(define parsed-args
(command-line #:program "raco pollen render"
#:argv (vector-drop (current-command-line-arguments) 1) ; snip the 'render' from the front
@ -115,7 +114,6 @@ version print the version" (current-server-port) (make-publish-di
[("-r" "--recursive") "Render subdirectories recursively"
(render-with-subdirs? 'recursive)]
[("-s" "--subdir") "Render subdirectories nonrecursively" (render-with-subdirs? 'include)]
[("-f" "--force") "Force render" (force-render? #true)]
#:once-any
[("-d" "--dry-run") "Print paths that would be rendered" (special-output? 'dry-run)]
[("-n" "--null") "Suppress file output" (special-output? 'null)]
@ -125,18 +123,7 @@ version print the version" (current-server-port) (make-publish-di
#:args other-args
other-args))
(define timestamp (current-seconds)) ; keeps timestamp consistent through whole render
(define (handle-batch-render paths)
(when (force-render?)
;; forcing works like `touch`: updates the mod date of the files,
;; which invalidates any cached results.
(let force-paths ([paths paths])
(for* ([path (in-list paths)]
[sp (in-value (if (pagetree-source? path) path (get-source path)))]
#:when sp)
(file-or-directory-modify-seconds sp timestamp)
(when (pagetree-source? sp)
(force-paths (pagetree->paths sp))))))
(apply render-batch (map very-nice-path paths) #:parallel (render-parallel?) #:special (special-output?)))
(parameterize ([current-poly-target (render-target-wanted)]) ;; applies to both cases
@ -167,37 +154,41 @@ version print the version" (current-server-port) (make-publish-di
(when (render-with-subdirs?)
(for ([path (in-list dirlist)]
#:when (directory-exists? path))
(render-one-dir (->complete-path path)))))))]
(render-one-dir (->complete-path path)))))))]
[path-args ;; path mode
(message (format "rendering ~a" (string-join (map ->string path-args) " ")))
(handle-batch-render path-args)]))))
(define (start-project-server dir
[http-port 8080]
[launch-wanted #false]
[localhost-wanted #false])
(when dir
(parameterize ([current-project-root dir]
[current-server-port (or http-port (setup:project-server-port))]
[current-server-listen-ip (and localhost-wanted "127.0.0.1")])
(message "starting project server ...")
((dynamic-require 'pollen/private/project-server 'start-server) (format "/~a" (setup:main-pagetree dir)) launch-wanted))))
(define (handle-start)
(define launch-wanted #f)
(define localhost-wanted #f)
(define-values (dir http-port)
(command-line
#:program "raco pollen start"
#:argv (vector-drop (current-command-line-arguments) 1) ; snip the 'start' from the front
#:once-each
[("--launch" "-l") "Launch browser after start" (set! launch-wanted #t)]
[("--local") "Restrict access to localhost" (set! localhost-wanted #t)]
#:args ([dir (current-directory)] [port #f])
(define parsed-dir
(path->directory-path (normalize-path (very-nice-path dir))))
(unless (directory-exists? parsed-dir)
(error (format "~a is not a directory" parsed-dir)))
(define parsed-port (and port (string->number port)))
(when (and parsed-port (not (exact-positive-integer? parsed-port)))
(error (format "~a is not a valid port number" parsed-port)))
(values parsed-dir parsed-port)))
(parameterize ([current-project-root dir]
[current-server-port (or http-port (setup:project-server-port))]
[current-server-listen-ip (and localhost-wanted "127.0.0.1")]
[current-session-interactive? #true])
(message "starting project server ...")
((dynamic-require 'pollen/private/project-server 'start-server) (format "/~a" (setup:main-pagetree dir)) launch-wanted)))
(define clargs
(command-line #:program "raco pollen start"
#:argv (vector-drop (current-command-line-arguments) 1) ; snip the 'start' from the front
#:once-each
[("--launch" "-l") "Launch browser after start" (set! launch-wanted #t)]
[("--local") "Restrict access to localhost" (set! localhost-wanted #t)]
#:args other-args
other-args))
(define dir (path->directory-path (get-first-arg-or-current-dir clargs)))
(unless (directory-exists? dir)
(error (format "~a is not a directory" dir)))
(define http-port (with-handlers ([exn:fail? (λ (e) #f)])
(string->number (cadr clargs))))
(when (and http-port (not (exact-positive-integer? http-port)))
(error (format "~a is not a valid port number" http-port)))
(start-project-server dir http-port launch-wanted localhost-wanted))
(define (make-publish-dir-name [project-root (current-directory)] [arg-command-name #f])
(define user-publish-path
@ -222,7 +213,7 @@ version print the version" (current-server-port) (make-publish-di
(and (>= (length xs) (length prefix))
(andmap equal? prefix (for/list ([(x idx) (in-indexed xs)]
#:break (= idx (length prefix)))
x))))
x))))
((explode-path possible-subdir) . has-prefix? . (explode-path possible-superdir)))
(define (handle-publish)
@ -284,8 +275,7 @@ version print the version" (current-server-port) (make-publish-di
(cond
[do-publish-operation?
(when (directory-exists? dest-dir)
(with-handlers ([exn:fail:filesystem? (λ (exn) (raise-user-error 'publish (format "operation failed: could not delete ~a" dest-dir)))])
(delete-directory/files dest-dir)))
(delete-directory/files dest-dir))
(copy-directory/files source-dir dest-dir)
;; if source-dir is provided, we want it to be treated as current-directory.
;; if no source-dir is provided, it is set to current-directory,

@ -1,23 +0,0 @@
#lang racket/base
(provide (prefix-out pollen- (all-defined-out)))
(define main-export 'doc) ; don't forget to change fallback template too
(define meta-export 'metas)
(define meta-tag-name 'meta)
(define define-meta-name 'define-meta)
(define preproc-source-ext 'pp)
(define markup-source-ext 'pm)
(define markdown-source-ext 'pmd)
(define null-source-ext 'p)
(define pagetree-source-ext 'ptree)
(define template-source-ext 'pt)
(define scribble-source-ext 'scrbl)
(define poly-source-ext 'poly) ; extension that signals source can be used for multiple output targets
(define cache-dir-name "compiled")
(define cache-subdir-name "pollen")
(define template-prefix "template")
(define fallback-template-prefix "fallback")
(define template-meta-key "template")
(define old-cache-names '("pollen.cache" "pollen-cache"))
(define splicing-tag '@)
(define here-path-key 'here-path)
(define extension-escape-char #\_)

@ -1,10 +0,0 @@
#lang info
;; 210309
;; for unknown reason "mode-indentation.rkt"
;; started causing CI failures since 210215
;; consistently on 6.7, 6.8, 6.9, 7.7CS, 7.8CS, 7.9CS
;; I assume it has something to do with the fact that
;; it imports `framework` and `racket/gui`,
;; OTOH why does it fail in these?
(define test-omit-paths '("mode-indentation.rkt"))

@ -6,9 +6,7 @@
framework)
#|
Identical to scribble/private/indentation except it uses #\◊ rather than #\@ as the command char, because these values are hard-coded within the indentation module.
https://github.com/racket/gui/blob/master/gui-lib/scribble/private/indentation.rkt
Identical to scribble/private/indentation except it uses #\◊ rather than #\@ as the command char.
In the unit tests, `scribble/base` became `pollen/markup`
and `scribble/manual` became `pollen/markdown`

@ -1,7 +1,7 @@
#lang racket/base
(require racket/promise
racket/contract/base
"../constants.rkt") ; to get splicing char
pollen/setup) ; to get splicing char
#|
161017:
This is a slightly amended version of scribble/text/output
@ -129,7 +129,7 @@ This version will also splice lists that begin with the splicing char.
(define npfx (pfx+col (pfx+ pfx lpfx)))
(set-mcar! pfxs npfx) (set-mcdr! pfxs 0)
(if (list? c)
(let ([c (if (eq? pollen-splicing-tag (car c)) ; patch to cooperate with splicing char
(let ([c (if (eq? (setup:splicing-tag) (car c)) ; patch to cooperate with splicing char
(cdr c)
c)])
(for ([c (in-list c)]) (loop c)))

@ -1,22 +1,8 @@
# This allows us to launch Python and pygments once, and pipe to it
# continuously.
# continuously. Input format is:
#
# There are four options:
# 1. Language (used to determine the lexer)
# 2. Line numbers to highlight
# 3. Encoding to use for the output
# 4. HTML Class to use for the output
#
# These can be specified as arguments when this script is first invoked, or on a
# per invocation.
#
# To set the options for each invocation, the format is:
#
# __LANG__ <lexer-name>
# __LINENOS__ <true|false>
# __LINES__ <list-of-highlighted-lines>
# __CSS__ <CSS-class>
# __ENC__ <encoding>
# <lexer-name>
# <list-of-highlighted-lines>
# <code>
# ...
# __END__
@ -31,120 +17,57 @@
# ...
# __END__
from __future__ import print_function
import sys
import optparse
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound
from pygments.formatters import HtmlFormatter
def get_lexer(lang):
if not lang:
get_lexer_by_name("text", encoding="guess")
try:
return get_lexer_by_name(lang, encoding="guess")
except ClassNotFound:
print("No lexer was found for the given language. Using plain text instead.", file=sys.stderr)
return get_lexer_by_name("text", encoding="guess")
parser = optparse.OptionParser()
parser.add_option('--linenos', action="store_true", dest="linenos")
parser.add_option('--cssclass', default="source", dest="cssclass")
parser.add_option('--encoding', default="utf-8", dest="encoding")
parser.add_option('--language', dest="language")
(options, _) = parser.parse_args()
# Set initial options
config = {
'linenos': options.linenos,
'cssclass': options.cssclass,
'encoding': options.encoding,
'hl_lines': []
}
lexer = get_lexer(options.language)
lexer = ""
code = ""
lines_to_highlight = ""
py_version = sys.version_info.major
sys.stdout.write("ready\n")
sys.stdout.flush()
while 1:
line_raw = sys.stdin.readline()
if not line_raw:
break
# Without trailing space, \n, or \n
line = line_raw.rstrip()
if line == '__EXIT__':
break
elif line == '__END__':
# Lex input finished. Lex it.
formatter = HtmlFormatter(linenos=config['linenos'],
cssclass=config['cssclass'],
encoding=config['encoding'],
hl_lines=config['hl_lines'])
formatter = HtmlFormatter(linenos=options.linenos,
cssclass=options.cssclass,
encoding="utf-8",
hl_lines=lines_to_highlight)
if py_version >= 3:
sys.stdout.write(highlight(code, lexer, formatter).decode("utf-8"))
else:
sys.stdout.write(highlight(code, lexer, formatter))
sys.stdout.write('\n__END__\n')
sys.stdout.flush()
# Reset the configuration for the next invocation. Most options are
# actually persisted between runs, except for the code itself and the
# lines to be highlighted.
lexer = ""
code = ""
config['hl_lines'] = []
elif code == "":
# Only check for new options at the beginning of a a fresh invocation
if line.startswith("__LANG__"):
# Use the provided language to find the appropriate lexer.
try:
lang = line.split()[1]
lexer = get_lexer(lang)
except IndexError:
print("No lexer was found for the given language. Using plain text instead.", file=sys.stderr)
lexer = get_lexer_by_name("text", encoding="guess")
elif line.startswith("__LINENOS__"):
try:
option = line.split()[1]
if option.lower() == "true":
config['linenos'] = True
elif option.lower() == "false":
config['linenos'] = False
else:
pass
except IndexError:
print("__LINENOS__ option must be given a `true` or `false` value",
file=sys.stderr)
elif line.startswith("__LINES__"):
# The list of lines to highlight is formatted as string of
# whitespace-separated integers
lines = line.split()[1:]
config['hl_lines'] = [int(str) for str in lines]
elif line.startswith("__CSS__"):
try:
config['cssclass'] = line.split[1]
except IndexError:
print("Could not parse CSS class line.", file=sys.stderr)
elif line.startswith("__ENC__"):
try:
config['encoding'] = line.split[1]
except IndexError:
print("Could not parse encoding line.", file=sys.stderr)
else:
# Done with configuration for this invocation, start accumulating
# code. Use `line_raw` because we want trailing space, \n, \r
code += line_raw
lines_to_highlight = ""
elif lexer == "":
# Starting another lex. First line is the lexer name.
try:
lexer = get_lexer_by_name(line, encoding="guess")
except ClassNotFound:
lexer = get_lexer_by_name("text", encoding="guess")
elif lines_to_highlight == "":
# Starting another lex. Second line is list of lines to highlight,
# formatted as string of whitespace-separated integers
lines_to_highlight = [int(str) for str in line.split()]
else:
# Accumulate more code
# Use `line_raw`: Do want trailing space, \n, \r

@ -19,9 +19,10 @@
(parameterize ([current-directory (dirname (->complete-path starting-path))])
(let loop ([dir (current-directory)][path filename-to-find])
(and dir ; dir is #f when it hits the top of the filesystem
(match (simple-form-path path)
[(? exists-proc sfp) sfp]
[_ (loop (dirname dir) (build-path 'up path))])))))
(let ([completed-path (path->complete-path path)])
(if (exists-proc completed-path)
(simplify-path completed-path)
(loop (dirname dir) (build-path 'up path))))))))
;; for files like svg that are not source in pollen terms,
@ -56,7 +57,7 @@
(not (regexp-match #rx"^\\." (path->string path))))
(define+provide (escape-last-ext x [escape-char pollen-extension-escape-char])
(define+provide (escape-last-ext x [escape-char (setup:extension-escape-char)])
;((pathish?) (char?) . ->* . coerce/path?)
;; if x has a file extension, reattach it with the escape char
(define current-ext (get-ext x))
@ -75,7 +76,7 @@
(define second cadr)
(define third caddr)
(define (last x) (car (reverse x)))
(define+provide (unescape-ext x [escape-char pollen-extension-escape-char])
(define+provide (unescape-ext x [escape-char (setup:extension-escape-char)])
;((coerce/string?) (char?) . ->* . coerce/path?)
;; if x has an escaped extension, unescape it.
(define-values (base _ dir?) (split-path x))
@ -127,7 +128,7 @@
(define+provide (has-poly-ext? x)
(equal? (get-ext x) (->string pollen-poly-source-ext)))
(equal? (get-ext x) (->string (setup:poly-source-ext))))
(module-test-external
(check-true (has-poly-ext? "foo.poly"))
@ -146,7 +147,7 @@
(define-syntax (define-utility-functions stx)
(syntax-case stx ()
[(_ STEM)
(with-syntax ([STEM-SOURCE-EXT (format-id stx "pollen-~a-source-ext" #'STEM)]
(with-syntax ([SETUP:STEM-SOURCE-EXT (format-id stx "setup:~a-source-ext" #'STEM)]
[STEM-SOURCE? (format-id stx "~a-source?" #'STEM)]
[GET-STEM-SOURCE (format-id stx "get-~a-source" #'STEM)]
[HAS/IS-STEM-SOURCE? (format-id stx "has/is-~a-source?" #'STEM)]
@ -157,7 +158,7 @@
;; does file have particular extension
(define+provide (STEM-SOURCE? x)
#;(any/c . -> . boolean?)
(and (pathish? x) (has-ext? (->path x) STEM-SOURCE-EXT) #true))
(and (pathish? x) (has-ext? (->path x) (SETUP:STEM-SOURCE-EXT)) #true))
;; non-theoretical: want the first possible source that exists in the filesystem
(define+provide (GET-STEM-SOURCE x)
@ -184,19 +185,19 @@
(list x) ; already has the source extension
#,(if (eq? (syntax->datum #'STEM) 'scribble)
#'(if (x . has-ext? . 'html) ; different logic for scribble sources
(list (add-ext (remove-ext* x) STEM-SOURCE-EXT))
(list (add-ext (remove-ext* x) (SETUP:STEM-SOURCE-EXT)))
#false)
#'(let ([x-ext (get-ext x)]
[source-ext STEM-SOURCE-EXT])
[source-ext (SETUP:STEM-SOURCE-EXT)])
(cons
(add-ext x source-ext) ; standard
(if x-ext ; has existing ext, therefore needs escaped version
(cons
(add-ext (escape-last-ext x) source-ext)
(if (ext-in-poly-targets? x-ext x) ; needs multi + escaped multi
(let ([x-multi (add-ext (remove-ext x) pollen-poly-source-ext)])
(let ([x-multi (add-ext (remove-ext x) (setup:poly-source-ext))])
(list
(add-ext x-multi STEM-SOURCE-EXT)
(add-ext x-multi (SETUP:STEM-SOURCE-EXT))
(add-ext (escape-last-ext x-multi) source-ext)))
null))
null))))))
@ -293,7 +294,7 @@
(define+provide (special-path? path)
(define special-paths (append default-cache-names '("compiled" ".git" ".gitignore" ".hg" ".svn" "CVS" "Makefile" ".DS_Store")))
(define special-paths (append default-cache-names '("compiled" ".git" ".gitignore" ".hg" ".svn" "CVS" "Makefile")))
(and (member (path->string (last (explode-path path))) special-paths) #t))
(module-test-internal

@ -2,7 +2,6 @@
(require (for-syntax racket/base
syntax/strip-context
"../setup.rkt"
"splice.rkt"
"split-metas.rkt")
racket/list
"to-string.rkt"
@ -24,7 +23,7 @@
(define (stringify xs) (apply string-append (map to-string xs)))
(define (parse xs-in parser-mode root-proc)
(define xs (splice (strip-leading-newlines xs-in) pollen-splicing-tag))
(define xs (splice (strip-leading-newlines xs-in) (setup:splicing-tag)))
(cond
[(eq? parser-mode default-mode-pagetree) (decode-pagetree xs)]
[(eq? parser-mode default-mode-markup) (apply root-proc (remove-voids xs))]
@ -38,12 +37,12 @@
(define-syntax (pollen-module-begin stx)
(syntax-case stx ()
[(_ PARSER-MODE . EXPRS)
(with-syntax ([META-HASH (split-metas #'EXPRS pollen-define-meta-name)]
[METAS-ID pollen-meta-export]
[METAS-ID-CALLER (datum->syntax #'EXPRS pollen-meta-export)]
(with-syntax ([META-HASH (split-metas #'EXPRS (setup:define-meta-name))]
[METAS-ID (setup:meta-export)]
[METAS-ID-CALLER (datum->syntax #'EXPRS (setup:meta-export))]
[ROOT-ID (datum->syntax #'EXPRS (setup:main-root-node))]
[POLLEN/TOP (datum->syntax #'EXPRS 'pollen/top)]
[DOC-ID pollen-main-export]
[DOC-ID (setup:main-export)]
[ALL-DEFINED-OUT (datum->syntax #'EXPRS '(all-defined-out))])
#'(doclang:#%module-begin
DOC-ID ; positional arg for doclang-raw: name of export

@ -3,7 +3,6 @@
racket/path
racket/place
racket/match
racket/format
"file-utils.rkt"
"cache-utils.rkt"
"log.rkt")
@ -31,7 +30,7 @@
pagetree-source?))])
(proc path))
#:unless (path-cached? path))
(simple-form-path path)))
(path->complete-path path)))
(cond
[wants-dry-run? (for-each message uncached-paths)]
@ -53,7 +52,7 @@
(let loop ()
(define path (place-channel-put/get ch (list 'want-job)))
(place-channel-put ch (list 'job-finished path
(with-handlers ([exn:fail? (λ (e) (cons #false (exn-message e)))])
(with-handlers ([exn:fail? (λ (e) #f)])
(path->hash path))))
(loop))))
(handle-evt wp (λ (val) (list* wpidx wp val)))))
@ -66,15 +65,15 @@
[(? null?) (loop null actives)]
[(cons path rest)
(place-channel-put wp path)
(message (format "caching @ job ~a: ~a" (~r (add1 wpidx) #:min-width (string-length (~r job-count)) #:pad-string " ") (find-relative-path starting-dir path)))
(message (format "caching @ job ~a: ~a" (add1 wpidx) (find-relative-path starting-dir path)))
(loop rest (cons wpidx actives))])]
[(list wpidx wp 'job-finished path result)
(match result
[(cons #false exn-msg) (message (format "caching failed on job ~a: ~a\n because ~a" (add1 wpidx) (find-relative-path starting-dir path) exn-msg))]
[_ (cache-ref! (paths->key 'source path) (λ () result))])
(if result
(cache-ref! (paths->key 'source path) (λ () result))
(message (format "caching failed on job ~a: ~a" (add1 wpidx) (find-relative-path starting-dir path))))
(loop paths (remq wpidx actives))])))]
[else (for ([path (in-list uncached-paths)])
(message (format "caching: ~a" (find-relative-path starting-dir path)))
(match (with-handlers ([exn:fail? (λ (e) (cons #false (exn-message e)))]) (path->hash path))
[(cons #false exn-msg) (message (format "caching failed: ~a\n because ~a" (find-relative-path starting-dir path) exn-msg))]
(match (with-handlers ([exn:fail? (λ (e) #f)]) (path->hash path))
[#false (message (format "caching failed: ~a" (find-relative-path starting-dir path)))]
[result (cache-ref! (paths->key 'source path) (λ () result))]))]))

@ -193,7 +193,7 @@
(define source-minus-ext (unescape-ext (remove-ext source)))
(define source-second-ext (get-ext source-minus-ext))
(cond ; multi source. expand to multiple output files.
[(and source-second-ext (equal? source-second-ext (->string pollen-poly-source-ext)))
[(and source-second-ext (equal? source-second-ext (->string (setup:poly-source-ext (->complete-path source)))))
(define source-base (remove-ext source-minus-ext))
(define output-names (map (λ (ext) (->string (add-ext source-base ext))) (setup:poly-targets (->complete-path source))))
(cons #f `(div ,@(map (λ (on) `(a ((href ,on)) ,on (span ((class "file-ext")) "." ,source-first-ext ,(format " (from ~a)" (->string (find-relative-path dashboard-dir source)))))) output-names)))]

@ -1,6 +1,7 @@
#lang racket/base
(require racket/async-channel
racket/runtime-path
(require racket/runtime-path
racket/match
web-server/servlet-env
web-server/dispatch
web-server/web-server
web-server/servlet-dispatch
@ -8,6 +9,7 @@
(prefix-in files: web-server/dispatchers/dispatch-files)
(prefix-in sequencer: web-server/dispatchers/dispatch-sequencer)
web-server/dispatchers/filesystem-map
net/url
net/sendurl
"project-server-routes.rkt"
"log.rkt"
@ -50,11 +52,11 @@
[("127.0.0.1") "localhost"]
[else clsi]))
"project server permitting access to all clients")))
(define ch (make-async-channel))
(message "ready to rock")
(define stop-func
(parameterize ([error-print-width 1000])
(serve
#:confirmation-channel ch
#:dispatch (sequencer:make
(dispatch/servlet pollen-servlet)
(make-static-dispatcher-sequence
@ -63,16 +65,9 @@
(dispatch/servlet route-404))
#:listen-ip (current-server-listen-ip)
#:port (current-server-port))))
(define exn-or-port
(sync ch))
(when (exn? exn-or-port)
(message "project server failed to start")
(sync (system-idle-evt))
(exit 1))
(message "ready to rock")
(when open-browser-window?
(send-url (string-append server-name servlet-path)))
(if return?
stop-func
(with-handlers ([exn:break? (λ (e) (stop-func) (message "project server stopped"))])
(do-not-return))))
(do-not-return))))

@ -22,9 +22,9 @@
[(eq? reader-mode default-mode-auto)
(let ([val (cond [(get-ext reader-here-path) => string->symbol])])
(cond
[(eq? val pollen-pagetree-source-ext) default-mode-pagetree]
[(eq? val pollen-markup-source-ext) default-mode-markup]
[(eq? val pollen-markdown-source-ext) default-mode-markdown]
[(eq? val (setup:pagetree-source-ext)) default-mode-pagetree]
[(eq? val (setup:markup-source-ext)) default-mode-markup]
[(eq? val (setup:markdown-source-ext)) default-mode-markdown]
[else default-mode-preproc]))]
[else reader-mode]))
@ -46,11 +46,11 @@
;; an inline Pollen submodule doesn't have "pollen.rkt" or `here-path`
[POLLEN-REQUIRE-AND-PROVIDES (require+provide-directory-require-files pollen-require-path)]
[HERE-PATH reader-here-path]
[HERE-KEY pollen-here-path-key]
[HERE-KEY (setup:here-path-key)]
[SOURCE-LINES source-stx]
[DOC pollen-main-export]
[META-MOD pollen-meta-export]
[METAS-ID pollen-meta-export]
[DOC (setup:main-export)]
[META-MOD (setup:meta-export)]
[METAS-ID (setup:meta-export)]
[PARSER-MODE-FROM-READER parser-mode-from-reader])
#'(module runtime-wrapper racket/base
(module configure-runtime racket/base
@ -119,12 +119,11 @@
[(drracket:default-extension)
(symbol->string
(cond
[(eq? mode default-mode-auto) pollen-preproc-source-ext]
[(eq? mode default-mode-preproc) pollen-preproc-source-ext]
[(eq? mode default-mode-markdown) pollen-markdown-source-ext]
[(eq? mode default-mode-markup) pollen-markup-source-ext]
[(eq? mode default-mode-pagetree) pollen-pagetree-source-ext]))]
[(module-language) 'pollen]
[(eq? mode default-mode-auto) (setup:preproc-source-ext)]
[(eq? mode default-mode-preproc) (setup:preproc-source-ext)]
[(eq? mode default-mode-markdown) (setup:markdown-source-ext)]
[(eq? mode default-mode-markup) (setup:markup-source-ext)]
[(eq? mode default-mode-pagetree) (setup:pagetree-source-ext)]))]
[else default])))
(define-syntax-rule (reader-module-begin mode . _)

@ -29,8 +29,8 @@
(let ([source-path (syntax->datum #'SOURCE-PATH-STRING)])
(with-syntax ([DIRECTORY-REQUIRE-FILES
(replace-context #'here (require-directory-require-files source-path))]
[DOC-ID pollen-main-export]
[METAS-ID pollen-meta-export]
[DOC-ID (setup:main-export source-path)]
[METAS-ID (setup:meta-export source-path)]
[COMMAND-CHAR (setup:command-char source-path)])
#'(#%module-begin
DIRECTORY-REQUIRE-FILES
@ -44,10 +44,8 @@
(define doc (cached-doc SOURCE-PATH-STRING))
(define metas (current-metas))
(define here (path->pagenode
(or (select-from-metas pollen-here-path-key metas) 'unknown)))
(or (select-from-metas (setup:here-path-key SOURCE-PATH-STRING) metas) 'unknown)))
(if (bytes? doc) ; if main export is binary, just pass it through
doc
;; allows `require` in a template
(splicing-let-syntax ([require (make-rename-transformer #'local-require)])
(include-template #:command-char COMMAND-CHAR (file TEMPLATE-PATH-STRING))))))
(include-template #:command-char COMMAND-CHAR (file TEMPLATE-PATH-STRING)))))
(provide result)))))]))

@ -1,10 +1,10 @@
#lang racket/base
(require racket/match
racket/list
"constants.rkt")
racket/list)
(provide (all-defined-out))
;; (string->symbol (format "~a" #\u200B))
(define splice-signal-tag '@)
(define (attrs? x)
(match x
@ -18,7 +18,7 @@
[(cons (== splicing-tag eq?) _) #true]
[_ #false]))
(define (splice x [splicing-tag pollen-splicing-tag])
(define (splice x [splicing-tag splice-signal-tag])
; (listof txexpr-elements?) . -> . (listof txexpr-elements?))
(let loop ([x x])
(if (list? x) ; don't exclude `attrs?` here, because it will exclude valid splice input like '((@ "foo"))
@ -32,14 +32,14 @@
(module+ test
(require rackunit)
(check-equal? (splice `((div 1 (,pollen-splicing-tag 2 "" (,pollen-splicing-tag 3 (div 4 (,pollen-splicing-tag 5))) 6) "" 7)))
(check-equal? (splice `((div 1 (,splice-signal-tag 2 "" (,splice-signal-tag 3 (div 4 (,splice-signal-tag 5))) 6) "" 7)))
'((div 1 2 3 (div 4 5) 6 7)))
(check-equal? (splice `((,pollen-splicing-tag 1 (,pollen-splicing-tag 2 "" (,pollen-splicing-tag 3 (div 4 (,pollen-splicing-tag 5))) 6) "" 7)))
(check-equal? (splice `((,splice-signal-tag 1 (,splice-signal-tag 2 "" (,splice-signal-tag 3 (div 4 (,splice-signal-tag 5))) 6) "" 7)))
'(1 2 3 (div 4 5) 6 7))
(check-equal? (splice `((,pollen-splicing-tag "foo" "" "bar"))) '("foo" "bar"))
(check-equal? (splice `((,splice-signal-tag "foo" "" "bar"))) '("foo" "bar"))
(check-equal? (splice null) null)
(check-equal? (splice '(a ((href "")(foo "bar")) "zam")) '(a ((href "")(foo "bar")) "zam"))
(check-equal? (splice `((,pollen-splicing-tag "str"))) '("str")))
(check-equal? (splice `((,splice-signal-tag "str"))) '("str")))
;; this will strip all empty lists.

@ -1 +1 @@
1710316839
1586206283

@ -2,8 +2,6 @@
(require racket/file
racket/path
racket/match
racket/string
racket/format
racket/place
racket/list
racket/dict
@ -34,7 +32,7 @@
(require racket/runtime-path)
(define-runtime-path sample-dir "test/data/samples")
(define samples (parameterize ([current-directory sample-dir])
(map simple-form-path (filter (λ (name) (regexp-match "sample-" name)) (directory-list ".")))))
(map path->complete-path (filter (λ (name) (regexp-match "sample-" name)) (directory-list ".")))))
(define-values (sample-01 sample-02 sample-03) (apply values samples)))
;; each key for mod-date-hash is a list of file / mod-date pairs (using pollen/cache keymaking function)
@ -49,84 +47,72 @@
(define (mod-date-missing-or-changed? source-path template-path)
(not (hash-has-key? mod-date-hash (paths->key 'output source-path template-path))))
(struct $job (source output) #:transparent)
(struct $jobresult (job finished-successfully) #:transparent)
(define (parallel-render jobs-in worker-count-arg)
(define (parallel-render source-paths-in job-count-arg)
;; if jobs are already in the cache, pull them out before assigning workers
;; using worker to fetch from cache is slower
(define-values (uncached-jobs previously-cached-jobs)
(for/fold ([ujobs null]
[pcjobs null])
([job (in-list jobs-in)])
(define-values (uncached-source-paths previously-cached-jobs)
(for/fold ([usps null]
[pcjs null])
([source-path (in-list source-paths-in)])
(match (let/ec exit
(define output-path (or (->output-path source-path) #false))
(define template-path
(cache-ref! (template-cache-key ($job-source job) ($job-output job)) (λ () (exit 'template-miss))))
(render-to-file-if-needed ($job-source job) template-path ($job-output job) (λ () (exit 'render-miss))))
[(? symbol? sym) (values (cons job ujobs) pcjobs)]
[_ (values ujobs (cons ($jobresult job #true) pcjobs))])))
(define worker-count
(cache-ref! (template-cache-key source-path output-path) (λ () (exit 'template-miss))))
(render-to-file-if-needed source-path template-path output-path (λ () (exit 'render-miss))))
[(? symbol? sym) (values (cons source-path usps) pcjs)]
[_ (values usps (cons (cons source-path #true) pcjs))])))
(define job-count
(min
(length uncached-jobs)
(match worker-count-arg
(length uncached-source-paths)
(match job-count-arg
[#true (processor-count)]
[(? exact-positive-integer? count) count]
[_ (raise-user-error 'render-batch "~a is not an exact positive integer or #true" worker-count-arg)])))
[_ (raise-user-error 'render-batch "~a is not an exact positive integer or #true" job-count-arg)])))
;; initialize the workers
(define worker-evts
(for/list ([wpidx (in-range worker-count)])
(define wp
(place ch
(let loop ()
(match-define (list project-root source-path output-path poly-target)
(place-channel-put/get ch (list 'wants-job)))
;; we manually propagate our parameter values for
;; current-project-root and current-poly-target
;; because parameter values are not automatically shared
;; between parallel threads.
(parameterize ([current-project-root project-root]
[current-poly-target poly-target])
(place-channel-put/get ch (list 'wants-lock output-path))
;; trap any exceptions and pass them back as crashed jobs.
;; otherwise, a crashed rendering place can't recover, and the parallel job will be stuck.
(place-channel-put ch
(cons
;; when rendering fails, first argument is the exception message
(with-handlers ([exn:fail? (λ (e) (exn-message e))])
(match-define-values (_ _ ms _)
;; we don't use `render-to-file-if-needed` because we've already checked the render cache
;; if we reached this point, we know we need a render
(time-apply render-to-file (list source-path #f output-path)))
;; when rendering succeeds, first argument is rendering time in ms
ms)
(list source-path output-path))))
(loop))))
(for/list ([wpidx (in-range job-count)])
(define wp (place ch
(let loop ()
(match-define (cons path poly-target)
(place-channel-put/get ch (list 'wants-job)))
(parameterize ([current-poly-target poly-target])
(place-channel-put/get ch (list 'wants-lock (->output-path path)))
;; trap any exceptions and pass them back as crashed jobs.
;; otherwise, a crashed rendering place can't recover, and the parallel job will be stuck.
(with-handlers ([exn:fail? (λ (e) (place-channel-put ch (list 'crashed-job path #f)))])
(match-define-values (_ _ ms _)
;; we don't use `render-to-file-if-needed` because we've already checked the render cache
;; if we reached this point, we know we need a render
(time-apply render-to-file (list path)))
(place-channel-put ch (list 'finished-job path ms))))
(loop))))
(handle-evt wp (λ (val) (list* wpidx wp val)))))
(define poly-target (current-poly-target))
(struct $lock (worker path) #:transparent)
;; `locks` and `blocks` are (listof $lock)
(let loop ([jobs (reverse uncached-jobs)]
;; `locks` and `blocks` are (listof (cons/c evt? path?))
(let loop ([source-paths (reverse uncached-source-paths)]
[locks-in null]
[blocks-in null]
[completed-job-results previously-cached-jobs] ; (listof jobresult)
;; `completed-jobs` is (listof (cons/c path? boolean?))
[completed-jobs previously-cached-jobs]
[completed-job-count (length previously-cached-jobs)])
;; try to unblock blocked workers
(define-values (locks blocks)
(for/fold ([locks locks-in]
[blocks null])
([block (in-list blocks-in)])
(match-define ($lock wp path) block)
(match-define (cons wp path) block)
(cond
[(member path (map $lock-path locks))
[(member path (dict-values locks))
(values locks (cons block blocks))]
[else
(place-channel-put wp 'lock-approved)
(values (cons block locks) blocks)])))
(cond
[(eq? completed-job-count (length jobs-in))
[(eq? completed-job-count (length source-paths-in))
;; second bite at the apple for crashed jobs.
;; 1) many crashes that arise in parallel rendering are
;; a result of concurrency issues (e.g. shared files not being readable at the right moment).
@ -138,112 +124,76 @@
;; if it was a concurrency-related error, it will disappear.
;; if it was a legit error, the render will stop and print a trace.
;; crashed jobs are completed jobs that weren't finished
(for/list ([jr (in-list completed-job-results)]
#:unless ($jobresult-finished-successfully jr))
($jobresult-job jr))]
(for/list ([(path finished?) (in-dict completed-jobs)]
#:unless finished?)
path)]
[else
(match (apply sync worker-evts)
[(list wpidx wp 'wants-job)
(match jobs
[(? null?) (loop null locks blocks completed-job-results completed-job-count)]
[(cons ($job source-path output-path) rest)
(place-channel-put wp (list (current-project-root) source-path output-path poly-target))
(loop rest locks blocks completed-job-results completed-job-count)])]
[(list wpidx wp status-arg source-path output-path)
;; if the render was successful, the status arg is a number representing milliseconds spent rendering.
;; if not, the status argument is the exception message.
(define job-finished? (exact-nonnegative-integer? status-arg))
(match status-arg
[ms #:when job-finished?
(message
(format "rendered @ job ~a /~a ~a"
(~r (add1 wpidx) #:min-width (string-length (~r worker-count)) #:pad-string " ")
(find-relative-path (current-project-root) output-path)
(if (< ms 1000) (format "(~a ms)" ms) (format "(~a s)" (/ ms 1000.0)))))]
[(? string? exn-msg)
(match source-paths
[(? null?) (loop null locks blocks completed-jobs completed-job-count)]
[(cons path rest)
(place-channel-put wp (cons path poly-target))
(loop rest locks blocks completed-jobs completed-job-count)])]
[(list wpidx wp (and (or 'finished-job 'crashed-job) tag) path ms)
(match tag
['finished-job
(message
(format "rendered parallel @ job ~a /~a ~a"
(add1 wpidx)
(find-relative-path (current-project-root) (->output-path path))
(if (< ms 1000) (format "(~a ms)" ms) (format "(~a s)" (/ ms 1000.0)))))]
[_
(message
(format "render crash @ job ~a /~a (retry pending)\n because ~a"
(format "render crash @ job ~a /~a (retry pending)"
(add1 wpidx)
(find-relative-path (current-project-root) output-path)
exn-msg))]
[_ (raise-result-error 'render "exact-nonnegative-integer or string" status-arg)])
(loop jobs
(match (findf (λ (lock) (equal? ($lock-worker lock) wp)) locks)
(find-relative-path (current-project-root) (->output-path path))))])
(loop source-paths
(match (assoc wp locks)
[#false locks]
[lock (remove lock locks)])
blocks
(let ([jr ($jobresult ($job source-path output-path) job-finished?)])
(cons jr completed-job-results))
(cons (cons path (eq? tag 'finished-job)) completed-jobs)
(add1 completed-job-count))]
[(list wpidx wp 'wants-lock output-path)
(loop jobs locks (append blocks (list ($lock wp output-path))) completed-job-results completed-job-count)])])))
[(list wpidx wp 'wants-lock path)
(loop source-paths locks (append blocks (list (cons wp path))) completed-jobs completed-job-count)])])))
(define current-null-output? (make-parameter #f))
(define+provide/contract (render-batch #:parallel [wants-parallel-render? #false]
#:special [special-output #false]
#:output-paths [output-paths-in #false] . paths-in)
(() (#:parallel any/c
#:special (or/c boolean? symbol?)
#:output-paths (or/c #false (listof pathish?)))
#:rest (listof pathish?) . ->* . void?)
#:special [special-output #false] . paths-in)
((#:parallel any/c) (#:special (or/c boolean? symbol?)) #:rest (listof pathish?) . ->* . void?)
;; Why not just (for-each render ...)?
;; Because certain files will pass through multiple times (e.g., templates)
;; And with render, they would be rendered repeatedly.
;; Using reset-modification-dates is sort of like session control.
(reset-mod-date-hash!)
;; we need to handle output-paths in parallel
;; because `raco pollen render` can take an output path for poly source.
;; meaning, if source is "test.poly.pm" and we get `raco pollen render test.txt`,
;; then the output path argument should force .txt rendering, regardless of `current-poly-target` setting
;; so the output path may contain information we need that we can't necessarily derive from the source path.
(define all-jobs
;; we generate the output paths in parallel with the source paths
;; rather than afterward, because
;; for poly files we want to be able to look at
;; the original path provided as an argument
;; but the path arguments might also include pagetrees,
;; which expand to multiple files.
;; so this keeps everything correlated correctly.
(cond
[(and output-paths-in (= (length paths-in) (length output-paths-in)))
;; explicit list of paths: create jobs directly
(for/list ([path (in-list paths-in)]
[output-path (in-list output-paths-in)])
($job path output-path))]
[else
(let loop ([paths paths-in] [sps null] [ops null])
(match paths
[(? null?)
;; it's possible that we have multiple output names for one poly file
;; so after we expand, we only remove duplicates where both the source and dest in the pair
;; are the same
(let* ([pairs (remove-duplicates (map cons sps ops))]
[pairs (sort pairs path<? #:key car)]
[pairs (sort pairs path<? #:key cdr)])
(for/list ([pr (in-list pairs)])
($job (car pr) (cdr pr))))]
[(cons path rest)
(match (->complete-path path)
[(? pagetree-source? pt)
(loop (append (pagetree->paths pt) rest) sps ops)]
[(app ->source-path sp) #:when (and sp (file-exists? sp))
(define op (match path
[(== (->output-path path)) path]
[_ (->output-path sp)]))
(loop rest (cons sp sps) (cons op ops))]
[_ (loop rest sps ops)])]))]))
(define expanded-source-paths
(let loop ([paths paths-in] [acc null])
(match paths
[(? null?) (sort (remove-duplicates acc) string<? #:key path->string)]
[(cons path rest)
(match (->complete-path path)
[(? pagetree-source? pt)
(loop (append (pagetree->paths pt) rest) acc)]
[(app ->source-path (and (not #false) (? file-exists?) sp))
(loop rest (cons sp acc))]
[_ (loop rest acc)])])))
(cond
[(null? all-jobs) (message "[no paths to render]")]
[(eq? special-output 'dry-run) (for-each message (map $job-source all-jobs))]
[else
(parameterize ([current-null-output? (eq? special-output 'null)])
(for-each (λ (job) (render-to-file-if-needed ($job-source job) #f ($job-output job)))
(match wants-parallel-render?
;; returns crashed jobs for serial rendering
[#false all-jobs]
[worker-count-arg (parallel-render all-jobs worker-count-arg)])))]))
[(null? expanded-source-paths) (message "[no paths to render]")]
[(eq? special-output 'dry-run) (for-each message expanded-source-paths)]
[else (parameterize ([current-null-output? (eq? special-output 'null)])
(for-each render-to-file-if-needed
(match wants-parallel-render?
;; returns crashed jobs for serial rendering
[#false expanded-source-paths]
[jobs-arg (parallel-render expanded-source-paths jobs-arg)])))]))
(define (pagetree->paths pagetree-or-path)
(parameterize ([current-directory (current-project-root)])
(map ->complete-path (pagetree->list (match pagetree-or-path
[(? pagetree? pt) pt]
[_ (cached-doc pagetree-or-path)])))))
(define+provide/contract (render-pagenodes pagetree-or-path)
((or/c pagetree? pathish?) . -> . void?)
@ -259,20 +209,6 @@
(define ram-cache (make-hash))
(define (get-external-render-proc v)
(match v
[(list (? module-path? mod) (? symbol? render-proc-id))
(with-handlers ([exn:fail:filesystem:missing-module?
(λ (e) (raise
(exn:fail:contract (string-replace (exn-message e) "standard-module-name-resolver" "external-renderer")
(exn-continuation-marks e))))]
[exn:fail:contract? ;; raised if dynamic-require can't find render-proc-id
(λ (e) (raise
(exn:fail:contract (string-replace (exn-message e) "dynamic-require" "external-renderer")
(exn-continuation-marks e))))])
(dynamic-require mod render-proc-id))]
[_ (raise-argument-error 'external-renderer "value in the form '(module-path proc-id)" v)]))
;; note that output and template order is reversed from typical
(define (render-to-file-base caller
force?
@ -299,11 +235,7 @@
[(not render-cache-activated?) 'render-cache-deactivated]
[else #false]))
(when render-needed?
(define render-thunk (or maybe-render-thunk
(λ () ((or (let ([val (setup:external-renderer)])
(and val (get-external-render-proc val)))
render)
source-path template-path output-path)))) ; returns either string or bytes
(define render-thunk (or maybe-render-thunk (λ () (render source-path template-path output-path)))) ; returns either string or bytes
(define render-result
(cond
[render-cache-activated?
@ -455,23 +387,22 @@
(with-handlers ([exn:fail:contract? (λ (e) #f)]) ; in case source-path doesn't work with cached-require
(parameterize ([current-directory (current-project-root)])
(define source-metas (cached-metas source-path))
(define template-name (match (select-from-metas pollen-template-meta-key source-metas) ; #f or atom or list
[(? list? names)
(for/first ([name (in-list names)]
#:when (equal? (get-ext name) (->string output-path-ext)))
name)]
[other other]))
(define template-name-or-names ; #f or atom or list
(select-from-metas (setup:template-meta-key source-path) source-metas))
(define template-name (if (list? template-name-or-names)
(findf (λ (tn) (eq? (get-ext tn) output-path-ext)) template-name-or-names)
template-name-or-names))
(and template-name (simplify-path (cleanse-path (build-path (dirname source-path) template-name)))))))
(define (get-default-template source-path output-path-ext)
(and output-path-ext
(let ([default-template-filename (add-ext pollen-template-prefix output-path-ext)])
(let ([default-template-filename (add-ext (setup:template-prefix source-path) output-path-ext)])
(find-upward-from source-path default-template-filename file-exists-or-has-source?))))
(define (get-fallback-template source-path output-path-ext)
(and output-path-ext
(build-path (current-server-extras-path)
(add-ext pollen-fallback-template-prefix output-path-ext))))
(add-ext (setup:fallback-template-prefix source-path) output-path-ext))))
(define (template-cache-key source-path output-path)
(paths->key 'template source-path (current-poly-target) output-path))
@ -482,45 +413,42 @@
[maybe-output-path]
[(->output-path source-path)]
[else #false]))
(define (cache-thunk)
(match source-path
[(or (? markup-source?) (? markdown-source?))
;; output-path may not have an extension
(define output-path-ext (cond
[(get-ext output-path)]
[(current-poly-target)]
[else #false]))
(for/or ([proc (list get-template-from-metas
get-default-template
get-fallback-template)])
(file-exists-or-has-source? (proc source-path output-path-ext)))]
[_ #false]))
(cond
[(or (current-session-interactive?) (not (setup:render-cache-active source-path)))
;; don't cache templates in interactive session, for fresher reloads
;; this makes it possible to add template and have it show up in next render
(cache-thunk)]
;; otherwise, within a rendering session, this will prevent repeat players like "template.html.p"
;; from hitting the file cache repeatedly
[else
(define key (template-cache-key source-path output-path))
(hash-ref! ram-cache key (λ () (cache-ref! key cache-thunk)))]))
#;(module-test-external
(define key (template-cache-key source-path output-path))
(hash-ref! ram-cache
;; within a session, this will prevent repeat players like "template.html.p"
;; from hitting the file cache repeatedly
key
(λ ()
(cache-ref! key
(λ ()
(match source-path
[(or (? markup-source?) (? markdown-source?))
;; output-path may not have an extension
(define output-path-ext (cond
[(get-ext output-path)]
[(current-poly-target)]
[else #false]))
(for/or ([proc (list get-template-from-metas
get-default-template
get-fallback-template)])
(file-exists-or-has-source? (proc source-path output-path-ext)))]
[_ #false]))))))
(module-test-external
(require pollen/setup sugar/file sugar/coerce)
(define fallback.html (build-path (current-server-extras-path)
(add-ext pollen-fallback-template-prefix 'html)))
(add-ext (setup:fallback-template-prefix) 'html)))
(check-equal? (get-template-for (->complete-path "foo.poly.pm")) fallback.html)
(check-equal? (get-template-for (->complete-path "foo.html.pm")) fallback.html)
(define fallback.svg (build-path (current-server-extras-path)
(add-ext pollen-fallback-template-prefix 'svg)))
(add-ext (setup:fallback-template-prefix) 'svg)))
(parameterize ([current-poly-target 'svg])
(check-equal? (get-template-for (->complete-path "foo.poly.pm")) fallback.svg)
(check-equal? (get-template-for (->complete-path "foo.html.pm")) fallback.html))
(define fallback.missing (build-path (current-server-extras-path)
(add-ext pollen-fallback-template-prefix 'missing)))
(add-ext (setup:fallback-template-prefix) 'missing)))
(parameterize ([current-poly-target 'missing])
(check-false (get-template-for (->complete-path "foo.poly.pm")))
(check-equal? (get-template-for (->complete-path "foo.html.pm")) fallback.html)))

@ -15,7 +15,7 @@ This is the core design principle of Pollen. Consistent with this principle, Pol
@item{@bold{A Pollen project consists of source files + static files.} A @italic{source file} is a file that can be compiled to produce certain output. A @italic{static file} is usable as it stands (e.g., an SVG file or webfont). Generally, the textual content of your book will live in source files, and other elements will be static files.}
@item{@bold{Source control is a good idea.} Because Pollen projects are software projects, they can be easily managed with systems for source control and collaboration. If you're a writer at heart, don't fear these systems — the learning curve is repaid by revision & edit tracking that's much easier than it is with Word or PDF files.}
@item{@bold{Source control is a good idea.} Because Pollen projects are software projects, they can be easily managed with systems for source control and collaboration, like @link["http://github.com"]{GitHub}. If you're a writer at heart, don't fear these systems — the learning curve is repaid by revision & edit tracking that's much easier than it is with Word or PDF files.}
]

@ -9,7 +9,7 @@
@defmodule[pollen/cache]
The slowest part of a Pollen @racket[render] is compiling a source file. Because Pollen allows source files to be edited and previewed dynamically, these files get recompiled a lot. Therefore, Pollen stores copies of the exports of source files — namely, whatever is stored in @code[(format "~a" pollen-main-export)] and @code[(format "~a" pollen-meta-export)] — in a cache so they can be reused.
The slowest part of a Pollen @racket[render] is compiling a source file. Because Pollen allows source files to be edited and previewed dynamically, these files get recompiled a lot. Therefore, Pollen stores copies of the exports of source files — namely, whatever is stored in @code[(format "~a" default-main-export)] and @code[(format "~a" default-meta-export)] — in a cache so they can be reused.
In each directory of your project, Pollen writes cache files into a subdirectory called @filepath{compiled}. The files are stored on disk so they can be reused between sessions. If you delete files within a cache directory (or the whole thing), don't worry — everything will get regenerated. (However, I don't recommend trying to read or write directly to any @filepath{compiled} directory, as the implementation details of the cache are subject to change.)
@ -43,7 +43,7 @@ Be warned that this will make your rendering much slower. But you will be guaran
@section{Scope of dependency tracking}
The compile cache tracks the modification date of the source file, the current setting of @secref["The_POLLEN_environment_variable"], and the modification dates of the template and @filepath{pollen.rkt} (if they exist). For @tt{poly} source files, it also tracks the @racket[current-poly-target]. It also tracks files you've listed in the optional setup value @racket[setup:cache-watchlist] and environment variables listed in the optional setup value @racket[setup:envvar-watchlist].
The compile cache tracks the modification date of the source file, the current setting of @secref["The_POLLEN_environment_variable"], and the modification dates of the template and @filepath{pollen.rkt} (if they exist). For @tt{poly} source files, it also tracks the @racket[current-poly-target]. It also tracks any files you've listed in the optional setup value @racket[setup:cache-watchlist].
It does not, however, track every possible dependency. So in a complex project, it's possible to create deep dependencies that aren't noticed by the cache. In particular, Pollen does not track pagetree files as dependencies of other source files. Thus, if you change a pagetree, you'll ordinarily need to use @exec{raco pollen reset} to clear the caches.
@ -70,6 +70,8 @@ Attempt to retrieve the requested value out of the cache. If it's not there, or
These functions are the lower-level cousins of @racket[get-doc] and @racket[get-metas], which have a more convenient interface. Unless you have a special reason, you're better off using those.
Despite their names, these functions actually rely on @racket[setup:main-export] and @racket[setup:meta-export] (which default to @id[default-main-export] and @id[default-meta-export]). Thus, if you override those names, everything will still work as expected.
If you want the speed benefit of the cache, you should use @racket[cached-doc] and @racket[cached-metas] to get data from Pollen source files in preference to functions like @racket[require], @racket[local-require], and @racket[dynamic-require]. Those will also work. They'll just be slower.

@ -21,8 +21,6 @@ Pollen uses a special character — the @italic{lozenge}, which looks like this:
I chose the lozenge as the command character because a) it appears in almost every font, b) it's barely used in ordinary typesetting, c) it's not used in any programming language that I know of, and d) its shape and color allow it to stand out easily in code without being distracting.
Consideration (b) is especially important in a text-based language like Pollen. If Pollen used something more common as its command character, then every time you used that character in text, you'd have to specially escape it. This would make it cumbersome and annoying to import plain text into Pollen source files. This is the Pareto-optimal trade.
If you're using DrRacket, you can use the @onscreen{Insert Command Char} button at the top of the editing window to — you guessed it — insert the command character.
If you're using a different editor, here's how you type it:
@ -31,9 +29,9 @@ If you're using a different editor, here's how you type it:
@(linebreak)@bold{Windows}: holding down Alt, type 9674 on the num pad
@(linebreak)@bold{GNU/Linux, BSD}: Type Ctrl + Shift + U, then 25CA, then Enter
For more information on entering arbitrary Unicode characters, see @link["https://en.wikipedia.org/wiki/Unicode_input"]{Wikipedia}.
For more information on entering arbitrary Unicode glyphs, see @link["https://en.wikipedia.org/wiki/Unicode_input"]{Wikipedia}.
@subsection{``But I don't want to use the lozenge ...''}
@subsection{``But I don't want to use it ...''}
Fine, but you have to pick @italic{something} as your command character. If you don't like this one, you can override it within a project — see @seclink["setup-overrides"].
@ -614,7 +612,7 @@ Second, the metas are collected into a hash table that is exported with the name
'#hasheq((dog . "Roxy") (cat . "Chopper") (here-path . "unsaved-editor"))
}
The only key that's automatically defined in every meta table is @racket['#,pollen-here-path-key], which is the absolute path to the source file. (In this case, because the file hasn't been saved, you'll see the @val{unsaved-editor} name instead.)
The only key that's automatically defined in every meta table is @racket['#,(setup:here-path-key)], which is the absolute path to the source file. (In this case, because the file hasn't been saved, you'll see the @val{unsaved-editor} name instead.)
Still, you can override this too:
@ -748,14 +746,12 @@ And the metas:
@codeblock{
#lang racket/base
(require "path/to/your-pollen-source") ; doc and metas and everything else
(require (submod "path/to/your-pollen-source" metas)) ; just metas
(require "pollen-source.rkt") ; doc and metas and everything else
(require (submod "pollen-source.rkt" metas)) ; just metas
}
The @id{metas} submodule gives you access to the @id{metas} hashtable @italic{without} compiling the rest of the file. So if you need to harvest metas from a set of source files — for instance, page titles (for a table of contents) or categories — using @racket[require] with the submodule will be faster.
@bold{Pro tip #3}: Within a tag function, you can access the metas of the source currently being evaluated with @racket[current-metas].
@subsubsection{Inserting a comment}
Two options.

@ -16,7 +16,8 @@ These functions are automatically imported into every Pollen source file (meanin
@section{Metas}
The only key that's automatically defined in every meta table is @racket['#,pollen-here-path-key], which holds the absolute path to the source file. For instance, you could retrieve this value with @racket[(select-from-metas '#,pollen-here-path-key metas)].
The only key that's automatically defined in every meta table is @racket['#,(setup:here-path-key)], which holds the absolute path to the source file. For instance, you could retrieve this value with @racket[(select-from-metas '#,(setup:here-path-key) metas)]. You can use something other than @racket['#,(setup:here-path-key)] as the key by overriding @racket[setup:here-path-key].
For a full introduction to metas, see @secref["Inserting_metas"].
@ -31,7 +32,7 @@ You can retrieve a meta value — even in the same document where you define it
@section{Splicing}
@defform[(\@ arg ...)]
The splicing tag signals that a list should be merged into its containing expression. The splicing tag is @racket['\@].
Splicing tag: signals that a list should be merged into its containing expression. You can use something other than @racket[\@] by overriding @racket[setup:splicing-tag].
@examples[#:eval my-eval
(module splicer pollen/markup
@ -40,24 +41,6 @@ The splicing tag signals that a list should be merged into its containing expres
doc
]
The splicing tag is useful when you want to return a list of X-expressions in a situation where you can only return one. For instance, @secref["Tag_functions"] can only return one X-expression. But if we wrap the list of X-expressions in a splicing tag, they behave like a single X-expression. Later, Pollen will merge the list elements into the surrounding expression (as shown above).
@examples[#:eval my-eval
(require pollen/tag)
(code:comment @#,t{wrong: function returns a list of X-expressions})
(define-tag-function (multi attrs elems)
'("foo" "bar"))
(code:comment @#,t{right: function returns a list of X-expressions})
(code:comment @#,t{as elements inside a splicing tag})
(define-tag-function (multi2 attrs elems)
'(\@ "foo" "bar"))
]
Though the splicing tag is cosmetically identical to the abbreviated notation of @litchar{@"@"} for @racket[unquote-splicing], and has a similar purpose, it's not the same thing. The splicing tag isn't a variable — it's just a symbol that Pollen treats specially when generating output.
@defform[(when/splice condition pollen-args)]
If @racket[_condition] is true, put the @racket[_pollen-args] into the document. Within a template file, usually invoked like so:

@ -44,7 +44,18 @@ This function doesn't do much on its own. Rather, it provides the hooks upon whi
Recall that in Pollen, all @secref["tags-are-functions"]. By default, the @racket[_tagged-xexpr] from a source file is tagged with @racket[root]. So the typical way to use @racket[decode] is to attach your decoding functions to it, and then define @racket[root] to invoke your @racket[decode] function. Then it will be automatically applied to every @racket[doc] during compile.
@margin-note{@link["https://docs.racket-lang.org/pollen-tfl/_pollen_rkt_.html#%28def._%28%28lib._pollen-tfl%2Fpollen..rkt%29._root%29%29"]{Here's an example} of invoking @racket[decode] via the @racket[root] tag. That example is part of the @racket[pollen-tfl] sample project, which you can install & study separately.}
For instance, here's how @racket[decode] is attached to @racket[root] in @link["http://practicaltypography.com"]{@italic{Butterick's Practical Typography}}. There's not much to it —
@racketblock[
(define (root . items)
(decode (txexpr 'root '() items)
#:txexpr-elements-proc decode-paragraphs
#:block-txexpr-proc (compose1 hyphenate wrap-hanging-quotes)
#:string-proc (compose1 smart-quotes smart-dashes)
#:exclude-tags '(style script)))
]
@margin-note{The @racket[hyphenate] function is not part of Pollen, but rather the @link["http://github.com/mbutterick/hyphenate"]{@racket[hyphenate] package}, which you can install separately.}
This illustrates another important point: even though @racket[decode] presents an imposing list of arguments, you're unlikely to use all of them at once. These represent possibilities, not requirements. For instance, let's see what happens when @racket[decode] is invoked without any of its optional arguments.
@ -291,9 +302,9 @@ The @racket[_linebreaker] argument can either be @racket[#f] (which will delete
(decode-paragraphs
[elements (listof xexpr?)]
[paragraph-wrapper (or/c txexpr-tag? ((listof xexpr?) . -> . txexpr?)) 'p]
[#:linebreak-proc linebreak-proc (txexpr-elements? . -> . txexpr-elements?) decode-linebreaks]
[#:linebreak-proc linebreak-proc ((listof xexpr?) . -> . (listof xexpr?)) decode-linebreaks]
[#:force? force-paragraph? boolean? #f])
txexpr-elements?]
(listof xexpr?)]
Find paragraphs within @racket[_elements] and wrap them with @racket[_paragraph-wrapper]. Also handle linebreaks using @racket[decode-linebreaks].
What counts as a paragraph? Any @racket[_elements] that are either a) explicitly set apart with a paragraph separator, or b) adjacent to a @racket[block-txexpr?] (in which case the paragraph-ness is implied).

@ -15,17 +15,17 @@ Pollen handles six kinds of source files:
@itemlist[
@item{@bold{Preprocessor}, with file extension @ext[pollen-preproc-source-ext]}
@item{@bold{Preprocessor}, with file extension @ext[default-preproc-source-ext]}
@item{@bold{Markup}, with file extension @ext[pollen-markup-source-ext]}
@item{@bold{Markup}, with file extension @ext[default-markup-source-ext]}
@item{@bold{Markdown}, with file extension @ext[pollen-markdown-source-ext]}
@item{@bold{Markdown}, with file extension @ext[default-markdown-source-ext]}
@item{@bold{Null}, with file extension @ext[pollen-null-source-ext]}
@item{@bold{Null}, with file extension @ext[default-null-source-ext]}
@item{@bold{Scribble}, with file extension @ext[pollen-scribble-source-ext]}
@item{@bold{Scribble}, with file extension @ext[default-scribble-source-ext]}
@item{@bold{Pagetree}, with file extension @ext[pollen-pagetree-source-ext]. This is the only source type that does not produce an output file.}
@item{@bold{Pagetree}, with file extension @ext[default-pagetree-source-ext]. This is the only source type that does not produce an output file.}
]
@ -170,7 +170,7 @@ In all cases, if there is no corresponding source, return @racket[#f].
path?]
Convert a source path @racket[_p] into its corresponding output path. This function simply generates a path for a file — it does not ask whether the file exists.
If @racket[_p] has a @seclink["The_poly_output_type"]{@id[pollen-poly-source-ext] output type}, then @racket[->output-path] uses @racket[current-poly-target] as the output-path extension.
If @racket[_p] has a @seclink["The_poly_output_type"]{@id[default-poly-source-ext] output type}, then @racket[->output-path] uses @racket[current-poly-target] as the output-path extension.
Otherwise, there are no type-specific variants for this function because the output path of a Pollen source file is @seclink["Saving___naming_your_source_file"]{determined by its name}.

@ -27,7 +27,7 @@ For ease of use, the behavior of the Pollen language departs from the standard R
Commands must start with the special lozenge character @litchar{◊}. Other material is interpreted as plain text. See @secref["pollen-command-syntax"] for more.
You can change the command character for a project by overriding @racket[pollen-command-char].
You can change the command character for a project by overriding @racket[default-command-char].
@bold{How is this different from Racket?} In Racket, everything is a command, and plain text must be quoted.
@ -46,12 +46,14 @@ By default, every Pollen source file exports two identifiers:
Contains the output of the file. The type of output depends on the source format (about which, more below).}
@defthing[metas hasheq?]{
A table of keyvalue pairs with extra information that is extracted from the source. These @racket[metas] will always contain the key @racket['#,pollen-here-path-key], which returns a string representation of the full path to the source file. Beyond that, the only @racket[metas] are the ones that are specified within the source file (see the source formats below for more detail on how to specify metas).}
A table of keyvalue pairs with extra information that is extracted from the source. These @racket[metas] will always contain the key @racket['#,(setup:here-path-key)], which returns a string representation of the full path to the source file. Beyond that, the only @racket[metas] are the ones that are specified within the source file (see the source formats below for more detail on how to specify metas).}
As usual, you can use @racket[require], @racket[local-require], or @racket[dynamic-require] to retrieve these values. But within a Pollen project, the faster way is to use @racket[get-doc] and @racket[get-metas].
Pollen source files also make the @racket[metas] hashtable available through a submodule, unsurprisingly called @racket[metas]. So rather than importing a source file with @racket[(require "source.html.pm")], you can @racket[(require (submod "source.html.pm" metas))]. Accessing the metas this way avoids fully compiling the source file, and thus will usually be faster.
The names @racket[doc] and @racket[metas] can be changed for a project by overriding @racket[default-main-export] and @racket[default-meta-export].
@margin-note{The Pollen rendering system relies on these two exported identifiers, but otherwise doesn't care how they're generated. Thus, the code inside your Pollen source file could be written in @tt{#lang racket} or @tt{#lang whatever}. As long as you @racket[provide] those two identifiers and follow Pollen's file-naming conventions, your source file will be renderable.}
@bold{How is this different from Racket?} In Racket, you must explicitly @racket[define] and then @racket[provide] any values you want to export.
@ -69,9 +71,9 @@ If a file called @filepath{pollen.rkt} exists in the same directory with a sourc
@bold{How is this different from Racket?} In Racket, you must explicitly import files using @racket[require].
@subsection{Preprocessor (@(format ".~a" pollen-preproc-source-ext) extension)}
@subsection{Preprocessor (@(format ".~a" default-preproc-source-ext) extension)}
Invoke the preprocessor dialect by using @code{#lang pollen/pre} as the first line of your source file, or by using @code{#lang pollen} with a file extension of @code{@(format ".~a" pollen-preproc-source-ext)}. These forms are equivalent:
Invoke the preprocessor dialect by using @code{#lang pollen/pre} as the first line of your source file, or by using @code{#lang pollen} with a file extension of @code{@(format ".~a" default-preproc-source-ext)}. These forms are equivalent:
@racketmod[#:file "sample.css.pp" pollen
@ -94,9 +96,9 @@ The output of the preprocessor dialect, provided by @racket[doc], is plain text.
@subsection{Markdown (@(format ".~a" pollen-markdown-source-ext) extension)}
@subsection{Markdown (@(format ".~a" default-markdown-source-ext) extension)}
Invoke the Markdown dialect by using @code{#lang pollen/markdown} as the first line of your source file, or by using @code{#lang pollen} with a file extension of @code{@(format ".~a" pollen-markdown-source-ext)}. These forms are equivalent:
Invoke the Markdown dialect by using @code{#lang pollen/markdown} as the first line of your source file, or by using @code{#lang pollen} with a file extension of @code{@(format ".~a" default-markdown-source-ext)}. These forms are equivalent:
@racketmod[#:file "sample.txt.pmd" pollen
@ -110,9 +112,9 @@ _...source...
The output of the Markdown dialect, provided by @racket[doc], is a tagged X-expression.
@subsection{Markup (@(format ".~a" pollen-markup-source-ext) extension)}
@subsection{Markup (@(format ".~a" default-markup-source-ext) extension)}
Invoke the Pollen markup dialect by using @code{#lang pollen/markup} as the first line of your source file, or by using @code{#lang pollen} with a file extension of @code{@(format ".~a" pollen-markup-source-ext)}. These forms are equivalent:
Invoke the Pollen markup dialect by using @code{#lang pollen/markup} as the first line of your source file, or by using @code{#lang pollen} with a file extension of @code{@(format ".~a" default-markup-source-ext)}. These forms are equivalent:
@racketmod[#:file "about.html.pm" pollen
@ -125,10 +127,10 @@ _...source...
The output of the Pollen markup dialect, provided by @racket[doc], is a tagged X-expression.
@subsection{Pagetree (@(format ".~a" pollen-pagetree-source-ext) extension)}
@subsection{Pagetree (@(format ".~a" default-pagetree-source-ext) extension)}
Invoke the pagetree dialect by using @code{#lang pollen/ptree} as the first line of your source file, or by using @code{#lang pollen} with a file extension of @code{@(format ".~a" pollen-pagetree-source-ext)}. These forms are equivalent:
Invoke the pagetree dialect by using @code{#lang pollen/ptree} as the first line of your source file, or by using @code{#lang pollen} with a file extension of @code{@(format ".~a" default-pagetree-source-ext)}. These forms are equivalent:
@racketmod[#:file "main.ptree" pollen
@ -152,12 +154,12 @@ These aren't source formats because they don't contain a @tt{#lang pollen} line.
@subsection{Scribble (@(format ".~a" pollen-scribble-source-ext) extension)}
@subsection{Scribble (@(format ".~a" default-scribble-source-ext) extension)}
Scribble files are recognized by the project server and can be compiled and previewed in single-page mode.
@subsection{Null (@(format ".~a" pollen-null-source-ext) extension)}
@subsection{Null (@(format ".~a" default-null-source-ext) extension)}
Files with the null extension are simply rendered as a copy of the file without the extension, so @filepath{index.html.p} becomes @filepath{index.html}.

@ -98,58 +98,5 @@ In general, I subscribe to the view that software should let you do what you wan
I've been using Pollen daily for several years (and will continue to do so, because my main work is writing). I've made Pollen available because a) I'm certain that others have had the same frustrations that I have, and b) feature suggestions and bug reports make it more useful for everyone.
I hope you enjoy using it.
@section{Getting more help}
@subsection{Bugs and feature requests}
Can be submitted as @link["https://git.matthewbutterick.com/mbutterick/pollen/issues"]{issues} at the main Pollen source repository.
@subsection{Questions & discussion}
For general tips and how-to questions, use the @link["https://forums.matthewbutterick.com/c/typesetting/"]{Pollen discussion forum}. I'll also use that list to post major changes and new features. You need an account to post (free and easy to set up with an email address).
(BTW, the former ``pollenpub'' Google Group and the ``pollen-users'' GitHub repo are now deprecated.)
@subsection{Can I see the source for @italic{Practical Typography} or @italic{Typography for Lawyers}?}
Yes, a tutorial project based on the previous version of @link["http://typographyforlawyers.com/"]{@italic{Typography for Lawyers}} is available by installing the @link["https://docs.racket-lang.org/pollen-tfl/"]{pollen-tfl} package the same way you installed Pollen.
The current versions of @italic{Practical Typography} & @italic{Typography for Lawyers} are generated from a single set of Pollen source files, which is a complication that makes them less suitable for an introductory tutorial. Still, even though this tutorial project is based on an earlier version, the coding techniques are very close to what I still use. Learn with confidence.
@subsection{Utilities & libraries}
@link["https://github.com/malcolmstill/pollen-count"]{pollen-count}: enumeration and cross-referencing library by Malcolm Still
@link["https://github.com/lijunsong/pollen-mode"]{pollen-mode}: Emacs mode for Pollen by Junsong Li
@link["https://github.com/basus/pollen-mode"]{Pollen mode}: Emacs mode for Pollen by Shrutarshi Basu
@link["https://docs.racket-lang.org/pollen-component/"]{Pollen Component}: Component-based development for Pollen by Leandro Facchinetti
@link["https://docs.racket-lang.org/css-expr/"]{CSS-expressions}: S-expression-based CSS by Leandro Facchinetti
@link["https://github.com/lijunsong/pollen-rock"]{Pollen Rock}: rendering server and an in-browser editor for Pollen
@link["https://github.com/appliedsciencestudio/talks/tree/master/mxnet"]{Polllen as a front end for Reveal.js} by Dave Liepmann. Reveal.js is a library that allows you to create slide presentations in pure HTML/CSS that run in the browser.
@subsection{More projects & guides}
@link["https://digitalwords.net"]{Digital Words} by Júda Ronén [@link["https://gitlab.com/rwmpelstilzchen/digitalwords.net"]{source}]
@link["https://thelocalyarn.com/excursus/secretary"]{Secretary of Foreign Relations} by Joel Dueck [@link["https://github.com/otherjoel/try-pollen"]{source}]
@link["https://github.com/fasiha/pollen-guide"]{A Poor Guide to Pollen} by Ahmed Fasih
@link["https://youtu.be/20GGVNBykaw"]{The World's Most Dangerous Racket Programmer} and @link["https://youtu.be/IMz09jYOgoc"]{Like a Blind Squirrel in a Ferrari}: short talks about Pollen that I gave at RacketCons 2013 and 2014, respectively.
@link["http://mstill.io"]{mstill.io blog} by Malcolm Still [@link["https://github.com/malcolmstill/mstill.io"]{source}]
I hope you enjoy using it. If you get stuck on something not covered here, see @secref["Getting_more_help" #:doc '(lib "pollen/scribblings/pollen.scrbl")].

@ -10,4 +10,4 @@
This module is licensed under the MIT License.
Source repository at @link["https://git.matthewbutterick.com/mbutterick/pollen/"]{https://git.matthewbutterick.com/mbutterick/pollen/}. Suggestions & corrections welcome.
Source repository at @link["http://github.com/mbutterick/pollen"]{http://github.com/mbutterick/pollen}. Suggestions & corrections welcome.

@ -1,20 +1,9 @@
#lang at-exp racket/base
(require (for-syntax racket/base
racket/syntax)
racket/format
racket/runtime-path
scribble/core
scribble/decode
scribble/html-properties
scribble/latex-properties
scribble/manual
scribble/private/manual-sprop)
(require (for-syntax racket/base racket/syntax pollen/setup) scribble/core scribble/manual scribble/private/manual-sprop scribble/decode scribble/html-properties racket/runtime-path racket/format pollen/setup)
(provide (all-defined-out) (all-from-out racket/runtime-path))
(define-runtime-path mb-css "mb.css")
(define-runtime-path mb-tex "mb.tex")
(define (link-tt url) (link url (tt url)))
@ -24,18 +13,17 @@
(define (fileblock filename . inside)
(compound-paragraph
(style "fileblock" (list* (alt-tag "div") 'multicommand
(box-mode "RfileboxBoxT" "RfileboxBoxC" "RfileboxBoxB")
(tex-addition mb-tex)
(box-mode "RfileboxBoxT" "RfileboxBoxC" "RfileboxBoxB")
scheme-properties))
(list
(paragraph (style "fileblockFiletitle" (list* (alt-tag "div") (box-mode* "RfiletitleBox") (tex-addition mb-tex) scheme-properties))
(paragraph (style "fileblock_filetitle" (list* (alt-tag "div") (box-mode* "RfiletitleBox") scheme-properties))
(list (make-element
(style "fileblockFilename" (list (css-style-addition mb-css) (tex-addition mb-tex)))
(style "fileblock_filename" (list (css-style-addition mb-css)))
(if (string? filename)
(filepath filename)
filename))))
(compound-paragraph
(style "fileblockFilecontent" (list* (alt-tag "div") (box-mode* "RfilecontentBox") (tex-addition mb-tex) scheme-properties))
(style "fileblock_filecontent" (list* (alt-tag "div") (box-mode* "RfilecontentBox") scheme-properties))
(decode-flow inside)))))
(define (convert-newlines args)
@ -48,28 +36,17 @@
(nested (racketerror (racketfont* (convert-newlines args)))))
(define (foreign-code . args)
(compound-paragraph (style "foreignCode" (list (css-style-addition mb-css)
(alt-tag "div")
(tex-addition mb-tex)))
(list (apply verbatim args))))
(compound-paragraph (style "foreign-code" (list (css-style-addition mb-css) (alt-tag "div"))) (list (apply verbatim args))))
(define (terminal . args)
(compound-paragraph (style "terminal" (list (css-style-addition mb-css)
(alt-tag "div")
(tex-addition mb-tex)))
(list (apply verbatim args))))
(compound-paragraph (style "terminal" (list (css-style-addition mb-css) (alt-tag "div"))) (list (apply verbatim args))))
(define (browser . args)
(compound-paragraph (style "browser" (list (css-style-addition mb-css)
(alt-tag "div")
(tex-addition mb-tex)))
(list (paragraph (style #f null) (convert-newlines args)))))
(compound-paragraph (style "browser" (list (css-style-addition mb-css) (alt-tag "div"))) (list (paragraph (style #f null) (convert-newlines args)))))
(define (noskip-note)
(nested #:style (style "noskip" (list (css-style-addition mb-css)
(alt-tag "div")
(tex-addition mb-tex)))
(nested #:style (style "noskip" (list (css-style-addition mb-css) (alt-tag "div")))
(margin-note "Dont skip this section! It explains an essential Pollen concept.")))
@ -81,6 +58,20 @@
(define-runtime-path id name)
(image id xs ...)))]))
(define-syntax (defoverridable stx)
(syntax-case stx ()
[(_ name predicate? desc ...)
(with-syntax* ([default-name (format-id #'here "default-~a" #'name)]
[value (let ([v (syntax-local-eval #'default-name)])
(cond
[(and (list? v) (andmap symbol? v) (> (length v) 5)) #`'#,'(see below)]
[(or (symbol? v) (list? v)) #`'#,v]
[(procedure? v) '(λ (path) #f)]
[else v]))]
[setup:name (format-id stx "setup:~a" #'name)])
#`(deftogether ((defproc (setup:name) predicate?)
(defthing default-name predicate? #:value value))
desc ...))]))
(define (val . args)
(racketvalfont (element 'tt (map ~v args))))

@ -26,7 +26,7 @@
width: 90%;
}
.fileblockFiletitle{
.fileblock_filetitle{
background: #eee;
text-align:right;
padding: 0.15em;
@ -42,13 +42,13 @@
color: #666;
}
.foreignCode {
.foreign-code {
margin-bottom: 1em;
padding: 0.5em;
background: #fcfcfc;
color: #666;
}
.terminal .SIntrapara, .browser .SIntrapara, .foreignCode .SIntrapara {
.terminal .SIntrapara, .browser .SIntrapara, .foreign-code .SIntrapara {
margin: 0 0 0 0;
}

@ -1,20 +0,0 @@
\newcommand{\terminal}[1]{#1}
\newcommand{\browser}[1]{#1}
\newcommand{\foreignCode}[1]{#1}
\newenvironment{fileblock}{}{}
\definecolor{fileboxborder}{gray}{0.5}
\definecolor{fileboxbackground}{gray}{0.9}
\definecolor{noskipbackground}{gray}{0.5}
\definecolor{noskipforeground}{gray}{1}
\newcommand{\fileblockFiletitle}[1]{\fcolorbox{fileboxborder}{fileboxbackground}{\makebox[\textwidth][r]{#1}}}
\newcommand{\fileblockFilename}[1]{#1}
\newenvironment{fileblockFilecontent}{}{}
\newenvironment{noskip}{}{}
% pdflatex chokes on emoji. Use ∇ in place of the guitar in setup.scrbl
\DeclareUnicodeCharacter{1F3B8}{$\nabla$}

@ -0,0 +1,50 @@
#lang scribble/manual
@title{Getting more help}
@section{Bugs and feature requests}
Can be submitted as @link["https://github.com/mbutterick/pollen/issues"]{GitHub issues} at the main Pollen source repository.
@section{Questions & discussion}
For general tips and how-to questions, use the @link["https://github.com/mbutterick/pollen-users/issues"]{pollen-users discussion group} (on GitHub). I'll also use that list to post major changes and new features.
You need a GitHub account to post. If you don't have one, don't panic — they're free and easy to set up with an email address. @link["https://github.com/mbutterick/pollen-users"]{Instructions here}.
(BTW, the former ``pollenpub'' Google Group is now deprecated.)
@section{Utilities & libraries}
@link["https://github.com/malcolmstill/pollen-count"]{pollen-count}: enumeration and cross-referencing library by Malcolm Still
@link["https://github.com/lijunsong/pollen-mode"]{pollen-mode}: Emacs mode for Pollen by Junsong Li
@link["https://github.com/basus/pollen-mode"]{Pollen mode}: Emacs mode for Pollen by Shrutarshi Basu
@link["https://docs.racket-lang.org/pollen-component/"]{Pollen Component}: Component-based development for Pollen by Leandro Facchinetti
@link["https://docs.racket-lang.org/css-expr/"]{CSS-expressions}: S-expression-based CSS by Leandro Facchinetti
@link["https://github.com/lijunsong/pollen-rock"]{Pollen Rock}: rendering server and an in-browser editor for Pollen
@link["https://github.com/appliedsciencestudio/talks/tree/master/mxnet"]{Polllen as a front end for Reveal.js} by Dave Liepmann. Reveal.js is a library that allows you to create slide presentations in pure HTML/CSS that run in the browser.
@section{Can I see the source for Practical Typography or Typography for Lawyers?}
Yes, the source for @link["http://typographyforlawyers.com/"]{Typography for Lawyers} is available. In terms of content, TFL was originally the basis of Practical Typography. But in terms of code, this new TFL website is essentially a clone of Practical Typography, but rewritten to be clearer and more instructive, with extensive source comments. [@link["https://github.com/mbutterick/pollen-tfl"]{source}]
@section{More projects & guides}
@link["https://digitalwords.net"]{Digital Words} by Júda Ronén [@link["https://gitlab.com/rwmpelstilzchen/digitalwords.net"]{source}]
@link["https://thelocalyarn.com/excursus/secretary"]{Secretary of Foreign Relations} by Joel Dueck [@link["https://github.com/otherjoel/try-pollen"]{source}]
@link["https://github.com/fasiha/pollen-guide"]{A Poor Guide to Pollen} by Ahmed Fasih
@link["https://youtu.be/20GGVNBykaw"]{The World's Most Dangerous Racket Programmer} and @link["https://youtu.be/IMz09jYOgoc"]{Like a Blind Squirrel in a Ferrari}: short talks about Pollen that I gave at RacketCons 2013 and 2014, respectively.
@link["http://mstill.io"]{mstill.io blog} by Malcolm Still [@link["https://github.com/malcolmstill/mstill.io"]{source}]

@ -24,7 +24,7 @@ Pagetrees surface throughout the Pollen system. They're primarily used for navig
@section{Making pagetrees with a source file}
A pagetree source file either starts with @code{#lang pollen} and uses the @racketfont{@(format ".~a" pollen-pagetree-source-ext)} extension, or starts with @code{#lang pollen/ptree} and then can have any file extension.
A pagetree source file either starts with @code{#lang pollen} and uses the @racketfont{@(format ".~a" default-pagetree-source-ext)} extension, or starts with @code{#lang pollen/ptree} and then can have any file extension.
Unlike other Pollen source files, since the pagetree source is not rendered into an output format, the rest of the filename is up to you.
@ -436,7 +436,7 @@ Return the pagenode immediately after @racket[_p]. For @racket[next*], return al
[pagetree-source (or/c pagetree? pathish?)])
pagetree?
]
Get a pagetree from a @ext[pollen-pagetree-source-ext] source file, namely @racket[_pagetree-source]. If @racket[_pagetree-source] is already a pagetree, just pass it through.
Get a pagetree from a @ext[default-pagetree-source-ext] source file, namely @racket[_pagetree-source]. If @racket[_pagetree-source] is already a pagetree, just pass it through.
@defproc[

@ -47,6 +47,7 @@ Or, if you can find a better digital-publishing tool, use that. But I'm never go
@include-section["programming-pollen.scrbl"]
@include-section["module-reference.scrbl"]
@include-section["unstable-module-reference.scrbl"]
@include-section["more-help.scrbl"]
@include-section["acknowledgments.scrbl"]
@include-section["license.scrbl"]
@include-section["version-history.scrbl"]

@ -17,7 +17,6 @@ Start a new document. Change the top line to:
The first line of every Pollen source file will start with @code{#lang pollen}.
@margin-note{If you prefer to use the command line and an editor other than DrRacket, equivalent command-line instructions follow at the end of each section. If you're using DrRacket, you can ignore these.}
@section{Running a source file}
@ -60,11 +59,6 @@ document.write('Hello world');
printf("Hello world");
}
@bold{Command line}: save the file as @filepath{hello.txt.pp} and then run:
@terminal{
> racket hello.txt.pp
}
@section{Naming, saving, and rendering a source file}
@ -161,12 +155,6 @@ Paradise Theatre}
Notice what happened — the Pollen project server dynamically regenerated the output file (@filepath{hello.txt}) from the source file (@filepath{hello.txt.pp}) after you edited the source. If you like, try making some more changes to @filepath{hello.txt.pp}, and reloading the browser to see the updates in @filepath{hello.txt}. The project server will regenerate the file whenever it changes.
@bold{Command line}: to see the changes after each edit, run:
@terminal{
> raco pollen render hello.txt.pp
> cat hello.txt
}
@section{Intermission}
@ -224,8 +212,6 @@ In your web browser, reload @link["http://localhost:8080/margin.html"]{@filepath
Still, this is the tiniest tip of the iceberg. The Pollen preprocessor gives you access to everything in the Racket programming language — including string manipulation, math functions, and so on.
@bold{Command line}: type the lozenge using whatever keyboard method you prefer (see @secref["the-lozenge"] for suggestions).
@section{Markdown mode}
When used as a preprocessor, Pollen's rule is that what you write is what you get. But if you're targeting HTML, who wants to type out all those @code{<tedious>tags</tedious>}? You can make Pollen do the heavy lifting by using an @defterm{authoring mode}.
@ -291,13 +277,6 @@ Pollen is handling three tasks here: interpreting the commands in the source, co
But what if you wanted to use Pollen as a preprocessor that outputs a Markdown file? No problem — just change the source name from @filepath{downtown.html.pmd} to @filepath{downtown.md.pp}. Changing the extension from @filepath{.pmd} to @filepath{.pp} switches Pollen from Markdown mode back to preprocessor mode. And changing the base name from @filepath{downtown.html} to @filepath{downtown.md} updates the name of the output file (and thereby skips the HTML conversion).
@bold{Command line}: to render the new source file after each edit, run:
@terminal{
> raco pollen render downtown.html.pmd
}
And then view the resulting @filepath{downtown.html} file however you like.
@section{Pollen markup}
@ -358,14 +337,6 @@ Return to the @link["http://localhost:8080/index.ptree"]{project dashboard} and
Pollen markup takes a little more effort to set up. But it also allows you more flexibility. If you want to do semantic markup, or convert your source into @seclink["fourth-tutorial"]{multiple output formats}, or handle complex page layouts — it's the way to go. (For more, see @seclink["Writing_with_Pollen_markup"
#:doc '(lib "pollen/scribblings/pollen.scrbl")].)
@bold{Command line}: to render the new source file after each edit, run:
@terminal{
> raco pollen render uptown.html.pm
}
And then view the resulting @filepath{uptown.html} file however you like.
@section{Templates}
The HTML pages we just made looked pretty dull. For the last stop on the quick tour, let's fix that.
@ -392,14 +363,6 @@ This is a simple HTML file that should look familiar, except for the two templat
Return to your web browser and reload @link["http://localhost:8080/uptown.html"]{@filepath{uptown.html}}. (Or @link["http://localhost:8080/downtown.html"]{@filepath{downtown.html}} — both will work.) The page will be rendered with the new @filepath{template.html}. As before, you can edit the template or the source and the project server will dynamically update the output file.
@bold{Command line}: to refresh the output after each edit of @filepath{template.html}, run:
@terminal{
> raco pollen render uptown.html.pm downtown.html.pm
}
And then view the resulting @filepath{uptown.html} and @filepath{downtown.html} files however you like.
@section{PS for Scribble users}
Pollen can also be used as a dynamic preview server for Scribble files. From your terminal, do the following:

@ -83,8 +83,6 @@ This command can be invoked two ways: in source mode or directory mode.
In both modes, the optional @exec{--dry-run} or @exec{-d} switch prints the paths that would be rendered by this command without actually doing so.
In both modes, the optional @exec{--force} or @exec{-f} switch forces a fresh render from source, even if the file is already cached, by updating the modification date of the file (à la @exec{touch}). Thus, if modification dates are important to you, don't use this option.
In both modes, the optional @exec{--null} or @exec{-n} switch renders as usual, but doesn't write any files. (Convenient if you're arranging special render behavior, for instance writing to a database or network server.)
@ -102,9 +100,7 @@ Paths can also be specified as output rather than input paths, and the correspon
> raco pollen render foo.html
> raco pollen render foo.html bar.html zam.css}
If a pagetree file is included in @racket[_source], all the files it lists will be rendered using the above rules.
The optional @exec{--target} or @exec{-t} switch specifies the render target to use for multi-output source files. (Files of other types encountered in @racket[_source] will still be rendered as usual.) If the target is omitted, the renderer will use whatever target appears first in @racket[(setup:poly-targets)].
The optional @exec{--target} or @exec{-t} switch specifies the render target for multi-output source files. If the target is omitted, the renderer will use whatever target appears first in @racket[(setup:poly-targets)].
@terminal{
> raco pollen render -t pdf foo.poly.pm}
@ -130,9 +126,11 @@ As a rule of thumb, parallel rendering works best if you do @exec{raco setup} fi
> raco pollen render -p
}
@italic{Warning}: In all cases, the newly rendered output file will overwrite any previous output file.
@bold{Directory mode}: @racket[raco pollen render _directory] renders all preprocessor source files and then all pagetree files found in the specified directory. If none of these files are found, a pagetree will be generated for the directory (which will include all source files, but also everything else that exists there; see @secref["The_automatic_pagetree"]) and then rendered. If the @racket[_directory] argument is omitted, the command defaults to the current directory.
@bold{Directory mode}: @racket[raco pollen render _directory] renders all preprocessor source files and then all pagetree files found in the specified directory. If none of these files are found, a pagetree will be generated for the directory (which will include all source files) and then rendered. If the @racket[_directory] argument is omitted, the command defaults to the current directory.
In directory mode, this command can be invoked with two other optional arguments (in addition to the @exec{--target}, @exec{--parallel}, and @exec{--jobs} switches mentioned above):
@ -181,8 +179,6 @@ The alternative @exec{--jobs <count>} or @exec{-j <count>} switch does the same
> raco pollen setup -j 4
}
@margin-note{As of mid-2020, Pollen's parallel-processing performance under the CS (= Chez Scheme) variant of Racket is worse than ordinary Racket. If you use Racket CS, you may get better results using @exec{-j 4} (which will limit the operation to four cores) than @exec{-p} (which will use all available cores).}
The optional @exec{--dry-run} or @exec{-d} switch prints the paths that would be compiled by this command without actually doing so.

@ -75,7 +75,7 @@ Note that @racket[_pt-or-pt-source] is used strictly as a list of files to rende
Find a template file for @racket[_source-path], with the following priority:
@itemlist[#:style 'ordered
@item{If the @racket[metas] for @racket[_source-path] have a key for @code[(format "~a" pollen-template-meta-key)], then use the value of this key, e.g. —
@item{If the @racket[metas] for @racket[_source-path] have a key for @code[(format "~a" default-template-meta-key)], then use the value of this key, e.g. —
@code{◊(define-meta template "my-template.html")}
@ -88,7 +88,7 @@ If your project has @seclink["fourth-tutorial"]{multiple output targets}, you ca
}
@item{If this key doesn't exist, or refers to a nonexistent file, look for a default template with the name @code[(format "~a.[output extension]" pollen-template-prefix)]. Meaning, if @racket[_source-path] is @code[(format "intro.html.~a" pollen-markup-source-ext)], the output path would be @code["intro.html"], so the default template would be @code[(format "~a.html" pollen-template-prefix)]. Look for this default template in the same directory as the source file, and then search upwards within successive parent directories. (Corollary: a default template in the project root will apply to all files in the project unless overridden within a subdirectory.)}
@item{If this key doesn't exist, or refers to a nonexistent file, look for a default template with the name @code[(format "~a.[output extension]" default-template-prefix)]. Meaning, if @racket[_source-path] is @code[(format "intro.html.~a" default-markup-source-ext)], the output path would be @code["intro.html"], so the default template would be @code[(format "~a.html" default-template-prefix)]. Look for this default template in the same directory as the source file, and then search upwards within successive parent directories. (Corollary: a default template in the project root will apply to all files in the project unless overridden within a subdirectory.)}
@item{If this file doesn't exist, use the fallback template as a last resort. (See @secref["Templates"
#:tag-prefixes '("tutorial-2")

@ -1,26 +1,10 @@
#lang scribble/manual
@(require "mb-tools.rkt")
@(require scribble/eval pollen/setup racket/string (for-label (except-in racket #%top) racket/runtime-path syntax/modresolve (except-in pollen #%module-begin #%top) pollen/render pollen/setup pollen/top))
@(require scribble/eval pollen/setup racket/string (for-label (except-in racket #%top) racket/runtime-path syntax/modresolve (except-in pollen #%module-begin #%top) pollen/setup pollen/top))
@(define my-eval (make-base-eval))
@(my-eval `(require pollen pollen/setup))
@(require (for-syntax racket/base racket/syntax pollen/setup))
@(define-syntax (defoverridable stx)
(syntax-case stx ()
[(_ name predicate? desc ...)
(with-syntax* ([default-name (format-id #'here "default-~a" #'name)]
[value (let ([v (syntax-local-eval #'default-name)])
(cond
[(and (list? v) (andmap symbol? v) (> (length v) 5)) #`'#,'(see below)]
[(or (symbol? v) (list? v)) #`'#,v]
[(procedure? v) '(λ (path) #f)]
[else v]))]
[setup:name (format-id stx "setup:~a" #'name)])
#`(deftogether ((defproc (setup:name) predicate?)
(defthing default-name predicate? #:value value))
desc ...))]))
@title{Setup}
@defmodule[pollen/setup]
@ -71,6 +55,23 @@ Every @racket[setup:]@racket[_name] function will resolve the current value of t
Determines the default HTTP port for the project server.}
@defoverridable[main-export symbol?]{The main X-expression exported from a compiled Pollen source file.}
@defoverridable[meta-export symbol?]{The meta hashtable exported from a compiled Pollen source file.}
@defoverridable[extension-escape-char char?]{Character for escaping output-file extensions within source-file names.}
@deftogether[(
@defoverridable[preproc-source-ext symbol?]
@defoverridable[markup-source-ext symbol?]
@defoverridable[markdown-source-ext symbol?]
@defoverridable[null-source-ext symbol?]
@defoverridable[pagetree-source-ext symbol?]
@defoverridable[template-source-ext symbol?]
@defoverridable[scribble-source-ext symbol?]
)]{File extensions for Pollen source files.}
@defoverridable[main-pagetree string?]{Pagetree that Pollen dashboard loads by default in each directory.}
@ -88,6 +89,8 @@ Determines the default HTTP port for the project server.}
@defoverridable[command-char char?]{The magic character that indicates a Pollen command, function, or variable.}
@defoverridable[template-prefix string?]{Prefix of the default template.}
@deftogether[(
@(defoverridable newline string?)
@ -144,6 +147,12 @@ Both the names and the values of environment variables are case-insensitive, so
@history[#:added "1.1"]}
@defoverridable[splicing-tag symbol?]{Key used to signal that an X-expression should be spliced into its containing X-expression.}
@defoverridable[poly-source-ext symbol?]{Extension that indicates a source file can target multiple output types.}
@defoverridable[poly-targets (listof symbol?)]{List of symbols that denotes the possible targets of a @racket['poly] source file.}
@ -153,16 +162,13 @@ Both the names and the values of environment variables are case-insensitive, so
@history[#:added "1.5"]}
@defoverridable[allow-unbound-ids? boolean?]{Predicate that controls whether Pollen converts unbound identifiers into default tags by altering the behavior of @racket[#%top] in @racketmodname[pollen/top].
@defoverridable[allow-unbound-ids? boolean?]{Predicate that controls whether Pollen converts unbound identifiers into default tags by altering the behavior of @racket[#%top] in @racketmodname[pollen/top].
@history[#:added "2.0"]}
@history[#:added "2.0"]}
@defoverridable[external-renderer (or/c (list/c module-path? symbol?) #f)]{A module path and identifier (suitable for use with @racket[dynamic-require]) that provide a function for Pollen to call instead of @racket[render] when rendering files needed by the @seclink["Using_the_project_server"]{project server} or when running @secref["raco_pollen_render"]. The function must accept the same arguments as @racket[render-to-file] and should return the final output as a @tech[#:doc '(lib "scribblings/reference/reference.scrbl")]{string} or @tech[#:doc '(lib "scribblings/reference/reference.scrbl")]{byte string}. Pollen will always write this return value out to the output file for you.
@defoverridable[here-path-key 'symbol]{Key used to store the path of the source file in its metas table. No idea why you'd want to change this.}
Setting this value gives you full control over (and responsibility for) how Pollen converts the compiled @racketidfont{doc} and @racketidfont{metas} from source files into their final output. Your renderer should be able to handle any of Pollens @seclink["Source_formats"]{source formats} or @seclink["Utility_formats"]{utility formats}. The operation of Pollens @racket[render] function is not affected by setting this value, so your renderer can use it as a fallback.
@history[#:added "3.2"]}
@section{Parameters}
I mean @italic{parameters} in the Racket sense, i.e. values that can be fed to @racket[parameterize].

@ -16,7 +16,7 @@ That's no longer true. The web is now more than 20 years old. During that time,
But one part hasn't improved much: the way we make web pages. Over the years, tools promising to simplify web development have come and mostly gone — from @link["http://www.macobserver.com/reviews/pagemill2.shtml"]{PageMill} to @link["http://www.adobe.com/products/dreamweaver.html"]{Dreamweaver} to @link["http://www.squarespace.com"]{Squarespace}. Meanwhile, serious web jocks have remained loyal to the original HTML power tool: the humble text editor.
In one way, this makes sense. Web pages are made mostly of text-based data — HTML, CSS, JavaScript, and so on — and the simplest way to manipulate this data is with a text editor. While HTML and CSS are not programming languages — you can't even compute 1 + 1 — they lend themselves to semantic and logical structure that's most easily expressed by editing them as text. Furthermore, text-based editing makes debugging and performance improvements easier.
In one way, this makes sense. Web pages are made mostly of text-based data — HTML, CSS, JavaScript, and so on — and the simplest way to mainpulate this data is with a text editor. While HTML and CSS are not programming languages — you can't even compute 1 + 1 — they lend themselves to semantic and logical structure that's most easily expressed by editing them as text. Furthermore, text-based editing makes debugging and performance improvements easier.
But text-based editing is also limited. Though the underlying description of a web page is notionally human-readable, it's optimized to be readable by other software — namely, web browsers. HTML in particular is verbose and easily mistyped. And isn't it fatally dull to manage all the boilerplate, like surrounding every paragraph with @code{<p>...</p>}? Yes, it is.

@ -32,7 +32,7 @@ As I mentioned in the @secref["big-picture"], Pollen is built using Racket, and
But if not, or if you're just a curious character:
One of the key features of Racket as a programming language is that it provides tools to create @italic{other} programming languages. These languages might look & behave @link["http://docs.racket-lang.org/ts-guide/index.html"]{like Racket}. Or they @link["http://hashcollision.org/brainfudge/index.html"]{might not}. These languages might serve a general purpose, but more often they're specialized for a particular purpose, in which case they're known as @italic{domain-specific languages}, or @italic{DSLs}.
One of the key features of Racket as a programming language is that it provides tools to create @italic{other} programming languages. These languages might look & behave @link["http://docs.racket-lang.org/ts-guide/index.html"]{like Racket}. Or they @link["http://hashcollision.org/brainfudge/"]{might not}. These languages might serve a general purpose, but more often they're specialized for a particular purpose, in which case they're known as @italic{domain-specific languages}, or @italic{DSLs}.
If you find this a strange idea, you're not alone. Most programmers — and until recently, me too — have never made or used DSLs. If you have a programming problem to solve, you start with a general-purpose language like Python or Java or Ruby, and go from there. Nothing wrong with that.

@ -199,11 +199,11 @@ The goal of this whole endeavor was to derive multiple output files from one sou
@seclink["Templates" #:tag-prefixes '("tutorial-2")] should be familiar to you by now. As usual, the name of the template is @tt{template} plus the relevant file extension, so in this case @filepath{template.txt.p}. Add the file as follows:
@fileblock["template.txt.p" @codeblock|{
◊(require racket/list)
◊(local-require racket/list)
◊(apply string-append (filter string? (flatten doc)))
}|]
What we're doing here is converting the X-expression to text in a smarter way. We use @racket[require] to bring in @racketmodname[racket/list] so we can use the @racket[flatten] function.
What we're doing here is converting the X-expression to text in a smarter way. Because we're in a template, we use @racket[local-require] (rather than plain @racket[require]) to bring in @racketmodname[racket/list] so we can use the @racket[flatten] function.
To understand what the next line does, just read it from the inside out: ``Take the @racket[doc] export from the source file (which is an X-expression), @racket[flatten] it into a list, @racket[filter] with @racket[string?] (creating a list that's only strings) and @racket[apply] the @racket[string-append] function to these, resulting in one big string.'' Which is exactly what we need for a plain-text file.
@ -304,7 +304,7 @@ Then a @filepath{template.ltx.p}:
@fileblock["template.ltx.p" @codeblock|{
\documentclass[a4paper,12pt]{letter}
\begin{document}
◊(require racket/list)
◊(local-require racket/list)
◊(apply string-append (filter string? (flatten doc)))
\end{document}
}|]
@ -366,7 +366,7 @@ The template, not as easy:
@fileblock["template.pdf.p" @codeblock|{
◊(require racket/file racket/system)
◊(local-require racket/file racket/system)
◊(define latex-source ◊string-append{
\documentclass[a4paper,12pt]{letter}
\begin{document}
@ -391,7 +391,7 @@ First, we use @filepath{template.pdf.p} rather than @filepath{template.pdf} for
A quick narrative of the rest:
@codeblock|{
◊(require racket/file racket/system)
◊(local-require racket/file racket/system)
}|
We need @racketmodname[racket/file] for @racket[display-to-file] and @racket[file->bytes]; we need @racketmodname[racket/system] for @racket[system] (to use the command line).

@ -21,7 +21,7 @@ Pygments is a Python library (though you don't need to know any Python to use it
@subsection[#:tag "pygments-with-pollen"]{Using Pygments with Pollen}
I used @link["http://pygments.org/"]{Pygments} for syntax highlighting in @link["https://beautifulracket.com/"]{@italic{Beautiful Racket}}. Links to the source are available at the bottom of the article.
I used @link["http://pygments.org/"]{Pygments} for syntax highlighting in @link["http://unitscale.com/mb/technique/dual-typed-untyped-library.html"]{this article made with Pollen}. Links to the source are available at the bottom of the article.
@itemlist[#:style 'ordered

@ -226,22 +226,15 @@ I am **so** happy to be writing this.
Before you preview this file in the project server, click the @onscreen{Run} button in DrRacket just to see what the file produces. You'll see something like this:
@repl-output{
'(root
  (h1 ((id "deep-thought")) "Deep Thought")
  (p "I am " (strong "so") " happy to be writing this."))
}
@repl-output{'(root (h1 ((id "deep-thought")) "Deep Thought")
(p "I am " (strong "so") " happy to be writing this."))}
You should now be able to recognize this as an X-expression. In authoring mode, Pollen compiles your Markdown into the corresponding HTML entities, but then provides the data as an X-expression rather than finished HTML.
From what you learned in the last section, it should be evident that this X-expression will convert to HTML that looks like this:
@terminal{
<root>
  <h1 id="deep-thought">Deep Thought</h1>
  <p>I am <strong>so</strong> happy to be writing this.</p>
</root>
}
@terminal{<root><h1 id="deep-thought">Deep Thought</h1>
<p>I am <strong>so</strong> happy to be writing this.</p></root>}
``But what's this @code{root} tag? That's not HTML.'' An X-expression that holds other X-expressions must have a root tag. So in the spirit of obviousness, every X-expression produced by Pollen in authoring mode will start with @code{root}. If you don't need it, you can discard it (we'll cover this below, in @secref[#:tag-prefixes '("tutorial-2")]{Templates}). Though as you'll learn in the @seclink["third-tutorial"]{third tutorial}, @code{root} also creates a useful hook for further processing — it's not a superfluous accessory.
@ -298,7 +291,7 @@ And two major differences:
@margin-note{``So a template is also a Pollen source file?'' Not quite. More accurately, it's a fragment of Pollen source that is completed by adding the X-expression that comes out of one of your source files. Because of this, there are a few extra limitations on the code you can put in a template, though with easy workarounds.}
@margin-note{``So a template is also a Pollen source file?'' Not quite. More accurately, it's a fragment of Pollen source that is completed by adding the X-expression that comes out of one of your source files. Because of this, there are a few extra limitations on the code you can put in a template, though with easy workarounds (for instance, you can't use @racket[require] in a template, but you can use @racket[local-require], which accomplishes the same thing).}
To see how this works, let's return to the source file we started in the last section:
@ -371,6 +364,9 @@ Finally, we need to include the X-expression from our source file. By convention
◊(->html (html (head (meta #:charset "UTF-8")) (body doc)))
}
@margin-note{You can change the name of @code{doc} by overriding @racket[default-main-export].}
To summarize: this template contains a skeletal HTML page (in X-expression format). We drop @code{doc} into the template to indicate where the X-expression of our source file should be inserted. Finally, we convert the whole X-expression to HTML with @racket[->html].
``So I have to convert my HTML template to an X-expression?'' No. That's optional. You can also put hard-coded HTML in your template. Here's an equivalent way of writing @filepath{fallback.html.p}, with explicit HTML:
@ -405,9 +401,6 @@ Beyond that, all we need to do make sure our template has the three key ingredie
In your project directory, create a new file called @filepath{template.html.p}:
@margin-note{If you're using DrRacket on Mac OS to save this file, it may insist on adding a @filepath{rkt} extension to the filename. If so, you can either correct the filename after you save the file, or instead use a different text editor to create @filepath{template.html.p}.}
@fileblock["template.html.p"
@codeblock[#:keep-lang-line? #f]{
#lang pollen

@ -195,7 +195,7 @@ Then you have two options for adding attributes. The verbose way corresponds to
Each keyvalue pair is in parentheses, and then the list of pairs is within parentheses, with a @racket[quote] (@litchar{'}) at the front that signals that the text should be used literally.
But this is boring to type out, so Pollen also allows you to specify attributes in tag functions with Racket-style @seclink["keyword-args" #:doc '(lib "scribblings/guide/guide.scrbl")]{keyword arguments}:
But this is boring to type out, so Pollen also allows you to specify attributes with Racket-style @seclink["keyword-args" #:doc '(lib "scribblings/guide/guide.scrbl")]{keyword arguments}:
@fileblock["article.html.pm" @codeblock{
#lang pollen
@ -205,8 +205,6 @@ But this is boring to type out, so Pollen also allows you to specify attributes
In this form, each attribute name is prefixed with @litchar{#:}, indicating a keyword argument. As before, the attribute value is in quotation marks following the keyword name.
@margin-note{This keyword notation will work by default with any tag. When you're making a custom tag function, use @racket[define-tag-function] (rather than the usual @racket[define]) if you want your tag function to support keyword notation the same way.}
Both of these forms will produce the same X-expression:
@repl-output{'(span ((class "author")(id "primary")(living "true")) "Prof. Leonard")}
@ -515,7 +513,7 @@ This will produce an error in DrRacket:
@errorblock{
pollen markup error: in '(root "Pi is close to " 3.141592653589793 "." "\n" "The hyperbolic sine of pi is close to " 11.548739357257748 "."), 3.141592653589793 is not a valid element (must be txexpr, string, symbol, XML char, or cdata)}
This code would not, however, produce an error if it were being run as a Pollen preprocessor file, because the preprocessor automatically converts numbers to strings. If you'd like to verify this, change the suffix to @code{.pp} and run the file again.
This code would not, however, produce an error if it were being run as a Pollen preprocessor file, because the prepreocessor automatically converts numbers to strings. If you'd like to verify this, change the suffix to @code{.pp} and run the file again.
@subsection[#:tag-prefix "tutorial-3"]{Introducing @filepath{pollen.rkt}}

@ -12,7 +12,7 @@ Inconsistent with this system, Pollen's version also appends a build number, whi
@section{Source code}
Pollen's source code is @link["https://git.matthewbutterick.com/mbutterick/pollen/"]{available from this Git repo}. The @tt{MASTER} branch of the repo will always contain the most recent stable version.
Pollen's source code is @link["http://github.com/mbutterick/pollen"]{available from this Git repo}. The @tt{MASTER} branch of the repo will always contain the most recent stable version.
Racket's @link["http://pkg.racket-lang.org"]{package catalog} relies on this branch, so if you get your updates with @tt{raco pkg update pollen}, you'll get the most recent updates from this branch.
@ -24,25 +24,6 @@ Beyond keeping the commit history available, I make no promise to maintain the p
@section{Changelog}
@subsection{Version 3.2}
Added @racket[setup:external-renderer].
@subsection{Version 3.1}
Downgraded the following @racket[pollen/setup] values from configurable to fixed: @racket[here-path-key], @racket[extension-escape-char].
@subsection{Version 3.0}
Changed rendering model to share a namespace between sequential renders, improving speed.
Added @racket[--force] switch to @secref["raco_pollen_render" #:doc '(lib "pollen/scribblings/pollen.scrbl")].
Added @racket[--dry-run] switch to @secref["raco_pollen_publish" #:doc '(lib "pollen/scribblings/pollen.scrbl")].
Downgraded the following @racket[pollen/setup] values from configurable to fixed: @racket[splicing-tag], @racket[preproc-source-ext], @racket[markup-source-ext], @racket[markdown-source-ext], @racket[null-source-ext], @racket[pagetree-source-ext], @racket[template-source-ext], @racket[scribble-source-ext], @racket[poly-source-ext], @racket[cache-dir-name], @racket[cache-subdir-name], @racket[template-prefix], @racket[fallback-template-prefix], @racket[template-meta-key], @racket[main-export], @racket[meta-export], @racket[meta-tag-name], @racket[define-meta-name].
@subsection{Version 2.2}
Added @racket[--null] and @racket[--dry-run] switches to @secref["raco_pollen_render" #:doc '(lib "pollen/scribblings/pollen.scrbl")].

@ -1,9 +1,6 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax)
racket/runtime-path
racket/path
"private/constants.rkt")
(provide (all-from-out "private/constants.rkt"))
racket/runtime-path)
(define-syntax-rule (define+provide ID EXPR ...)
(begin
@ -19,13 +16,11 @@
(let-values ([(dir name dir?) (split-path path)])
dir))
(provide find-nearest-default-directory-require)
(define (find-nearest-default-directory-require maybe-dir)
(define (get-path-to-override maybe-dir)
(define starting-dir (cond
[(not maybe-dir) (current-directory)]
[(directory-exists? maybe-dir) maybe-dir]
[else (define dir (dirname maybe-dir))
(and (not (eq? 'relative dir)) (simplify-path (path->complete-path dir (current-directory))))]))
[else (dirname maybe-dir)]))
(let loop ([dir starting-dir][path default-directory-require])
(and dir ; dir is #f when it hits the top of the filesystem
(let ([simplified-path (simplify-path (path->complete-path path starting-dir))])
@ -48,27 +43,22 @@
(define DEFAULT-NAME DEFAULT-VALUE)
;; can take a dir argument that sets start point for (get-path-to-override) search.
(define (NAME-THUNKED [dir #false])
;; exn:fail:contract? is raised if setup submodule doesn't exist
;; in which case we use the default value.
;; but if something else is amiss, we want to let it bubble up
(define setup-module-path (find-nearest-default-directory-require dir))
(with-handlers ([exn:fail:contract? (λ (exn) DEFAULT-NAME)]
;; certain errors in pollen.rkt will arrive here
;; they do not indicate a defective setup module, so pass them through
[exn:fail:read? raise] ; syntactic failure (e.g., missing paren)
[exn:fail:syntax? raise] ; semantic failure (e.g., unbound identifier)
[exn:fail:filesystem? raise] ; filesystem failure (e.g., too many open files)
[exn? (λ (exn) (raise-user-error 'pollen/setup
(format "defective `setup` submodule in ~v\n~a" (path->string setup-module-path) (exn-message exn))))])
(dynamic-require `(submod ,setup-module-path WORLD-SUBMOD)
'NAME
(λ () DEFAULT-NAME))))))]))
(with-handlers ([exn:fail? (λ (exn) DEFAULT-NAME)])
(dynamic-require `(submod ,(get-path-to-override dir) WORLD-SUBMOD)
'NAME
(λ () DEFAULT-NAME))))))]))
(define-settable cache-watchlist null)
(define-settable envvar-watchlist null)
(define-settable preproc-source-ext 'pp)
(define-settable markup-source-ext 'pm)
(define-settable markdown-source-ext 'pmd)
(define-settable null-source-ext 'p)
(define-settable pagetree-source-ext 'ptree)
(define-settable template-source-ext 'pt)
(define-settable scribble-source-ext 'scrbl)
;; these are deliberately not settable because they're just internal signalers, no effect on external interface
(define+provide default-mode-auto 'auto)
(define+provide default-mode-preproc 'pre)
@ -77,19 +67,31 @@
(define+provide default-mode-pagetree 'ptree)
(define+provide default-mode-template 'template)
(define+provide default-cache-names (cons pollen-cache-dir-name pollen-old-cache-names))
(define-settable old-cache-names '("pollen.cache" "pollen-cache"))
(define-settable cache-dir-name "compiled")
(define-settable cache-subdir-name "pollen")
(define+provide default-cache-names (list* (cache-dir-name) (old-cache-names)))
(define-settable decodable-extensions (list pollen-markup-source-ext pollen-pagetree-source-ext))
(define-settable decodable-extensions (list (markup-source-ext) (pagetree-source-ext)))
(define-settable main-pagetree (format "index.~a" pollen-pagetree-source-ext))
(define-settable main-pagetree (format "index.~a" (pagetree-source-ext)))
(define-settable pagetree-root-node 'pagetree-root)
(define-settable main-root-node 'root)
(define-settable command-char #\◊)
(define-settable template-command-char #\∂)
(define-settable template-prefix "template")
(define-settable fallback-template-prefix "fallback")
(define-settable template-meta-key "template")
(define-settable main-export 'doc) ; don't forget to change fallback template too
(define-settable meta-export 'metas)
(define-settable meta-tag-name 'meta)
(define-settable define-meta-name 'define-meta)
;; tags from https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
(define-settable block-tags (cons (main-root-node) '(address article aside blockquote body canvas dd div dl dt fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li main nav noscript ol output p pre section table tfoot ul video)))
(define-settable block-tags (cons (main-root-node) '(address article aside blockquote body canvas dd div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li main nav noscript ol output p pre section table tfoot ul video)))
(define-settable newline "\n")
(define-settable linebreak-separator (newline))
@ -104,11 +106,6 @@
(define+provide current-render-source (make-parameter #f))
;; used to distinguish one-shot rendering (e.g., using `raco pollen setup` or `render`
;; from an interactive session with the project server (using `raco pollen start`)
;; in one-shot mode, certain features needed for dynamic recompilation are disabled for speed.
(define+provide current-session-interactive? (make-parameter #false))
(define-settable dashboard-css "poldash.css")
(define-runtime-path server-extras-dir "private/server-extras")
@ -116,6 +113,8 @@
(define-settable publish-directory "publish")
(define-settable extension-escape-char #\_)
(define-settable compile-cache-active #t)
(define-settable render-cache-active #t)
(define-settable compile-cache-max-size (* 10 1024 1024)) ; = 10 megabytes
@ -128,11 +127,14 @@
(define-settable trim-whitespace? #t)
(define-settable here-path-key 'here-path)
(define-settable splicing-tag '@)
(define-settable poly-source-ext 'poly) ; extension that signals source can be used for multiple output targets
(define-settable poly-targets '(html)) ; current target applied to multi-output source files
(define+provide current-poly-target (make-parameter (car (poly-targets))))
(define-settable index-pages '("index.html"))
(define-settable allow-unbound-ids? #true)
(define-settable external-renderer #false)
(define-settable allow-unbound-ids? #true)

@ -6,8 +6,10 @@
(define paren-match (cadr matches))
paren-match)
(define splicing-tag (setup:splicing-tag))
(define (has-outer-splice-tag? x)
(and (pair? x) (eq? (get-tag x) pollen-splicing-tag)))
(and (pair? x) (eq? (get-tag x) splicing-tag)))
(define+provide/contract (->html x-arg-maybe-spliced
#:tag [tag #f]
@ -29,7 +31,7 @@
(define x (if (list? x-arg)
(splice (if (txexpr? x-arg)
x-arg
(cons 'html x-arg)) pollen-splicing-tag) ; list of txexpr-elements
(cons 'html x-arg)) splicing-tag) ; list of txexpr-elements
x-arg))
(when (and (not (txexpr? x)) attrs (not tag))

@ -3,4 +3,5 @@
(module setup racket/base
(provide (all-defined-out))
(define compile-cache-active #f))
(define compile-cache-active #f)
(define extension-escape-char #\$))

@ -1,3 +0,0 @@
#lang pollen
this is bar

@ -1,3 +0,0 @@
#lang pollen
this is foo

@ -1,4 +0,0 @@
#lang pollen/ptree
foo.txt
bar.txt

@ -1,5 +0,0 @@
#lang racket/base
(module setup racket/base
(provide poly-targets)
(define poly-targets '(html txt)))

@ -1,2 +1,2 @@
◊(require racket/list)
◊(local-require racket/list)
◊(apply string-append (filter string? (flatten doc)))

@ -1,6 +0,0 @@
#lang racket/base
(module setup racket/base
(provide (all-defined-out))
(define project-server-port
9876))

@ -1,2 +1,2 @@
◊(require racket/list)
◊(local-require racket/list)
◊(apply string-append (filter string? (flatten doc)))

@ -3,7 +3,7 @@
;; define-runtime-path only allowed at top level
(define-runtime-path test-dir "data/escape-ext")
(define-runtime-path test-file "data/escape-ext/test_html.pp")
(define-runtime-path test-file "data/escape-ext/test$html.pp")
(define-runtime-path result-file "data/escape-ext/test.html")
;; `find-exe` avoids reliance on $PATH of the host system

@ -1,12 +0,0 @@
#lang at-exp racket/base
(require rackunit
racket/runtime-path
pollen/file)
(define-runtime-path example "data/ext/example.html")
(define-runtime-path example-pm "data/ext/example.html.pm")
(define-runtime-path another "data/ext/sub/another.html")
(define-runtime-path another-pm "data/ext/sub/another.html.pm")
(check-equal? (get-markup-source example) example-pm)
(check-equal? (get-markup-source another) another-pm)

@ -0,0 +1,44 @@
#lang at-exp racket/base
(require rackunit racket/port racket/system racket/runtime-path compiler/find-exe pollen/setup)
;; define-runtime-path only allowed at top level
(define-runtime-path override-dir "data/override")
(define-runtime-path test.ptree "data/override/test.ptree")
(define-runtime-path test.html.pm "data/override/test.html.pm")
(define-runtime-path test.html.pmd "data/override/test.html.pmd")
(define-runtime-path test.html.pp "data/override/test.html.pp")
(define-runtime-path test.ptreeover "data/override/test.ptreeover")
(define-runtime-path test.html.pmover "data/override/test.html.pmover")
(define-runtime-path test.html.pmdover "data/override/test.html.pmdover")
(define-runtime-path test.html.ppover "data/override/test.html.ppover")
(define-runtime-path test-cmd.html.ppover "data/override/test-cmd.html.ppover")
(define-runtime-path test-exports.html.ppover "data/override/test-exports.html.ppover")
(define-runtime-path test-require.html.pmover "data/override/test-require.html.pmover")
;; `find-exe` avoids reliance on $PATH of the host system
(define racket-path (find-exe))
;; parameterize needed to pick up override file
(parameterize ([current-directory override-dir]
[current-project-root override-dir])
(when racket-path
(define (run path)
(define cmd-string (format "'~a' ~a" racket-path path))
(with-output-to-string (λ () (system cmd-string))))
;; raco is in same dir as racket
(define path-to-raco (path->string (simplify-path (build-path (find-exe) 'up "raco"))))
;; files with ordinary extensions will not be recognized in override dir, and thus behave like preproc
(check-equal? (run test.ptree) "test\n====")
(check-equal? (run test.html.pm) "test\n====")
(check-equal? (run test.html.pmd) "test\n====")
(check-equal? (run test.html.pp) "test\n====")
(check-equal? (run test.ptreeover) "'(pagetree-root test ====)")
(check-equal? (run test.html.pmover) "'(rootover \"test\" \"\\n\" \"====\")")
(check-equal? (run test.html.pmdover) "'(rootover (h1 ((id \"test\")) \"test\"))")
(check-equal? (run test.html.ppover) "test\n====")
(check-equal? (run test-cmd.html.ppover) "2")
(check-equal? (dynamic-require test-exports.html.ppover 'docover) "2")
(check-equal? (hash-ref (dynamic-require test-exports.html.ppover 'metasover) 'dog) "Roxy")
(check-equal? (dynamic-require test-require.html.pmover 'docover) '(rootover "foobar"))))

@ -1,27 +0,0 @@
#lang at-exp racket/base
(require rackunit racket/runtime-path pollen/render racket/file pollen/setup)
;; define-runtime-path only allowed at top level
(define-runtime-path dir "data/pagetree-output")
(define-runtime-path index.ptree "data/pagetree-output/index.ptree")
(define-runtime-path foo.txt.pp "data/pagetree-output/foo.txt.pp")
(define-runtime-path foo.txt "data/pagetree-output/foo.txt")
(define-runtime-path bar.txt.pp "data/pagetree-output/bar.txt.pp")
(define-runtime-path bar.txt "data/pagetree-output/bar.txt")
(define-runtime-path pollen-cache "data/pagetree-output/compiled")
(parameterize ([current-output-port (open-output-string)]
[current-directory dir]
[current-project-root dir])
;; passing "index.ptree" as argument should work
(for ([parallel? (list #true #false)])
(render-batch #:parallel parallel? index.ptree)
(check-true (file-exists? foo.txt))
(check-equal? (file->string foo.txt) "this is foo")
(delete-file foo.txt)
(check-true (file-exists? bar.txt))
(check-equal? (file->string bar.txt) "this is bar")
(delete-file bar.txt)))
(delete-directory/files pollen-cache)

@ -1,30 +0,0 @@
#lang at-exp racket/base
(require rackunit racket/runtime-path pollen/render racket/file pollen/setup txexpr xml)
;; define-runtime-path only allowed at top level
(define-runtime-path poly-output-path-dir "data/poly-output-path")
(define-runtime-path pollen.rkt "data/poly-output-path/pollen.rkt")
(define-runtime-path test.poly.pm "data/poly-output-path/test.poly.pm")
(define-runtime-path test.txt "data/poly-output-path/test.txt")
(define-runtime-path test.html "data/poly-output-path/test.html")
(define-runtime-path pollen-cache "data/poly-output-path/compiled")
(parameterize ([current-output-port (open-output-string)]
[current-directory poly-output-path-dir]
[current-project-root poly-output-path-dir])
(for ([parallel? (list #true #false)])
;; passing "text.txt" as argument should force use of `txt` rendering
(render-batch #:parallel parallel? test.txt)
(check-equal? (file->string test.txt) "(root hello world)")
(delete-file test.txt)
(check-false (file-exists? test.html))
;; passing poly source as argument should result in default (html) rendering
(render-batch #:parallel parallel? test.poly.pm)
(check-txexprs-equal?
(string->xexpr (file->string test.html))
(string->xexpr "<html><head><meta charset=\"UTF-8\"/></head><body><root>hello world</root></body></html>"))
(delete-file test.html)
(check-false (file-exists? test.txt))))
(delete-directory/files pollen-cache)

@ -2,15 +2,11 @@
(require rackunit
pollen/setup
racket/runtime-path
pollen/render
racket/file)
pollen/render)
;; define-runtime-path only allowed at top level
(define-runtime-path poly-dir "data/poly")
(define-runtime-path poly-source "data/poly/test.poly.pm")
(define-runtime-path pollen-cache "data/poly/compiled")
(define-runtime-path test.txt "data/poly/test.txt")
(define-runtime-path test.html "data/poly/test.html")
(parameterize ([current-directory poly-dir]
[current-project-root poly-dir]
@ -18,20 +14,4 @@
(parameterize ([current-poly-target 'txt])
(check-equal? (render poly-source) "TITLE is **big**"))
(parameterize ([current-poly-target 'html])
(check-equal? (render poly-source) (format "~v" '(root (h2 "title") " is " (strong "big"))))))
(parameterize ([current-output-port (open-output-string)]
[current-directory poly-dir]
[current-project-root poly-dir])
;; make sure that batch works with multiple output files
;; related to one poly sourc
;; or duplicate output files (which will only be rendered once)
(for ([parallel? (list #true #false)])
(render-batch #:parallel parallel? test.html test.txt test.html)
(check-equal? (file->string test.txt) "TITLE is **big**")
(check-equal? (file->string test.html) (format "~v" '(root (h2 "title") " is " (strong "big"))))
(delete-file test.txt)
(delete-file test.html)))
(delete-directory/files pollen-cache)
(check-equal? (render poly-source) (format "~v" '(root (h2 "title") " is " (strong "big"))))))

@ -1,51 +0,0 @@
#lang racket/base
(require racket/port
racket/runtime-path
racket/tcp
rackunit)
(define-runtime-path project-port-dir "data/project-port")
(define the-port
(dynamic-require
`(submod ,(build-path project-port-dir "pollen.rkt") setup)
'project-server-port))
(define-values (in out)
(make-pipe))
(define thd
(parameterize ([current-output-port out]
[current-error-port out]
[current-directory project-port-dir]
[current-command-line-arguments (vector "start")]
[exit-handler (lambda (code)
(fail (format "abnormal exit from raco command~n code: ~a" code))
(kill-thread thd))])
(thread
(lambda ()
(dynamic-require '(submod pollen/private/command raco) #f)))))
(dynamic-wind
void
(lambda ()
(sync
(handle-evt
(regexp-match-evt #rx"ready to rock" in)
void)
(handle-evt
(alarm-evt (+ (current-inexact-milliseconds) 5000))
(lambda (_)
(fail "timed out while waiting for server to start"))))
(with-handlers ([exn:fail?
(lambda (e)
(fail (format "failed to connect to server: ~a" (exn-message e))))])
(define-values (cin cout)
(tcp-connect "127.0.0.1" the-port))
(close-output-port cout)
(close-input-port cin)))
(lambda ()
(break-thread thd)
(thread-wait thd)))

@ -16,8 +16,7 @@
;; test makes sure that file render changes after pollen.rkt changes
(parameterize ([current-output-port (open-output-string)]
[current-directory rerequire-dir]
[current-project-root rerequire-dir]
[current-session-interactive? #true])
[current-project-root rerequire-dir])
(display-to-file @string-append{#lang racket/base
(provide id)

@ -130,18 +130,11 @@ if zero is False:
(unless (running?)
(start python-executable line-numbers? css-class))
(cond [(running?)
;; This works with a simple wrapper around Pygments defined in pipe.py.
;; First send over the configuration options, then code to highlight.
;; pipe.py also supports an encoding option, but seems unnecessary to
;; use at this point.
(fprintf pyg-out "__LANG__ ~a~n" lang)
(fprintf pyg-out "__LINES__ ~a~n" (string-join (map number->string hl-lines) " "))
(fprintf pyg-out "__LINENOS__ ~a~n"
(if line-numbers? "true" "false"))
;; order of writing arguments is significant: cooperates with pipe.py
(displayln lang pyg-out)
(displayln (string-join (map number->string hl-lines) " ") pyg-out)
(displayln code pyg-out)
(displayln "__END__" pyg-out)
;; Read back the highlighted code
(let loop ([s ""])
(match (read-line pyg-in 'any)
["__END__" (with-input-from-string s read-html-as-xexprs)]

Loading…
Cancel
Save