Compare commits

..
Author SHA1 Message Date
swaits a76b261348 chore(easy-typography): rm rogue pdf 2025-01-09 12:17:26 -07:00
swaits 093fcf88fd fix(easy-typography): incorporates changes from community
Incoroporates changes from [this
PR](https://github.com/typst/packages/pull/1527) and updates tests
accordingly.

Thank you to [neuralpain](https://github.com/neuralpain) and
[ssotoen](https://github.com/ssotoen) for the suggestions and code
fixes.
2025-01-09 12:06:06 -07:00
swaits 5ad6c10b65 feat(easy-typography): initial implementation 2025-01-07 22:52:47 -07:00
swaits df889d8d72 feat(glossy): add sort: true parameter to glossary() 2024-12-21 22:27:07 -07:00
swaits c008b5bd86 feat(glossy): release 0.5.1 2024-12-20 12:48:19 -07:00
swaits 842166c211 fix(glossy): use codepoints (not bytes!) in article code
Fixes [#18](https://github.com/swaits/typst-collection/issues/18)
2024-12-20 12:37:21 -07:00
swaits c37c6750c6 feat(glossy): release 0.5.0
New feature:

`init-glossary()` now accepts a `format-term()` function which gives the
user control over how the short-form and long-form of the terms are
assembled based on the needed mode ("short", "long", or "both").

Change:

Default theme changed to `theme-academic`, which is probably more
generally useful than the prior (`theme-twocol`).
2024-12-20 11:28:32 -07:00
swaits 03d82458bb feat(glossy): change default theme to theme-academic 2024-12-20 11:28:32 -07:00
swaits 725f657f49 feat(glossy): adds format-term customizability
Idea [from Discord
conversation](https://discord.com/channels/1054443721975922748/1318670789150642246/1319338465757757562).

Let's users more precisely control how short-form and long-form terms
are used based on the mode ("short", "long", or "both").

Defaults to `__default-format-term()` as below:

```typst
// Formats a term string based on the specified mode.
//
// Given mode, long-form, and short-form, this function returns the formatted
// term based on the mode. When mode is ...
//
// - "short" -> returns "short-form"
// - "long" -> returns "long-form"
// - "both" -> returns "short-form (long-form)"
//
// Parameters:
//   mode (string): The mode in which to format the term. Possible values are "short", "long", or "both".
//   short-form (string): The short form of the term.
//   long-form (string): The long form of the term.
//
// Returns:
//   string: The formatted term based on the specified mode.
//
#let __default-format-term(mode, short-form, long-form) = {
    if mode == "short" {
      short-form
    } else if mode == "long" {
      long-form
    } else {
      // mode assumed to be "both"
      long-form + " (" + short-form + ")"
    }
}
```
2024-12-20 11:28:32 -07:00
swaits cf139b66f6 chore(glossy): rm trailing whitespace 2024-12-20 11:28:31 -07:00
swaits 461439d2f9 chore: update .build.yml (missing cd into repo dir) 2024-12-19 10:54:12 -07:00
swaits 607814713a chore: update .build.yml (change $HOME for ~) 2024-12-19 10:52:13 -07:00
swaits 4d94a3f7f2 chore: update .build.yml (remove duplicate clone) 2024-12-19 10:48:11 -07:00
swaits bc011bfa6b chore: update .build.yml 2024-12-19 10:44:36 -07:00
swaits 1e1cb91163 feat(glossy): terms now link to glossary entries
- Merges [16](https://github.com/swaits/typst-collection/pull/16).
- Fixes [3](https://github.com/swaits/typst-collection/issues/3).

A big PR from [@eltos](https://github.com/eltos)!

This adds labels for each `key`, so that auto-complete (in the typst.app
/ `typst-ide`) works properly. It also makes it so terms can link to
their glossary entry. In the case that terms are used but no glossary is
shown (which is a core feature of Glossy), placeholder labels are used
so that the auto-complete still works.

All tests, but one (theme-gallery), passed straight from the PR. The
ddiff in the `theme-gallery` test were non-visible (ie a few pixels),
making it effectively passing too. Updated that test so it passes, and
updated the theme screenshot to match its output as well.

Huge thanks to [@eltos](https://github.com/eltos) who demonstrates a
deep understanding of Typst!
2024-12-19 09:36:49 -07:00
Philipp Niedermayer 255bda30d4 Typo 2024-12-18 20:21:27 +00:00
Philipp Niedermayer 2b6debb7d1 Make terms clickable links to glossary list 2024-12-18 20:07:01 +00:00
Philipp Niedermayer 80eeb9240c Fix intendation 2024-12-18 20:07:01 +00:00
Philipp Niedermayer 76fb6b9ea7 Simplifies term usage tracking
- Uniqfies the duplicate term usage tracking via counter + state to just using the counter. Refreactor the code with the two methods "mark_term_used" and "is_term_used".
2024-12-18 20:06:53 +00:00
Philipp Niedermayer 16ceebdc70 Simply label usage
- Adds a label with the entry key for autocompletion
  - either in the glossary (if it is visible and there is a corresponding entry)
  - or invisible during init-glossary
- Use a single label for all usages of the entry in the text. This simplifies the back-referencing logic significantly and also avoids cluttering the auto-complete list

closes https://github.com/swaits/typst-collection/issues/3
2024-12-18 20:06:53 +00:00
swaits 2286037bd6 chore(glossy): release version 0.4.0
## New features:

**Articles with `a`/`an` modifier**

Now you can include articles using this new modifier. The articles may
be defined in your dictionary entry (fields `artcile`, and
`longarticle`). But, if you don't define them, Glossy will do a
reasonably good job at guessing them.

This modifier is also allowed before the term. For example, you might
have this term:

```yaml
www: Worldwide Web
```

And you could display it with an article by any of these:

```typst
@a:www
@an:www
@www:a
@www:an
```

These, `a` and `an` are exactly equivalent. They're just provided for
your convenience. Use either or both.

The `a`/`an` modifier works with all modifiers except `pl` and
`def`/`desc`.

If you want to define custom articles for your terms, do so like this:

```typst
#let glossary = (
  rf: (
    short: "RF",
    article: "an",
    long: "radio frequency",
    longarticle: "a",
  )
  uts: (
    short: "UTS",
    article: "a",
    long: "untranslatable string",
    longarticle: "an",
  )
)
```

But again, in most cases (for English) you shouldn't need to because
Glossy should usually get it right.

Fixes [#12](https://github.com/swaits/typst-collection/issues/12).

## Other changes:

- added test which exhausts all reference options
- added panic if 'def'/'desc' used when no `description` field exists
- significantly improved the (English) pluralizer function
- `__gls()` function refactored, cleaned up
- removed a rogue PDF

## Contributors:

- [@eltos](https://github.com/eltos)
- [@theRealProHacker](https://github.com/theRealProHacker)
2024-12-18 10:15:20 -07:00
swaits a8e0ef7c02 test(glossy): add test to exhaust all reference options 2024-12-18 10:14:18 -07:00
swaits ba8fdda1bf feat(glossy): improve pluralize 2024-12-18 06:08:52 -07:00
swaits b1aa11705c chore(glossy): cleanup rogue PDF 2024-12-18 06:08:51 -07:00
34 changed files with 1647 additions and 170 deletions

No files matched your search

+21 -7
View File
@@ -1,13 +1,27 @@
image: alpine/edge
packages:
- git
secrets:
- 88cce185-d2ec-4573-9546-e33f36f79bbf
sources:
- git+ssh://git@git.sr.ht/~swaits/typst-collection
environment:
# repo and user names on both sr.ht and github
REPO: typst-collection
USER: swaits
tasks:
- mirror-to-github: |
cd ~/typst-collection
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
# Explicitly fetch all branches & tags
- fetch-all-branches: |
cd "$HOME/$REPO"
git fetch origin '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' --prune
git remote add github git@github.com:swaits/typst-collection.git
- get-github-public-key: |
ssh-keyscan -t rsa github.com >> "$HOME/.ssh/known_hosts"
- add-github-remote: |
cd "$HOME/$REPO"
git remote add github "git@github.com:$USER/$REPO.git"
- mirror-to-github: |
cd "$HOME/$REPO"
git push --mirror github
+2
View File
@@ -11,6 +11,8 @@ links below to their main page.
- [**codly-languages**](https://typst.app/universe/package/codly-languages): A
set of language configurations for use with
[codly](https://typst.app/universe/package/codly).
- [easy-typography](https://typst.app/universe/package/easy-typography): Sets up
sensible typography defaults.
- [**glossy**](https://typst.app/universe/package/glossy): A very simple
glossary system with easily customizable output.
- [**rfc-vibe**](https://typst.app/universe/package/rfc-vibe): Bring RFC language
+2
View File
@@ -0,0 +1,2 @@
tests/**/out/
tests/**/diff/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Stephen Waits <steve@waits.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+65
View File
@@ -0,0 +1,65 @@
# Easy Typography for Typst
A Typst package that simplifies professional typography by providing sensible
defaults and easy customization options. Focus on your content while ensuring
beautiful, readable documents.
## Features
- 🎨 Precise heading scale with clear hierarchy
- 📏 Optimal line height and paragraph spacing
- 📖 Professional text justification and hyphenation
- ⚖️ Balanced vertical rhythm throughout
- ⚡ Simple configuration with reasonable defaults
## Usage
Basic usage with default settings:
```typst
#import "@preview/easy-typography:0.1.0": *
#show: easy-typography
= Your Document Title
Your content here...
```
Customized usage with specific fonts:
```typst
#show: easy-typography.with(
fonts: (
heading: "Source Sans Pro",
body: "Source Serif Pro"
),
body-size: 11pt,
paper: "a4",
margin: 2cm
)
```
## Configuration Options
- `body-size`: Base size for body text (default: 10pt)
- `fonts`: Dictionary specifying heading and body fonts
- `heading`: Font for headings (default: "Libertinus Sans")
- `body`: Font for body text (default: "Libertinus Serif")
- `paper`: Paper size setting (optional)
- `margin`: Page margin setting (optional)
## Example Output
The package automatically handles:
- Heading sizes with natural visual hierarchy (H1-H5)
- Optimal spacing between elements
- Professional text justification
- Smart hyphenation
- Consistent vertical rhythm
See the [example output](thumbnail.png) for more information and a complete
example.
## License
MIT License - See [LICENSE](LICENSE) for details.
+1
View File
@@ -0,0 +1 @@
#import "src/main.typ": easy-typography
+29
View File
@@ -0,0 +1,29 @@
// Constants
// space above H1
#let heading-above-max = 1.25em
// space above H5
#let heading-above-min = 0.80em
// space below H1
#let heading-below-max = 0.65em
// space below H5
#let heading-below-min = 0.55em
// font size for H1
#let heading-size-max = 1.10em
// font size for H5
#let heading-size-min = 1.00em
// default text weight -- light is best for reading, and printers are fine with
// it these days
#let body-weight = "light"
// line spacing -- tight; efficient but still readable with good fonts
#let line-spacing = 1.30
// paragraph spacing -- defaults to a double-space
#let paragraph-spacing = 1.70
+102
View File
@@ -0,0 +1,102 @@
#import "constants.typ": *
/// The main function for easy typography setup.
///
/// - body-size (): The size of body text (default 10pt).
/// - fonts (): A dictionary specifying heading/body fonts.
/// - paper (str): The paper size to use (none to skip).
/// - margin (): Margin for the page (none to skip).
/// -> content
#let easy-typography(
body-size: 10pt,
fonts: (heading: "Libertinus Sans", body: "Libertinus Serif"),
paper: none,
margin: none,
body
) = {
// Optional page setup
if paper != none {
set page(paper: paper)
}
if margin != none {
set page(margin: margin)
}
// Paragraphs
set par(
leading: line-spacing * 0.5em,
spacing: paragraph-spacing * 0.5em,
justify: true,
linebreaks: "optimized",
)
// Body text
set text(
font: fonts.body,
fallback: false,
style: "normal",
weight: body-weight,
stretch: 100%,
size: body-size,
tracking: 0pt,
spacing: 100% + 0pt,
baseline: 0pt,
overhang: true,
hyphenate: true,
kerning: true,
ligatures: true,
number-width: "proportional",
// number-type: "lining", // commented: intentionally left up to the font to choose
)
show table: set text(number-width: "tabular")
/// Top-heavy easing function for heading sizes/spacing.
///
/// `sqrt(t)` gives biggest decrease at top, gentlest at bottom.
///
/// - max (length): Biggest size (H1)
/// - min (length): Smallest size (H5)
/// - level (length): From 1 to 5
/// -> length
let compute-size(max, min, level) = {
if level <= 1 {
max
} else if level >= 5 {
min
} else {
let t = (level - 1) / 4
max - (max - min) * calc.sqrt(t)
}
}
// Heading weight logic
let compute-weight(level) = {
if level <= 1 {
"bold"
} else if level == 2 {
"semibold"
} else if level == 3 {
"medium"
} else {
"regular"
}
}
// Show headings using computed size/spacing values
show heading: it => block(
breakable: false,
sticky: true,
above: compute-size(heading-above-max, heading-above-min, it.level),
below: compute-size(heading-below-max, heading-below-min, it.level),
text(
font: fonts.heading,
size: compute-size(heading-size-max, heading-size-min, it.level),
weight: compute-weight(it.level),
it
)
)
// Finally, render the body
body
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 769 KiB

+125
View File
@@ -0,0 +1,125 @@
#import "/lib.typ": *
#import "@preview/codly:1.2.0": *
#import "@preview/codly-languages:0.1.1": *
#show: codly-init.with()
#codly(languages: codly-languages)
#show: easy-typography.with(
fonts: (heading: "Source Sans 3", body: "Source Serif 4"),
)
= Introducing Easy Typography
#set heading(numbering: (..nums) => {
numbering("1.1.", ..nums.pos().slice(1))
})
The `easy-typography` package transforms complex typographic decisions into
simple choices, letting you focus on your content while ensuring professional
results. By adjusting the settings to match your specific needs, you can refine
the aesthetic or adapt your layout for everything from casual reading to formal
publication.
== Core Typography Features
The package manages:
#columns(2)[
- Precise heading scale with a clear hierarchy
- Optimal line height and paragraph spacing
#colbreak()
- Professional text justification and hyphenation
- Balanced vertical rhythm throughout
]
These features ensure that your document is both visually appealing and easy to
read.
=== Type Formatting
This package automatically adjusts line spacing, paragraph spacing, and
justification to maintain a clean layout. Headings are also carefully weighted
to balance them against the body text, so you can focus on content rather than
tweaking spacing and sizing. Standard formatting like *bold* and _italic_
integrates seamlessly with `easy-typography`'s approach.
=== Heading Levels
The heading scale gracefully steps down, ensuring that each level remains
distinct yet consistent. Behind the scenes, `easy-typography` calculates the
ideal size for each heading, preserving a cohesive visual hierarchy as your
document gets deeper. This approach supports manuals, academic papers, and any
long-form text where structure matters. It also helps in shorter documents,
guaranteeing a crisp layout with minimal effort.
== Why Typography Matters
Good typography isn't just about aesthetics. It's about effective communication.
Well-designed text:
#columns(2)[
- Improves reading comprehension
- Reduces eye strain
- Maintains reader engagement
#colbreak()
- Establishes visual hierarchy
- Conveys professionalism
]
Notice how this document's typography enhances readability. The justified text,
proper hyphenation, and optimized line breaks create a clean, professional
appearance. With each heading level, the user can quickly scan and digest
important information.
== Example Usage and Output
#set heading(numbering: none)
#show raw.where(block: true): set text(size: 7pt)
#grid(
columns: (55%, auto),
gutter: 1.0em,
[
// code
```typst
#import "@preview/easy-typography:0.1.0": *
#show: easy-typography.with(
fonts: (
heading: "Source Sans Pro",
body: "Source Serif Pro"
),
)
#lorem(6)
= Level One
#lorem(6)
== Level Two
#lorem(6)
=== Level Three
#lorem(6)
==== Level Four
#lorem(6)
===== Level Five
#lorem(6)
```
],
box(
stroke: 0.5pt + silver,
inset: 0.5em,
radius: 0.2em,
[
#lorem(6)
= Level One
#lorem(6)
== Level Two
#lorem(6)
=== Level Three
#lorem(6)
==== Level Four
#lorem(6)
===== Level Five
#lorem(6)
]
) // box
)
Binary file not shown.

After

Width:  |  Height:  |  Size: 306 KiB

+10
View File
@@ -0,0 +1,10 @@
[package]
name = "easy-typography"
version = "0.1.0"
entrypoint = "lib.typ"
authors = ["Stephen Waits <steve@waits.net>"]
license = "MIT"
description = "Sets up sensible typography defaults."
keywords = ["easy", "typography", "defaults"]
repository = "https://github.com/swaits/typst-collection"
exclude = ["thumbnail.png", "tests"]
+4 -3
View File
@@ -41,7 +41,7 @@ different goals:
### Import the package
```typst
#import "@preview/glossy:0.3.0": *
#import "@preview/glossy:0.5.1": *
```
### Defining Glossary Terms
@@ -186,8 +186,9 @@ Display the glossary using the `glossary()` function:
```typst
#glossary(
title: "Web Development Glossary", // Optional: defaults to Glossary
theme: my-theme, // Optionaal: defaults to theme-twocol
title: "Web Development Glossary", // Optional: defaults to Glossary theme:
my-theme, // Optional: defaults to theme-academic
sort: true, // Optional: whether or not to sort the glossary
ignore-case: false, // Optional: ignore case when sorting terms
groups: ("Web") // Optional: Filter to specific groups
)
+166 -144
View File
@@ -5,7 +5,6 @@
#import "./utils.typ": *
#let __gloss_entries = state("__gloss_entries", (:))
#let __gloss_used = state("__gloss_used", (:))
#let __gloss_label_prefix = "__gloss:"
@@ -24,7 +23,7 @@
// Returns:
// dictionary: Normalized dictionary with all expected keys populated
//
// Throws:
// Panics:
// - If 'short' key is missing when using normal (non-abbreviated) syntax
// - If 'short' value is not a string
// - If 'short' value is an empty string
@@ -98,7 +97,7 @@
// Returns:
// dictionary: The glossary entry associated with the key
//
// Throws:
// Panics:
// - If the key does not exist in the glossary
//
#let __get_entry(key) = {
@@ -110,70 +109,56 @@
entries.at(key)
}
// Creates a prefixed label string for dictionary entries and term usage.
//
// Parameters:
// key (string): The glossary entry key
//
// Returns:
// string: The prefixed label string for dictionary entries
//
#let __dict_label_str(key) = {
__gloss_label_prefix + key
}
// Creates a label object for dictionary entries.
//
// Parameters:
// key (string): The glossary entry key
//
// Returns:
// label: A Typst label object for the dictionary entry
//
#let __dict_label(key) = {
label(__dict_label_str(key))
}
// Creates a prefixed label string for term usage in documents.
//
// Parameters:
// key (string): The glossary entry key
// index (int): The occurrence index of the term in the document
//
// Returns:
// string: The prefixed label string for term usage
//
#let __term_label_str(key, index) = {
__gloss_label_prefix + key + "." + str(index)
}
// Creates a label object for term usage in documents.
//
// Parameters:
// key (string): The glossary entry key
// index (int): The occurrence index of the term in the document
//
// Returns:
// label: A Typst label object for the term usage
//
#let __term_label(key, index) = {
label(__term_label_str(key, index))
#let __term_label(key) = {
label(__gloss_label_prefix + key)
}
// Updates the term usage count in the glossary state.
// Updates the term usage in the glossary state.
//
// Parameters:
// key (string): The glossary entry key
// count (int): The number of times the term has been used
//
// Returns:
// none: Updates state as a side effect
//
#let __save_term_usage(key, count) = {
__gloss_used.update(state => {
state.insert(key, count)
state
})
#let __mark_term_used(key) = {
counter(__gloss_label_prefix + key).step()
}
// Queries the term usage
//
// Parameters:
// key (string): The glossary entry key
// location (location): The location in the document. Use none for end of document
//
// Returns:
// boolean: If the entry is used above the location in the document
//
#let __is_term_used(key, location: none) = {
let c = counter(__gloss_label_prefix + key)
c = if location == none {c.final()} else {c.at(location)}
c.at(0) > 0
}
// Determine if the glossary contains a visible entry
//
// Parameters:
// key (string): The glossary entry key
//
// Returns:
// boolean: If the term is visible in the glossary (and the label is unique)
//
#let __has_glossary_entry(key) = {
query(<glossary>).len() > 0 and query(selector(label(key)).after(<glossary>)).len() == 1
}
// Renders a glossary term with various formatting options.
@@ -189,6 +174,7 @@
// - "def" or "desc": Show the term's description instead of its name.
// - "a" or "an": Prepend an article, chosen from the entry (short or long form).
// show-term (function): A function that renders the chosen term.
// term-links (boolean): If terms should be clickable links leading to glossary
//
// Behavior:
// - Without modifiers, the first use of a term shows "Long form (short form)",
@@ -201,7 +187,7 @@
// content: The fully formatted term, including optional article, capitalization,
// usage tracking metadata, and the chosen form (short, long, or both).
//
#let __gls(key, modifiers: array, show-term: function) = {
#let __gls(key, modifiers: array, format-term: function, show-term: function, term-links: true) = {
// ---------------------------------------------------------------------------
// Check for illegal modifier combinations
// ---------------------------------------------------------------------------
@@ -216,27 +202,22 @@
// Retrieve the glossary entry and its label
// ---------------------------------------------------------------------------
let entry = __get_entry(key)
let entry_label = __dict_label_str(key)
// ---------------------------------------------------------------------------
// If "def" or "desc" modifier is present, show the entry's description immediately
// ---------------------------------------------------------------------------
if "def" in modifiers or "desc" in modifiers {
if entry.description == none {
panic("Use of 'def'/'desc' requires a description be defined.")
}
return show-term([#entry.description])
}
// ---------------------------------------------------------------------------
// Manage term usage counting and determine if it's the first reference
// ---------------------------------------------------------------------------
let entry_counter = counter(entry_label)
entry_counter.step()
let key_index = entry_counter.get().first()
let is_first_use = key_index == 0
// ---------------------------------------------------------------------------
// Record another usage of this term (increment the usage counter)
// ---------------------------------------------------------------------------
__save_term_usage(key, key_index + 1)
let is_first_use = not __is_term_used(key, location: here())
__mark_term_used(key)
// ---------------------------------------------------------------------------
// Helper Functions
@@ -267,27 +248,6 @@
}
}
// get_term(mode): Returns the appropriate term string based on the mode.
// mode is one of "short", "long", or "both".
// - "short": Returns the short form.
// - "long": Returns the long form.
// - "both": Returns "Long form (short form)".
// We rely on prior logic to ensure that when mode = "both" or "long", a long form is available.
let get_term = (mode) => {
let short_form = pluralize_term(entry.short, entry.plural)
let long_form = pluralize_term(entry.long, entry.longplural) // none safe here
if mode == "short" {
// Just the short form.
short_form
} else if mode == "long" {
// Just the long form.
long_form
} else {
// mode == "both": "Long form (short form)".
long_form + " (" + short_form + ")"
}
}
// get_article(mode): Returns the appropriate article string based on the mode.
// - If wants_article is false, returns an empty string.
// - If mode is "short", return the short article.
@@ -356,21 +316,40 @@
// Determine mode using the helper function
let mode = determine_mode(wants_both, wants_long, wants_short, is_first_use, long_available)
// Get the article and term for the chosen mode, then apply capitalization if requested
let (article, term) = capitalize_term(get_article(mode), get_term(mode))
// Pluralize (if requested)
let short-form = pluralize_term(entry.short, entry.plural)
let long-form = pluralize_term(entry.long, entry.longplural) // `none` safe here
// Apply format-term() to get the term
let formatted-term = format-term(mode, short-form, long-form)
if type(formatted-term) != "string" {
// This is because we still need to capitalize the term, and we cannot do
// that with content, thus requiring a string here.
// TODO: consider if we want to capitalize *before* this. First intuition is
// "no".
panic("Your cutsom format-term() function must return a string.")
}
// Get the article, then capitalize either the article or term (if requested)
let (article, term) = capitalize_term(get_article(mode), formatted-term)
// ---------------------------------------------------------------------------
// Construct and return the final output
// ---------------------------------------------------------------------------
context {
[#article#show-term(term)#metadata(term)#__term_label(key, key_index)]
let linked-term = if term-links and __has_glossary_entry(key) {
link(label(key), term)
} else {
term
}
[#article#show-term(linked-term)#metadata(term)#__term_label(key)]
// |^^^^^^^|^^^^^^^^^ |^^^^^^^^ |^^^^^^^^^^^^
// \_art. | | |
// \_ apply user formatting function to the term
// | |
// \_ metadata lets us label (ie it's "labelable")
// |
// \_ i.e. <__gloss.key.0>, etc.
// \_ i.e. <__gloss:key>, etc.
// for backlink from glossary
}
}
@@ -383,36 +362,63 @@
//
// Parameters:
// key (string): The glossary entry key
// count (int): Number of times the term appears in the document
//
// Returns:
// content: Comma-separated list of linked page numbers
//
// Example output: "1, 3, 5" where each number links to the term usage on that page
//
#let __create_backlinks(key, count) = {
// Convert term (key + count) to labels with their displayed page numbers
let page_labels = range(count).map(i => {
let label = __term_label(key, i)
let loc = locate(label)
(
label,
numbering(__default(loc.page-numbering(), "1"), ..counter(page).at(loc))
)
})
#let __create_backlinks(key) = {
return context query(__term_label(key)) // find all reference
.map(meta => { // extract location and page number (or symbol)
let loc = meta.location()
let page = numbering(__default(loc.page-numbering(), "1"), ..counter(page).at(loc))
(loc, page)
})
.dedup(key: ((loc, page)) => page) // deduplicate by page
.map(((loc, page)) => link(loc, page)) // create links
.join(", ")
}
// Filter out repeated page numbers using a regular loop
let seen = (:)
let singulated = ()
for (label, page) in page_labels {
if not seen.keys().contains(page) {
seen.insert(page, true)
singulated.push((label, page))
// Formats a term string based on the specified mode.
//
// Given mode, long-form, and short-form, this function returns the formatted
// term based on the mode. When mode is ...
//
// - "short" -> returns "short-form"
// - "long" -> returns "long-form"
// - "both" -> returns "short-form (long-form)"
//
// Parameters:
// mode (string): The mode in which to format the term. Possible values are "short", "long", or "both".
// short-form (string): The short form of the term.
// long-form (string): The long form of the term.
//
// Returns:
// string: The formatted term based on the specified mode.
//
#let __default-format-term(mode, short-form, long-form) = {
if mode == "short" {
short-form
} else if mode == "long" {
long-form
} else {
// mode assumed to be "both"
long-form + " (" + short-form + ")"
}
}
}
// Convert resulting set to array of links
singulated.map(((label, page)) => link(label, page)).join(", ")
// Styles a term to control its display in a document.
//
// Parameters:
// term-body (content'ish): the unstyled output from __gls()
//
// Returns:
// content: display ready content (assumed based on `term-body`)
//
#let __default-show-term(term-body) = {
// Default: just render it like normal text
term-body
}
// Initializes the glossary system and sets up term reference handling.
@@ -429,17 +435,20 @@
// - values are entry dictionaries containing term details
// show-term ((content) => content): Optional function to customize term rendering
// Default: Returns term content unchanged
// term-links (boolean): If terms should be clickable links leading to glossary
// body (content): Document content to process
//
// Returns:
// content: Processed document content with glossary functionality enabled
//
// Throws:
// Panics:
// - If entries parameter is not a dictionary
//
#let init-glossary(
entries,
show-term: (term-body) => term-body,
format-term: __default-format-term,
show-term: __default-show-term,
term-links: true,
body
) = context {
// Type checking
@@ -449,12 +458,17 @@
let checked-entry = z.parse(entry, dict-schema, scope: ("dictionary entry",))
checked-entries.insert(checked-key, checked-entry)
}
let checked-format-term = z.parse(show-term, z.function(), scope: ("format-term",))
let checked-show-term = z.parse(show-term, z.function(), scope: ("show-term",))
let checked-body = z.parse(body, z.content(), scope: ("body",))
// Process and store each glossary entry
for (key, entry) in entries {
__add_entry(key, __normalize_entry(key, entry))
// Create placeholder labels for autocompletion (if not already present)
context if not __has_glossary_entry(key) [
#metadata(key)#label(key)
]
}
// Set up reference handling for glossary terms
@@ -479,7 +493,7 @@
// Now see if this is an actual glossary term key
if __has_entry(key) {
// Found in dictionary, render via __gls()
__gls(key, modifiers: modifiers.map(lower), show-term: show-term)
__gls(key, modifiers: modifiers.map(lower), format-term: format-term, show-term: show-term, term-links: term-links)
} else {
// Not one of ours, so just pass it through
r
@@ -521,12 +535,13 @@
// Returns:
// content: Formatted glossary content
//
// Throws:
// Panics:
// - If a requested group doesn't exist
//
#let glossary(
title: "Glossary",
theme: theme-twocol,
theme: theme-academic,
sort: true,
ignore-case: false,
groups: (),
) = context {
@@ -539,7 +554,7 @@
// Collect and organize entries by group
let output = (:)
let all_entries = __gloss_entries.final()
let all_used = __gloss_used.final()
let all_used = all_entries.keys().filter(key => __is_term_used(key))
// Determine which groups to process
let all_groups = all_entries
@@ -569,52 +584,59 @@
let current_entries = ()
// Collect all used entries for this group
for (key, count) in all_used {
for key in all_used {
let entry = all_entries.at(key)
if entry.at("group") == group {
current_entries.push((
short: entry.at("short"),
long: entry.at("long"),
description: entry.at("description"),
label: [#metadata(key)#__dict_label(key)],
pages: __create_backlinks(key, count)
label: [#metadata(key)#label(key)],
pages: __create_backlinks(key)
))
}
}
// Add non-empty groups to output
if current_entries.len() > 0 {
group = if group == none { "" } else { group }
// Add non-empty groups to output
if current_entries.len() > 0 {
group = if group == none { "" } else { group }
// sort entries by case insensitivity if requested
let sorted_entries = current_entries
// 1. create array of tuples with (lower [if ignore-case], entry)
.map(e => { if ignore-case { (lower(e.short), e) } else { (e.short, e) } })
// 2. sort the tuples (by first element then second)
.sorted(key: t => t.first())
// 3. strip away the tuple's first element, leaving an array of entries
.map(t => t.last())
// sort entries by case insensitivity if requested
let sorted_entries = if sort {
current_entries
// 1. create array of tuples with (lower [if ignore-case], entry)
.map(e => { if ignore-case { (lower(e.short), e) } else { (e.short, e) } })
// 2. sort the tuples (by first element then second)
.sorted() // NOTE: sorted() is NOT language-aware
// 3. strip away the tuple's first element, leaving an array of entries
.map(t => t.last())
} else {
current_entries
}
// add entries to this group's output map
output.insert(group, sorted_entries)
// add entries to this group's output map
output.insert(group, sorted_entries)
}
}
}
// Render the glossary using the theme
let group_index = 0
(checked-theme.section)(
title,
for (group, entries) in output {
(checked-theme.group)(
group,
group_index,
output.len(),
for (i, entry) in entries.enumerate() {
(checked-theme.entry)(entry, i, entries.len())
}
)
group_index += 1
}
)
[
#metadata("glossary")<glossary>
#(checked-theme.section)(
title,
for (group, entries) in output {
(checked-theme.group)(
group,
group_index,
output.len(),
for (i, entry) in entries.enumerate() {
(checked-theme.entry)(entry, i, entries.len())
}
)
group_index += 1
}
)
]
}
+112 -14
View File
@@ -10,29 +10,127 @@
// word: The singular word to pluralize
// Returns: The pluralized form of the word, or none if input is none
#let __pluralize(word) = {
// early exit with invalid input
// Early exit for invalid input
if word == none {
return none
}
// Define helper functions for checking endings
// Helper functions for checking endings
let ends_with = (suffix) => lower(word).ends-with(suffix)
let ends_with_any = (suffixes) => suffixes.any((suffix) => ends_with(suffix))
// Handle special cases for "es" endings (s, x, z, sh, ch)
if ends_with_any(( "s", "x", "z", "sh", "ch" )) {
// Map of irregular plurals for common words
let irregulars = (
"alumna": "alumnae",
"alumnus": "alumni",
"analysis": "analyses",
"appendix": "appendices",
"basis": "bases",
"cactus": "cacti",
"child": "children",
"crisis": "crises",
"criterion": "criteria",
"datum": "data",
"foot": "feet",
"fungus": "fungi",
"goose": "geese",
"man": "men",
"medium": "media",
"mouse": "mice",
"nucleus": "nuclei",
"oasis": "oases",
"person": "people",
"phenomenon": "phenomena",
"stimulus": "stimuli",
"thesis": "theses",
"tooth": "teeth",
"woman": "women",
)
// Set of plural-only words
let plural_only = (
"advice",
"alumni",
"bison",
"children",
"criteria",
"data",
"deer",
"feet",
"fish",
"geese",
"information",
"media",
"men",
"mice",
"money",
"moose",
"octopi",
"octopodes",
"people",
"scissors",
"series",
"sheep",
"species",
"teeth",
"trousers",
"women",
)
// Irregular suffixes
let f_to_ves = ("leaf", "loaf", "calf", "half", "wolf", "thief")
let fe_to_ves = ("wife", "knife", "life")
let o_to_os = ("photo", "piano", "halo", "radio", "video", "studio", "solo", "taco", "memo", "zero")
// Convenience
let w = lower(word)
// Check for words already plural
if plural_only.contains(w) {
return word
}
// Check for irregular singulars
if irregulars.keys().contains(w) {
return irregulars.at(w)
}
// Standard pluralization rules
if ends_with("iz") {
word + "zes"
} else if ends_with_any(("s", "x", "z", "sh", "ch")) {
word + "es"
} else if ends_with("y") and not ends_with_any(( "a", "e", "i", "o", "u" )) {
// Convert y to ies when y follows a consonant
word.slice(0, -1) + "ies"
} else if ends_with("y") {
if not ends_with_any(("ay", "ey", "iy", "oy", "uy")) {
word.slice(0, -1) + "ies"
} else {
word + "s"
}
} else if ends_with("f") {
// Convert f to ves
word.slice(0, -1) + "ves"
if f_to_ves.contains(w) {
word.slice(0, -1) + "ves"
} else {
word + "s"
}
} else if ends_with("fe") {
// Convert fe to ves
word.slice(0, -2) + "ves"
if fe_to_ves.contains(w) {
word.slice(0, -2) + "ves"
} else {
word + "s"
}
} else if ends_with("us") {
word.slice(0, -2) + "i"
} else if ends_with("is") {
word.slice(0, -2) + "es"
} else if ends_with("on") {
word + "s"
} else if ends_with("o") {
if o_to_os.contains(w) {
word + "s"
} else {
word + "es"
}
} else {
// Default case: just add s
word + "s"
}
}
@@ -105,7 +203,7 @@
if is_acronym {
// Use acronym rules
let first_char = upper_word.slice(0,1)
let first_char = upper_word.codepoints().slice(0,1).first()
if acronym_vowels.contains(first_char) {
"an"
} else {
@@ -113,7 +211,7 @@
}
} else {
// Non-acronym rules
let first_char = lower_word.slice(0,1)
let first_char = lower_word.codepoints().slice(0,1).first()
// Special cases for words matching a set of known 'silent h' prefixes
let silent_h_words = (
+1 -1
View File
@@ -17,7 +17,7 @@
short: "TPS",
long: "test procedure specification",
description: "A document on how to run all the test procedures"),
unused: "Unused term, which shouldn't print in the glossary."
unused: "Unused term, which shouldn't print in the glossary."
)
#show: init-glossary.with(myGlossary, show-term: (body) => [#emph(body)])
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

+208
View File
@@ -0,0 +1,208 @@
#import "/lib.typ": *
#let myGlossary = (
html: (
short: "HTML",
long: "Hypertext Markup Language",
description: "A standard language for creating web pages",
group: "Web"),
css: (
short: "CSS",
long: "Cascading Style Sheets",
description: "A language used for describing the presentation of a document",
group: "Web"),
tps: (
short: "TPS",
long: "test procedure specification",
description: "A document on how to run all the test procedures"),
concise: "Concise syntax!",
shortonly: (
short: "shortonly!!!"),
unused: "Unused term, which shouldn't print in the glossary."
)
#set page(width: 6.5in, height: auto, margin: 1em)
#let test-content = {
table(
columns: 3,
table.header(
[`short`], [`long`], [`both`],
),
[@html:short], [@html:long], [@html:both],
[@css:short], [@css:long], [@css:both],
[@tps:short], [@tps:long], [@tps:both],
[@concise:short], [@concise:long], [@concise:both],
[@shortonly:short], [@shortonly:long], [@shortonly:both],
table.hline(stroke: 2pt),
[@html:short:cap], [@html:long:cap], [@html:both:cap],
[@a:css:short], [@a:css:long], [@a:css:both],
[@tps:short:pl], [@tps:long:pl], [@tps:both:pl],
[@concise:a:cap:short], [@concise:a:cap:long], [@concise:a:cap:both],
[@an:shortonly:short], [@an:shortonly:long], [@an:shortonly:both],
)
[@a:tps:cap is @tps:def.]
}
// ---------------------------------------------------------------------------------
#let format-basic(mode, short-form, long-form) = {
if mode == "short" {
short-form
} else if mode == "long" {
long-form
} else {
long-form + " (" + short-form + ")"
}
}
#init-glossary(myGlossary, format-term: format-basic)[#test-content]
// ---------------------------------------------------------------------------------
#let format-reverse(mode, short-form, long-form) = {
if mode == "short" {
short-form
} else if mode == "long" {
long-form
} else {
short-form + " [" + long-form + "]"
}
}
#init-glossary(myGlossary, format-term: format-reverse)[#test-content]
// ---------------------------------------------------------------------------------
#let format-uppercase-short(mode, short-form, long-form) = {
let short-up = upper(short-form);
if mode == "short" {
short-up
} else if mode == "long" {
long-form
} else {
long-form + " (" + short-up + ")"
}
}
#init-glossary(myGlossary, format-term: format-uppercase-short)[#test-content]
// ---------------------------------------------------------------------------------
#let format-prefix-suffix(mode, short-form, long-form) = {
if mode == "short" {
"Term: " + short-form + "."
} else if mode == "long" {
"Term: " + long-form + "."
} else {
"Term: " + long-form + " (" + short-form + ")."
}
}
#init-glossary(myGlossary, format-term: format-prefix-suffix)[#test-content]
// ---------------------------------------------------------------------------------
#let format-conditional-separator(mode, short-form, long-form) = {
let separator = if short-form.len() > 4 { " / " } else { ", " };
let has_long = long-form != none and long-form != "";
if mode == "short" {
short-form
} else if mode == "long" {
if has_long { long-form } else { short-form }
} else {
if has_long {
long-form + separator + short-form
} else {
short-form
}
}
}
#init-glossary(myGlossary, format-term: format-conditional-separator)[#test-content]
// ---------------------------------------------------------------------------------
// 1. Braces and Labels
// Idea: Use different bracket styles and labels based on the mode.
#let format-braces(mode, short-form, long-form) = {
if mode == "short" {
"{" + short-form + "}"
} else if mode == "long" {
"[" + long-form + "]"
} else {
long-form + " <" + short-form + ">"
}
}
#init-glossary(myGlossary, format-term: format-braces)[#test-content]
// ---------------------------------------------------------------------------------
// 2. Mode-Based Prefix
// Idea: Add a prefix indicating the mode, and then show the term(s).
#let format-mode-prefix(mode, short-form, long-form) = {
let prefix = if mode == "short" { "S:" } else if mode == "long" { "L:" } else { "B:" };
if mode == "short" {
prefix + short-form
} else if mode == "long" {
prefix + long-form
} else {
prefix + long-form + " & " + short-form
}
}
#init-glossary(myGlossary, format-term: format-mode-prefix)[#test-content]
// ---------------------------------------------------------------------------------
// 3. Conditional Fallback for Missing Long
// Idea: If no long-form is provided, use the short-form in all cases.
#let format-fallback-long(mode, short-form, long-form) = {
let has_long = long-form != none and long-form != "";
if mode == "short" {
short-form
} else if mode == "long" {
if has_long { long-form } else { short-form }
} else {
if has_long { long-form + " (" + short-form + ")" } else { short-form }
}
}
#init-glossary(myGlossary, format-term: format-fallback-long)[#test-content]
// ---------------------------------------------------------------------------------
// 4. Uppercase Both Terms in Both Mode
// Idea: Always uppercase for both mode, normal otherwise.
#let format-uppercase-both(mode, short-form, long-form) = {
if mode == "short" {
short-form
} else if mode == "long" {
long-form
} else {
upper(long-form) + " (" + upper(short-form) + ")"
}
}
#init-glossary(myGlossary, format-term: format-uppercase-both)[#test-content]
// ---------------------------------------------------------------------------------
// 5. Append Length Info
// Idea: In both mode, append the length of each string.
#let format-length-info(mode, short-form, long-form) = {
let s_len = str(short-form.len())
let l_len = if long-form != none and long-form != "" { str(long-form.len()) } else { "0" }
if mode == "short" {
short-form + " [len:" + s_len + "]"
} else if mode == "long" {
long-form + " [len:" + l_len + "]"
} else {
long-form + " (" + short-form + ") [L:" + l_len + ", S:" + s_len + "]"
}
}
#init-glossary(myGlossary, format-term: format-length-info)[#test-content]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 184 KiB

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 79 KiB

+23
View File
@@ -0,0 +1,23 @@
first:
short: "DAL"
long: "first"
second:
short: "cab"
long: "second"
third:
short: "delta"
long: "third"
fourth:
short: "COO"
long: "fourth"
fifth:
short: "cuckoo"
long: "fifth"
sixth:
short: "ČR"
long: "sixth"
Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

+13
View File
@@ -0,0 +1,13 @@
#import "/lib.typ":*
#show: init-glossary.with(yaml("glossary.yml"))
@first, @second, @third, @fourth, @fifth, @sixth
#glossary(ignore-case: false, sort: true)
#line(length: 20em)
#glossary(ignore-case: true, sort: true)
#line(length: 20em)
#glossary(ignore-case: false, sort: false)
#line(length: 20em)
#glossary(ignore-case: true, sort: false)
Binary file not shown.
+308
View File
@@ -0,0 +1,308 @@
#import "/src/utils.typ": __pluralize
#let plural_tests = (
("BUS", "BUSes"),
("Box", "Boxes"),
("Buzz", "Buzzes"),
("CHURCH", "CHURCHes"),
("Lady", "Ladies"),
("Leaf", "Leaves"),
("Loaf", "Loaves"),
("ability", "abilities"),
("account", "accounts"),
("advice", "advice"),
("age", "ages"),
("agent", "agents"),
("alumna", "alumnae"),
("alumni", "alumni"),
("alumnus", "alumni"),
("answer", "answers"),
("appendix", "appendices"),
("apple", "apples"),
("art", "arts"),
("artist", "artists"),
("attention", "attentions"),
("ax", "axes"),
("baby", "babies"),
("ball", "balls"),
("bank", "banks"),
("basis", "bases"),
("beauty", "beauties"),
("bed", "beds"),
("belief", "beliefs"),
("berry", "berries"),
("bird", "birds"),
("book", "books"),
("bottle", "bottles"),
("box", "boxes"),
("boy", "boys"),
("branch", "branches"),
("brother", "brothers"),
("brush", "brushes"),
("bus", "buses"),
("business", "businesses"),
("cactus", "cacti"),
("cake", "cakes"),
("calf", "calves"),
("car", "cars"),
("care", "cares"),
("carrot", "carrots"),
("cart", "carts"),
("cat", "cats"),
("chair", "chairs"),
("chance", "chances"),
("change", "changes"),
("chef", "chefs"),
("chief", "chiefs"),
("child", "children"),
("church", "churches"),
("city", "cities"),
("class", "classes"),
("cloud", "clouds"),
("coach", "coaches"),
("comfort", "comforts"),
("company", "companies"),
("computer", "computers"),
("confidence", "confidences"),
("cookie", "cookies"),
("corpus", "corpuses"),
("country", "countries"),
("courage", "courages"),
("cow", "cows"),
("criterion", "criteria"),
("culture", "cultures"),
("cup", "cups"),
("danger", "dangers"),
("dart", "darts"),
("day", "days"),
("deer", "deer"),
("desk", "desks"),
("development", "developments"),
("dish", "dishes"),
("dog", "dogs"),
("door", "doors"),
("dream", "dreams"),
("education", "educations"),
("egg", "eggs"),
("elephant", "elephants"),
("employee", "employees"),
("energy", "energies"),
("entertainment", "entertainments"),
("exam", "exams"),
("experience", "experiences"),
("family", "families"),
("farm", "farms"),
("father", "fathers"),
("fish", "fish"),
("floor", "floors"),
("flower", "flowers"),
("fly", "flies"),
("focus", "focuses"),
("foot", "feet"),
("fork", "forks"),
("fox", "foxes"),
("freedom", "freedoms"),
("friend", "friends"),
("future", "futures"),
("game", "games"),
("garden", "gardens"),
("gas", "gases"),
("gift", "gifts"),
("girl", "girls"),
("glass", "glasses"),
("goat", "goats"),
("goose", "geese"),
("grass", "grasses"),
("guy", "guys"),
("half", "halves"),
("hand", "hands"),
("hat", "hats"),
("head", "heads"),
("health", "healths"),
("help", "helps"),
("hero", "heroes"),
("history", "histories"),
("holiday", "holidays"),
("hope", "hopes"),
("horse", "horses"),
("house", "houses"),
("idea", "ideas"),
("image", "images"),
("information", "information"),
("interest", "interests"),
("island", "islands"),
("journey", "journeys"),
("joy", "joys"),
("justice", "justices"),
("key", "keys"),
("keyboard", "keyboards"),
("king", "kings"),
("kiss", "kisses"),
("kitchen", "kitchens"),
("knife", "knives"),
("knowledge", "knowledges"),
("lady", "ladies"),
("lamp", "lamps"),
("laptop", "laptops"),
("law", "laws"),
("leaf", "leaves"),
("learning", "learnings"),
("leg", "legs"),
("letter", "letters"),
("life", "lives"),
("light", "lights"),
("line", "lines"),
("lion", "lions"),
("loaf", "loaves"),
("love", "loves"),
("luck", "lucks"),
("man", "men"),
("map", "maps"),
("market", "markets"),
("match", "matches"),
("memory", "memories"),
("milk", "milks"),
("money", "money"),
("monitor", "monitors"),
("month", "months"),
("mosquito", "mosquitoes"),
("mother", "mothers"),
("mountain", "mountains"),
("mouse", "mice"),
("movie", "movies"),
("name", "names"),
("nation", "nations"),
("neck", "necks"),
("night", "nights"),
("nucleus", "nuclei"),
("ocean", "oceans"),
("octopi", "octopi"),
("octopodes", "octopodes"),
("octopus", "octopuses"),
("office", "offices"),
("onion", "onions"),
("opinion", "opinions"),
("orange", "oranges"),
("page", "pages"),
("park", "parks"),
("party", "parties"),
("peace", "peaces"),
("peach", "peaches"),
("pen", "pens"),
("person", "people"),
("phenomenon", "phenomena"),
("phone", "phones"),
("photo", "photos"),
("piano", "pianos"),
("picture", "pictures"),
("pig", "pigs"),
("place", "places"),
("plane", "planes"),
("plant", "plants"),
("plate", "plates"),
("play", "plays"),
("player", "players"),
("pocket", "pockets"),
("potato", "potatoes"),
("power", "powers"),
("printer", "printers"),
("problem", "problems"),
("program", "programs"),
("proof", "proofs"),
("puppy", "puppies"),
("queen", "queens"),
("quiz", "quizzes"),
("radio", "radios"),
("rain", "rains"),
("respect", "respects"),
("responsibility", "responsibilities"),
("river", "rivers"),
("road", "roads"),
("roof", "roofs"),
("room", "rooms"),
("safe", "safes"),
("school", "schools"),
("scissors", "scissors"),
("sea", "seas"),
("series", "series"),
("sheep", "sheep"),
("ship", "ships"),
("shoe", "shoes"),
("shop", "shops"),
("shore", "shores"),
("sister", "sisters"),
("sky", "skies"),
("snow", "snows"),
("solo", "solos"),
("son", "sons"),
("song", "songs"),
("sound", "sounds"),
("spoon", "spoons"),
("star", "stars"),
("station", "stations"),
("stone", "stones"),
("store", "stores"),
("story", "stories"),
("street", "streets"),
("student", "students"),
("studio", "studios"),
("success", "successes"),
("sun", "suns"),
("syllabus", "syllabuses"),
("table", "tables"),
("taco", "tacos"),
("teacher", "teachers"),
("team", "teams"),
("television", "televisions"),
("test", "tests"),
("thief", "thieves"),
("thing", "things"),
("time", "times"),
("tomato", "tomatoes"),
("tooth", "teeth"),
("town", "towns"),
("toy", "toys"),
("tree", "trees"),
("trousers", "trousers"),
("truth", "truths"),
("umbrella", "umbrellas"),
("valley", "valleys"),
("victory", "victories"),
("video", "videos"),
("village", "villages"),
("wall", "walls"),
("watch", "watches"),
("water", "waters"),
("wealth", "wealths"),
("week", "weeks"),
("wife", "wives"),
("window", "windows"),
("wisdom", "wisdoms"),
("wish", "wishes"),
("wolf", "wolves"),
("woman", "women"),
("wood", "woods"),
("word", "words"),
("work", "works"),
("year", "years"),
("zero", "zeros"),
(none, none),
)
#for (singular, expected) in plural_tests {
let result = __pluralize(singular)
if result != expected {
panic(
"Pluralization failed for: "
+ (if singular == none { "none" } else { str(singular) })
+ ". Expected: "
+ (if expected == none { "none" } else { str(expected) })
+ ", got: "
+ (if result == none { "none" } else { str(result) })
)
}
}
#set page(height: auto, width: auto, margin: 1em)
"Success! All pluralizations determined properly!"
+390
View File
@@ -0,0 +1,390 @@
// Brutal test for `glossy` functionality
//
// This file tries to exercise every known feature of `glossy` based on the demo.
// The goal is to cover all possible term definitions, modifiers, and reference forms.
//
// - Test terms with all combinations of fields: short, long, description, group, article, longarticle
// - Terms with missing fields
// - Terms with vowel/consonant starting for testing articles
// - Terms with conflicting modifiers (short/long/both), capitalization (cap), plural (pl), article (a/an), desc, def
// - Terms that appear and terms that are never referenced
// - Multiple glossaries with different themes and groups
// - Custom show-term callbacks
//
// This is not a narrative; it's a comprehensive brute-force test.
//
// Assumptions/Features Inferred:
// - @key references a glossary term by its key
// - Modifiers: short, long, both, cap, pl, a, an, def, desc
// - a/an modifiers can appear before or after the key
// - Terms can have custom 'article' or 'longarticle' fields to override default articles
// - Terms not referenced should not appear in a glossary unless forced
// - Conflicting modifiers: short/long/both - only one displays, in priority: both > long > short?
// - desc and def presumably show description or definition fields inline
// - The `show-term` callback in `init-glossary` modifies how inline references are displayed
// - `#glossary` can be called multiple times with different filters and themes
// - Terms can be grouped, and `#glossary` can be limited to certain groups
// - Terms with unusual keys or missing fields
// - Terms starting with vowels to test articles (e.g., 'an' vs 'a')
// - Terms that define custom `article` or `longarticle` fields
//
// We attempt to create a large dictionary with diverse entries.
#import "/lib.typ": *
#let exhaustiveGlossary = (
html: (
short: "HTML",
long: "Hypertext Markup Language",
description: "A standard language for creating web pages",
group: "Web"
),
css: (
short: "CSS",
long: "Cascading Style Sheets",
description: "A language used for describing the presentation of documents",
group: "Web"
),
// Term with no description
js: (
short: "JS",
long: "JavaScript",
group: "Web"
),
// Term with only a short field
tcp: (
short: "TCP",
group: "Networking"
),
// Term with only a long field
// should panic!
//udp: (
// long: "User Datagram Protocol",
// group: "Networking"
//),
// Term with short and description, but no long
ip: (
short: "IP",
description: "A unique identifier for a host or network interface",
group: "Networking"
),
// Term with custom articles and everything defined
api: (
short: "API",
long: "Application Programming Interface",
description: "A set of protocols and tools for building software",
article: "an", // custom article for short form
longarticle: "an", // custom article for long form
group: "Software"
),
// Term starting with a vowel, no custom article, to test default a/an logic
xml: (
short: "XML",
long: "Extensible Markup Language",
description: "A markup language defining rules for encoding documents",
group: "Data"
),
// Term starting with a consonant, no custom article
cpu: (
short: "CPU",
long: "Central Processing Unit",
description: "The primary component of a computer that performs calculations",
group: "Hardware"
),
// Term without any fields (just a string), should be handled gracefully
bare: "A bare term with no fields",
// Term with only description
// should panic!
//desconly: (
// description: "Just a description, no short or long",
// group: "Misc"
//),
// Term with article fields but missing short and long (should test fallback)
// should panic!
//articonly: (
// article: "an",
// longarticle: "a",
// description: "Has only articles and a description",
// group: "Misc"
//),
// Term with uppercase key
SSL: (
short: "SSL",
long: "Secure Sockets Layer",
description: "A protocol for encrypting information over the internet",
group: "Security"
),
// Term that will not be referenced
unusedterm: (
short: "UNUSED",
long: "Unused Term",
description: "Should not appear since it's never referenced"
),
// Term that tests pluralization with custom fields maybe
doc: (
short: "doc",
long: "document",
description: "A single piece of written matter",
group: "Misc"
),
// Terms that might require checking conflicting modifiers
tps: (
short: "TPS",
long: "test procedure specification",
description: "A document describing test procedures",
group: "Testing"
),
// Term that might appear multiple times
http: (
short: "HTTP",
long: "Hypertext Transfer Protocol",
description: "A protocol for distributed, collaborative, hypermedia information systems",
group: "Web"
)
)
// Initialize the glossary with a custom show-term callback
#show: init-glossary.with(
exhaustiveGlossary,
show-term: (body) => [#strong(body)]
)
#set heading(numbering: "1.1")
#set page(height: 9.5in, width: 7in, margin: 1em, numbering: "1")
= Brutal `glossy` Test
This document tries all reference forms and modifiers on a large set of terms.
== Basic references without modifiers
- @html
- @css
- @js
- @tcp
//- @udp // should panic!
- @ip
- @api
- @xml
- @cpu
- @bare
//- @desconly // should panic!
//- @articonly // should panic!
- @SSL
- @doc
- @tps
- @http
== Using plural modifier (pl)
- @html:pl
- @css:pl
- @js:pl
- @tcp:pl
//- @udp:pl // should panic!
- @ip:pl
- @api:pl
- @xml:pl
- @cpu:pl
- @bare:pl
//- @desconly:pl // should panic!
//- @articonly:pl // should panic!
- @SSL:pl
- @doc:pl
- @tps:pl
- @http:pl
== Using capitalization modifier (cap)
- @html:cap
- @css:cap
- @js:cap
- @tcp:cap
//- @udp:cap // should panic!
- @ip:cap
- @api:cap
- @xml:cap
- @cpu:cap
- @bare:cap
//- @desconly:cap // should panic!
//- @articonly:cap // should panic!
- @SSL:cap
- @doc:cap
- @tps:cap
- @http:cap
== Using articles (a/an) before the key
- @a:html (consonant start)
- @a:css
- @an:ip (starts with vowel sound?)
- @an:api (has custom article 'an')
- @a:cpu (consonant)
- @an:xml (starts with vowel)
//- @an:articonly (has custom article fields) // should panic!
- @an:SSL (S pronounced 'es')
- @a:doc
== Using articles after the key
- @html:a
- @css:an
- @ip:a
- @api:a (custom article should still apply)
- @cpu:an (might not make sense since CPU starts with C sound - test behavior)
- @xml:a
//- @articonly:an // should panic!
- @SSL:a
- @doc:an
== Using def and desc modifiers
- @html:def (show definition/long?)
- @css:desc (show description)
//- @js:def // should panic!
- @ip:desc
- @api:def
- @xml:desc
- @cpu:def
//- @desconly:def (no short/long, just desc) // should panic!
//- @articonly:desc // should panic!
- @tps:def
- @tps:desc
- @http:def
- @http:desc
== Using short, long, both modifiers
- @html:short
- @html:long
- @html:both
- @css:short
- @css:long
- @css:both
//- @udp:long (only has long) // should panic!
- @tcp:short (only has short)
- @ip:short
- @ip:long (no long defined, fallback?)
- @api:long
- @xml:both
- @cpu:both
- @doc:short
- @doc:long
- @doc:both
- @tps:short
- @tps:long
- @tps:both
== Conflicting multiple modifiers combined (short, long, both together)
- @tps:short:long
- @tps:short:both
- @tps:long:both
- @tps:short:long:both
- @html:both:long:short
- @doc:long:short
- @cpu:both:long:short
- @api:short:long:both
== Combining capitalization and plural with short/long/both
- @html:long:pl:cap
- @css:both:cap:pl
- @doc:short:pl:cap
- @api:both:pl:cap
- @ip:long:pl:cap (no long, see what happens)
- @bare:long:pl:cap (no fields)
//- @desconly:both:pl:cap (no short/long) // should panic!
//- @articonly:short:cap:pl (no short defined) // should panic!
- @SSL:both:pl:cap
- @tps:long:pl:cap
- @http:both:pl:cap
== Combining articles with other modifiers
- @a:html:long
- @an:ip:long
- @api:a:long (custom article)
//- @xml:an:both:pl (articles + plural? Should fail or ignore?) // should panic!
- @cpu:an:both:cap
- @SSL:a:short:cap
//- @doc:an:long:pl // should panic!
(We know articles + pl is not compatible, checking behavior.)
//== Attempt referencing nonexistent keys
//
//- @nonexistent (Should show something like ?? or error?) // should panic!
//- @nonexistent:long:pl:cap:a:def (extreme) // should panic!
== Create a big table testing all fields of one term
#table(
columns: 3,
table.header([*Input*],[*Output*],[*Comment*]),
[`@api` ], [@api], ["default"],
[`@api:short` ], [@api:short], ["short only"],
[`@api:long` ], [@api:long], ["long only"],
[`@api:both` ], [@api:both], ["both"],
[`@api:def` ], [@api:def], ["definition (long)"],
[`@api:desc` ], [@api:desc], ["description"],
[`@a:api` ], [@a:api], ["article before key"],
[`@api:a` ], [@api:a], ["article after key"],
[`@api:cap` ], [@api:cap], ["capitalize"],
[`@api:pl` ], [@api:pl], ["plural"],
[`@api:long:cap`], [@api:long:cap],["long + cap"],
[`@api:both:pl` ], [@api:both:pl], ["both + pl"]
)
== Multiple glossaries with themes and group filtering
= Glossaries
== Full Glossary (all terms)
#glossary(title: "Full Glossary", theme: theme-chicago-index)
== Web Only
#glossary(title: "Web Terms", groups: ("Web",), theme: theme-compact)
== Networking Only
#glossary(title: "Networking Terms", groups: ("Networking",), theme: theme-basic)
== Misc and Data
#glossary(title: "Misc & Data", groups: ("Misc","Data"), theme: theme-basic)
== Just Testing terms
#glossary(title: "Testing Terms", groups: ("Testing",), theme: theme-chicago-index)
== Hardware group
#glossary(title: "Hardware Terms", groups: ("Hardware",), theme: theme-chicago-index)
== Unreferenced entries
#glossary(title: "Unreferenced (Should Contain Unused?)", groups: ("Security",), theme: theme-chicago-index)
== Empty group glossary
#glossary(title: "Empty Group Glossary", groups: (""), theme: theme-basic)
= End of Brutal Test
Binary file not shown.

Before

Width:  |  Height:  |  Size: 651 KiB

After

Width:  |  Height:  |  Size: 651 KiB

+23
View File
@@ -0,0 +1,23 @@
cab:
short: "cab"
long: "taxi cab"
coo:
short: "COO"
long: "Chief Operations Officer"
cuckoo:
short: "cuckoo"
long: "really crazy"
delta:
short: "delta"
long: "difference between two values"
dal:
short: "DAL"
long: "Delta Airlines"
čr:
short: "ČR"
long: "Česká Republika"
Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

+20
View File
@@ -0,0 +1,20 @@
#import "/lib.typ":*
#set text(lang: "cs", region: "CZ")
#show: init-glossary.with(yaml("glossary.yml"))
#glossary(ignore-case: true)
#line(length: 20em)
@čr
@cab
@coo
@cuckoo
@delta
@dal
Binary file not shown.

Before

Width:  |  Height:  |  Size: 651 KiB

After

Width:  |  Height:  |  Size: 651 KiB

+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "glossy"
version = "0.3.0"
version = "0.5.1"
entrypoint = "lib.typ"
authors = ["Stephen Waits <steve@waits.net>"]
license = "MIT"