txt section numbering, @typeface :middle/:lift and html scale, NewGardinerOmni, html :leading (from dev 9fa469dd74ed)

Section headings under txt are numbered inside a @document only; @typeface
gains :middle and :lift and its :scale now means the same in html and
pdf; NewGardinerOmni ships (OFL 1.1, Mark-Jan Nederhof) and @egyptian /
@chinese replace @cjk; @table :leading and :colsep reach html; kdesc
--typeface help names the flag; @document.txt is a Python class.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
ackandClaude Fable 5.1 committed 2026-09-18 20:02:44 +02:00
1 parent 0ead40f272
commit 63956c00e5
26 files changed
+437 -173

No files matched your search

+4 -1
View File
@@ -51,7 +51,10 @@ document.so : $(LOCAL_OBJECTS) $(SKS_OBJECTS) $(LIBRARY) document.cpp | deps
document.cpp -o $@ $(ALL_OBJECTS) -lklammertext $(LDLIBS)
clean :
rm -f $(LOCAL_OBJECTS) $(LOCAL_DEPFILES) *.so *~ __pycache__
rm -f $(LOCAL_OBJECTS) $(LOCAL_DEPFILES) *.so *~
# document_txt.py is imported at render time (2026-09-18), so this
# directory now exists here; rm -f refused it and failed every clean.
rm -rf __pycache__
# Include generated dependency files (if they exist)
-include $(LOCAL_DEPFILES)
+4 -15
View File
@@ -62,21 +62,10 @@
: Top-level document structure
@@
@@document.html,tex :: @eval :cpp *KLAMMERTEXT_HOME*/sks/document/document document @ @@
# The following definition of @document.txt is not adequate (it ignores :files,
# for example), but it enables tests of other txt klammers for now. When one of
# the arguments is empty, the justifcation postprocess should remove multiple
# lines, but __VSPACE__ inserts a space character, which prevents the lines
# removal from the justification function. You can also see the extra space
# before the *subtitle* value.
@@document.html,tex ::
@eval :cpp *KLAMMERTEXT_HOME*/sks/document/document document @
@@
@@document.txt ::
@eval "*title*".upper() @ @nl@
*subtitle*
*author* @nl@
*date*
*text*
@eval document_txt.Document(K) @
@@
-23
View File
@@ -1,23 +0,0 @@
import kutil
import html_util
import tex_util
class Document(klammer_base.Klammer_base):
def __init__(self, K):
super().__init__(K)
def html(self):
if self.include_css == "true":
css_code, css_files = html_util.css(self.css, self._sks_enabled)
head = html_util.head(self.title, css_files=css_files, css_code=css_code)
else:
head = head = html_util.head(self.title, include_fonts=self.include_fonts == "true")
return html_util.page(head, self.body)
def tex(self):
ragged_right = self.ragged_right in {"true", "True", "1"}
return tex_util.page(
self.title, self.subtitle, self.leading, self.pointsize, ragged_right, self.body)
def txt(self):
return self.body
+6 -20
View File
@@ -340,9 +340,14 @@ std::string Document_class::typeface_preamble()
std::stringstream ss {};
for (size_t i = 0; i < m_extra_typefaces.size(); i++) {
const auto& [name, scale] = m_extra_typefaces[i];
// Compared by directory name, as collect_typefaces() compares: a
// @typeface may write the family name or the store's directory
// name, and family_name holds what the css declares (2026-09-12),
// so a name-for-name comparison missed the directory spelling and
// left \ktface<n> undefined in the .tex (found 2026-09-17).
const Resolved_font* rf = nullptr;
for (const auto& f : m_resolved_extra)
if (f.family_name == name) rf = &f;
if (f.dir_name == name_to_dirname(name)) rf = &f;
if (!rf) continue;
// \newfontfamily declares a switch command, unlike \setmainfont,
// which changes the document's font permanently.
@@ -351,22 +356,3 @@ std::string Document_class::typeface_preamble()
}
return ss.str();
}
/*
void output_msg(const std::string& msg)
{
std::cout << red;
(void)K::log(1, msg);
std::cout << black;
}
void Document_class::create_directory(const std::string& directory)
{
if (write_files) {
fs::create_directories(directory);
} else {
output_msg("Output directory: " + directory);
}
}
*/
+19
View File
@@ -1,3 +1,4 @@
#include <iomanip>
#include "util.h"
#include "error.h"
#include "log.h"
@@ -118,6 +119,24 @@ std::string Document_class::font_definitions()
ss << " --sans-serif: \"" << m_resolved_sans.family_name << "\", sans-serif;\n";
if (!m_mono_typeface.empty())
ss << " --monospace: \"" << m_resolved_mono.family_name << "\", monospace;\n";
// The factor a @typeface span's font-size is multiplied by (2026-09-18).
// font.css renders the body at "font-size-adjust: ex-height 0.5", so
// the text the reader sees is 0.5 / x-height times its nominal size
// (EB Garamond, x-height 0.400: 1.25). A @typeface span switches
// the adjust OFF (a script with no x-height cannot be matched), so
// its ":scale N" was N times the NOMINAL size -- about a fifth
// smaller against the visible text than the same N in pdf, where
// fontspec's Scale= is against text rendered at nominal size.
// Folding the body's enlargement in here makes :scale mean the
// same thing in both targets. Emitted as a custom property the
// span multiplies in with calc(), so a fragment rendered without
// @document falls back to 1. SYNC: the anchor 0.5 is font.css's.
const float xheight_anchor = 0.5f;
if (m_resolved_serif.xheight_ratio > 0.0f) {
std::stringstream factor {};
factor << std::setprecision(4) << xheight_anchor / m_resolved_serif.xheight_ratio;
ss << " --typeface_scale: " << factor.str() << ";\n";
}
ss << "}\n";
}
// Font-size normalization across families is no longer emitted from
+33
View File
@@ -0,0 +1,33 @@
import kutil
import klammer_base
import phases
class Document(klammer_base.Klammer_base):
def __init__(self, K):
super().__init__(K)
if self.files:
raise Exception("The :files option is not defined for the 'txt' target")
def html(self):
raise Exception("Implemented by document.cpp")
def tex(self):
raise Exception("Implemented by document.cpp")
def txt(self):
# The document marker: section numbering under txt is a document
# service, and the numbering phase numbers only when it finds this
# at the head of the text (a fragment, as kdesc renders, has none).
result = phases.txt_document_marker() + "\n"
if self.title:
result += f"@b {self.title} @ @nl@\n"
if self.subtitle:
result += f"@b {self.subtitle} @ @nl@\n"
result += "\n"
if self.author:
result += f"@i {self.author} @ @nl@\n"
if self.date:
result += f"@i {self.date} @ @nl@\n"
result += "\n"
result += self.text
return result
+29 -4
View File
@@ -26,13 +26,28 @@ font as document text instead of setting anything. @typeface is the
temporary, all-target replacement.
]#
@@typeface.k name | text :scale.float 1.0 :
@@typeface.k name | text :scale.float 1.0 :middle.bool :lift.length :
A temporary change of typeface for *text*: the typeface *name* is
resolved in the Klammertext font store (the directories of
KLAMMERTEXT_FONTS, then the distribution's own), and the document
declares and localizes it automatically -- writing this klammer is the
only declaration needed. *scale* multiplies the surrounding text size,
which a script whose glyphs are drawn small usually wants.
only declaration needed. *scale* multiplies the size of the surrounding
text as it appears, the same in html and pdf, which a script whose glyphs
are drawn small usually wants.
*middle* centres *text* on the surrounding line instead of standing it on
the baseline -- for a script with no baseline relationship to the text,
such as hieroglyphs, whose font declares a tall ascender that would
otherwise open up every line the glyphs sit in. Html only: in tex a
row is already as tight as its tallest glyph. Never for a Latin
typeface, whose baseline must stay shared with the text around it.
*lift* shifts *text* up by a length (down when negative), in em, pt or
px -- the correction for a font that draws its glyphs off the baseline,
which is a property of the font and so belongs in the klammer that names
it: Noto Sans Egyptian Hieroglyphs floats its signs and wants about
0.15em, NewGardinerOmni stands them on the baseline and wants none.
Html and tex alike; the txt target has no vertical position.
The change ends with *text*: nothing after it is affected. Under the
txt target a typeface cannot be expressed at all, so *text* is emitted
@@ -107,9 +122,19 @@ than a typeface -- xeCJK for the tex path), so this klammer errors with
the list of available typefaces until one is installed with
"kdesc --typeface install". That is the honest behaviour: the klammer
states what it needs and the store reports what it has.
]#
@@cjk.k text : Set *text* in a typeface that supports CJK @@
@@cjk.html,tex,txt :: @typeface Noto Sans CJK SC | *text* @ @@
]#
# Only defining on Chinese style for now; could be parameterized.
@@chinese.k text :scale.float 1 : Set *text* in a Chinese font @@
@@chinese.html,tex,txt :: @typeface Noto Serif SC :scale *scale* | *text* @ @@
# Egyptian hieroglyphs
@@egyptian.k text :scale.float 1.75 : Set *text* in an Egyptian hieroglyph font @@
@@egyptian.html,tex,txt :: @typeface NewGardinerOmni :scale *scale* :middle | *text* @ @@
# @@egyptian.html,tex,txt :: @typeface Noto Sans Egyptian Hieroglyphs :scale *scale* :middle | *text* @ @@
@@fraktur.k s : Set text *s* in Fraktur @@
@@fraktur.tex :: \textfrak{*s*} @@
+52 -3
View File
@@ -60,9 +60,38 @@ class Typeface(klammer_base.Klammer_base):
# this sits inside a double-quoted html attribute. What is quoted
# here is the MARKER: @document replaces it with the resolved
# family name (see the marker note above).
# The size is the scale times the body's own enlargement: the body
# is rendered at "font-size-adjust: ex-height 0.5" (font.css), so
# the visible text is larger than its nominal size, and a span
# with the adjust off at a plain "Nem" sat about a fifth smaller
# against it than the same :scale in pdf. @document emits the
# factor as --typeface_scale (document_html.cpp, font_definitions);
# the fallback 1 is for a fragment rendered without @document.
# The "*" of calc() survives the @eval re-read (tested 2026-09-18);
# the "--" of the property name is hidden below with the rest.
style = "', serif; font-size-adjust: none"
if float(self.scale) != 1.0:
style += f"; font-size: {float(self.scale)}em"
style += f"; font-size: calc({float(self.scale)}em * var(--typeface_scale, 1))"
# :middle -- for a script with no baseline relationship to the
# text. A browser sizes the span's inline box from the FONT's
# ascender and descender, not the glyph's ink, and centres it on
# the content area's midpoint; a hieroglyph font declares an
# ascender of 1.0 em and no descender (NewGardinerOmni; Noto:
# 1.324/-0.326), so at :scale 1.75 the box sat half an em too
# high and every table row grew from 31 to 47 px (Noto: 62).
# line-height 1 drops the body's leading from the enlarged box and
# vertical-align middle centres it on the PARENT's x-height, which
# is why this uses the text's metrics, not the script font's zeros.
# Measured 2026-09-18: 40 px, the floor the ink allows; line-height
# 0 alone gave 31 px with the glyphs overlapping the rows above.
# Off by default: a Latin typeface must keep the shared baseline.
if self.middle:
style += "; line-height: 1; vertical-align: middle"
if self.lift_length():
# Relative positioning moves the ink and nothing else: the
# line box is laid out as if the span had not moved, which is
# what a baseline correction wants (vertical-align would
# re-lay the line). Negative top = up, as \raisebox in tex.
style += f"; position: relative; top: -{self.lift_length()}"
# The STYLE is markup, so its typographically active characters are
# hidden: the html target's transforms turn a single quote into a
# curly one, which broke the css font-family value. The MARKER is
@@ -81,7 +110,27 @@ class Typeface(klammer_base.Klammer_base):
# makes the change temporary (the retired @font emitted a bare
# \setmainfont, which changed the font for the rest of the
# document).
return "{" + typeface_marker(self.name, self.scale) + " " + self.text + "}"
group = "{" + typeface_marker(self.name, self.scale) + " " + self.text + "}"
if self.lift_length():
# A \raisebox produced HERE is safe from the generator escaping
# pass: this klammer is applied after a generator's result has
# been escaped, so its backslash is never swept -- the trap
# @nl.tex fell into (2026-09-07) is a klammer applied inside a
# generator's ARGUMENT, which @typeface shares with @b and @i.
return "\\raisebox{" + self.lift_length() + "}" + group
return group
def lift_length(self):
# :lift, validated to the units both targets can move by. The
# length argtype admits w/h fractions and a quoted string, which
# mean nothing as a vertical shift; a bare number would be columns
# or lines and is refused for the same reason.
lift = self.lift
if not lift:
return ""
if not re.fullmatch(r"-?(\d+\.?\d*|\.\d+)(em|pt|px)", lift):
raise Exception(f"@typeface :lift takes a length in em, pt or px, not '{lift}'")
return lift
def txt(self):
# A typeface cannot be expressed in plain text. Declared in the
+1 -42
View File
@@ -19,8 +19,7 @@ class Image(klammer_base.Klammer_base):
id = 0
def __init__(self, K, as_string=True, width=None):
super().__init__(K)
# pprint.pprint(self.__dict__)
# self.show()
# /dev/shm is a fast RAM-backed tmpfs on Linux; on macOS it does not
# exist, so fall back to the platform temp directory.
cache_dir = "/dev/shm"
@@ -47,22 +46,12 @@ class Image(klammer_base.Klammer_base):
def html(self):
img_dir = f"{self.K_output_dir}/{self.K_output_basename}/{self.Image_output_dir}"
# output_dir = self.K_output_dir or "."
# input_basename = self.__dict__.get("K_input_name", "")
# input_basename = "/" + input_basename if input_basename else ""
# img_dir = f"{output_dir}/{self.image_output_dir}{input_basename}"
#print("img_dir:", img_dir)
if not os.path.exists(img_dir):
os.makedirs(img_dir)
if not os.path.exists(f"{img_dir}/{os.path.basename(self.source)}"):
shutil.copy2(self.source, img_dir)
# width, scale_x, scale_y = kutil.parse_length(
# "html",
# self.width if self.width != "none" else self.image_default_width)
scale_x, scale_y = 1, 1 # Old
result = E("img")
@@ -72,9 +61,6 @@ class Image(klammer_base.Klammer_base):
filename = f"{self.Image_output_dir}/{os.path.basename(self.source)}"
result.attr("src", filename).attr("alt", os.path.basename(filename))
#if self.width:
# kutil.msg("rel: " + str(self.rel_fraction))
length, value, ltype = kutil.parse_width("html", self.width, self.rel_fraction)
if ltype == "w":
@@ -90,19 +76,6 @@ class Image(klammer_base.Klammer_base):
if self.border:
result.cls("image_border")
# print(result)
#result.attr("style", f"width: {width}")
# if width and width != "none":
# result.attr("style", f"width: {width}")
# if width == "none":
# if scale_x:
# result.attr("style", "width: 0px;")
# result.attr("scale-x", scale_x)
# elif scale_y:
# result.attr("style", "height: 0px;")
# result.attr("scale-y", scale_y)
if self.file_error:
self.caption += self.file_error_message
@@ -120,14 +93,7 @@ class Image(klammer_base.Klammer_base):
def tex(self):
# kutil.msg(f"number: {self.number}")
#selfsource, width, height = self.cache.get(self.K_target, self.basename)
source = os.path.abspath(self.source)
#if self.abswidth != 0:
# width = f"{self.abswidth}\\paperwidth"
#if self.caption or self.number:
# width = "\\textwidth"
#else:
width = kutil.parse_width("tex", self.width, self.rel_fraction)[0]
width = re.sub("px", "pt", width)
#result = f'\\includegraphics[width={width}]{{{source}}}'
@@ -138,8 +104,6 @@ class Image(klammer_base.Klammer_base):
result = latex_util.add_caption(
result, "Figure", self.number, self.caption, width,
self.hpos, self.caption_side, offset=self.offset)
#result, "Figure", self.number, self.caption, self.hpos, self.caption_side,
#self.width, self.caption_side_center, self.vmargin, self.caption_margin)
else:
result = f'\\includegraphics[width={width}]{{{source}}}'
result = latex_util.caption_wrapper(result, self.hpos, offset=self.offset)
@@ -150,8 +114,3 @@ class Image(klammer_base.Klammer_base):
# box material: it must sit in vertical mode or it is typeset beside
# any text it follows.
return latex_util.block(result)
# Better to cause an error; there's no good text substitute for an image
# def txt(self):
# return f"[Image: {self.basename}\nCaption: {self.caption}]"
-8
View File
@@ -1,4 +1,3 @@
import pprint
import re
import kutil
@@ -41,25 +40,18 @@ def hide_typographic(s):
class Klammer_base:
def __init__(self, K):
#args = {k:escape(v) for k, v in K.__dict__.items()
args = {k:v for k, v in K.__dict__.items()
if not k.startswith('__')}
for key in args:
setattr(self, key, args[key])
#setattr(self, "_klammer_name", klammer_name)
#pprint.pprint(self.__dict__)
def html(self):
#return '[{}: HTML]'.format(self.__class__.__name__)
return None
def tex(self):
#return '[{}: LaTeX]'.format(self.__class__.__name__)
return None
def txt(self):
#return '[{}: Plain text]'.format(self.__class__.__name__)
return None
def show(self, label=""):
+2 -1
View File
@@ -29,7 +29,8 @@ class List(klammer_base.Klammer_base):
body = "\n\n".join([f"\\item {e}" for e in self.items])
command = {'ol' : 'enumerate', 'ul' : 'itemize'}[self.list_type]
init = ""
if self.__dict__.get("initial") and self.initial != 1:
# :initial is @ol's alone (list.k); a @ul has no such attribute.
if getattr(self, "initial", 1) != 1:
init = "\\addtocounter{enumi}{" + str(self.initial - 1) + "}"
#topsep = '[noitemsep,topsep=0pt]'
topsep = "[noitemsep,topsep=0pt," if self.compressed else "[topsep=0pt,itemsep=2pt,"
+13 -8
View File
@@ -1,6 +1,11 @@
# Book-specific component headings (others possible to correspond to
# the front and back matter of a book):
@@section_args.o :id :n.int -1 :
Common arguments for section headings. If *n* is not the default, it is used
as the section number.
@@
@@preface.k :id :name Preface : Preface text @@
@@preface.html,tex,txt :: @eval section.Section(K, "preface") eval@ @@
@@ -9,30 +14,30 @@
@@part.k title :id :name Part : Part heading @@
@@part.html,tex,txt :: @eval section.Section(K, 0) eval@ @@
@@s1.k title :id :n : Top level division, numbered @@
@@s1.k title @section_args@ : Top level division, numbered @@
@@s1.html,tex,txt :: @eval section.Section(K, 1) eval@ @@
@@s2.k title :id :n : Second level division, numbered @@
@@s2.k title @section_args@ : Second level division, numbered @@
@@s2.html,tex,txt :: @eval section.Section(K, 2) eval@ @@
@@s3.k title :id :n : Third level division, numbered @@
@@s3.k title @section_args@ : Third level division, numbered @@
@@s3.html,tex,txt :: @eval section.Section(K, 3) eval@ @@
@@s4.k title :id :n : Fourth level division, numbered @@
@@s4.k title @section_args@ : Fourth level division, numbered @@
@@s4.html,tex,txt :: @eval section.Section(K, 4) eval@ @@
@@s5.k title :id :n : Fifth level division, numbered @@
@@s5.k title @section_args@ : Fifth level division, numbered @@
@@s5.html,tex,txt :: @eval section.Section(K, 5) eval@ @@
@@s6.k title :id :n : Sixth level division, numbered @@
@@s6.k title @section_args@ : Sixth level division, numbered @@
@@s6.html,tex,txt :: @eval section.Section(K, 6) eval@ @@
@@s7.k title :id :n : Seventh level division, numbered @@
@@s7.k title @section_args@ : Seventh level division, numbered @@
@@s7.html,tex,txt :: @eval section.Section(K, 7) eval@ @@
# Unnumbered section headings:
@@h1.k title :id :n : Top level division, unnumbered @@
@@h1.k title :id : Top level division, unnumbered @@
@@h1.html,tex,txt :: @eval section.Section(K, 1, numbered=False) eval@ @@
@@h2.k title :id : Second level division, unnumbered @@
+17 -8
View File
@@ -1,5 +1,6 @@
import kutil
import klammer_base
import phases
NUMBER_VAR = "___NUM___"
@@ -48,7 +49,6 @@ class Section(klammer_base.Klammer_base):
# names = "part chapter section subsection subsubsection paragraph subparagraph subsubparagraph subsubsubparagraph".split()
names = "part sA sB sC sD sE".split()
#self.show()
if self.id:
id = self.id
else:
@@ -56,13 +56,8 @@ class Section(klammer_base.Klammer_base):
Section.label_number += 1
result = ''
if self.__dict__.get("n") and self.n:
if getattr(self, "n", -1) > -1: # absent for @part and @h1..@h7
result += f'\\setcounter{{chapter}}{{{int(self.n)-1}}}\n'
#if self.id:
# result +=
#if self.level == 1:
#result += '\\newpage\n\n'
# result += '\\vspace*{24pt}'
suffix = "" if self.numbered else "*"
result += f'\\{names[self.level]}{suffix}{{{self.title}}}'
result += f'\n\\hypertarget{{{id}}}{{}}'
@@ -73,4 +68,18 @@ class Section(klammer_base.Klammer_base):
return result
def txt(self):
return f"@b {self.title} @"
# The number is a marker phases.txt_insert_section_numbers resolves
# -- to a number inside a @document, to nothing outside one -- so
# the space after it is the marker's, not the title's. A preface
# and an unnumbered heading carry no marker at all; a part carries
# a level-0 marker and its name, as the html "Part" prefix.
if self.preface:
return f"@b {self.name} @"
if not self.numbered:
return f"@b {self.title} @"
# :n comes from section_args, which @part and the @h headings do
# not declare, so it is absent there rather than -1.
marker = phases.txt_section_marker(self.level, getattr(self, "n", -1))
if self.level == 0:
return f"@b {marker} {self.name} {self.title} @"
return f"@b {marker} {self.title} @"
+7 -2
View File
@@ -12,8 +12,13 @@ tr:first-child {
td {
/* padding-left: 1rem; */
padding: .1rem .5rem .2rem .5rem;
/* Vertical space is the table's line-height (:leading, set on the
<table> by table.py -- the html equivalent of \arraystretch), so no
vertical padding here: it was an html-only extra that kept rows
looser than the pdf's. Horizontal padding is :colsep, the same
value that becomes \tabcolsep; the fallback is for a table that
reaches this rule without the property. */
padding: 0 var(--colsep, 4pt);
vertical-align: top;
}
+20 -2
View File
@@ -575,6 +575,24 @@ class Table(klammer_base.Klammer_base):
# would wrap it as a stray <p> inside the table.
return E("colgroup").body(cols.strip(), newline=False).str(), layout, table_width
def html_style(self):
# :leading and :colsep under html (2026-09-18; both were tex-only).
# \arraystretch multiplies the row strut, which is \baselineskip,
# 1.2 times the font size -- so :leading L is a 1.2 L em row, and
# the html equivalent is that line-height on the table, inherited
# by every cell. The cells' vertical padding went with it
# (table.css): an html-only extra with no tex counterpart, which
# kept a :leading 1 table 0.3rem looser per row than its pdf.
# :colsep is a custom property the td rule reads for its horizontal
# padding (padding does not inherit); the flush-edge classes still
# zero the outer ones. Measured 2026-09-18: rows of :leading 1 and
# :leading 2 in the ratio 1:2 in both targets.
line_height = f"{1.2 * float(self.leading):.4g}"
# Hidden: the result is re-read and the html target's transforms
# would turn the property's "--" into an en dash (font.py's trap).
return klammer_base.hide_typographic(
f"line-height: {line_height}; --colsep: {self.colsep}")
def html(self):
result = ""
for row_i, row in enumerate(self.cells):
@@ -592,7 +610,7 @@ class Table(klammer_base.Klammer_base):
# algorithm), matching the tex \ratio division. The max-width
# cap goes on the caption wrapper when there is one (the table's
# own percentage would be circular in a shrink-to-fit wrapper).
result = E("table").body(result)
result = E("table").body(result).attr("style", self.html_style())
if self.number or self.caption:
result = html_util.add_caption(
result, "Table", self.number, self.caption,
@@ -605,7 +623,7 @@ class Table(klammer_base.Klammer_base):
result = html_util.hpos_container(result, self.hpos, self.offset).str()
return result
colgroup, layout, table_width = self.html_colgroup()
result = E("table").body(colgroup + result)
result = E("table").body(colgroup + result).attr("style", self.html_style())
if self.number or self.caption:
# The caption wrapper carries the width (a percentage on the
# shrink-to-fit wrapper itself would be circular) and the table
+44
View File
@@ -248,6 +248,50 @@ def txt_format_footnotes(text, K):
+ label + " " + footnote + "\n\n")
return result
# Section numbering under txt (2026-09-18). Numbering is a DOCUMENT
# service, as it is in html (a pass @document runs over the page) and tex
# (LaTeX's own counters inside the document): a heading rendered outside
# a @document -- kdesc's renders of the ref/ generators -- is not
# numbered. Document.txt() (sks/document/document_txt.py) opens its
# result with the document marker; Section.txt() emits a section marker
# carrying the level and the :n override; this phase, first in the txt
# and ansi lists, numbers the headings when the document marker is there
# and strips every marker either way. A heading at a level with no
# parent numbers as "0.1", as html and tex print it -- the txt target
# does not diverge from them. The single-source functions are the
# TODO #47 pattern.
def txt_document_marker():
return "__KTEXTDOCUMENT__"
def txt_section_marker(level, n=-1):
# LEVEL 0 is a part, 1-7 the sections; N > -1 sets the number.
return f"__KTEXTSECTION__{level}__{n}__"
def txt_insert_section_numbers(text, K):
# The marker is the first thing the document emits, but the result
# reaches the phase behind whatever newlines the apply left in front.
head = text.lstrip()
in_document = head.startswith(txt_document_marker())
if in_document:
text = head[len(txt_document_marker()):].lstrip("\n")
levels = [0] * 8 # 0: parts; 1-7: sections (parts do not reset them, as in LaTeX)
marker_rgx = re.compile(r"__KTEXTSECTION__(\d+)__(-?\d+)__ ?")
def number(match):
if not in_document:
return ""
level, n = int(match.group(1)), int(match.group(2))
levels[level] = n if n > -1 else levels[level] + 1
if level == 0:
return f"{levels[0]} " # a part resets nothing below it
for i in range(level + 1, len(levels)):
levels[i] = 0
return ".".join(str(v) for v in levels[1:level + 1]) + " "
return marker_rgx.sub(number, text)
# HTML
def html_footnote_marker():
return "kt-footnote"
+2
View File
@@ -63,6 +63,7 @@ of this: neither the transforms nor the quoting reach it.
' ' |
~ __KTEXTNBSP__
:after_apply
phases.txt_insert_section_numbers ;
phases.txt_format_footnotes ;
phases.txt_insert_captions ;
phases.txt_justify_blocks ;
@@ -83,6 +84,7 @@ of this: neither the transforms nor the quoting reach it.
@@@target ansi | Plain text with ANSI escape sequences for type styles
:includes txt
:after_apply
phases.txt_insert_section_numbers ;
phases.txt_format_footnotes ;
phases.txt_insert_captions ;
phases.txt_justify_blocks ;