rsyntaxtree 2.5.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: f32301303f9acaffacc1783b5c66380187cb4394d559060f520bcbab64831680
4
- data.tar.gz: 80e8d7d6922d6025cbdef82a3efd64ee83ec8c60ff6f17f9607aefd4f7d8f782
3
+ metadata.gz: 5e475a4be7e86a3711b0bae566fa74360b099c9f3e3c021226b0b85e20e6c75a
4
+ data.tar.gz: ab88b55b26314b5867fa6775b0d0ea1d24927d278e63f7d182bb6d21ded83f9a
5
5
  SHA512:
6
- metadata.gz: cf8ebd19d64a05f09c88974c833ea87da9495b375f125e02a4ff34146b0ea2364115dc17cd08c3c9454d73f3a8e262a3a19f42c555f7af231901a19eb0813cad
7
- data.tar.gz: 0c5361ece29a29b4965d59bff8ef4f210a427c49643228c9afb92f8c2c012921752d53988898a720a1652a906c26a2b2f81de5b7876563747f35b3f5c41a4694
6
+ metadata.gz: 4f4f85b37c02d5142403ea517e4e8d9637fb4902399fa541473f795c3485e5821f6254e35ceea8c528cc9dfc313e5e257186cfea401d7c99e26fd469b3c1aff0
7
+ data.tar.gz: ba9057d0cd782d041fa3d34b05424eed8abe0886b8472bf9208722377fd2e8d5c442dcef941d8d1fa9c4ebf2ff28a2d716fb288cc1db7c042877c7217b687334
data/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
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
+
20
+ ## [2.6.0] - 2026-11-12
21
+
22
+ ### Added
23
+ - `leafstyle: dashed` (`-l dashed`): the line down to each word dashed, every line between nodes solid
24
+ - Gallery: each example lists its leaf alignment, and its number can be found with the browser's search
25
+
26
+ ### Fixed
27
+ - Two movement paths that meet at one label no longer cross, and run on one level when nothing else is in the way
28
+
3
29
  ## [2.5.0] - 2026-11-04
4
30
 
5
31
  ### 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.5.0
15
- date-released: 2026-11-04
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
@@ -18,7 +18,7 @@ CONFIG_VALIDATORS = {
18
18
  outdir: ->(v) { FileTest.directory?(v) ? nil : "must be an existing directory path" },
19
19
  outfilename: ->(v) { v.is_a?(String) ? nil : "must be a string" },
20
20
  format: ->(v) { FORMATS.include?(v.to_s) || v.to_s == "lsif" ? nil : "must be #{FORMAT_LIST_MESSAGE}" },
21
- leafstyle: ->(v) { OPTION_VALUES[:leafstyle].include?(v.to_s) ? nil : "must be auto, triangle, bar, or nothing" },
21
+ leafstyle: ->(v) { OPTION_VALUES[:leafstyle].include?(v.to_s) ? nil : "must be auto, triangle, bar, dashed, or nothing" },
22
22
  fontstyle: ->(v) { OPTION_VALUES[:fontstyle].include?(v.to_s) ? nil : "must be sans, serif, cjk, or mono" },
23
23
  fontsize: ->(v) { v.is_a?(Integer) && v >= 6 && v <= 26 ? nil : "must be in the range of 6-26" },
24
24
  linewidth: ->(v) { v.is_a?(Numeric) && v >= 0.5 && v <= 3.0 ? nil : "must be in the range of 0.5-3.0" },
@@ -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
@@ -110,7 +115,7 @@ opts = Optimist.options do
110
115
  opt :outdir, "Output directory", default: "./", short: :o
111
116
  opt :outfilename, "Output file base name", default: "syntree", short: :u
112
117
  opt :format, "Output format: #{FORMAT_LIST_MESSAGE}", default: "png", short: :f
113
- opt :leafstyle, "visual style of tree leaves: auto, triangle, bar, or nothing", default: "auto", short: :l
118
+ opt :leafstyle, "visual style of tree leaves: auto, triangle, bar, dashed, or nothing", default: "auto", short: :l
114
119
  opt :fontstyle, "Font style: sans, serif, cjk, mono", default: "sans", short: :n
115
120
  opt :fontsize, "Size: 6-26", default: 16, short: :s
116
121
  opt :linewidth, "Size: 0.5-3.0", default: 1.0, short: :i
@@ -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
@@ -147,7 +157,7 @@ Optimist.die :direction, "must be one of: #{OPTION_VALUES[:direction].join(', ')
147
157
  Optimist.die :derivation, "must be one of: #{OPTION_VALUES[:derivation].join(', ')}" unless OPTION_VALUES[:derivation].include?(opts[:derivation])
148
158
  Optimist.die :hyphen, "must be markup or literal" unless OPTION_VALUES[:hyphen].include?(opts[:hyphen])
149
159
  Optimist.die :format, "must be #{FORMAT_LIST_MESSAGE}" unless FORMATS.include?(opts[:format])
150
- Optimist.die :leafstyle, "must be auto, triangle, bar, or nothing" unless OPTION_VALUES[:leafstyle].include?(opts[:leafstyle])
160
+ Optimist.die :leafstyle, "must be auto, triangle, bar, dashed, or nothing" unless OPTION_VALUES[:leafstyle].include?(opts[:leafstyle])
151
161
  Optimist.die :fontstyle, "must be sans, serif, cjk, or mono" unless OPTION_VALUES[:fontstyle].include?(opts[:fontstyle])
152
162
  Optimist.die :fontsize, "must be in the range of 6-26" unless opts[:fontsize] >= 6 && opts[:fontsize] <= 26
153
163
  Optimist.die :linewidth, "must be in the range of 0.5-3.0" unless opts[:linewidth] >= 0.5 && opts[:linewidth] <= 3.0
@@ -450,8 +450,10 @@ module RSyntaxTree
450
450
  end
451
451
 
452
452
  # `through` carries the connector chosen above a run of joints leaf
453
- # alignment inserted, down that run to the child it reaches.
454
- def draw_connector(id = 1, through = nil)
453
+ # alignment inserted, down that run to the child it reaches; `dashed`
454
+ # carries how far a dashed line has run so far, so that its dash goes on
455
+ # unbroken through each joint.
456
+ def draw_connector(id = 1, through = nil, dashed = 0)
455
457
  parent = @element_list.get_id(id)
456
458
  children = parent.children.map { |c| @element_list.get_id(c) }
457
459
 
@@ -466,23 +468,32 @@ module RSyntaxTree
466
468
 
467
469
  if through
468
470
  child = children.first
469
- line_to_parent(parent, child) if through == :line
470
- draw_connector(child.id, (through if child.inserted_joint))
471
+ draw_connector(child.id, (through if child.inserted_joint), dashed + draw_line(parent, child, through, dashed))
471
472
  return
472
473
  end
473
474
 
474
475
  chosen = children.map do |child|
475
476
  joints, target = past_inserted_joints(child)
476
477
  connector = connector_for(parent, target, children.size == 1)
478
+ connector = :dashed if connector == :line && @leafstyle == "dashed" && ETYPE_LEAF == target.type
479
+ run = 0
477
480
  case connector
478
481
  when :triangle then triangle_to_parent(parent, target, joints)
479
- when :line then line_to_parent(parent, child)
482
+ when :line, :dashed then run = draw_line(parent, child, connector, 0)
480
483
  else no_connector(parent, target, joints)
481
484
  end
482
- [child, connector]
485
+ [child, connector, run]
483
486
  end
484
487
 
485
- chosen.each { |child, connector| draw_connector(child.id, (connector if child.inserted_joint)) }
488
+ chosen.each { |child, connector, run| draw_connector(child.id, (connector if child.inserted_joint), run) }
489
+ end
490
+
491
+ # A line, dashed when it is one of the lines leafstyle `dashed` draws down
492
+ # to a word. Returns how long it is, for the piece below to carry on from.
493
+ def draw_line(parent, child, connector, dashed)
494
+ return 0 unless %i[line dashed].include?(connector)
495
+
496
+ line_to_parent(parent, child, dash_from: (dashed if connector == :dashed)).to_f
486
497
  end
487
498
 
488
499
  # Leaf alignment puts joints between a node and the child it reaches. They
@@ -507,7 +518,7 @@ module RSyntaxTree
507
518
  case @leafstyle
508
519
  when "auto"
509
520
  forced || child.contains_phrase ? :triangle : :line
510
- when "bar"
521
+ when "bar", "dashed"
511
522
  forced ? :triangle : :line
512
523
  when "nothing", "none"
513
524
  if forced
@@ -609,6 +620,12 @@ module RSyntaxTree
609
620
  # the :ordered nest mode only; see tidy_compress.
610
621
  TIDY_LEVEL_BALANCE = 1.0
611
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
+
612
629
  # Base multiplier for the minimum clearance between adjacent subtrees.
613
630
  # At 1.0 (= raw h_gap_between_nodes) leaf labels sit closer than in the
614
631
  # standard layout, which reads as crowded; 2.5 restores comparable air
@@ -671,6 +688,37 @@ module RSyntaxTree
671
688
  rects
672
689
  end
673
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
+
674
722
  # [leftmost leaf center, rightmost leaf center] of the subtree rooted
675
723
  # at +id+, or nil when the subtree has no leaf.
676
724
  def subtree_leaf_center_span(id)
@@ -772,8 +820,16 @@ module RSyntaxTree
772
820
  parents = @element_list.get_elements.reject { |e| e.children.empty? }
773
821
  parents.sort_by { |p| [-p.level, -p.id] }.each do |parent|
774
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 = []
775
829
  children.each_cons(2) do |left_child, right_child|
776
- 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))
777
833
  delta = clearance.nil? ? 0.0 : tidy_gap - clearance
778
834
 
779
835
  case @tidy_nest
@@ -798,26 +854,27 @@ module RSyntaxTree
798
854
  end
799
855
  end
800
856
 
801
- # Level-balance floor (:ordered only): keep the pair at least a
802
- # fraction of the widest child-level spread found inside its own
803
- # two subtrees. Nesting can tuck an upper pair far narrower than
804
- # the level right below it — an inversion that reads as a
805
- # 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.
806
862
  #
807
863
  # :none does not need it, since the leaf-span guard already
808
- # prevents such inversions. :free deliberately goes without: it is
809
- # the end of the scale where density outranks even branch angles,
810
- # and with the floor in place it compressed no further than
811
- # :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.
812
869
  #
813
870
  # Compression is a negative delta (the right subtree moves left),
814
871
  # so the floor bounds delta from below.
815
- if @tidy_nest == :ordered && delta.negative?
872
+ if %i[ordered free].include?(@tidy_nest) && delta.negative?
816
873
  dist = (right_child.horizontal_indent + right_child.content_width / 2.0) -
817
874
  (left_child.horizontal_indent + left_child.content_width / 2.0)
818
875
  below = [left_child, right_child].map { |c| child_spread(c) }.compact.max
819
876
  if below
820
- min_dist = below * TIDY_LEVEL_BALANCE
877
+ min_dist = below * (@tidy_nest == :free ? TIDY_LEVEL_BALANCE_FREE : TIDY_LEVEL_BALANCE)
821
878
  delta = [delta, min_dist - dist].max
822
879
  end
823
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)
@@ -56,8 +56,11 @@ module RSyntaxTree
56
56
  @nodes << build_node(element)
57
57
  end
58
58
 
59
- def line_to_parent(parent, child)
60
- @edges << { from: parent.id, to: child.id, type: "dominance", connector: "line" }
59
+ def line_to_parent(parent, child, dash_from: nil)
60
+ edge = { from: parent.id, to: child.id, type: "dominance", connector: "line" }
61
+ edge[:dashed] = true if dash_from
62
+ @edges << edge
63
+ 0
61
64
  end
62
65
 
63
66
  # A triangle spans from the parent to its child, through any joints leaf
@@ -215,21 +218,29 @@ module RSyntaxTree
215
218
  element.content.each do |l|
216
219
  next unless l[:type] == :text
217
220
 
218
- segments = l[:elements].map { |e| build_segment(e) }.compact
221
+ segments = l[:elements].flat_map { |e| build_segments(e) }
219
222
  lines << { segments: segments } unless segments.empty?
220
223
  end
221
224
 
222
225
  {
223
- raw: element.raw_content,
226
+ raw: Element.plain_text(element.raw_content.to_s),
224
227
  lines: lines
225
228
  }
226
229
  end
227
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
+
228
239
  def build_segment(run)
229
240
  return nil if run[:decoration].include?(:whitespace) && run[:text].strip.empty?
230
241
 
231
242
  segment = {
232
- text: run[:text].gsub(WHITESPACE_BLOCK, " ").gsub('&#62;', '>').gsub('&#60;', '<'),
243
+ text: Element.plain_text(run[:text].gsub(WHITESPACE_BLOCK, " ")),
233
244
  decorations: run[:decoration].map(&:to_s).reject { |d| d == "whitespace" }
234
245
  }
235
246
  # A feature matrix used to reach this document as an empty segment
@@ -239,6 +250,7 @@ module RSyntaxTree
239
250
  # cells split on the tab stops, rules kept as rows of their own, a
240
251
  # matrix inside a cell recursing.
241
252
  segment[:matrix] = { rows: build_matrix_rows(run[:matrix]) } if run[:decoration].include?(:matrix) && run[:matrix]
253
+ segment[:color] = run[:color] if run[:color]
242
254
  segment
243
255
  end
244
256
 
@@ -253,8 +265,7 @@ module RSyntaxTree
253
265
  if run[:decoration].include?(:tabstop)
254
266
  cells << []
255
267
  else
256
- segment = build_segment(run)
257
- cells.last << segment if segment
268
+ cells.last.concat(build_segments(run))
258
269
  end
259
270
  end
260
271
  { cells: cells }
@@ -338,6 +349,9 @@ module RSyntaxTree
338
349
  edges: @edges,
339
350
  paths: @paths_data
340
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]
341
355
  JSON.pretty_generate(data)
342
356
  end
343
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: [] }] }