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.
@@ -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
@@ -189,7 +193,8 @@ module RSyntaxTree
189
193
 
190
194
  label = extract_label(element)
191
195
  escaped_label = escape_latex(label)
192
- head = "#{escaped_label}#{region_option(element)}"
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
@@ -202,6 +207,17 @@ module RSyntaxTree
202
207
  end
203
208
  end
204
209
 
210
+ # The edge down to a word is dashed when leafstyle asks for it, every
211
+ # piece of it: leaf alignment runs it through joints, and forest gives
212
+ # each joint the edge from the node above. Added to the edge style the
213
+ # tree sets, not in place of it, so the width holds.
214
+ def leaf_edge_option(element)
215
+ return "" unless @params[:leafstyle] == "dashed"
216
+
217
+ element = @element_list.get_id(element.children.first) while element.inserted_joint
218
+ element.type == ETYPE_LEAF ? ", edge+=dashed" : ""
219
+ end
220
+
205
221
  # forest node option that paints a semi-transparent plane behind the whole
206
222
  # subtree governed by +element+ (region shade). Uses forest's "fit to=tree"
207
223
  # on the background layer so the plane sits below the tree. Empty string
@@ -217,6 +233,31 @@ module RSyntaxTree
217
233
  "fit to=tree]{};}}"
218
234
  end
219
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
+
220
261
  # Map an RSyntaxTree color (name or #hex) to a TikZ fill color expression.
221
262
  # SVG/CSS color names and #hex codes are resolved to a TikZ inline rgb
222
263
  # expression so the figure compiles without depending on which color names
@@ -272,21 +313,20 @@ module RSyntaxTree
272
313
  next
273
314
  end
274
315
 
275
- # Remove RSyntaxTree-specific whitespace block
276
- 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("■", " "))
277
319
  texts << text unless text.strip.empty?
278
320
  end
279
321
  end
280
322
  texts
281
323
  end
282
324
 
283
- # 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.
284
328
  def escape_latex(text)
285
- result = text.dup
286
- LATEX_ESCAPE_MAP.each do |char, escaped|
287
- result.gsub!(char, escaped)
288
- end
289
- result
329
+ text.gsub(LATEX_SPECIALS) { |c| LATEX_ESCAPE_MAP[c] }
290
330
  end
291
331
  end
292
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.5.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
@@ -55,14 +58,16 @@ OPTION_VALUES = {
55
58
  # an alias until 3.0. It collided with a code-intelligence format of the
56
59
  # same initials, and claimed an interchange nobody else had implemented.
57
60
  format: FORMATS + ["lsif"],
58
- leafstyle: %w[auto triangle bar nothing],
59
- fontstyle: ["sans", "serif", "cjk", "mono", "noto-sans", "noto-serif", "noto-sans-mono", "cjk zenhei"],
61
+ leafstyle: %w[auto triangle bar dashed nothing],
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.5.0
4
+ version: 2.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yoichiro Hasebe