Merge remote-tracking branch 'hyphenate/master'

main
Matthew Butterick 3 years ago
commit 8eedb97bb6

@ -0,0 +1,43 @@
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 hyphenate and its dependencies
run: raco pkg install --auto --batch
- name: Run the tests
run: xvfb-run raco test -j 4 -p hyphenate

@ -0,0 +1,18 @@
# for Racket
compiled/
# for Mac OS X
.DS_Store
.AppleDouble
.LSOverride
Icon
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
hyphenate/scribblings/hyphenate.html
hyphenate/scribblings/*.css
hyphenate/scribblings/*.js

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

@ -0,0 +1,3 @@
Hyphenate
© 2014-2016 Matthew Butterick
Licensed under the LGPL (see "LGPL.txt")

@ -0,0 +1,33 @@
## hyphenate ![Build Status](https://github.com/mbutterick/hyphenate/workflows/CI/badge.svg)
Racket implementation of the KnuthLiang hyphenation algorithm.
Install from the command line like so:
raco pkg install hyphenate
Later, you an update like so:
raco pkg update hyphenate
Import in standard mode:
(require hyphenate)
Or in safe mode (adds contracts):
(require (submod hyphenate safe))
And enjoy:
(hyphenate "Hyphenation algorithm" #\-)
> "Hy-phen-ation al-go-rithm"
Full docs are installed with the package. You can also [read the docs here](http://pkg-build.racket-lang.org/doc/hyphenate).
## Project status
Complete. Maintained but no further updates planned. Once upon a time, I had an ambition to support more languages. But I dont personally need that, and no one is clamoring for it.

@ -0,0 +1,2 @@
#lang s-exp "private/bootstrap.rkt"
fr

@ -0,0 +1 @@
#lang hyphenate/private/exception-prep

File diff suppressed because it is too large Load Diff

@ -0,0 +1,4 @@
#lang info
(define scribblings '(("scribblings/hyphenate.scrbl" ())))
(define compile-omit-paths '("tests.rkt"))
(define post-install-collection "post-installer.rkt")

@ -0,0 +1,7 @@
#lang racket
(require "us.rkt")
(provide (all-from-out "us.rkt"))
(module+ safe
(require (submod "us.rkt" safe))
(provide (all-from-out (submod "us.rkt" safe))))

@ -0,0 +1,8 @@
#lang racket/base
(provide (all-defined-out))
(define (post-installer home-dir)
(for ([mod '(hyphenate/us hyphenate/fr)])
(displayln (format "running post-installer in ~a" mod))
(define proc (dynamic-require mod 'post-installer))
(proc home-dir)))

@ -0,0 +1,85 @@
#lang racket/base
(require (for-syntax racket/base syntax/strip-context)
txexpr/base
sugar/define
racket/contract
racket/file
racket/fasl
(only-in xml xexpr/c)
(prefix-in core: hyphenate/private/core))
(provide (rename-out [mb #%module-begin]) #%top-interaction #%top #%datum #%app)
;; An exception-word is a string of word characters or hyphens.
(define (exception-word? x)
(and (string? x) (regexp-match #px"^(\\p{L}|-)+$" x) #t))
(define (exception-words? xs)
(and (list? xs) (andmap exception-word? xs)))
(define hyphenate/c
((xexpr?) ((or/c char? string?)
#:exceptions exception-words?
#:min-length (or/c integer? #f)
#:omit-word (string? . -> . any/c)
#:omit-string (string? . -> . any/c)
#:omit-txexpr (txexpr? . -> . any/c)
#:min-left-length (or/c (and/c integer? positive?) #f)
#:min-right-length (or/c (and/c integer? positive?) #f)
#:min-hyphens (and/c integer? positive?)) . ->* . xexpr/c))
(define (make-hyphenate-function patterns exceptions)
(make-keyword-procedure
;; put caches here so they can persist across successive invocations of the function.
;; but remain distinct between instantiations of this module (say, us vs fr)
;; pass them as arguments to the core:hyphenate func
(let ([word-cache exceptions] ; preload exceptions
[pattern-cache patterns])
(λ (kws kw-args . rest)
(keyword-apply core:hyphenate kws kw-args word-cache pattern-cache rest)))))
(define (make-unhyphenate-function)
(make-keyword-procedure
(λ (kws kw-args . rest)
(keyword-apply core:unhyphenate kws kw-args rest))))
(define unhyphenate/c
((xexpr/c) ((or/c char? string?)
#:omit-word (string? . -> . any/c)
#:omit-string (string? . -> . any/c)
#:omit-txexpr (txexpr? . -> . any/c)) . ->* . xexpr/c))
(define (load-from-cache-if-possible module-path cache-path id-sym)
(unless (and (file-exists? cache-path)
(> (file-or-directory-modify-seconds cache-path)
(file-or-directory-modify-seconds module-path)))
(with-output-to-file cache-path
(λ () (s-exp->fasl (dynamic-require module-path id-sym) (current-output-port)))
#:exists 'replace))
(with-input-from-file cache-path
(λ () (fasl->s-exp (current-input-port)))))
(define-syntax (mb stx)
(syntax-case stx ()
[(_ DIR)
(let* ([base (let-values ([(base name _) (split-path (syntax-source stx))])
base)]
[dir (build-path base (symbol->string (syntax->datum #'DIR)))])
(with-syntax ([PATTERNS-PATH (build-path dir "patterns.rkt")]
[PATTERN-CACHE-PATH (build-path dir "compiled" "patterns-cache.rktd")]
[EXCEPTIONS-PATH (build-path dir "exceptions.rkt")]
[EXCEPTIONS-CACHE-PATH (build-path dir "compiled" "exceptions-cache.rktd")]
[PATTERNS-ID 'patterns]
[EXCEPTIONS-ID 'exceptions])
#'(#%module-begin
(define PATTERNS-ID (load-from-cache-if-possible PATTERNS-PATH PATTERN-CACHE-PATH 'PATTERNS-ID))
;; a file-cached hash is immutable, so convert it
(define EXCEPTIONS-ID (make-hash (hash->list (load-from-cache-if-possible EXCEPTIONS-PATH EXCEPTIONS-CACHE-PATH 'EXCEPTIONS-ID))))
(define+provide (post-installer home-dir)
(load-from-cache-if-possible PATTERNS-PATH PATTERN-CACHE-PATH 'PATTERNS-ID)
(load-from-cache-if-possible EXCEPTIONS-PATH EXCEPTIONS-CACHE-PATH 'EXCEPTIONS-ID))
(define+provide+safe hyphenate
hyphenate/c
(make-hyphenate-function PATTERNS-ID EXCEPTIONS-ID))
(define+provide+safe unhyphenate
unhyphenate/c
(make-unhyphenate-function)))))]))

@ -0,0 +1,218 @@
#lang racket/base
(require txexpr/base racket/string racket/list)
(provide hyphenate unhyphenate word->hyphenation-points exception-word->word+pattern string->hashpair)
(module+ test
(require rackunit))
;; module default values
(define default-min-length 5)
(define default-min-left-length 2)
(define default-min-right-length 2)
(define default-joiner #\u00AD)
(define default-min-hyphen-count 1)
(define (exception-word->word+pattern ew)
;; an exception word indicates its breakpoints with added hyphens
(define word (string-replace ew "-" ""))
;; pattern has same number of points as word letters. 1 marks hyphenation point; 0 no hyphenation
(define points
(cdr (map (λ (x) (if (equal? x "-") 1 0)) (regexp-split #px"\\p{L}" ew))))
;; use list here so we can `apply` in `add-exception-word`
(list word points))
(module+ test
(check-equal? (exception-word->word+pattern "snôw-man") '("snôwman" (0 0 0 1 0 0 0)))
(check-equal? (exception-word->word+pattern "snôwman") '("snôwman" (0 0 0 0 0 0 0)))
(check-equal? (exception-word->word+pattern "sn-ôw-ma-n") '("snôwman" (0 1 0 1 0 1 0))))
(define (add-exception-word word-cache word)
;; `hash-set!` not `hash-ref!`, because we want an exception to override an existing value
(apply hash-set! word-cache (exception-word->word+pattern word)))
(define (remove-exception-word word-cache word)
(hash-remove! word-cache (string-replace word "-" "")))
(define (string->natural i)
(let* ([result (string->number i)]
[result (and result (inexact->exact result))]
[result (and (exact-nonnegative-integer? result) result)])
result))
(module+ test
(check-equal? (string->natural "Foo") #f)
(check-equal? (string->natural "1.0") 1)
(check-equal? (string->natural "-3") #f))
(define (string->hashpair pat)
(define-values (strs nums)
(for/lists (strs nums)
;; using unicode-aware regexps to allow unicode hyphenation patterns
;; a pattern is a list of subpatterns, each of which is a character possibly followed by a number.
;; also, the first position may just have a number.
([subpat (in-list (regexp-match* #px"^\\d?|(\\p{L}|\\p{P})\\d?" pat))])
(define str (cond
[(regexp-match #px"(\\p{L}|\\p{P})?" subpat) => car]
[else ""]))
(define num (cond
[(regexp-match #px"\\d" subpat) => (compose1 string->natural car)]
[else 0]))
(values str num)))
(list (string-append* strs) nums))
(module+ test
(check-equal? (string->hashpair "2'2") '("'" (2 2)))
(check-equal? (string->hashpair ".â4") '("" (0 0 4)))
(check-equal? (string->hashpair ".ý4") '("" (0 0 4)))
(check-equal? (string->hashpair "'ý4") '("" (0 0 4)))
(check-equal? (string->hashpair "ý4") '("’ý" (0 0 4)))
(check-equal? (string->hashpair "4ý-") '("ý-" (4 0 0)))
(check-equal? (string->hashpair ".ach4") '(".ach" (0 0 0 0 4))))
(define (calculate-max-pattern patterns)
;; each pattern is a list of numbers
;; all the patterns have the same length
;; run max against parallel elements
(apply map (λ xs (apply max xs)) patterns))
(module+ test
(require rackunit)
(check-equal? (calculate-max-pattern '((1 0 0))) '(1 0 0))
(check-equal? (calculate-max-pattern '((1 0 0) (0 1 0))) '(1 1 0))
(check-equal? (calculate-max-pattern '((1 0 0) (0 1 0) (0 0 1))) '(1 1 1))
(check-equal? (calculate-max-pattern '((1 2 3) (2 3 1) (3 1 2))) '(3 3 3)))
(define (make-points word word-cache pattern-cache)
(hash-ref! word-cache word
(λ ()
;; dots are used to denote the beginning and end of the word when matching patterns
(define boundary-marker ".")
(define word-with-boundaries (format "~a~a~a" boundary-marker (string-downcase word) boundary-marker))
(define word-length (string-length word-with-boundaries))
(define default-zero-pattern (make-list (add1 word-length) 0))
;; walk through all the substrings and see if there's a matching pattern.
(define matching-patterns
(for*/list ([start (in-range word-length)]
[end (in-range start word-length)]
[substr (in-value (substring word-with-boundaries start (add1 end)))]
[partial-pattern (in-value (hash-ref pattern-cache (string->symbol substr) #f))]
#:when partial-pattern)
;; pad out partial-pattern to full length
;; (so we can compare patterns to find max value for each slot)
(define left-zeroes (make-list start 0))
(define right-zeroes (make-list (- (add1 word-length) (length partial-pattern) start) 0))
(append left-zeroes partial-pattern right-zeroes)))
(define max-pattern (calculate-max-pattern (cons default-zero-pattern matching-patterns)))
;; for point list generated from a pattern,
;; drop first two elements because they represent hyphenation weight
;; before the starting "." and between "." and the first letter.
;; drop last element because it represents hyphen after last "."
;; after you drop these two, then each number corresponds to
;; whether a hyphen goes after that letter.
(drop-right (drop max-pattern 2) 1))))
;; Find hyphenation points in a word. This is not quite synonymous with syllables.
(define (word->hyphenation-points word
word-cache pattern-cache
[min-length #f]
[min-left-length #f]
[min-right-length #f])
(cond
[(< (string-length word) (or min-length default-min-length)) (list word)]
[else
;; points is a list corresponding to the letters of the word.
;; to create a no-hyphenation zone of length n, zero out the first n-1 points
;; and the last n points (because the last value in points is always superfluous)
(define word-points
(let* ([points (make-points word word-cache pattern-cache)]
[left-zeroes (min (or min-left-length default-min-left-length) (length points))]
[right-zeroes (min (or min-right-length default-min-right-length) (length points))])
(for/list ([(point idx) (in-indexed points)])
(if (<= left-zeroes (add1 idx) (- (length points) right-zeroes))
point
0))))
;; odd-valued points in the pattern denote hyphenation points
(define odd-point-indexes (for/list ([(wp idx) (in-indexed word-points)]
#:when (odd? wp))
idx))
;; the hyphenation goes after the indexed letter, so add1 to the raw points for slicing
(define breakpoints (append (list 0) (map add1 odd-point-indexes) (list (string-length word))))
(for/list ([start (in-list breakpoints)]
[end (in-list (cdr breakpoints))]) ; shorter list controls exit of loop
(substring word start end))]))
;; joiner contract allows char or string; this coerces to string.
(define (joiner->string joiner) (format "~a" joiner))
(define (apply-proc proc x [omit-string (λ (x) #f)] [omit-txexpr (λ (x) #f)] [joiner default-joiner])
(let loop ([x x])
(cond
[(and (string? x) (not (omit-string x)))
;; handle intercapped words as capitalized pieces
(define letter-before-uc #px"(?<=\\p{Ll})(?=\\p{Lu}\\p{Ll})") ; match xXx but not xXX or XXX
(string-join (for/list ([x (in-list (string-split x letter-before-uc))])
(proc x)) (joiner->string joiner))]
[(and (txexpr? x) (not (omit-txexpr x)))
(make-txexpr (get-tag x) (get-attrs x) (map loop (get-elements x)))]
[else x])))
(define (hyphenate word-cache pattern-cache x [joiner default-joiner]
#:exceptions [extra-exceptions empty]
#:min-length [min-length default-min-length]
#:min-left-length [min-left-length default-min-left-length]
#:min-right-length [min-right-length default-min-right-length]
#:min-hyphens [min-hyphens-added default-min-hyphen-count]
#:omit-word [omit-word? (λ (x) #f)]
#:omit-string [omit-string? (λ (x) #f)]
#:omit-txexpr [omit-txexpr? (λ (x) #f)])
;; todo?: connect this regexp pattern to the one used in word? predicate
(for-each (λ (ee) (add-exception-word word-cache ee)) extra-exceptions)
(define word-pattern #px"\\p{L}+") ;; more restrictive than exception-word
(define (replacer word . words)
(cond
[(omit-word? word) word]
[else (define hyphenation-points
(word->hyphenation-points word word-cache pattern-cache min-length min-left-length min-right-length))
(cond
[(>= (sub1 (length hyphenation-points)) min-hyphens-added)
(string-join hyphenation-points (joiner->string joiner))]
[else word])]))
(define (insert-hyphens text) (regexp-replace* word-pattern text replacer))
(begin0
(apply-proc insert-hyphens x omit-string? omit-txexpr? joiner)
;; deleting from the main cache is cheaper than having to do two cache lookups for every word
;; (missing words will just be regenerated later)
(for-each (λ (ee) (remove-exception-word word-cache ee)) extra-exceptions)))
(define (unhyphenate x [joiner default-joiner]
#:omit-word [omit-word? (λ (x) #f)]
#:omit-string [omit-string? (λ (x) #f)]
#:omit-txexpr [omit-txexpr? (λ (x) #f)])
(define word-pattern (pregexp (format "[\\w~a]+" joiner)))
(define (replacer word . words)
(if (not (omit-word? word))
(string-replace word (joiner->string joiner) "")
word))
(define (remove-hyphens text) (regexp-replace* word-pattern text replacer))
(apply-proc remove-hyphens x omit-string? omit-txexpr?))

@ -0,0 +1,21 @@
#lang racket/base
(require racket/string racket/list hyphenate/private/core)
(provide (rename-out [emb #%module-begin]) #%app #%datum #%top-interaction)
(define-syntax-rule (emb STRS)
(#%module-begin
(provide exceptions)
(define exceptions (for/hash ([str (in-list (list . STRS))])
(define key+val (exception-word->word+pattern str))
(values (first key+val) (second key+val))))
(module+ main exceptions)))
(module+ reader
(require racket/port)
(provide (rename-out [exception-prep-read-syntax read-syntax]))
(define (exception-prep-read-syntax src in)
(with-syntax ([STRS (string-split (port->string in))])
(syntax->datum
#'(module exception-prep hyphenate/private/exception-prep
STRS)))))

@ -0,0 +1,21 @@
#lang racket/base
(require hyphenate/private/core racket/list racket/file)
(provide (rename-out [pmb #%module-begin]) #%app #%datum #%top-interaction)
(define-syntax-rule (pmb STRS)
(#%module-begin
(provide patterns)
(define patterns (for/hasheq ([str (in-list (list . STRS))])
(define key+val (string->hashpair str))
(values (string->symbol (first key+val)) (second key+val))))
(module+ main patterns)))
(module+ reader
(provide read-syntax)
(define (read-syntax src in)
(with-syntax ([STRS (for/list ([line (in-lines in)]
#:when (and (positive? (string-length line)) ; omit empty
(not (regexp-match #rx"^;" line)))) ; omit comments
line)])
(syntax->datum #'(module patterns hyphenate/private/pattern-prep
STRS)))))

@ -0,0 +1,240 @@
#lang scribble/manual
@(require scribble/eval (for-label txexpr racket hyphenate xml))
@(define my-eval (make-base-eval))
@(my-eval `(require txexpr hyphenate xml))
@title{Hyphenate}
@author[(author+email "Matthew Butterick" "mb@mbtype.com")]
@defmodule[#:multi (hyphenate (submod hyphenate safe))]
A simple hyphenation engine that uses the KnuthLiang hyphenation algorithm originally developed for TeX. I have added little to their work. Accordingly, I take little credit.
@section{Installation}
At the command line:
@verbatim{raco pkg install hyphenate}
After that, you can update the package like so:
@verbatim{raco pkg update hyphenate}
@section{Importing the module}
The module can be invoked two ways: fast or safe.
Fast mode is the default, which you get by importing the module in the usual way: @code{(require hyphenate)}.
Safe mode enables the function contracts documented below. Use safe mode by importing the module as @code{(require (submod hyphenate safe))}.
@section{Interface}
@defproc[
(hyphenate
[xexpr xexpr/c]
[joiner (or/c char? string?) (integer->char #x00AD)]
[#:exceptions exceptions (listof string?) empty]
[#:min-length length (or/c integer? false?) 5]
[#:min-left-length left-length (or/c (and/c integer? positive?) #f) 2]
[#:min-right-length right-length (or/c (and/c integer? positive?) #f) 2]
[#:min-hyphens min-hyphen-count (and/c integer? positive?) 1]
[#:omit-word word-test (string? . -> . any/c) (λ (x) #f)]
[#:omit-string string-test (string? . -> . any/c) (λ (x) #f)]
[#:omit-txexpr txexpr-test (txexpr? . -> . any/c) (λ (x) #f)])
xexpr/c]
Hyphenate @racket[_xexpr] by calculating hyphenation points and inserting @racket[_joiner] at those points. By default, @racket[_joiner] is the soft hyphen (Unicode 00AD = decimal 173). Words shorter than @racket[#:min-length] @racket[_length] will not be hyphenated. To hyphenate words of any length, use @racket[#:min-length] @racket[#f].
@margin-note{The REPL displays a soft hyphen as @code{\u00AD}. But in ordinary use, you'll only see a soft hyphen when it appears at the end of a line or page as part of a hyphenated word. Otherwise it's not displayed. In most of the examples here, I use a standard hyphen for clarity (by adding @code{#\-} as an argument).}
@examples[#:eval my-eval
(hyphenate "snowman polymorphism")
(hyphenate "snowman polymorphism" #\-)
(hyphenate "snowman polymorphism" #:min-length 13)
(hyphenate "snowman polymorphism" #:min-length #f)
]
The @racket[#:min-left-length] and @racket[#:min-right-length] keyword arguments set the minimum distance between a potential hyphen and the left or right ends of the word. The default is 2 characters. Larger values will reduce hyphens, but also prevent small words from breaking. These values will override a smaller @racket[#:min-length] value.
@examples[#:eval my-eval
(hyphenate "snowman polymorphism" #\-)
(hyphenate "snowman polymorphism" #\- #:min-left-length #f)
(hyphenate "snowman polymorphism" #\- #:min-length 2 #:min-left-length 5)
(hyphenate "snowman polymorphism" #\- #:min-right-length 6)
(code:comment @#,t{Next words won't be hyphenated becase of large #:min-left-length})
(hyphenate "snowman polymorphism" #\- #:min-length #f #:min-left-length 15)
]
Another way of controlling hyphen frequency is with the @racket[#:min-hyphens] keyword argument, which sets the minimum number of hyphens in a hyphenatable word. (It has no effect on non-hyphenatable words.) The default is 1 hyphen. Larger values will reduce hyphens, but also prevent small words from breaking.
@examples[#:eval my-eval
(hyphenate "snowman polymorphism" #\-)
(hyphenate "snowman polymorphism" #\- #:min-hyphens 1)
(code:comment @#,t{next "snowman" won't be hyphenated becase it doesn't have 2 hyphens})
(hyphenate "snowman polymorphism" #\- #:min-hyphens 2)
(code:comment @#,t{next "polymorphism" won't be hyphenated becase it doesn't have 3 hyphens})
(hyphenate "snowman polymorphism" #\- #:min-hyphens 3)
]
Because the hyphenation is based on an algorithm rather than a dictionary, it makes good guesses with unusual words:
@examples[#:eval my-eval
(hyphenate "scraunched strengths" #\-)
(hyphenate "RacketCon" #\-)
(hyphenate "supercalifragilisticexpialidocious" #\-)
]
Using the @racket[#:exceptions] keyword, you can pass hyphenation exceptions as a list of words with hyphenation points marked with regular hyphens (@racket["-"]). If an exception word contains no hyphens, that word will never be hyphenated.
@examples[#:eval my-eval
(hyphenate "polymorphism" #\-)
(hyphenate "polymorphism" #\- #:exceptions '("polymo-rphism"))
(hyphenate "polymorphism" #\- #:exceptions '("polymorphism"))
]
Knuth & Liang were sufficiently confident about their algorithm that they originally released it with only 14 exceptions: @italic{associate[s], declination, obligatory, philanthropic, present[s], project[s], reciprocity, recognizance, reformation, retribution}, and @italic{table}. Admirable bravado, but it's not hard to discover others that need adjustment.
@examples[#:eval my-eval
(hyphenate "wrong: columns signage lawyers" #\-)
(hyphenate "right: columns signage lawyers" #\-
#:exceptions '("col-umns" "sign-age" "law-yers"))
]
The KnuthLiang algorithm is designed to omit legitimate hyphenation points (i.e., generate false negatives) more often than it creates erroneous hyphenation points (i.e., false positives). This is good policy. Perfect hyphenation — that is, hyphenation that represents an exact linguistic syllabification of each word — is superfluous for typesetting. Hyphenation simply seeks to mark possible line-break and page-break locations for whatever layout engine is drawing the text. The ultimate goal is to permit more even text flow. Like horseshoes and hand grenades, close is good enough. And a word wrongly hyphenated is more likely to be noticed by a reader than a word inefficiently hyphenated.
For this reason, certain words can't be hyphenated algorithmically, because the correct hyphenation depends on meaning, not merely on spelling. For instance:
@examples[#:eval my-eval
(hyphenate "adder")
]
This is the right result. If you used @italic{adder} to mean the machine, it would be hyphenated @italic{add-er}; if you meant the snake, it would be @italic{ad-der}. Better to avoid hyphenation than to hyphenate incorrectly.
You can send HTML-style X-expressions through @racket[hyphenate]. It will recursively hyphenate the text strings, while leaving the tags and attributes alone, as well as non-hyphenatable material (like character entities and CDATA).
@examples[#:eval my-eval
(hyphenate '(p "strangely" (em "formatted" (strong "snowmen"))) #\-)
(hyphenate '(headline [[class "headline"]] "headline") #\-)
(hyphenate '(div "The (span epsilon) entity:" epsilon) #\-)
]
Don't send raw HTML or XML through @racket[hyphenate]. It can't distinguish tags and attributes from textual content, so everything will be hyphenated, thus goofing up your file. But you can easily convert your HTML or XML to an X-expression, hyphenate it, and then convert back.
@examples[#:eval my-eval
(define html "<body style=\"background: yellow\">Hello</body>")
(hyphenate html #\-)
(xexpr->string (hyphenate (string->xexpr html) #\-))
]
If you're working with HTML, be careful not to include any @code{<script>} or @code{<style>} blocks, which contain non-hyphenatable data. You can protect that data by using the @racket[#:omit-txexpr] keyword to specify a @racket[_txexpr-test]. The test will be applied to all tagged X-expressions (see @racket[txexpr?]). When @racket[_txexpr-test] evaluates to true, the item will be skipped.
@examples[#:eval my-eval
(hyphenate '(body "processing" (script "no processing")) #\-)
(hyphenate '(body "processing" (script "no processing")) #\-
#:omit-txexpr (λ (tx) (member (get-tag tx) '(script))))
]
You can also use @racket[#:omit-txexpr] to omit tagged X-expressions with particular attributes. This can be used to selectively suppress hyphenation at the markup level.
@examples[#:eval my-eval
(hyphenate '(p (span "processing") (span [[klh "no"]] "processing")) #\-)
(hyphenate '(p (span "processing") (span [[klh "no"]] "processing")) #\-
#:omit-txexpr (λ (tx) (and (attrs-have-key? tx 'klh)
(equal? (attr-ref tx 'klh) "no"))))
]
Similarly, you can use the @racket[#:omit-word] argument to avoid words that match @racket[_word-test]. Convenient if you want to prevent hyphenation of certain sets of words, like proper names:
@examples[#:eval my-eval
(hyphenate "Brennan Huff likes fancy sauce" #\-)
(define capitalized? (λ (word) (let ([letter (substring word 0 1)])
(equal? letter (string-upcase letter)))))
(hyphenate "Brennan Huff likes fancy sauce" #\- #:omit-word capitalized?)
]
Sometimes you need @racket[#:omit-word] to prevent unintended consequences. For instance, if you're using ligatures in CSS, certain groups of characters (fi, fl, ffi, et al.) will be replaced by a single glyph. That looks snazzy, but adding soft hyphens between any of these pairs will defeat the ligature substitution, creating inconsistent results. With @racket[#:omit-word], you can skip these words:
@margin-note{``Wouldn't it be better to exclude certain pairs of letters rather than whole words?'' Yes. But for now, that's not supported.}
@examples[#:eval my-eval
(hyphenate "Hufflepuff golfing final on Tuesday" #\-)
(define (ligs? word)
(ormap (λ (lig) (regexp-match lig word))
'("ff" "fi" "fl" "ffi" "ffl")))
(hyphenate "Hufflepuff golfing final on Tuesday" #\- #:omit-word ligs?)
]
@defproc[
(unhyphenate
[xexpr xexpr/c]
[joiner (or/c char? string?) @(integer->char #x00AD)]
[#:omit-word word-test (string? . -> . any/c) (λ (x) #f)]
[#:omit-string string-test (string? . -> . any/c) (λ (x) #f)]
[#:omit-txexpr txexpr-test (txexpr? . -> . any/c) (λ (x) #f)])
xexpr/c]
Remove @racket[_joiner] from @racket[_xexpr]. Like @racket[hyphenate], it works on nested X-expressions, and offers the same @racket[#:omit-] options.
@examples[#:eval my-eval
(hyphenate '(p "strangely" (em "formatted" (strong "snowmen"))) #\-)
(unhyphenate '(p "strange-ly" (em "for-mat-ted" (strong "snow-men"))) #\-)
]
A side effect of using @racket[hyphenate] is that soft hyphens (or whatever the @racket[_joiner] is) will be embedded in the output text. If you need to support copying of text, for instance in a GUI application, you'll probably want to strip out the hyphenation before the copied text is moved to the clipboard.
@examples[#:eval my-eval
(hyphenate "ribbon-cutting ceremony")
(unhyphenate (hyphenate "ribbon-cutting ceremony"))
]
Use this function cautiously — if @racket[_joiner] appeared in the original input to @racket[hyphenate], the output from @racket[unhyphenate] won't be the same string.
@examples[#:eval my-eval
(hyphenate "ribbon-cutting ceremony" #\-)
(unhyphenate (hyphenate "ribbon-cutting ceremony" #\-) #\-)
]
Keep in mind that soft hyphens could appear in your input string. Certain word processors allow users to @link["http://practicaltypography.com/optional-hyphens.html"]{insert soft hyphens} in their text.
@examples[#:eval my-eval
(hyphenate "True\u00ADType typefaces")
(unhyphenate (hyphenate "True\u00ADType typefaces"))
(hyphenate (unhyphenate "True\u00ADType typefaces") #\-)
]
@section{French}
@defmodule[#:multi (hyphenate/fr (submod hyphenate/fr safe))]
French hyphenation is available by importing the module as @racketmodname[hyphenate/fr] or @racketmodname[(submod hyphenate/fr safe)] and using the @racket[hyphenate] function normally. Below, notice that the word ``formidable'' hyphenates differently in French.
@examples[#:eval my-eval
(hyphenate "formidable" #\-)
(module fr racket/base
(require hyphenate/fr)
(hyphenate "formidable" #\-))
(require 'fr)
]
The two languages are in separate submodules for performance reasons. That way, they can maintain separate caches of hyphenated words.
There is no way to use @racket[hyphenate] in ``polyglot'' mode, where English and French are detected automatically. It is possible, however, to mix both the English and French @racket[hyphenate] functions in a single file, and apply them as needed. To avoid a name conflict between the two @racket[hyphenate] functions, you'll need to use @racket[prefix-in]:
@examples[#:eval my-eval
(require (prefix-in fr: hyphenate/fr))
(hyphenate "formidable" #\-)
(fr:hyphenate "formidable" #\-)
]
@section{License & source code}
This module is licensed under the LGPL.
Source repository at @link["http://github.com/mbutterick/hyphenate"]{http://github.com/mbutterick/hyphenate}. Suggestions & corrections welcome.

@ -0,0 +1,88 @@
#lang racket/base
(require (submod hyphenate safe) txexpr/base rackunit)
(define omit-em-tag (λ (x) (member (car x) '(em))))
(define omit-p-tag (λ (x) (member (car x) '(p))))
(define omit-foo-zam-tag (λ (x) (member (car x) '(foo zam))))
(define ends-with-s (λ (x) (regexp-match #rx"s$" x)))
(define omit-script-tag (λ (x) (member (car x) '(script))))
(define tx-with-attr (λ (x) (with-handlers ([exn:fail? (λ (exn) #f)])
(equal? (attr-ref x 'hyphens) "no-thanks"))))
(check-equal? (hyphenate "edges") "edges") ;; word without matching patterns
(check-equal? (hyphenate "polymorphism") "poly\u00ADmor\u00ADphism")
(check-equal? (hyphenate "polymorphism" #:min-hyphens 1) "poly\u00ADmor\u00ADphism")
(check-equal? (hyphenate "polymorphism" #:min-hyphens 2) "poly\u00ADmor\u00ADphism")
(check-equal? (hyphenate "polymorphism" #:min-hyphens 3) "polymorphism")
(check-equal? (hyphenate "polymorphism" #:min-hyphens 42) "polymorphism")
(check-equal? (hyphenate "POLYmorPHISM") "POLY\u00ADmor\u00ADPHISM")
(check-equal? (hyphenate "polymorphism" #:min-length 100) "polymorphism")
(check-equal? (hyphenate "ugly" #:min-length 1) "ug\u00ADly")
(check-equal? (hyphenate "ugly" #:min-length 1 #:min-hyphens 2) "ugly")
(check-equal? (unhyphenate "poly\u00ADmor\u00ADphism") "polymorphism")
(check-equal? (hyphenate "polymorphism" #\-) "poly-mor-phism")
(check-equal? (hyphenate "compotumi" #\-) "com-po-tu-mi")
(check-equal? (hyphenate "CompOtumi" #\-) "Comp-Otu-mi")
(check-equal? (hyphenate "polymorphism" "foo") "polyfoomorfoophism")
(check-equal? (unhyphenate "polyfoomorfoophism" "foo") "polymorphism")
(check-equal? (hyphenate "circular polymorphism squandering") "cir\u00ADcu\u00ADlar poly\u00ADmor\u00ADphism squan\u00ADder\u00ADing")
(check-equal? (hyphenate "circular polymorphism squandering" #:min-hyphens 2) "cir\u00ADcu\u00ADlar poly\u00ADmor\u00ADphism squan\u00ADder\u00ADing")
(check-equal? (hyphenate "circular polymorphism squandering" #:min-hyphens 3) "circular polymorphism squandering")
(check-equal? (hyphenate '(p "circular polymorphism" amp (em "squandering"))) '(p "cir\u00ADcu\u00ADlar poly\u00ADmor\u00ADphism" amp (em "squan\u00ADder\u00ADing")))
(check-equal? (hyphenate "present project") "present project") ; exception words
;; test these last so exceptions have been set up already
;(check-equal? (word->hyphenation-points "polymorphism") '("poly" "mor" "phism"))
;(check-equal? (word->hyphenation-points "present") '("present")) ; exception word
;(check-true (exception-word? "Foobar"))
;(check-true (exception-word? "foobar"))
;(check-false (exception-word? "foobar!"))
;(check-true (exception-word? "foo-bar"))
;(check-false (exception-word? "foo bar"))
;; omit certain tags
(check-equal? (hyphenate '(p "circular polymorphism" amp (em "squandering")) #:omit-txexpr omit-em-tag)
'(p "cir\u00ADcu\u00ADlar poly\u00ADmor\u00ADphism" amp (em "squandering")))
(check-equal? (hyphenate '(p "circular polymorphism" amp (em "squandering")) #:omit-txexpr omit-p-tag)
'(p "circular polymorphism" amp (em "squandering")))
(check-equal? (hyphenate '(p (foo "circular") (bar "circular") (zam "circular")) #:omit-txexpr omit-foo-zam-tag)
'(p (foo "circular") (bar "cir\u00ADcu\u00ADlar") (zam "circular")))
; omit txexprs with an attribute
(check-equal? (hyphenate '(p (foo ((hyphens "no-thanks")) "circular") (foo "circular"))
#:omit-txexpr tx-with-attr)
'(p (foo ((hyphens "no-thanks")) "circular") (foo "cir\u00ADcu\u00ADlar")))
;; omit strings that end with "s"
#;(check-equal? (hyphenate '(p (foo "curses tailfeathers") (foo "curses tailfeather")) #:omit-string ends-with-s)
'(p (foo "curses tailfeathers") (foo "curs\u00ADes tail\u00ADfeath\u00ADer")))
;; omit words that end with "s"
#;(check-equal? (hyphenate '(p (foo "curses tailfeathers") (foo "curses tailfeather")) #:omit-word ends-with-s)
'(p (foo "curses tailfeathers") (foo "curses tail\u00ADfeath\u00ADer")))
(check-equal? (unhyphenate '(p (script "tail-feathers") (em "tail-feathers")) #\- #:omit-txexpr omit-script-tag)
'(p (script "tail-feathers") (em "tailfeathers")))
(check-equal? (unhyphenate '(p "cir-cu-lar poly-mor-phism" "cir-cu-lar poly-mor-phisms") #\- #:omit-string ends-with-s)
'(p "circular polymorphism" "cir-cu-lar poly-mor-phisms"))
(check-equal? (hyphenate "polymorphism" #\- #:min-left-length 5 #:min-right-length 5) "polymor-phism")
(check-equal? (hyphenate "polymorphism" #\- #:min-left-length 3 #:min-right-length 7) "poly-morphism")
(check-equal? (hyphenate "polymorphism" #\- #:min-left-length 7 #:min-right-length 7) "polymorphism")
(check-equal? (hyphenate "polymorphism" #\* #:exceptions '("polymo-rphism")) "polymo*rphism")
(check-equal? (hyphenate "polymorphism" #\* #:exceptions '("polymo-rphism")) "polymo*rphism")
(check-equal? (hyphenate "polymorphism" #\-) "poly-mor-phism") ; exceptions are temporary
(check-equal? (hyphenate "formidable" #\-) "for-mi-da-ble")
(module french racket/base
(require (submod hyphenate/fr safe) rackunit)
(check-equal? (hyphenate "formidable" #\-) "for-mi-dable")) ; hyphenates differently in French
(require 'french)

@ -0,0 +1,2 @@
#lang s-exp "private/bootstrap.rkt"
us

@ -0,0 +1,26 @@
#lang hyphenate/private/exception-prep
arc-min-ute
as-so-ciate
as-so-ciates
dec-li-na-tion
dis-tri-bu-tion
law-yer
law-yer-ing
law-yer-ly
law-yered
law-yers
oblig-a-tory
oki-na
oki-nas
phil-an-thropic
present
presents
project
projects
re-ci-pro-ci-ty
re-cog-ni-zance
real-ly
ref-or-ma-tion
ret-ri-bu-tion
ta-ble
ty-pog-ra-pher

File diff suppressed because it is too large Load Diff

@ -0,0 +1,6 @@
#lang info
(define version "0.2")
(define collection 'multi)
(define deps '("base" ["sugar" #:version "0.2"] ["txexpr" #:version "0.2"]))
(define update-implies '("txexpr" "sugar"))
(define build-deps '("scribble-lib" "racket-doc" "rackunit-lib"))
Loading…
Cancel
Save