rsyntaxtree 2.6.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: eb96318785756ecb47e67a06a809eb96bde5c4f63ceda113c13ba9bb221d032c
4
- data.tar.gz: 48f083c0cec6539557959b0205e61c503f2aeeb68dea8b06ba3e5faf3b8dba6e
3
+ metadata.gz: 5e475a4be7e86a3711b0bae566fa74360b099c9f3e3c021226b0b85e20e6c75a
4
+ data.tar.gz: ab88b55b26314b5867fa6775b0d0ea1d24927d278e63f7d182bb6d21ded83f9a
5
5
  SHA512:
6
- metadata.gz: fdd263b44eea3a6106bbdf504fe603d966e505d7f9b92251979fd373b5f50ddb15a686d87a3d9ec1ac6ce46d90a1153cfe79637063dabc3953542d66657d25c0
7
- data.tar.gz: 37ba04230f1909bf30433f67ea51e283f19b9f45eccee865912eaee7fbb7d272bdd28d340f055d17716f92e02352ad5459cac9b29a8366dfc75e657d2fc1886d
6
+ metadata.gz: 4f4f85b37c02d5142403ea517e4e8d9637fb4902399fa541473f795c3485e5821f6254e35ceea8c528cc9dfc313e5e257186cfea401d7c99e26fd469b3c1aff0
7
+ data.tar.gz: ba9057d0cd782d041fa3d34b05424eed8abe0886b8472bf9208722377fd2e8d5c442dcef941d8d1fa9c4ebf2ff28a2d716fb288cc1db7c042877c7217b687334
data/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.8.0] - 2026-11-18
4
+
5
+ ### Added
6
+ - `corner_label` (`--corner-label`): a short string, such as a judgement mark, set in a corner of the image beside the tree, with its position, size, colour and font style
7
+ - `@red(...)` and `@#3af(...)` colour part of a label: the words, decorations and shapes inside, outlines and hatching included
8
+
9
+ ### Changed
10
+ - `@` followed by a colour name and `(` now opens a coloured stretch: write `\@` where an `@` is meant as a character, as in `mail\@example(x)`
11
+ - `tidy: high` no longer closes a pair of branches far narrower than the pairs below it
12
+ - `mirror` with `direction: ltr` is refused with a hint, since its connectors were drawn through the labels
13
+ - A movement path to a phrase stops at the edge of the phrase and its shade instead of running through them to the label
14
+
15
+ ### Fixed
16
+ - A movement path no longer runs over a label packed under its end in `tidy` low, medium and high
17
+ - TikZ output writes `&`, `<`, `>` and backslashes in labels as characters, so the code compiles
18
+ - JSON labels carry `&` as a character rather than `&amp;`
19
+
3
20
  ## [2.6.0] - 2026-11-12
4
21
 
5
22
  ### Added
data/CITATION.cff CHANGED
@@ -11,8 +11,8 @@ repository-code: "https://github.com/yohasebe/rsyntaxtree"
11
11
  # Concept DOI: always resolves to the latest archived version on Zenodo
12
12
  doi: "10.5281/zenodo.21916150"
13
13
  license: MIT
14
- version: 2.6.0
15
- date-released: 2026-11-12
14
+ version: 2.8.0
15
+ date-released: 2026-11-18
16
16
  keywords:
17
17
  - linguistics
18
18
  - syntax tree
data/README.md CHANGED
@@ -165,7 +165,7 @@ Usage:
165
165
  |--------|-------------|---------|
166
166
  | `-o, --outdir` | Output directory | `./` |
167
167
  | `-f, --format` | Output format: png, svg, pdf, json, tikz | `png` |
168
- | `-l, --leafstyle` | Leaf style: auto, triangle, bar, nothing | `auto` |
168
+ | `-l, --leafstyle` | Leaf style: auto, triangle, bar, dashed, nothing | `auto` |
169
169
  | `-n, --fontstyle` | Font style: sans, serif, cjk, mono | `sans` |
170
170
  | `-s, --fontsize` | Font size: 6-26 | `16` |
171
171
  | `-i, --linewidth` | Line width relative to the font size: 0.5-3.0 (`1` = 5% of the font size) | `1.0` |
@@ -179,10 +179,15 @@ Usage:
179
179
  | `-v, --vheight` | How far apart levels sit (0.5-5.0) | `2.0` |
180
180
  | `--derivation` | Join each node to its daughters with one rule drawn across them: on, off | `off` |
181
181
  | `--hyphen` | How a hyphen reads: markup (`-underline-`) or literal | `markup` |
182
- | `-m, --mirror` | Flip the tree horizontally (RTL convention): on, off | `off` |
182
+ | `-m, --mirror` | Flip the tree horizontally (RTL convention), not with ltr: on, off | `off` |
183
183
  | `--shear` | Tilt the drawn figure, in degrees (-45 to 45, positive leans the top right) | `0` |
184
184
  | `--shear-plane` | The plane behind a sheared figure: on, off, or a colour | `on` |
185
185
  | `--vmargin` | Clearance between a label and its connectors (0.1-1.0, same above and below) | `0.4` |
186
+ | `--corner-label` | A short string set in a corner of the image, as written (no markup), such as a judgement mark | |
187
+ | `--corner-label-position` | Which corner: top-left, top-right, bottom-left, bottom-right | `top-left` |
188
+ | `--corner-label-size` | Size of the corner label (6-52) | 1.5 × font size |
189
+ | `--corner-label-color` | Colour of the corner label: a colour name or hex | `black` |
190
+ | `--corner-label-fontstyle` | Font style of the corner label: sans, serif, cjk, mono | font style |
186
191
  | `-r, --transparent` | Leave the background clear instead of painting it white: on, off | `off` |
187
192
  | `--validate` | Check the input without drawing: a JSON diagnosis on stdout, the verdict in the exit code | |
188
193
  | `--notation` | Print a short reference for the notation | |
data/bin/rsyntaxtree CHANGED
@@ -35,7 +35,12 @@ CONFIG_VALIDATORS = {
35
35
  tidy: ->(v) { OPTION_VALUES[:tidy].include?(v.to_s) ? nil : "must be off, symmetric, low, medium, or high" },
36
36
  hspacing: ->(v) { v.is_a?(Numeric) && v >= 0.5 && v <= 3.0 ? nil : "must be in the range of 0.5-3.0" },
37
37
  direction: ->(v) { OPTION_VALUES[:direction].include?(v.to_s) ? nil : "must be one of: #{OPTION_VALUES[:direction].join(', ')}" },
38
- hyphen: ->(v) { OPTION_VALUES[:hyphen].include?(v.to_s) ? nil : "must be markup or literal" }
38
+ hyphen: ->(v) { OPTION_VALUES[:hyphen].include?(v.to_s) ? nil : "must be markup or literal" },
39
+ corner_label: ->(v) { v.is_a?(String) ? nil : "must be a string" },
40
+ corner_label_position: ->(v) { OPTION_VALUES[:corner_label_position].include?(v.to_s) ? nil : "must be top-left, top-right, bottom-left, or bottom-right" },
41
+ corner_label_size: ->(v) { v.is_a?(Numeric) && NUMERIC_RANGES[:corner_label_size].cover?(v) ? nil : "must be in the range of 6-52" },
42
+ corner_label_color: ->(v) { RSyntaxTree::COLOR_NAMES.include?(v.to_s.downcase) || v.to_s =~ /\A#(\h{3}|\h{6})\z/ ? nil : "must be a colour name or a hex colour" },
43
+ corner_label_fontstyle: ->(v) { OPTION_VALUES[:corner_label_fontstyle].include?(v.to_s) ? nil : "must be sans, serif, cjk, or mono" }
39
44
  }.freeze
40
45
 
41
46
  # Validate configuration and return errors/warnings
@@ -128,6 +133,11 @@ opts = Optimist.options do
128
133
  opt :hspacing, "Horizontal spacing factor (counterpart of vheight): 0.5-3.0", default: 1.0, short: :none
129
134
  opt :direction, "Tree layout direction: ttb (top-to-bottom), ltr (left-to-right) or btt (bottom-to-top, the root last)", default: "ttb", short: :d
130
135
  opt :derivation, "Join each node to its daughters with one rule drawn across them, as a derivation is written, rather than with a line to each: on, off", default: "off", short: :none
136
+ opt :corner_label, "A short string set in a corner of the image, as written (no markup), such as a judgement mark", type: :string, short: :none
137
+ opt :corner_label_position, "Where the corner label goes: top-left, top-right, bottom-left, or bottom-right", default: "top-left", short: :none
138
+ opt :corner_label_size, "Size of the corner label: 6-52 (default: 1.5 times fontsize)", type: :float, short: :none
139
+ opt :corner_label_color, "Colour of the corner label: a colour name or a hex colour (default: black)", type: :string, short: :none
140
+ opt :corner_label_fontstyle, "Font style of the corner label: sans, serif, cjk, mono (default: fontstyle)", type: :string, short: :none
131
141
  opt :hyphen, "How a hyphen in a label reads: markup (-underline-) or literal (a hyphen; \-underline\- then underlines)", default: "markup", short: :none
132
142
  opt :validate, "Validate the input without drawing or writing a file: print a machine-readable diagnosis (JSON) to stdout and report the result in the exit code", short: :none
133
143
  opt :notation, "Print the notation reference to stdout and exit", short: :none
@@ -620,6 +620,12 @@ module RSyntaxTree
620
620
  # the :ordered nest mode only; see tidy_compress.
621
621
  TIDY_LEVEL_BALANCE = 1.0
622
622
 
623
+ # The same floor in the :free nest mode, set lower so that the mode keeps
624
+ # most of its density: a pair may close to this fraction of the widest
625
+ # pair below it, which still opens the narrowest branches up, the ones
626
+ # that stood steep beside the flat branches of a level further down.
627
+ TIDY_LEVEL_BALANCE_FREE = 0.8
628
+
623
629
  # Base multiplier for the minimum clearance between adjacent subtrees.
624
630
  # At 1.0 (= raw h_gap_between_nodes) leaf labels sit closer than in the
625
631
  # standard layout, which reads as crowded; 2.5 restores comparable air
@@ -682,6 +688,37 @@ module RSyntaxTree
682
688
  rects
683
689
  end
684
690
 
691
+ # Below each end of a movement path in the subtree, the column its line
692
+ # runs down on its way to the rail under the tree: packing a neighbour
693
+ # into it put a word under the line. Laid out before any flip or turn,
694
+ # the line always leaves towards larger y. Lines between nodes (+-1) are
695
+ # drawn straight across and need no column. A tree without a movement
696
+ # path is not walked for them.
697
+ def path_columns(id)
698
+ return [] unless path_columns?
699
+
700
+ columns = []
701
+ stack = [@element_list.get_id(id)]
702
+ until stack.empty?
703
+ node = stack.pop
704
+ if path_end?(node)
705
+ y0, y1, x0, x1 = effective_rect(node)
706
+ columns << [y1, Float::INFINITY, x0, x1] if y1 > y0
707
+ end
708
+ node.children.each { |c| stack << @element_list.get_id(c) }
709
+ end
710
+ columns
711
+ end
712
+
713
+ def path_columns?
714
+ @has_path_ends = @element_list.get_elements.any? { |e| path_end?(e) } if @has_path_ends.nil?
715
+ @has_path_ends
716
+ end
717
+
718
+ def path_end?(node)
719
+ node.path.any? { |marker| !marker.start_with?("-") }
720
+ end
721
+
685
722
  # [leftmost leaf center, rightmost leaf center] of the subtree rooted
686
723
  # at +id+, or nil when the subtree has no leaf.
687
724
  def subtree_leaf_center_span(id)
@@ -783,8 +820,16 @@ module RSyntaxTree
783
820
  parents = @element_list.get_elements.reject { |e| e.children.empty? }
784
821
  parents.sort_by { |p| [-p.level, -p.id] }.each do |parent|
785
822
  children = parent.children.map { |c| @element_list.get_id(c) }
823
+ # A path's column reaches down past sisters that end higher up, so in
824
+ # a tree with movement paths a sister is packed against everything
825
+ # placed before it — the labels and columns of every earlier sister.
826
+ # Without paths only the neighbour can be in the way, and comparing
827
+ # with it alone keeps a long row of sisters from growing quadratic.
828
+ placed = []
786
829
  children.each_cons(2) do |left_child, right_child|
787
- clearance = contour_clearance(subtree_rects(left_child.id), subtree_rects(right_child.id))
830
+ placed = [] unless path_columns?
831
+ placed.concat(subtree_rects(left_child.id), path_columns(left_child.id))
832
+ clearance = contour_clearance(placed, subtree_rects(right_child.id) + path_columns(right_child.id))
788
833
  delta = clearance.nil? ? 0.0 : tidy_gap - clearance
789
834
 
790
835
  case @tidy_nest
@@ -809,26 +854,27 @@ module RSyntaxTree
809
854
  end
810
855
  end
811
856
 
812
- # Level-balance floor (:ordered only): keep the pair at least a
813
- # fraction of the widest child-level spread found inside its own
814
- # two subtrees. Nesting can tuck an upper pair far narrower than
815
- # the level right below it — an inversion that reads as a
816
- # needle-thin top over flat lower branches.
857
+ # Level-balance floor: keep the pair at least a fraction of the
858
+ # widest child-level spread found inside its own two subtrees.
859
+ # Nesting can tuck an upper pair far narrower than the level right
860
+ # below it — an inversion that reads as a needle-thin top over flat
861
+ # lower branches.
817
862
  #
818
863
  # :none does not need it, since the leaf-span guard already
819
- # prevents such inversions. :free deliberately goes without: it is
820
- # the end of the scale where density outranks even branch angles,
821
- # and with the floor in place it compressed no further than
822
- # :ordered on all but a handful of trees.
864
+ # prevents such inversions. :free, the end of the scale where
865
+ # density comes first, takes a weaker floor: at full strength it
866
+ # compressed no further than :ordered on all but a handful of
867
+ # trees, and with none, a bare word beside a phrase stood at a
868
+ # sharply steeper angle than the levels around it.
823
869
  #
824
870
  # Compression is a negative delta (the right subtree moves left),
825
871
  # so the floor bounds delta from below.
826
- if @tidy_nest == :ordered && delta.negative?
872
+ if %i[ordered free].include?(@tidy_nest) && delta.negative?
827
873
  dist = (right_child.horizontal_indent + right_child.content_width / 2.0) -
828
874
  (left_child.horizontal_indent + left_child.content_width / 2.0)
829
875
  below = [left_child, right_child].map { |c| child_spread(c) }.compact.max
830
876
  if below
831
- min_dist = below * TIDY_LEVEL_BALANCE
877
+ min_dist = below * (@tidy_nest == :free ? TIDY_LEVEL_BALANCE_FREE : TIDY_LEVEL_BALANCE)
832
878
  delta = [delta, min_dist - dist].max
833
879
  end
834
880
  end
@@ -49,7 +49,11 @@ module RSyntaxTree
49
49
  # of the rule.
50
50
  if global && global[:derivation] && names_a_rule
51
51
  at = rule_name_break(content)
52
- name = at && content[(at + 2)..].to_s.strip
52
+ # Parentheses are escaped for the label's markup, not for the name:
53
+ # the backslash that escapes one goes, a pair of backslashes stays.
54
+ name = at && content[(at + 2)..].to_s.strip.gsub(/(\\+)([()])/) do
55
+ $1.size.odd? ? $1[0..-2] + $2 : $1 + $2
56
+ end
53
57
  if name && !name.empty?
54
58
  @rule_name = name
55
59
  # Kept whole, because whether this node has daughters — and so
@@ -80,6 +84,8 @@ module RSyntaxTree
80
84
  @region_color = results[:region_color]
81
85
  validate_color!(@color, content)
82
86
  validate_color!(@region_color, content)
87
+ Element.span_colors(@content).each { |c| validate_color!(c, content) }
88
+ Element.join_colour_runs(@content)
83
89
 
84
90
  @contains_phrase = false
85
91
  setup
@@ -134,6 +140,53 @@ module RSyntaxTree
134
140
  # "C++11" and "2+2" was read as one end of a movement path.
135
141
  PATH_MARKERS = /(?:\+-?>?<?\d+)+/
136
142
 
143
+ # The colours of the coloured stretches in a label's lines, nested
144
+ # matrices included.
145
+ def self.span_colors(lines)
146
+ lines.flat_map do |line|
147
+ next [] unless line[:type] == :text
148
+
149
+ line[:elements].flat_map do |e|
150
+ [*e[:span_colors], *(e[:matrix] ? span_colors(e[:matrix]) : [])]
151
+ end
152
+ end
153
+ end
154
+
155
+ # Runs that differ only in colour are one stretch of text, measured and
156
+ # set as one so that kerning and the joining of a script carry across the
157
+ # change; each part keeps its colour. Only runs with a colour are joined,
158
+ # so a label without one is laid out as it always was.
159
+ SET_APART = %i[box circle bar whitespace tabstop matrix].freeze
160
+
161
+ def self.join_colour_runs(lines)
162
+ lines.each do |line|
163
+ next unless line[:type] == :text
164
+
165
+ joined = []
166
+ line[:elements].each do |e|
167
+ join_colour_runs(e[:matrix]) if e[:matrix]
168
+ prev = joined.last
169
+ if prev && (prev[:parts] || prev[:color] || e[:color]) &&
170
+ prev[:decoration] == e[:decoration] && (e[:decoration] & SET_APART).empty?
171
+ prev[:parts] ||= [[prev[:text], prev[:color]]]
172
+ prev[:parts] << [e[:text], e[:color]]
173
+ prev[:text] += e[:text]
174
+ prev[:color] = nil
175
+ else
176
+ joined << e
177
+ end
178
+ end
179
+ line[:elements] = joined
180
+ end
181
+ end
182
+
183
+ # A label's text as written. What is drawn keeps &, < and > as the SVG
184
+ # entities the input is read into; the formats that are not SVG want the
185
+ # characters back.
186
+ def self.plain_text(text)
187
+ text.gsub("&#60;", "<").gsub("&#62;", ">").gsub("&amp;", "&")
188
+ end
189
+
137
190
  # Splits a label into what is drawn and its trailing path text, the
138
191
  # latter empty when there is none. A label that is nothing but markers
139
192
  # has no path: there would be nothing to draw them from.
@@ -177,6 +230,13 @@ module RSyntaxTree
177
230
  @global[:literal_hyphen] ? swap_hyphen_markup(text) : text
178
231
  end
179
232
 
233
+ # The opening of a coloured stretch, after an even run of backslashes
234
+ # (which are literal backslashes, so the '@' is not escaped), and a line
235
+ # or column break written \n or \t in the same way.
236
+ SPAN_OPENER = /(?<!\\)((?:\\\\)*)@(?:#\h{6}|#\h{3}|[a-zA-Z]+)\(/
237
+ EMPTY_SPAN = /(?<!\\)((?:\\\\)*)@(?:#\h{6}|#\h{3}|[a-zA-Z]+)\(\)/
238
+ UNESCAPED_BREAK = /(?<!\\)(?:\\\\)*\\[nt]/
239
+
180
240
  # One candidate repair per way of getting the notation wrong, tried in
181
241
  # order. Each is a whole edit of the label, not a pattern to recognise:
182
242
  # the diagnosis below applies one and asks the parser whether the label
@@ -188,8 +248,8 @@ module RSyntaxTree
188
248
  # bare '#' or '@' behind that the enclosure repair below would happily
189
249
  # blame itself for. Tried first, so a color mistake is named as one.
190
250
  [:invalid_color,
191
- ->(s) { s.sub(/\A%?@(?:#[0-9a-zA-Z]+|[a-zA-Z]+)?:/, "") },
192
- "A color is @name: with a CSS color name, or @#rgb: / @#rrggbb: with 3 or 6 hex digits (e.g. @blue:VP, @#3af:VP)."],
251
+ ->(s) { s.sub(/\A%?@(?:#[0-9a-zA-Z]+|[a-zA-Z]+)?:/, "").gsub(/(?<!\\)@#(?!(?:\h{6}|\h{3})\()[0-9a-zA-Z]*\(/, "\\(") },
252
+ "A color is @name: with a CSS color name, or @#rgb: / @#rrggbb: with 3 or 6 hex digits (e.g. @blue:VP, @#3af:VP, @red(word))."],
193
253
  [:angle_brackets,
194
254
  ->(s) { s.gsub(/(?<!\\)<([^<>]*[^<>\d][^<>]*)>/) { "⟨#{$1}⟩" } },
195
255
  "'<' and '>' mark whitespace here, not a list. Write the angle bracket characters themselves: ⟨NP⟩, 'hand⟨SUBJ,OBJ⟩'."],
@@ -204,6 +264,37 @@ module RSyntaxTree
204
264
  [:unclosed_matrix,
205
265
  ->(s) { s.scan("#(").size > s.scan("#)").size ? s + "#)" : s },
206
266
  "A matrix opened with '#(' is never closed with '#)'."],
267
+ # A coloured stretch left open, or written inside other markup. Asked
268
+ # before the single characters below, whose repairs would also get the
269
+ # label through and name the wrong mistake.
270
+ [:empty_markup,
271
+ # Filled rather than removed: a label of nothing but the stretch would
272
+ # be left with nothing to parse.
273
+ ->(s) { s.gsub(EMPTY_SPAN, '\\1x') },
274
+ "A coloured stretch @color() is empty: put what it colours inside it, or take it out."],
275
+ # Closed where it has to end: at the next line or column break, or else
276
+ # before the path markers at the end of the label.
277
+ [:unclosed_markup,
278
+ ->(s) {
279
+ opener = s.match(SPAN_OPENER)
280
+ break_at = opener && s.match(UNESCAPED_BREAK, opener.end(0))
281
+ next s unless break_at && break_at.end(0) <= Element.split_path(s).first.size
282
+
283
+ s.dup.insert(break_at.end(0) - 2, ")")
284
+ },
285
+ "A coloured stretch @color(...) closes within its line or cell: close it before the \\n or \\t, " \
286
+ "and give the next its own, as in @red(a)\\t@red(b)."],
287
+ [:unclosed_markup,
288
+ ->(s) {
289
+ next s unless s.match?(SPAN_OPENER)
290
+
291
+ label, path = Element.split_path(s)
292
+ "#{label})#{path}"
293
+ },
294
+ "A coloured stretch @color(...) is never closed with ')'; a ')' inside one is written \\)."],
295
+ [:unclosed_markup,
296
+ ->(s) { s.gsub(SPAN_OPENER, '\\1') },
297
+ "A coloured stretch sits inside other markup: put the colour outside, as in @red(**word**)."],
207
298
  # A derivation writes the name of each step after a column break, and
208
299
  # the combinators it is written with are made of the same characters as
209
300
  # the whitespace marker. Read as an ordinary tree such a label is
@@ -278,7 +369,8 @@ module RSyntaxTree
278
369
  "\n > #{content}",
279
370
  code: :unknown_color,
280
371
  label: content,
281
- hint: "Use a CSS color name or a hex code: @blue:VP, @#3af:VP, @#33aaff:VP.",
372
+ hint: "Use a CSS color name or a hex code: @blue:VP, @#3af:VP, @#33aaff:VP, or @blue(word) " \
373
+ "for part of a label. Write \\@ for an @ meant as a character.",
282
374
  retryable: true)
283
375
  end
284
376
 
@@ -308,6 +400,24 @@ module RSyntaxTree
308
400
  # carries an extra margin that holds the text clear of the connector above
309
401
  # it; a nested block sits inside that margin already, so counting it again
310
402
  # would leave a bracket half a line taller than the rows it encloses.
403
+ # A run's text as it is set: escaped square brackets as themselves, and a
404
+ # straight ASCII apostrophe (U+0027) as a curly one (U+2019) for smarter
405
+ # typography, e.g. the X-bar prime in "T'". Applied before metrics so the
406
+ # measured glyph matches the rendered one.
407
+ def typeset(text)
408
+ text.gsub('\\[', '[').gsub('\\]', ']').gsub("'", "’").gsub(Markup::KEPT_APOSTROPHE, "'")
409
+ end
410
+
411
+ # A run's text as it is measured.
412
+ def measurable(text)
413
+ text.gsub("\\\\", 'i').gsub("\\", "").gsub(" ", "x").gsub("%", "X")
414
+ end
415
+
416
+ # A run's text as the drawing keeps it.
417
+ def stored(text)
418
+ text.gsub(" ", WHITESPACE_BLOCK).gsub(">", '&#62;').gsub("<", '&#60;')
419
+ end
420
+
311
421
  def measure_lines(lines, nested: false)
312
422
  total_width = 0
313
423
  total_height = 0
@@ -379,18 +489,10 @@ module RSyntaxTree
379
489
  cell_start = false
380
490
  end
381
491
 
382
- text = e[:text]
383
- # Handle escaped square brackets
384
- text = text.gsub('\\[', '[')
385
- .gsub('\\]', ']')
386
- # Typographic apostrophe: render a straight ASCII apostrophe (U+0027)
387
- # as a curly apostrophe (U+2019) for smarter typography, e.g. the
388
- # X-bar prime in "T'". Applied before metrics so the measured glyph
389
- # matches the rendered one.
390
- text = text.gsub("'", "’").gsub(Markup::KEPT_APOSTROPHE, "'")
391
- e[:text] = text.gsub(" ", WHITESPACE_BLOCK)
392
- .gsub(">", '&#62;')
393
- .gsub("<", '&#60;')
492
+ text = typeset(e[:text])
493
+ e[:text] = stored(text)
494
+ typed_parts = e[:parts]&.map { |part, _| typeset(part) }
495
+ e[:parts]&.each_with_index { |part, i| part[0] = stored(typed_parts[i]) }
394
496
 
395
497
  @contains_phrase = true if text.include?(" ")
396
498
  decoration = e[:decoration]
@@ -428,12 +530,16 @@ module RSyntaxTree
428
530
  width += metrics.width
429
531
  end
430
532
  else
431
- text.gsub!("\\\\", 'i')
432
- text.gsub!("\\", "")
433
- text.gsub!(" ", "x")
434
- text.gsub!("%", "X")
533
+ text = measurable(text)
435
534
  metrics = FontMetrics.get_metrics(text, font, fontsize, style, weight)
436
535
  width = metrics.width
536
+ # A renderer may set each colour of a stretch on its own and
537
+ # drop the kerning between them, so the stretch has room for
538
+ # its parts set apart as well as together.
539
+ if typed_parts
540
+ apart = typed_parts.sum { |t| FontMetrics.get_metrics(measurable(t), font, fontsize, style, weight).width }
541
+ width = [width, apart].max
542
+ end
437
543
  end
438
544
 
439
545
  if e[:decoration].include?(:box) || e[:decoration].include?(:circle) || e[:decoration].include?(:bar)
@@ -218,21 +218,29 @@ module RSyntaxTree
218
218
  element.content.each do |l|
219
219
  next unless l[:type] == :text
220
220
 
221
- segments = l[:elements].map { |e| build_segment(e) }.compact
221
+ segments = l[:elements].flat_map { |e| build_segments(e) }
222
222
  lines << { segments: segments } unless segments.empty?
223
223
  end
224
224
 
225
225
  {
226
- raw: element.raw_content,
226
+ raw: Element.plain_text(element.raw_content.to_s),
227
227
  lines: lines
228
228
  }
229
229
  end
230
230
 
231
+ # A run set as one stretch with parts in different colours is a segment
232
+ # per part, as it was written.
233
+ def build_segments(run)
234
+ return [build_segment(run)].compact unless run[:parts]
235
+
236
+ run[:parts].filter_map { |text, color| build_segment(run.merge(text: text, color: color, parts: nil)) }
237
+ end
238
+
231
239
  def build_segment(run)
232
240
  return nil if run[:decoration].include?(:whitespace) && run[:text].strip.empty?
233
241
 
234
242
  segment = {
235
- text: run[:text].gsub(WHITESPACE_BLOCK, " ").gsub('&#62;', '>').gsub('&#60;', '<'),
243
+ text: Element.plain_text(run[:text].gsub(WHITESPACE_BLOCK, " ")),
236
244
  decorations: run[:decoration].map(&:to_s).reject { |d| d == "whitespace" }
237
245
  }
238
246
  # A feature matrix used to reach this document as an empty segment
@@ -242,6 +250,7 @@ module RSyntaxTree
242
250
  # cells split on the tab stops, rules kept as rows of their own, a
243
251
  # matrix inside a cell recursing.
244
252
  segment[:matrix] = { rows: build_matrix_rows(run[:matrix]) } if run[:decoration].include?(:matrix) && run[:matrix]
253
+ segment[:color] = run[:color] if run[:color]
245
254
  segment
246
255
  end
247
256
 
@@ -256,8 +265,7 @@ module RSyntaxTree
256
265
  if run[:decoration].include?(:tabstop)
257
266
  cells << []
258
267
  else
259
- segment = build_segment(run)
260
- cells.last << segment if segment
268
+ cells.last.concat(build_segments(run))
261
269
  end
262
270
  end
263
271
  { cells: cells }
@@ -341,6 +349,9 @@ module RSyntaxTree
341
349
  edges: @edges,
342
350
  paths: @paths_data
343
351
  }
352
+ # The mark set in a corner of the image, with its defaults filled in;
353
+ # absent when there is none.
354
+ data[:meta][:source][:params][:corner_label] = @params[:corner] if @params[:corner]
344
355
  JSON.pretty_generate(data)
345
356
  end
346
357
  end
@@ -39,12 +39,12 @@ class MarkupParser < Parslet::Parser
39
39
 
40
40
  rule(:path) { (str('+') >> str('-').maybe >> (str('>') | str('<')).maybe >> match('\d').repeat(1)).as(:path) }
41
41
  # rule(:escaped) { str('\\') >> match('[#<>{}\\^+*_=~\|\n\-]').as(:chr) }
42
- rule(:escaped) { str('\\') >> match('[#<>{}\\\\^+*_=~\\|\\n\\-\\[\\]%@]').as(:chr) }
42
+ rule(:escaped) { str('\\') >> match('[#<>{}\\\\^+*_=~\\|\\n\\-\\[\\]%@()]').as(:chr) }
43
43
  # A straight apostrophe is set as a curly one; `\'` asks for the straight
44
44
  # one itself. It comes through as a placeholder so the substitution, which
45
45
  # runs later on the joined text, can tell the two apart.
46
46
  rule(:kept_apostrophe) { str("\\'").as(:kept_apostrophe) }
47
- rule(:non_escaped) { ((match('[#<>{}\\^+*_=~\|\-]') | str('\\n') | str('\\t')).absent? >> any).as(:chr) }
47
+ rule(:non_escaped) { ((match('[#<>{}\\^+*_=~\|\-]') | str('\\n') | str('\\t') | span_open).absent? >> any).as(:chr) }
48
48
  rule(:text) { (kept_apostrophe | escaped | non_escaped).repeat(1).as(:text) }
49
49
 
50
50
  # Column separator. Every line of a label is cut at these into cells, and
@@ -89,11 +89,19 @@ class MarkupParser < Parslet::Parser
89
89
  # in labels too often to claim.
90
90
  rule(:matrix) { str('#(') >> matrix_line.repeat(1).as(:matrix) >> str('#)') }
91
91
  rule(:matrix_line) { (rule_line | double_rule_line | matrix_markup.repeat(1).as(:line)) >> (cr | str('#)').present?) }
92
- rule(:matrix_markup) { (matrix | tabstop | matrix_text | decoration | shape | bstroke) }
92
+ rule(:matrix_markup) { (matrix | tabstop | colored | matrix_text | decoration | shape | bstroke) }
93
93
  # Text inside a matrix stops at the closing delimiter as well.
94
94
  rule(:matrix_text) { (kept_apostrophe | escaped | (str('#)').absent? >> non_escaped)).repeat(1).as(:text) }
95
95
 
96
- rule(:markup) { (matrix | tabstop | text | decoration | shape | bstroke) }
96
+ # A coloured stretch of a label: @red(...) or @#c00(...). What is inside
97
+ # is ordinary markup on one line, drawn in that colour, and a stretch
98
+ # inside another keeps its own. A ')' inside is written \).
99
+ rule(:span_open) { str('@') >> (color_hex | color_name).as(:color_value) >> str('(') }
100
+ rule(:colored) { span_open >> span_markup.repeat(1).as(:colored) >> str(')') }
101
+ rule(:span_markup) { (colored | span_text | decoration | shape | bstroke) }
102
+ rule(:span_text) { (kept_apostrophe | escaped | (str(')').absent? >> non_escaped)).repeat(1).as(:text) }
103
+
104
+ rule(:markup) { (matrix | tabstop | colored | text | decoration | shape | bstroke) }
97
105
 
98
106
  # A label that is one whole matrix. The enclosure rules in :lines would
99
107
  # eat the '#' of '#(' before the matrix rule could see it, so a matrix
@@ -219,8 +227,18 @@ module Markup
219
227
  rule(matrix: subtree(:matrix)) {
220
228
  { text: +"", decoration: [:matrix], matrix: matrix }
221
229
  }
230
+ # Every run of a coloured stretch carries the colour, unless a stretch
231
+ # inside it gave the run one of its own first. Every colour a run sits
232
+ # inside is kept as well, so an outer one is still checked when inner
233
+ # stretches cover all of its text.
234
+ rule(color_value: simple(:color), colored: subtree(:runs)) {
235
+ [runs].flatten.each do |run|
236
+ run[:color] ||= color.to_s
237
+ (run[:span_colors] ||= []) << color.to_s
238
+ end
239
+ }
222
240
  rule(line: subtree(:line)) {
223
- { type: :text, elements: line }
241
+ { type: :text, elements: [line].flatten }
224
242
  }
225
243
  rule(extracr: subtree(:extracr)) {
226
244
  { type: :text, elements: [{ text: +" ", decoration: [] }] }
@@ -27,7 +27,15 @@ figure that was meant.
27
27
  - A straight apostrophe is typeset as the curly ’ (U+2019); \' keeps it
28
28
  straight.
29
29
  - A `+` followed by digits at the end of a label is a movement path (+1, +>2).
30
- \+ is a plus sign, so C\+\+11 and 2\+2 draw as written.
30
+ \+ is a plus sign, so C\+\+11 and 2\+2 draw as written. The markers come
31
+ last, after any coloured stretch: NP\n@gray(note)+>1, not @gray(note+>1).
32
+ - Decorations nest either way round (___*x*___ and *___x___* both draw small
33
+ italic), but a coloured stretch @color(...) goes outside them all:
34
+ @red(**x**), never **@red(x)**.
35
+ - `@` followed by a colour name or #hex and `(` opens a coloured stretch,
36
+ wherever it stands: bob@red(note) draws "bob" and a red "note". Write \@ for
37
+ an @ meant as a character there: mail\@example(x). A stretch holds at least
38
+ one character and closes within its line and its cell: @red(a)\t@red(b).
31
39
  - A backslash takes the character after it, whatever it is: \q draws q, and
32
40
  C:\path draws C:path. A backslash itself is \\.
33
41
  - A program building labels from text it did not choose should not copy
@@ -54,6 +62,7 @@ Structure:
54
62
  | an invisible joint, to align leaves | a label of only <>, as in [X [<> [Y y]] [Z z]] |
55
63
  | a movement path (dashed) | [S [NP a+1] [VP [V b] [NP c+1]]] |
56
64
  | the same, with an arrowhead | write +>1 on the end the arrow points at |
65
+ | a path to a phrase | +1 on a node with daughters: the line stops a clearance outside the phrase and its shade, on the word side |
57
66
  | an extra straight connector | +-1 on two nodes; +->1 for an arrowhead |
58
67
 
59
68
  Inside a label:
@@ -62,7 +71,7 @@ Inside a label:
62
71
  |----------------------------------------|-------------------|
63
72
  | italic, bold, both | *x*, **x**, ***x*** |
64
73
  | subscript, superscript | x_i_, x__2__ |
65
- | small capitals | H___EAD___ |
74
+ | smaller type (70%), as for small caps | H___EAD___ — on lower case it is simply smaller: ___*a<>note*___ |
66
75
  | overline, underline, strikethrough | =x=, -x-, ~x~ |
67
76
  | a line break; a blank line | a\nb (or a\ b); \n\n |
68
77
  | columns, aligned down the label | HEAD\t*verb*\nSPR\t⟨<>⟩ |
@@ -80,6 +89,8 @@ Around a label:
80
89
  | a whole label that is one matrix | [#(CAT\tS#) [#(CAT\tNP#) Kim] [#(CAT\tVP#) sleeps]] |
81
90
  | a region shade behind the subtree | %NP, coloured: %@blue:NP |
82
91
  | a colour | @red:NP, @#3af:NP, @#33aaff:NP (3 or 6 hex digits) |
92
+ | part of a label in colour | look @red(at) the chickens, @#3af({}->) — within one line, outside other markup; \) for a ')' inside |
93
+ | a note under a category | [NP\n@gray(___*causer*___) Pat] — small grey italic on the label's second line |
83
94
 
84
95
  An attribute-value matrix is columns plus an enclosure, and a value can be
85
96
  another matrix — nested with #( ... #), never with square brackets, which are
@@ -101,8 +112,8 @@ Options (the command line spells them --like-this):
101
112
  | linewidth | every line's weight, 0.5–3.0, as a ratio of the font size |
102
113
  | leafstyle | auto, bar, dashed, nothing — what joins a node to its leaf |
103
114
  | direction | ttb, ltr, btt |
104
- | mirror | flip the finished layout, for RTL scripts |
105
- | tidy | off, symmetric, low, medium, high — how tightly subtrees pack |
115
+ | mirror | flip the finished layout, for RTL scripts; not with direction ltr |
116
+ | tidy | off, symmetric, low, medium, high — how tightly subtrees pack; the packing modes leave the column under a movement path's end clear, which can widen a figure |
106
117
  | hspacing | how far apart sisters sit, 0.5–3.0 |
107
118
  | vheight | how far apart levels sit, 0.5–5.0 |
108
119
  | polyline | draw each connector as two right angles rather than a slanted line |
@@ -114,6 +125,9 @@ Options (the command line spells them --like-this):
114
125
  | shear | tilt the drawn figure: degrees, −45 to 45, positive leans the top right |
115
126
  | shear_plane | the plane behind a sheared figure: on (grey), off, or a colour; never drawn on a transparent background |
116
127
  | vmargin | clearance between a label and its connectors, 0.1–1.0, the same above and below |
128
+ | corner_label | a short string set in a corner of the image beside the tree, written as is (no markup) — a judgement mark such as * or ?? |
129
+ | corner_label_position | top-left, top-right, bottom-left, bottom-right |
130
+ | corner_label_size, corner_label_color, corner_label_fontstyle | 6–52 (1.5 × fontsize unless given), a colour name or hex (black unless given), a font style (fontstyle unless given) |
117
131
 
118
132
  hspacing and vheight are named for the top-to-bottom layout, and follow the
119
133
  tree rather than the page: with direction ltr, sisters stack downwards and
@@ -256,7 +256,7 @@ module RSyntaxTree
256
256
  # `\#` arrived at the grammar as a bare '#', which opens an enclosure,
257
257
  # so a label written with a hash in it lost the hash and everything
258
258
  # after it went inside brackets instead.
259
- when /[nt{}<>^+*_=~|%\-#@']/
259
+ when /[nt{}<>^+*_=~|%\-#@'()]/
260
260
  if escape
261
261
  token += '\\' + ch
262
262
  escape = false
@@ -51,6 +51,9 @@ module RSyntaxTree
51
51
  @shear_deg = (params[:shear] || 0).to_f
52
52
  @shear_k = (-Math.tan(@shear_deg * Math::PI / 180)).round(3)
53
53
  @shear_plane = params[:shear_plane] || "on"
54
+ @corner = params[:corner]
55
+ # The hatch pattern of each colour a coloured stretch asks for.
56
+ @span_hatches = {}
54
57
  @line_styles = "<line style='fill: none; stroke:#{@col_line}; stroke-width:#{@global[:stroke_normal]}; stroke-linejoin:round; stroke-linecap:round;' x1='X1' y1='Y1' x2='X2' y2='Y2' />\n"
55
58
  @polyline_styles = "<polyline style='stroke:#{@col_line}; stroke-width:#{@global[:stroke_normal]}; fill:none; stroke-linejoin:round; stroke-linecap:round;'
56
59
  points='CHIX CHIY MIDX1 MIDY1 MIDX2 MIDY2 PARX PARY' />\n"
@@ -145,6 +148,13 @@ module RSyntaxTree
145
148
  @height = y2
146
149
  end
147
150
 
151
+ corner = ""
152
+ if @corner
153
+ corner, x1, y1, x2, y2 = corner_label(x1, y1, x2, y2)
154
+ @width = x2
155
+ @height = y2
156
+ end
157
+
148
158
  extra_lines = @extra_lines.join("\n")
149
159
 
150
160
  # Rounded like the stroke widths are: the arithmetic leaves float dust
@@ -190,6 +200,10 @@ module RSyntaxTree
190
200
  </defs>
191
201
  HDR
192
202
 
203
+ # Only a figure with a hatched shape in a coloured stretch has these, and
204
+ # every other figure's header is left as it was.
205
+ header = header.sub(" </defs>", "#{span_hatch_patterns(hatch_cell, hatch_stroke)}\n </defs>") if @span_hatches.any?
206
+
193
207
  rect = <<~RCT
194
208
  <rect x="#{x1}" y="#{y1}" width="#{x2}" height="#{y2}" stroke="none" fill="white" />
195
209
  RCT
@@ -200,6 +214,8 @@ module RSyntaxTree
200
214
  # below tree connectors and labels.
201
215
  shades = @region_shades.join
202
216
 
217
+ footer = corner + footer
218
+
203
219
  if @shear_k.zero?
204
220
  if @transparent
205
221
  header + shades + @tree_data + extra_lines + footer
@@ -237,57 +253,65 @@ module RSyntaxTree
237
253
  end
238
254
  end
239
255
 
256
+ # A short string set in a corner of the finished image, such as the
257
+ # judgement mark of the sentence the tree is drawn for. It gets a strip of
258
+ # its own on its side of the canvas, so it never touches the tree and sits
259
+ # in the same place in every figure. Its top is level with the tree's
260
+ # highest ink, or its bottom with the lowest. It is drawn after the shear
261
+ # and the mirror, because it marks the image rather than the tree.
262
+ # Returns the text element and the grown canvas.
263
+ def corner_label(x1, y1, x2, y2)
264
+ size = @corner[:size] * FONT_SCALING
265
+ family = FontFamily.for_pango(@corner[:font_style])
266
+ m = FontMetrics.get_metrics(@corner[:text], family, size, :normal, :normal)
267
+ gap = @global[:h_gap_between_nodes]
268
+ inked = @element_list.get_elements.select { |e| e.ink_top && e.ink_bottom }
269
+ top = inked.map(&:ink_top).min || (y1 + gap)
270
+ bottom = inked.map(&:ink_bottom).max || (y1 + y2 - gap)
271
+ vertical, horizontal = @corner[:position].split("-")
272
+
273
+ baseline = if vertical == "top"
274
+ top + m.ink_above
275
+ else
276
+ bottom - (m.ink_height - m.ink_above)
277
+ end
278
+ # The strip holds both the advance and the ink, whichever reaches
279
+ # further, so a glyph that overhangs its origin is not cut off.
280
+ left = [0, m.ink_left].min
281
+ width = [m.width, m.ink_left + m.ink_width].max - left
282
+ if horizontal == "left"
283
+ x1 -= width + gap
284
+ x = x1 + gap - left
285
+ else
286
+ x = x1 + x2 - left
287
+ end
288
+ x2 += width + gap
289
+
290
+ # Grown downward or upward only when the mark is taller than the tree.
291
+ ink_t = baseline - m.ink_above
292
+ ink_b = ink_t + m.ink_height
293
+ new_y1 = [y1, ink_t - gap].min
294
+ y2 = [y1 + y2, ink_b + gap].max - new_y1
295
+ y1 = new_y1
296
+
297
+ text = "<text x='#{x.round(3)}' y='#{baseline.round(3)}' white-space='pre' " \
298
+ "style='fill: #{@corner[:color]}; stroke-width: 0; font-size: #{size.round(3)}px' " \
299
+ "font-family=\"#{FontFamily.for_svg(@corner[:font_style])}\">" \
300
+ "#{CGI.escapeHTML(@corner[:text])}</text>\n"
301
+ [text, x1.round(3), y1.round(3), x2.round(3), y2.round(3)]
302
+ end
303
+
240
304
  # Collect a background rectangle for every element flagged with '%'.
241
305
  # Outer (shallower) regions are emitted first so deeper ones layer on
242
306
  # top; with low opacity the overlap reads as a darker nesting.
243
307
  def collect_region_shades
244
- hctt = @global[:height_connector_to_text]
245
- pad = @global[:h_gap_between_nodes] # generous padding for the non-parent-facing edges
246
- pad_parent = hctt / 2.0 # tighter margin on the parent-facing edge of the root
247
- radius = hctt / 2.0
308
+ radius = @global[:height_connector_to_text] / 2.0
248
309
  stroke_width = @global[:stroke_normal]
249
310
  half = stroke_width / 2.0
250
311
  @element_list.get_elements.each do |element|
251
312
  next unless element.region
252
313
 
253
- b = region_subtree_bounds(element.id)
254
- left = b[:left] - pad
255
- right = b[:right] + pad
256
- top = b[:top] - pad
257
- bottom = b[:bottom] + pad
258
-
259
- # The edge facing the parent is handled specially so the incoming
260
- # connector neither overlaps nor touches the plane. That edge is the
261
- # TOP in top-to-bottom layout and the LEFT in left-to-right layout; the
262
- # other edges keep the generous padding. For a non-root node the edge
263
- # is placed midway between the connector anchor and the content edge
264
- # (even gap on both sides); the tree root has no incoming connector, so
265
- # it just gets a tighter-but-consistent margin there.
266
- is_root = element.parent.zero?
267
- if @direction == "ltr"
268
- anchor = element.horizontal_indent - hctt
269
- left = if is_root
270
- b[:left] - pad_parent
271
- elsif anchor < b[:left]
272
- (b[:left] + anchor) / 2.0
273
- else
274
- left
275
- end
276
- else
277
- anchor = element.vertical_indent + hctt / 2.0
278
- top = if is_root
279
- b[:top] - pad_parent
280
- elsif anchor < b[:top]
281
- (b[:top] + anchor) / 2.0
282
- else
283
- top
284
- end
285
- end
286
-
287
- x = left
288
- y = top
289
- w = right - left
290
- h = bottom - top
314
+ x, y, w, h = region_rect(element).values_at(:x, :y, :w, :h)
291
315
  # An explicit shade color is always honored (consistent with the
292
316
  # @color: node-text color); bare '%' falls back to gray.
293
317
  color = element.region_color || REGION_DEFAULT_COLOR
@@ -338,6 +362,68 @@ module RSyntaxTree
338
362
  # Union of element_visual_box over the subtree rooted at +id+, in final
339
363
  # drawing coordinates. Used to size region shades so the whole subtree
340
364
  # (labels, enclosures, brackets) sits inside the plane.
365
+ # How far a phrase reaches: the boxes of everything it holds, and the
366
+ # shade of any region in it, as the shade is painted.
367
+ def phrase_reach(element)
368
+ reach = region_subtree_bounds(element.id)
369
+ stack = [element]
370
+ until stack.empty?
371
+ node = stack.pop
372
+ if node.region
373
+ r = region_rect(node)
374
+ reach[:left] = [reach[:left], r[:x]].min
375
+ reach[:right] = [reach[:right], r[:x] + r[:w]].max
376
+ reach[:top] = [reach[:top], r[:y]].min
377
+ reach[:bottom] = [reach[:bottom], r[:y] + r[:h]].max
378
+ end
379
+ node.children.each { |c| stack << @element_list.get_id(c) }
380
+ end
381
+ reach
382
+ end
383
+
384
+ # The rectangle a region shade is painted in: the subtree's boxes with a
385
+ # gap around them, the edge facing the parent closer in.
386
+ def region_rect(element)
387
+ hctt = @global[:height_connector_to_text]
388
+ pad = @global[:h_gap_between_nodes] # generous padding for the non-parent-facing edges
389
+ pad_parent = hctt / 2.0 # tighter margin on the parent-facing edge of the root
390
+ b = region_subtree_bounds(element.id)
391
+ left = b[:left] - pad
392
+ right = b[:right] + pad
393
+ top = b[:top] - pad
394
+ bottom = b[:bottom] + pad
395
+
396
+ # The edge facing the parent is handled specially so the incoming
397
+ # connector neither overlaps nor touches the plane. That edge is the
398
+ # TOP in top-to-bottom layout and the LEFT in left-to-right layout; the
399
+ # other edges keep the generous padding. For a non-root node the edge
400
+ # is placed midway between the connector anchor and the content edge
401
+ # (even gap on both sides); the tree root has no incoming connector, so
402
+ # it just gets a tighter-but-consistent margin there.
403
+ is_root = element.parent.zero?
404
+ if @direction == "ltr"
405
+ anchor = element.horizontal_indent - hctt
406
+ left = if is_root
407
+ b[:left] - pad_parent
408
+ elsif anchor < b[:left]
409
+ (b[:left] + anchor) / 2.0
410
+ else
411
+ left
412
+ end
413
+ else
414
+ anchor = element.vertical_indent + hctt / 2.0
415
+ top = if is_root
416
+ b[:top] - pad_parent
417
+ elsif anchor < b[:top]
418
+ (b[:top] + anchor) / 2.0
419
+ else
420
+ top
421
+ end
422
+ end
423
+
424
+ { x: left, y: top, w: right - left, h: bottom - top }
425
+ end
426
+
341
427
  def region_subtree_bounds(id)
342
428
  b = element_visual_box(@element_list.get_id(id))
343
429
  @element_list.get_id(id).children.each do |c|
@@ -739,6 +825,8 @@ module RSyntaxTree
739
825
  # here, so this could no longer live inside the drawing loop.
740
826
  def render_run(e, this_x, text_y, element, col)
741
827
  out = +""
828
+ # A coloured stretch paints its marks and the shapes drawn around them.
829
+ col = e[:color] if e[:color]
742
830
  this_y = text_y
743
831
  escaped_text = e[:text].gsub('>', '&gt;').gsub('<', '&lt;');
744
832
  decorations = []
@@ -763,6 +851,7 @@ module RSyntaxTree
763
851
 
764
852
  style += "font-weight: bold; fill: #{@col_emph}; " if e[:decoration].include?(:bold) || e[:decoration].include?(:bolditalic)
765
853
  style += "font-style: italic; " if e[:decoration].include?(:italic) || e[:decoration].include?(:bolditalic)
854
+ style += "fill: #{col}; " if e[:color]
766
855
  style += "\""
767
856
 
768
857
  fontstyle = FontFamily.for_svg(@fontstyle)
@@ -775,7 +864,9 @@ module RSyntaxTree
775
864
  enc_width = e[:width]
776
865
  enc_x = this_x
777
866
 
778
- if e[:decoration].include?(:hatched)
867
+ if e[:decoration].include?(:hatched) && e[:color]
868
+ fill = "url(##{@span_hatches[col] ||= "hatchSpan#{@span_hatches.size}"})"
869
+ elsif e[:decoration].include?(:hatched)
779
870
  case element.type
780
871
  when ETYPE_LEAF
781
872
  fill = if @color
@@ -847,6 +938,14 @@ module RSyntaxTree
847
938
  elsif e[:decoration].include?(:whitespace)
848
939
  return [out, this_x + e[:width]]
849
940
  else
941
+ # Text that changes colour part way is still one stretch, set as one
942
+ # and painted part by part.
943
+ if e[:parts]
944
+ escaped_text = e[:parts].map do |part, color|
945
+ t = part.gsub('>', '&gt;').gsub('<', '&lt;')
946
+ color ? "<tspan style='fill: #{color};'>#{t}</tspan>" : t
947
+ end.join
948
+ end
850
949
  out << set_tspan(this_x, this_y, style, decoration, fontstyle, escaped_text)
851
950
  this_x += e[:width]
852
951
  end
@@ -920,6 +1019,15 @@ module RSyntaxTree
920
1019
  [out, this_x + advance - lead]
921
1020
  end
922
1021
 
1022
+ def span_hatch_patterns(cell, stroke)
1023
+ @span_hatches.map do |color, id|
1024
+ "<pattern id=\"#{id}\" x=\"10\" y=\"10\" width=\"#{cell}\" height=\"#{cell}\" " \
1025
+ "patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\">" \
1026
+ "<line x1=\"0\" y=\"0\" x2=\"0\" y2=\"#{cell}\" stroke=\"#{color}\" stroke-width=\"#{stroke}\"></line>" \
1027
+ "</pattern>"
1028
+ end.join("\n")
1029
+ end
1030
+
923
1031
  def draw_rectangle(x1, y1, width, height, col, bline = false)
924
1032
  swidth = bline ? @global[:stroke_bold] : @global[:stroke_normal]
925
1033
  @extra_lines << "<polygon style='stroke:#{col}; stroke-width:#{swidth}; fill:none; stroke-linejoin:round; stroke-linecap:round;'
@@ -991,8 +1099,21 @@ module RSyntaxTree
991
1099
  lgeom = nil
992
1100
  end
993
1101
  # A movement path leaves a label on the side the words are on: below
994
- # it top to bottom, above it bottom to top.
1102
+ # it top to bottom, above it bottom to top. A path to a phrase stops
1103
+ # at the edge of everything the phrase holds instead, its shade
1104
+ # included, so that it reads as reaching the phrase as a whole and
1105
+ # does not run in through the daughters to the label.
1106
+ path_x = x1
995
1107
  path_y = @direction == "btt" ? element.vertical_indent - @global[:height_connector_to_text] : y1
1108
+ if !element.children.empty? && element.path.any? { |marker| !marker.start_with?("-") }
1109
+ reach = phrase_reach(element)
1110
+ hctt = @global[:height_connector_to_text]
1111
+ case @direction
1112
+ when "ltr" then path_x = reach[:right] + hctt
1113
+ when "btt" then path_y = reach[:top] - hctt
1114
+ else path_y = reach[:bottom] + hctt
1115
+ end
1116
+ end
996
1117
  # How much of the label there is across the paths' run, for the ends
997
1118
  # that share it to be spread over: an even amount either side of the
998
1119
  # anchor, which left to right sits below the middle of the label.
@@ -1015,20 +1136,20 @@ module RSyntaxTree
1015
1136
  elsif /\A(?:>|<)(\d+)\z/ =~ tr
1016
1137
  tr = $1
1017
1138
  if path_pool_target[tr]
1018
- path_pool_target[tr] << [x1, path_y, across]
1139
+ path_pool_target[tr] << [path_x, path_y, across]
1019
1140
  else
1020
- path_pool_target[tr] = [[x1, path_y, across]]
1141
+ path_pool_target[tr] = [[path_x, path_y, across]]
1021
1142
  end
1022
1143
  path_flags << tr
1023
1144
  elsif path_pool_source[tr]
1024
1145
  if path_pool_other[tr]
1025
- path_pool_other[tr] << [x1, path_y, across]
1146
+ path_pool_other[tr] << [path_x, path_y, across]
1026
1147
  else
1027
- path_pool_other[tr] = [[x1, path_y, across]]
1148
+ path_pool_other[tr] = [[path_x, path_y, across]]
1028
1149
  end
1029
1150
  path_flags << tr
1030
1151
  else
1031
- path_pool_source[tr] = [x1, path_y, across]
1152
+ path_pool_source[tr] = [path_x, path_y, across]
1032
1153
  path_flags << tr
1033
1154
  end
1034
1155
  raise RSTError.new(+"Error: input text contains a path having more than two ends:\n > #{tr}", code: :path_multiple_ends, hint: "A path or line takes exactly two ends; check the numbers.", retryable: true) if path_flags.tally.any? { |_k, v| v > 2 } || line_flags.tally.any? { |_k, v| v > 2 }
@@ -10,6 +10,7 @@
10
10
  module RSyntaxTree
11
11
  class TikZGenerator
12
12
  LATEX_ESCAPE_MAP = {
13
+ '\\' => '\\textbackslash{}',
13
14
  '&' => '\\&',
14
15
  '%' => '\\%',
15
16
  '$' => '\\$',
@@ -18,8 +19,11 @@ module RSyntaxTree
18
19
  '{' => '\\{',
19
20
  '}' => '\\}',
20
21
  '~' => '\\textasciitilde{}',
21
- '^' => '\\textasciicircum{}'
22
+ '^' => '\\textasciicircum{}',
23
+ '<' => '\\textless{}',
24
+ '>' => '\\textgreater{}'
22
25
  }.freeze
26
+ LATEX_SPECIALS = Regexp.union(LATEX_ESCAPE_MAP.keys).freeze
23
27
 
24
28
  def initialize(element_list, params)
25
29
  @element_list = element_list
@@ -190,6 +194,7 @@ module RSyntaxTree
190
194
  label = extract_label(element)
191
195
  escaped_label = escape_latex(label)
192
196
  head = "#{escaped_label}#{leaf_edge_option(element)}#{region_option(element)}"
197
+ head += corner_label_option if element_id == 1
193
198
 
194
199
  children = element.children
195
200
  indent_str = " " * indent
@@ -228,6 +233,31 @@ module RSyntaxTree
228
233
  "fit to=tree]{};}}"
229
234
  end
230
235
 
236
+ # The corner label, set by the root once the whole tree is drawn, so the
237
+ # bounding box it stands beside is the tree's. Its size is kept as a
238
+ # ratio to the tree's type, which in LaTeX is the document's. Its spaces
239
+ # are tied, since TeX would drop them at the ends and merge them inside,
240
+ # and a trailing one is closed with an empty box, which the node's own
241
+ # end-of-text trimming does not remove.
242
+ CORNER_ANCHORS = {
243
+ "top-left" => ["north east", "north west", "-"],
244
+ "top-right" => ["north west", "north east", ""],
245
+ "bottom-left" => ["south east", "south west", "-"],
246
+ "bottom-right" => ["south west", "south east", ""]
247
+ }.freeze
248
+
249
+ def corner_label_option
250
+ corner = @params[:corner]
251
+ return "" unless corner
252
+
253
+ anchor, at, sign = CORNER_ANCHORS.fetch(corner[:position])
254
+ scale = (corner[:size] * FONT_SCALING / @params[:fontsize]).round(3)
255
+ ", tikz+={\\node[anchor=#{anchor}, inner sep=0pt, scale=#{scale}, " \
256
+ "text=#{tikz_region_color(corner[:color])}] " \
257
+ "at ([xshift=#{sign}0.5em]current bounding box.#{at}) " \
258
+ "{#{escape_latex(corner[:text]).tr(' ', '~')}#{'\\null' if corner[:text].end_with?(' ')}};}"
259
+ end
260
+
231
261
  # Map an RSyntaxTree color (name or #hex) to a TikZ fill color expression.
232
262
  # SVG/CSS color names and #hex codes are resolved to a TikZ inline rgb
233
263
  # expression so the figure compiles without depending on which color names
@@ -283,21 +313,20 @@ module RSyntaxTree
283
313
  next
284
314
  end
285
315
 
286
- # Remove RSyntaxTree-specific whitespace block
287
- text = el[:text].to_s.gsub("■", " ")
316
+ # Remove RSyntaxTree-specific whitespace block, and read the
317
+ # characters the parser keeps as SVG entities back as themselves.
318
+ text = Element.plain_text(el[:text].to_s.gsub("■", " "))
288
319
  texts << text unless text.strip.empty?
289
320
  end
290
321
  end
291
322
  texts
292
323
  end
293
324
 
294
- # Escape LaTeX special characters
325
+ # Escape LaTeX special characters, in one pass with a block: a
326
+ # replacement string would read the backslash in \& as a reference to
327
+ # the match, and a second pass would escape the first one's backslashes.
295
328
  def escape_latex(text)
296
- result = text.dup
297
- LATEX_ESCAPE_MAP.each do |char, escaped|
298
- result.gsub!(char, escaped)
299
- end
300
- result
329
+ text.gsub(LATEX_SPECIALS) { |c| LATEX_ESCAPE_MAP[c] }
301
330
  end
302
331
  end
303
332
  end
@@ -122,7 +122,10 @@ module FontMetrics
122
122
  # actually are: how tall the marks are, and how far the tallest reaches above
123
123
  # the baseline. A box or circle drawn around text needs the latter — sized by
124
124
  # the rhythm it would stand a head taller than the letters it encloses.
125
- Metrics = Struct.new(:width, :height, :ink_height, :ink_above)
125
+ # ink_left and ink_width place the marks across: where the first one
126
+ # starts, measured from the text's origin, and how far they run. A glyph can
127
+ # start left of its origin or run past its advance.
128
+ Metrics = Struct.new(:width, :height, :ink_height, :ink_above, :ink_left, :ink_width)
126
129
 
127
130
  # Vertical rhythm is defined deterministically from the font size rather
128
131
  # than taken from Pango's font-dependent logical extents. The 1.4 factor
@@ -165,7 +168,7 @@ module FontMetrics
165
168
  width, = layout.pixel_size
166
169
  ink, = layout.pixel_extents
167
170
  baseline = layout.baseline / Pango::SCALE.to_f
168
- Metrics.new(width, fontsize * LINE_HEIGHT_FACTOR, ink.height, baseline - ink.y)
171
+ Metrics.new(width, fontsize * LINE_HEIGHT_FACTOR, ink.height, baseline - ink.y, ink.x, ink.width)
169
172
  end
170
173
 
171
174
  def pango_layout
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RSyntaxTree
4
- VERSION = "2.6.0"
4
+ VERSION = "2.8.0"
5
5
  end
data/lib/rsyntaxtree.rb CHANGED
@@ -43,6 +43,9 @@ FORMAT_EXTENSIONS = {
43
43
  "tikz" => "tex" # forest code, to be included in a LaTeX document
44
44
  }.freeze
45
45
 
46
+ # The names a font style may be given by: the tree's, and the corner label's.
47
+ FONT_STYLE_VALUES = ["sans", "serif", "cjk", "mono", "noto-sans", "noto-serif", "noto-sans-mono", "cjk zenhei"].freeze
48
+
46
49
  # The values an option may carry, checked as given — before normalization —
47
50
  # so an alias the normalization already accepts keeps passing, and anything
48
51
  # else fails loudly instead of being silently read as something else. The
@@ -56,13 +59,15 @@ OPTION_VALUES = {
56
59
  # same initials, and claimed an interchange nobody else had implemented.
57
60
  format: FORMATS + ["lsif"],
58
61
  leafstyle: %w[auto triangle bar dashed nothing],
59
- fontstyle: ["sans", "serif", "cjk", "mono", "noto-sans", "noto-serif", "noto-sans-mono", "cjk zenhei"],
62
+ fontstyle: FONT_STYLE_VALUES,
60
63
  color: %w[modern traditional gray grey off none on true false],
61
64
  tidy: %w[off symmetric low medium high on compact true false],
62
65
  direction: %w[ttb ltr btt],
63
66
  hyphen: %w[markup literal],
64
67
  derivation: %w[on off true false yes no 0 1 none],
65
- leaf_align: %w[off words subtrees]
68
+ leaf_align: %w[off words subtrees],
69
+ corner_label_position: %w[top-left top-right bottom-left bottom-right],
70
+ corner_label_fontstyle: FONT_STYLE_VALUES
66
71
  }.freeze
67
72
 
68
73
  NUMERIC_RANGES = {
@@ -71,7 +76,8 @@ NUMERIC_RANGES = {
71
76
  vheight: 0.5..5.0,
72
77
  hspacing: 0.5..3.0,
73
78
  shear: -45..45,
74
- vmargin: 0.1..1.0
79
+ vmargin: 0.1..1.0,
80
+ corner_label_size: 6..52
75
81
  }.freeze
76
82
 
77
83
  # Options 2.0 removed, and what to say instead. An unknown key is passed over
@@ -110,7 +116,8 @@ DEFAULT_OPTS = {
110
116
  # unequal air — a little more below every label than above it, an
111
117
  # unadjusted leftover of measuring from the layout box — with the same
112
118
  # clearance on both sides of the ink.
113
- vmargin: 0.4
119
+ vmargin: 0.4,
120
+ corner_label_position: "top-left"
114
121
  }.freeze
115
122
 
116
123
  # A parse or generation failure. `message` is the human-readable text the
@@ -162,6 +169,7 @@ class RSTError < StandardError
162
169
  bare_hyphen
163
170
  empty_brackets
164
171
  empty_input
172
+ empty_markup
165
173
  incomplete_path
166
174
  internal_error
167
175
  invalid_color
@@ -341,7 +349,7 @@ module RSyntaxTree
341
349
  when "on", "true", "yes", "1" then "on"
342
350
  when "off", "false", "no", "0", "none" then "off"
343
351
  else
344
- unless COLOR_NAMES.include?(v.downcase) || v =~ /\A#(\h{3}|\h{6})\z/
352
+ unless color_value?(v)
345
353
  raise RSTError.new(+"Error: invalid value for option 'shear_plane': #{value.inspect}",
346
354
  code: :invalid_option, label: "shear_plane",
347
355
  hint: "'shear_plane' is on, off, a colour name, " \
@@ -355,14 +363,43 @@ module RSyntaxTree
355
363
  # Fonts are resolved by name through fontconfig (measurement via
356
364
  # Pango, rendering via the SVG font-family attribute), so all a
357
365
  # style needs is its family fallback chain.
358
- style = case value.to_s
359
- when "noto-sans-mono", "mono" then :mono
360
- when "noto-serif", "serif" then :serif
361
- when "cjk zenhei", "cjk" then :cjk
362
- else :sans
363
- end
366
+ style = font_style(value)
364
367
  fontset[:family] = FontFamily.for_pango(style)
365
368
  new_params[:fontstyle] = style.to_s
369
+ when :corner_label_fontstyle
370
+ new_params[key] = font_style(value).to_s
371
+ when :corner_label_position
372
+ new_params[key] = value.to_s
373
+ when :corner_label_size
374
+ new_params[key] = value.to_f
375
+ when :corner_label
376
+ # Written as given: it is a mark set beside the tree, not a label
377
+ # in it, so * and # are themselves rather than markup. Only what
378
+ # XML can carry: a control character would make an SVG no reader
379
+ # accepts.
380
+ v = begin
381
+ value.to_s.encode(Encoding::UTF_8)
382
+ rescue EncodingError
383
+ nil
384
+ end
385
+ unless v&.valid_encoding? && !v.match?(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/)
386
+ raise RSTError.new(+"Error: invalid value for option 'corner_label': #{value.inspect}",
387
+ code: :invalid_option, label: "corner_label",
388
+ hint: "'corner_label' is text without control characters.",
389
+ retryable: false)
390
+ end
391
+ new_params[key] = v unless v.strip.empty?
392
+ when :corner_label_color
393
+ v = value.to_s.strip
394
+ unless v.empty?
395
+ unless color_value?(v)
396
+ raise RSTError.new(+"Error: invalid value for option 'corner_label_color': #{value.inspect}",
397
+ code: :invalid_option, label: "corner_label_color",
398
+ hint: "'corner_label_color' is a colour name or a hex colour of 3 or 6 digits.",
399
+ retryable: false)
400
+ end
401
+ new_params[key] = v
402
+ end
366
403
  else
367
404
  new_params[key] = value
368
405
  end
@@ -394,6 +431,19 @@ module RSyntaxTree
394
431
  retryable: false)
395
432
  end
396
433
 
434
+ # Mirroring flips the finished layout from side to side, which is what a
435
+ # tree read right to left needs when it runs down the page. Laid out
436
+ # left to right, the flip puts each parent on the other side of its
437
+ # daughters, and the connectors, still drawn from a parent's right edge,
438
+ # were struck through the labels. Refused until it is drawn properly.
439
+ if @params[:mirror] == true && @params[:direction] == "ltr"
440
+ raise RSTError.new(+"Error: a tree drawn left to right cannot be mirrored",
441
+ code: :invalid_option, label: "mirror",
442
+ hint: "Mirroring is for a tree that runs down or up the page. Use direction " \
443
+ "ttb or btt, or turn mirror off.",
444
+ retryable: false)
445
+ end
446
+
397
447
  # Hiding the default connectors draws them in the background colour
398
448
  # rather than skipping them. A derivation's rules are drawn as connectors
399
449
  # but they are the figure itself, not a default the drawing adds, so
@@ -453,6 +503,35 @@ module RSyntaxTree
453
503
  @global[:stroke_bold] = (@params[:fontsize] * (0.05 * @params[:linewidth] + 0.05)).round(3)
454
504
  # hyphen: literal swaps the two readings of - when a label is parsed.
455
505
  @global[:literal_hyphen] = @params[:hyphen] == "literal"
506
+ # Everything the corner label needs, with its defaults filled in once
507
+ # for every format: half as large again as the tree's type, in the
508
+ # tree's face, in black.
509
+ # Set whether or not there is one, so a caller's own :corner never
510
+ # reaches the drawing.
511
+ @params[:corner] = if @params[:corner_label]
512
+ {
513
+ text: @params[:corner_label],
514
+ position: @params[:corner_label_position],
515
+ size: @params[:corner_label_size] || @params[:fontsize] / FONT_SCALING * 1.5,
516
+ color: @params[:corner_label_color] || "black",
517
+ font_style: @params[:corner_label_fontstyle] || @params[:fontstyle]
518
+ }
519
+ end
520
+ end
521
+
522
+ # A colour as a label's @color: takes it: a CSS name, or 3 or 6 hex digits.
523
+ def color_value?(value)
524
+ COLOR_NAMES.include?(value.downcase) || value.match?(/\A#(\h{3}|\h{6})\z/)
525
+ end
526
+
527
+ # The style a font style name stands for; anything unrecognised is sans.
528
+ def font_style(value)
529
+ case value.to_s
530
+ when "noto-sans-mono", "mono" then :mono
531
+ when "noto-serif", "serif" then :serif
532
+ when "cjk zenhei", "cjk" then :cjk
533
+ else :sans
534
+ end
456
535
  end
457
536
 
458
537
  # Two gates, because neither one alone tells the truth.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rsyntaxtree
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.6.0
4
+ version: 2.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yoichiro Hasebe