xlsxrb 0.1.18 → 0.2.1

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.
Files changed (77) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +200 -0
  3. data/README.md +35 -12
  4. data/lib/ruby_lsp/xlsxrb/completion_listener.rb +410 -80
  5. data/lib/xlsxrb/chart_builder.rb +251 -386
  6. data/lib/xlsxrb/dsl_helpers.rb +169 -68
  7. data/lib/xlsxrb/elements/cell.rb +37 -157
  8. data/lib/xlsxrb/elements/column.rb +11 -19
  9. data/lib/xlsxrb/elements/coordinate_access.rb +15 -86
  10. data/lib/xlsxrb/elements/image.rb +5 -72
  11. data/lib/xlsxrb/elements/metadata.rb +463 -817
  12. data/lib/xlsxrb/elements/row.rb +27 -145
  13. data/lib/xlsxrb/elements/styles.rb +30 -88
  14. data/lib/xlsxrb/elements/types.rb +6 -99
  15. data/lib/xlsxrb/elements/workbook.rb +19 -126
  16. data/lib/xlsxrb/elements/worksheet.rb +45 -316
  17. data/lib/xlsxrb/ooxml/reader/listeners/core_listeners.rb +4 -1
  18. data/lib/xlsxrb/ooxml/reader/listeners/drawing_listeners.rb +7 -7
  19. data/lib/xlsxrb/ooxml/reader/listeners/feature_listeners.rb +32 -17
  20. data/lib/xlsxrb/ooxml/reader.rb +49 -51
  21. data/lib/xlsxrb/ooxml/styles_parser.rb +26 -2
  22. data/lib/xlsxrb/ooxml/utils.rb +15 -2
  23. data/lib/xlsxrb/ooxml/workbook_parser.rb +0 -1
  24. data/lib/xlsxrb/ooxml/workbook_writer.rb +184 -94
  25. data/lib/xlsxrb/ooxml/worksheet_parser.rb +61 -29
  26. data/lib/xlsxrb/ooxml/worksheet_writer.rb +353 -261
  27. data/lib/xlsxrb/ooxml/writer/drawing_xml.rb +28 -11
  28. data/lib/xlsxrb/ooxml/writer/features_xml.rb +62 -16
  29. data/lib/xlsxrb/ooxml/writer/styles_xml.rb +1 -1
  30. data/lib/xlsxrb/ooxml/writer.rb +106 -42
  31. data/lib/xlsxrb/ooxml/xml_builder.rb +18 -0
  32. data/lib/xlsxrb/ooxml/xml_parser.rb +78 -5
  33. data/lib/xlsxrb/ooxml/zip_reader.rb +65 -15
  34. data/lib/xlsxrb/ooxml/zip_writer.rb +119 -30
  35. data/lib/xlsxrb/stream_row.rb +14 -118
  36. data/lib/xlsxrb/stream_sheet.rb +14 -261
  37. data/lib/xlsxrb/stream_writer.rb +807 -1537
  38. data/lib/xlsxrb/style_builder.rb +715 -593
  39. data/lib/xlsxrb/version.rb +1 -1
  40. data/lib/xlsxrb/workbook_builder.rb +403 -286
  41. data/lib/xlsxrb/worksheet_builder.rb +1297 -1458
  42. data/lib/xlsxrb.rb +281 -1079
  43. data/sig/generated/xlsxrb/chart_builder.rbs +202 -205
  44. data/sig/generated/xlsxrb/dsl_helpers.rbs +92 -16
  45. data/sig/generated/xlsxrb/elements/cell.rbs +12 -76
  46. data/sig/generated/xlsxrb/elements/column.rbs +0 -7
  47. data/sig/generated/xlsxrb/elements/coordinate_access.rbs +5 -41
  48. data/sig/generated/xlsxrb/elements/image.rbs +3 -29
  49. data/sig/generated/xlsxrb/elements/metadata.rbs +138 -151
  50. data/sig/generated/xlsxrb/elements/row.rbs +10 -53
  51. data/sig/generated/xlsxrb/elements/styles.rbs +1 -39
  52. data/sig/generated/xlsxrb/elements/workbook.rbs +14 -78
  53. data/sig/generated/xlsxrb/elements/worksheet.rbs +5 -121
  54. data/sig/generated/xlsxrb/ooxml/reader/listeners/feature_listeners.rbs +0 -4
  55. data/sig/generated/xlsxrb/ooxml/reader.rbs +0 -3
  56. data/sig/generated/xlsxrb/ooxml/styles_parser.rbs +1 -1
  57. data/sig/generated/xlsxrb/ooxml/utils.rbs +13 -3
  58. data/sig/generated/xlsxrb/ooxml/workbook_writer.rbs +17 -0
  59. data/sig/generated/xlsxrb/ooxml/worksheet_parser.rbs +16 -0
  60. data/sig/generated/xlsxrb/ooxml/worksheet_writer.rbs +58 -3
  61. data/sig/generated/xlsxrb/ooxml/writer/features_xml.rbs +10 -0
  62. data/sig/generated/xlsxrb/ooxml/writer.rbs +20 -14
  63. data/sig/generated/xlsxrb/ooxml/xml_builder.rbs +12 -0
  64. data/sig/generated/xlsxrb/ooxml/xml_parser.rbs +70 -0
  65. data/sig/generated/xlsxrb/ooxml/zip_reader.rbs +22 -7
  66. data/sig/generated/xlsxrb/ooxml/zip_writer.rbs +26 -1
  67. data/sig/generated/xlsxrb/stream_row.rbs +9 -44
  68. data/sig/generated/xlsxrb/stream_sheet.rbs +1 -158
  69. data/sig/generated/xlsxrb/stream_writer.rbs +491 -974
  70. data/sig/generated/xlsxrb/style_builder.rbs +464 -239
  71. data/sig/generated/xlsxrb/workbook_builder.rbs +124 -139
  72. data/sig/generated/xlsxrb/worksheet_builder.rbs +922 -686
  73. data/sig/generated/xlsxrb.rbs +56 -188
  74. data/sig/rexml.rbs +8 -0
  75. metadata +3 -5
  76. data/lib/xlsxrb/utils.rb +0 -251
  77. data/sig/generated/xlsxrb/utils.rbs +0 -200
@@ -22,8 +22,8 @@ module Xlsxrb
22
22
  ea = img[:edit_as] || "oneCell"
23
23
  img_pub_attr = img[:published] ? ' fPublished="1"' : ""
24
24
  parts << %(<xdr:twoCellAnchor editAs="#{xml_escape(ea)}"#{img_pub_attr}>)
25
- parts << anchor_xml("from", img[:from_col], img[:from_row], col_off: img[:from_col_off] || 0, row_off: img[:from_row_off] || 0)
26
- parts << anchor_xml("to", img[:to_col], img[:to_row], col_off: img[:to_col_off] || 0, row_off: img[:to_row_off] || 0)
25
+ parts << anchor_xml("from", img[:from_column] || img[:from_col], img[:from_row], col_off: img[:from_col_off] || 0, row_off: img[:from_row_off] || 0)
26
+ parts << anchor_xml("to", img[:to_column] || img[:to_col], img[:to_row], col_off: img[:to_col_off] || 0, row_off: img[:to_row_off] || 0)
27
27
  macro_attr = img[:macro] ? %( macro="#{xml_escape(img[:macro])}") : ""
28
28
  parts << "<xdr:pic#{macro_attr}>"
29
29
  descr_attr = img[:description] ? %( descr="#{xml_escape(img[:description])}") : ""
@@ -68,8 +68,8 @@ module Xlsxrb
68
68
  chart_ea_attr = chart[:edit_as] ? %( editAs="#{xml_escape(chart[:edit_as])}") : ""
69
69
  chart_pub_attr = chart[:published] ? ' fPublished="1"' : ""
70
70
  parts << "<xdr:twoCellAnchor#{chart_ea_attr}#{chart_pub_attr}>"
71
- parts << anchor_xml("from", chart[:from_col], chart[:from_row], col_off: chart[:from_col_off] || 0, row_off: chart[:from_row_off] || 0)
72
- parts << anchor_xml("to", chart[:to_col], chart[:to_row], col_off: chart[:to_col_off] || 0, row_off: chart[:to_row_off] || 0)
71
+ parts << anchor_xml("from", chart[:from_column] || chart[:from_col], chart[:from_row], col_off: chart[:from_col_off] || 0, row_off: chart[:from_row_off] || 0)
72
+ parts << anchor_xml("to", chart[:to_column] || chart[:to_col], chart[:to_row], col_off: chart[:to_col_off] || 0, row_off: chart[:to_row_off] || 0)
73
73
  gf_macro = chart[:frame_macro] ? xml_escape(chart[:frame_macro]) : ""
74
74
  parts << %(<xdr:graphicFrame macro="#{gf_macro}">)
75
75
  chart_frame_name = chart[:name] || chart[:title] || "Chart"
@@ -93,8 +93,8 @@ module Xlsxrb
93
93
  shape_ea_attr = shape[:edit_as] ? %( editAs="#{xml_escape(shape[:edit_as])}") : ""
94
94
  shape_pub_attr = shape[:published] ? ' fPublished="1"' : ""
95
95
  parts << "<xdr:twoCellAnchor#{shape_ea_attr}#{shape_pub_attr}>"
96
- parts << anchor_xml("from", shape[:from_col], shape[:from_row], col_off: shape[:from_col_off] || 0, row_off: shape[:from_row_off] || 0)
97
- parts << anchor_xml("to", shape[:to_col], shape[:to_row], col_off: shape[:to_col_off] || 0, row_off: shape[:to_row_off] || 0)
96
+ parts << anchor_xml("from", shape[:from_column] || shape[:from_col], shape[:from_row], col_off: shape[:from_col_off] || 0, row_off: shape[:from_row_off] || 0)
97
+ parts << anchor_xml("to", shape[:to_column] || shape[:to_col], shape[:to_row], col_off: shape[:to_col_off] || 0, row_off: shape[:to_row_off] || 0)
98
98
  sp_macro_attr = shape[:macro] ? %( macro="#{xml_escape(shape[:macro])}") : ""
99
99
  sp_textlink_attr = shape[:textlink] ? %( textlink="#{xml_escape(shape[:textlink])}") : ""
100
100
  parts << "<xdr:sp#{sp_macro_attr}#{sp_textlink_attr}>"
@@ -891,7 +891,8 @@ module Xlsxrb
891
891
 
892
892
  # : (untyped chart) -> untyped
893
893
  def generate_chart_xml(chart)
894
- chart_type = CHART_TYPE_MAP[chart[:type]] || "barChart"
894
+ # Charts read from files carry the element name ("lineChart") as their type.
895
+ chart_type = CHART_TYPE_MAP[chart[:type]] || CHART_TYPE_MAP.values.find { |element| element == chart[:type].to_s } || "barChart"
895
896
  parts = [
896
897
  XML_HEADER,
897
898
  %(<c:chartSpace xmlns:c="#{C_NS}" xmlns:a="#{A_NS}" xmlns:r="#{DOC_REL_NS}">)
@@ -1037,9 +1038,11 @@ module Xlsxrb
1037
1038
  ser_order = ser[:order] || idx
1038
1039
  parts << "<c:ser><c:idx val=\"#{idx}\"/><c:order val=\"#{ser_order}\"/>"
1039
1040
  parts << "<c:tx><c:strRef><c:f>#{xml_escape(ser[:name])}</c:f>#{str_cache_xml(ser[:name])}</c:strRef></c:tx>" if ser[:name]
1041
+ head_end = parts.size
1040
1042
  iin = ser[:invert_if_negative]
1041
1043
  parts << %(<c:invertIfNegative val="#{iin ? 1 : 0}"/>) unless iin.nil?
1042
1044
  parts << %(<c:explosion val="#{ser[:explosion]}"/>) if ser[:explosion]
1045
+ options_end = parts.size
1043
1046
  ser[:data_points]&.each do |dp|
1044
1047
  parts << "<c:dPt><c:idx val=\"#{dp[:idx]}\"/>"
1045
1048
  dp_iin = dp[:invert_if_negative]
@@ -1081,6 +1084,7 @@ module Xlsxrb
1081
1084
  parts << "<c:spPr>#{dp_sp_children}</c:spPr>" unless dp_sp_children.empty?
1082
1085
  parts << "</c:dPt>"
1083
1086
  end
1087
+ data_points_end = parts.size
1084
1088
  if ser[:fill_color] || ser[:no_fill] || ser[:line_color] || ser[:no_line] || ser[:line_width] || ser[:line_cap] || ser[:line_join] || ser[:line_dash]
1085
1089
  parts << "<c:spPr>"
1086
1090
  parts << %(<a:solidFill>#{color_xml(ser[:fill_color])}</a:solidFill>) if ser[:fill_color]
@@ -1102,6 +1106,7 @@ module Xlsxrb
1102
1106
  end
1103
1107
  parts << "</c:spPr>"
1104
1108
  end
1109
+ shape_end = parts.size
1105
1110
  if ser[:marker_symbol] || ser[:marker_size] || ser[:marker_fill] || ser[:marker_no_fill] || ser[:marker_line_color] || ser[:marker_line_dash] || ser[:marker_no_line]
1106
1111
  parts << "<c:marker>"
1107
1112
  parts << %(<c:symbol val="#{xml_escape(ser[:marker_symbol])}"/>) if ser[:marker_symbol]
@@ -1122,6 +1127,13 @@ module Xlsxrb
1122
1127
  end
1123
1128
  parts << "</c:marker>"
1124
1129
  end
1130
+ # The series schemas order these children spPr, then invertIfNegative, marker, or
1131
+ # explosion (by chart type), then dPt.
1132
+ options = parts[head_end...options_end]
1133
+ data_points = parts[options_end...data_points_end]
1134
+ shape = parts[data_points_end...shape_end]
1135
+ marker = parts[shape_end..]
1136
+ parts[head_end..] = shape + options + marker + data_points
1125
1137
  if (dl = ser[:data_labels] || chart[:data_labels])
1126
1138
  parts << "<c:dLbls>"
1127
1139
  dl[:labels]&.each do |lbl|
@@ -1333,8 +1345,11 @@ module Xlsxrb
1333
1345
  snb = chart[:show_neg_bubbles]
1334
1346
  parts << %(<c:showNegBubbles val="#{snb ? 1 : 0}"/>) unless snb.nil?
1335
1347
  parts << %(<c:sizeRepresents val="#{chart[:size_represents]}"/>) if chart[:size_represents]
1336
- parts << %(<c:firstSliceAng val="#{chart[:first_slice_ang]}"/>) if chart[:first_slice_ang]
1337
- parts << %(<c:holeSize val="#{chart[:hole_size]}"/>) if chart[:hole_size]
1348
+ # Doughnut charts carry both; Excel's defaults are 0 and 50.
1349
+ first_slice_ang = chart[:first_slice_ang] || (0 if g_type == "doughnutChart")
1350
+ hole_size = chart[:hole_size] || (50 if g_type == "doughnutChart")
1351
+ parts << %(<c:firstSliceAng val="#{first_slice_ang}"/>) if first_slice_ang
1352
+ parts << %(<c:holeSize val="#{hole_size}"/>) if hole_size
1338
1353
  if chart[:ser_lines]
1339
1354
  sl_spec = chart[:ser_lines]
1340
1355
  if sl_spec.is_a?(Hash)
@@ -1653,17 +1668,19 @@ module Xlsxrb
1653
1668
  sheet_comments.each_with_index do |c, idx|
1654
1669
  col, row = cell_to_col_row(c[:ref])
1655
1670
  shape_id = 1025 + idx
1656
- parts << %(<v:shape id="_x0000_s#{shape_id}" type="#_x0000_t202" style="position:absolute;margin-left:59.25pt;margin-top:1.5pt;width:108pt;height:59.25pt;z-index:#{idx + 1};visibility:hidden" fillcolor="#ffffe1" o:insetmode="auto">)
1671
+ parts << %(<v:shape id="_x0000_s#{shape_id}" type="#_x0000_t202" style="position:absolute;margin-left:59.25pt;margin-top:1.5pt;width:108pt;height:59.25pt;z-index:#{idx + 1};visibility:#{c[:visible] ? "visible" : "hidden"}" fillcolor="#ffffe1" o:insetmode="auto">)
1657
1672
  parts << '<v:fill color2="#ffffe1"/>'
1658
1673
  parts << '<v:shadow on="t" color="black" obscured="t"/>'
1659
1674
  parts << '<v:path o:connecttype="none"/>'
1660
1675
  parts << '<v:textbox style="mso-direction-alt:auto"><div style="text-align:left"></div></v:textbox>'
1661
1676
  parts << '<x:ClientData ObjectType="Note">'
1662
1677
  parts << "<x:MoveWithCells/><x:SizeWithCells/>"
1663
- parts << "<x:Anchor>#{col + 1}, 15, #{row}, 10, #{col + 3}, 15, #{row + 4}, 4</x:Anchor>"
1678
+ anchor = c[:anchor] || Xlsxrb::Elements::Comment.default_anchor(col, row)
1679
+ parts << "<x:Anchor>#{anchor.join(", ")}</x:Anchor>"
1664
1680
  parts << "<x:AutoFill>False</x:AutoFill>"
1665
1681
  parts << "<x:Row>#{row}</x:Row>"
1666
1682
  parts << "<x:Column>#{col}</x:Column>"
1683
+ parts << "<x:Visible/>" if c[:visible]
1667
1684
  parts << "</x:ClientData></v:shape>"
1668
1685
  end
1669
1686
  parts << "</xml>"
@@ -70,7 +70,8 @@ module Xlsxrb
70
70
  else
71
71
  (pivot_table[:row_fields].size + pivot_table[:col_fields].size + pivot_table[:data_fields].size).clamp(1, 100)
72
72
  end
73
- loc_attrs = %(<location ref="#{pivot_table[:dest_ref]}" firstHeaderRow="1" firstDataRow="1" firstDataCol="1")
73
+ loc_attrs = %(<location ref="#{pivot_table[:dest_ref]}" firstHeaderRow="#{pivot_table[:first_header_row] || 1}" ) +
74
+ %(firstDataRow="#{pivot_table[:first_data_row] || 1}" firstDataCol="#{pivot_table[:first_data_col] || 1}")
74
75
  loc_attrs << %( rowPageCount="#{pivot_table[:row_page_count]}") if pivot_table[:row_page_count]
75
76
  loc_attrs << %( colPageCount="#{pivot_table[:col_page_count]}") if pivot_table[:col_page_count]
76
77
  loc_attrs << "/>"
@@ -97,11 +98,18 @@ module Xlsxrb
97
98
  attrs << ' includeNewItemsInFilter="1"' if fa && fa[:include_new_items_in_filter]
98
99
 
99
100
  field_items = pivot_table[:items] && pivot_table[:items][fi]
100
- if field_items
101
+ axis_field = pivot_table[:row_fields].include?(fi) || pivot_table[:col_fields].include?(fi)
102
+ # The default subtotal item goes with the default subtotal; a field with
103
+ # defaultSubtotal="0" must not list it.
104
+ default_subtotal = !(fa && fa[:default_subtotal] == false)
105
+ if field_items || (axis_field && default_subtotal)
106
+ # A row or column field needs an <items> list; without known items it holds only the
107
+ # default subtotal, which Excel fills in when it refreshes the cache on open.
108
+ field_items ||= []
101
109
  parts << "<pivotField#{attrs}>"
102
- parts << %(<items count="#{field_items.size + 1}">)
110
+ parts << %(<items count="#{field_items.size + (default_subtotal ? 1 : 0)}">)
103
111
  field_items.size.times { |ix| parts << %(<item x="#{ix}"/>) }
104
- parts << '<item t="default"/>'
112
+ parts << '<item t="default"/>' if default_subtotal
105
113
  parts << "</items>"
106
114
  parts << "</pivotField>"
107
115
  else
@@ -169,7 +177,9 @@ module Xlsxrb
169
177
  # Parse source ref: "Sheet1!A1:C4" => sheet name + range.
170
178
  source = pivot_table[:source_ref]
171
179
  ws_name_attr = pivot_table[:source_name] ? %( name="#{xml_escape(pivot_table[:source_name])}") : ""
172
- if source.include?("!")
180
+ if source.nil?
181
+ parts << %(<cacheSource type="worksheet"><worksheetSource#{ws_name_attr}/></cacheSource>)
182
+ elsif source.include?("!")
173
183
  sname, srange = source.split("!", 2)
174
184
  sname = sname.delete("'")
175
185
  parts << %(<cacheSource type="worksheet"><worksheetSource ref="#{srange}" sheet="#{xml_escape(sname)}"#{ws_name_attr}/></cacheSource>)
@@ -194,8 +204,8 @@ module Xlsxrb
194
204
  field_items = pivot_table[:items] && pivot_table[:items][fi]
195
205
  if field_items
196
206
  parts << "<cacheField#{cf_attrs}>"
197
- parts << %(<sharedItems count="#{field_items.size}">)
198
- field_items.each { |v| parts << %(<s v="#{xml_escape(v.to_s)}"/>) }
207
+ parts << %(<sharedItems#{shared_items_attrs(field_items)} count="#{field_items.size}">)
208
+ field_items.each { |v| parts << shared_item_xml(v) }
199
209
  parts << "</sharedItems>"
200
210
  parts << "</cacheField>"
201
211
  else
@@ -207,6 +217,33 @@ module Xlsxrb
207
217
  parts.join
208
218
  end
209
219
 
220
+ # Attributes that describe the value types of a cache field's shared items.
221
+ # : (Array[untyped] values) -> String
222
+ def shared_items_attrs(values)
223
+ numbers = values.grep(Numeric)
224
+ strings = values.any? { |v| !v.nil? && !v.is_a?(Numeric) && v != true && v != false }
225
+ attrs = +""
226
+ attrs << ' containsSemiMixedTypes="0"' unless strings || values.include?(nil)
227
+ attrs << ' containsString="0"' unless strings
228
+ attrs << ' containsBlank="1"' if values.include?(nil)
229
+ unless numbers.empty?
230
+ attrs << ' containsNumber="1"'
231
+ attrs << ' containsInteger="1"' if numbers.all? { |n| n.is_a?(Integer) || n == n.to_i }
232
+ attrs << %( minValue="#{numbers.min}" maxValue="#{numbers.max}")
233
+ end
234
+ attrs
235
+ end
236
+
237
+ # : (untyped value) -> String
238
+ def shared_item_xml(value)
239
+ case value
240
+ when nil then "<m/>"
241
+ when true, false then %(<b v="#{value ? 1 : 0}"/>)
242
+ when Numeric then %(<n v="#{value}"/>)
243
+ else %(<s v="#{xml_escape(value.to_s)}"/>)
244
+ end
245
+ end
246
+
210
247
  # : (untyped pivot_table) -> untyped
211
248
  def generate_pivot_cache_records_xml(pivot_table)
212
249
  items = pivot_table[:items]
@@ -302,6 +339,13 @@ module Xlsxrb
302
339
  end
303
340
 
304
341
  # : (untyped value) -> untyped
342
+ # Escapes cell text: ST_Xstring (XmlBuilder.encode_xstring), then XML.
343
+ def xml_escape_text(value)
344
+ str = value.to_s
345
+ str = str.dup.force_encoding(Encoding::UTF_8) if str.encoding == Encoding::BINARY
346
+ xml_escape(XmlBuilder.encode_xstring(str))
347
+ end
348
+
305
349
  def xml_escape(value)
306
350
  value.to_s
307
351
  .gsub(/[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/, "")
@@ -315,8 +359,8 @@ module Xlsxrb
315
359
  # : (untyped rich_text) -> untyped
316
360
  def rich_text_xml(rich_text)
317
361
  rich_text.runs.map do |run|
318
- font = run.is_a?(Hash) ? run[:font] : run.font
319
- run_text = run.is_a?(Hash) ? run[:text] : run.text
362
+ font = run.respond_to?(:font) ? run.font : run[:font]
363
+ text = run.respond_to?(:text) ? run.text : run[:text]
320
364
  if font && !font.empty?
321
365
  rpr = +""
322
366
  rpr << "<b/>" if font[:bold]
@@ -338,14 +382,15 @@ module Xlsxrb
338
382
  mapped_va = StyleBuilder::VERT_ALIGN_MAP[va_val.to_sym] || va_val
339
383
  rpr << %(<vertAlign val="#{mapped_va}"/>)
340
384
  end
341
- rpr << %(<sz val="#{font[:sz]}"/>) if font[:sz]
385
+ font_sz = font[:size] || font[:sz]
386
+ rpr << %(<sz val="#{font_sz}"/>) if font_sz
342
387
  rpr << emit_color_xml(font)
343
388
  rpr << %(<rFont val="#{xml_escape(font[:name])}"/>) if font[:name]
344
389
  rpr << %(<family val="#{font[:family]}"/>) if font[:family]
345
390
  rpr << %(<scheme val="#{font[:scheme]}"/>) if font[:scheme]
346
- "<r><rPr>#{rpr}</rPr><t>#{xml_escape(run_text)}</t></r>"
391
+ "<r><rPr>#{rpr}</rPr><t>#{xml_escape_text(text)}</t></r>"
347
392
  else
348
- "<r><t>#{xml_escape(run_text)}</t></r>"
393
+ "<r><t>#{xml_escape_text(text)}</t></r>"
349
394
  end
350
395
  end.join
351
396
  end
@@ -372,7 +417,7 @@ module Xlsxrb
372
417
  f_attrs << %( r1="#{value.r1}") if value.r1
373
418
  f_attrs << %( r2="#{value.r2}") if value.r2
374
419
  end
375
- f_attrs << ' ca="1"' if value.calculate_always
420
+ f_attrs << ' ca="1"' if value.calculate_always?
376
421
  f_attrs << ' aca="1"' if value.aca
377
422
  f_attrs << ' bx="1"' if value.bx
378
423
  t_attr = ""
@@ -393,7 +438,7 @@ module Xlsxrb
393
438
  "<f#{f_attrs}/>"
394
439
  end
395
440
  parts = %(<c r="#{cell_ref}"#{t_attr}#{s_attr}#{ph_attr}>#{f_tag})
396
- parts << "<v>#{xml_escape(cached_val_str)}</v>" unless value.cached_value.nil?
441
+ parts << "<v>#{xml_escape_text(cached_val_str)}</v>" unless value.cached_value.nil?
397
442
  parts << "</c>"
398
443
  parts
399
444
  when Xlsxrb::Elements::RichText
@@ -424,7 +469,7 @@ module Xlsxrb
424
469
  idx = str_sst[value.to_s]
425
470
  %(<c r="#{cell_ref}" t="s"#{s_attr}#{ph_attr}><v>#{idx}</v></c>)
426
471
  else
427
- %(<c r="#{cell_ref}" t="inlineStr"#{s_attr}#{ph_attr}><is><t>#{xml_escape(value)}</t></is></c>)
472
+ %(<c r="#{cell_ref}" t="inlineStr"#{s_attr}#{ph_attr}><is><t>#{xml_escape_text(value)}</t></is></c>)
428
473
  end
429
474
  end
430
475
  end
@@ -695,7 +740,8 @@ module Xlsxrb
695
740
  XML_HEADER,
696
741
  %(<Properties xmlns="#{APP_NS}" xmlns:vt="#{VT_NS}">)
697
742
  ]
698
- parts << "<Application>#{xml_escape(@app_properties[:application])}</Application>" if @app_properties[:application]
743
+ app_val = @app_properties[:app_name] || @app_properties[:application]
744
+ parts << "<Application>#{xml_escape(app_val)}</Application>" if app_val
699
745
  parts << "<AppVersion>#{xml_escape(@app_properties[:app_version])}</AppVersion>" if @app_properties[:app_version]
700
746
  if @app_properties[:heading_pairs] && @app_properties[:titles_of_parts]
701
747
  hp = @app_properties[:heading_pairs]
@@ -335,7 +335,7 @@ module Xlsxrb
335
335
  # : (untyped brk, default_max: untyped) -> ::String
336
336
  def emit_brk_xml(brk, default_max:)
337
337
  brk = brk.to_h if brk.is_a?(Elements::MetadataRecord)
338
- if brk.is_a?(Hash) || brk.is_a?(Elements::PageBreak)
338
+ if brk.is_a?(Hash)
339
339
  attrs = %(id="#{brk[:id]}")
340
340
  attrs << %( min="#{brk[:min]}") if brk[:min]
341
341
  attrs << %( max="#{brk.respond_to?(:fetch) ? brk.fetch(:max, default_max) : (brk[:max] || default_max)}")
@@ -563,9 +563,13 @@ module Xlsxrb
563
563
  name = opts[:name]
564
564
  end
565
565
 
566
- font = @fonts[0] ? @fonts[0].dup : { name: "Calibri", sz: 11 }
566
+ font = @fonts[0] ? @fonts[0].dup : { name: "Calibri", sz: 11, size: 11 }
567
567
  font[:name] = (name || opts[:name]).to_s if name || opts[:name]
568
- font[:sz] = size || opts[:size] || opts[:sz] if size || opts[:size] || opts[:sz]
568
+ sz_val = size || opts[:size] || opts[:sz]
569
+ if sz_val
570
+ font[:sz] = sz_val
571
+ font[:size] = sz_val
572
+ end
569
573
  font[:family] = opts[:family] if opts.key?(:family)
570
574
  font[:charset] = opts[:charset] if opts.key?(:charset)
571
575
  font[:scheme] = opts[:scheme].to_s if opts.key?(:scheme)
@@ -577,8 +581,6 @@ module Xlsxrb
577
581
 
578
582
  @fonts[0] = font
579
583
  end
580
- # @deprecated Use {#default_font} instead. Will be removed in 0.2.0.
581
- alias set_default_font default_font
582
584
 
583
585
  # Sets the indexed colors palette (array of ARGB hex strings, e.g. ["FF000000", "FFFFFFFF"]).
584
586
  # rubocop:disable Naming/AccessorMethodName
@@ -742,13 +744,14 @@ module Xlsxrb
742
744
  (@sheet_views[sheet_name] || {}).dup
743
745
  end
744
746
 
745
- # Sets a freeze pane. row: rows to freeze from top, col: columns to freeze from left.
746
- # : (?row: ::Integer, ?col: ::Integer, ?sheet: untyped?) -> untyped
747
- def set_freeze_pane(row: 0, col: 0, sheet: nil)
747
+ # Sets a freeze pane. row: rows to freeze from top, column: columns to freeze from left.
748
+ # : (?row: ::Integer, ?col: ::Integer?, ?column: ::Integer?, ?sheet: untyped?) -> untyped
749
+ def set_freeze_pane(row: 0, col: nil, column: nil, sheet: nil)
748
750
  sheet_name = sheet || @sheet_order.first
749
751
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @freeze_panes.key?(sheet_name)
750
752
 
751
- @freeze_panes[sheet_name] = { row: row, col: col, state: :frozen }
753
+ col_val = column || col || 0
754
+ @freeze_panes[sheet_name] = { row: row, column: col_val, state: :frozen }
752
755
  end
753
756
 
754
757
  # Sets a split pane (non-frozen). x_split/y_split are in 1/20th of a point (twips).
@@ -1671,8 +1674,8 @@ module Xlsxrb
1671
1674
  end
1672
1675
 
1673
1676
  # Adds a comment on a cell.
1674
- # : (untyped cell_address, untyped text, ?author: ::String, ?sheet: untyped?, ?guid: untyped?, ?shape_id: untyped?) -> untyped
1675
- def add_comment(cell_address, text, author: "Author", sheet: nil, guid: nil, shape_id: nil)
1677
+ # : (untyped cell_address, untyped text, ?author: ::String, ?sheet: untyped?, ?guid: untyped?, ?shape_id: untyped?, ?visible: bool, ?anchor: Array[Integer]?) -> untyped
1678
+ def add_comment(cell_address, text, author: "Author", sheet: nil, guid: nil, shape_id: nil, visible: false, anchor: nil)
1676
1679
  validate_cell_address!(cell_address)
1677
1680
  sheet_name = sheet || @sheet_order.first
1678
1681
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @comments_data.key?(sheet_name)
@@ -1680,6 +1683,8 @@ module Xlsxrb
1680
1683
  entry = { ref: cell_address, text: text, author: author }
1681
1684
  entry[:guid] = guid if guid
1682
1685
  entry[:shape_id] = shape_id if shape_id
1686
+ entry[:visible] = true if visible
1687
+ entry[:anchor] = anchor if anchor
1683
1688
  @comments_data[sheet_name] << entry
1684
1689
  end
1685
1690
 
@@ -1766,22 +1771,27 @@ module Xlsxrb
1766
1771
  alias person_list persons
1767
1772
 
1768
1773
  # Adds a pivot table to the given sheet.
1769
- # source_ref: data source range (e.g. "Sheet1!A1:C4").
1770
- # row_fields: array of 0-based field indices for row axis.
1771
- # data_fields: array of { fld:, name:, subtotal: } hashes.
1772
- # col_fields: array of 0-based field indices for column axis.
1774
+ # source_ref: data source range (e.g. "Sheet1!A1:C4"), or nil with source_name: for a table source.
1775
+ # row_fields: array of 0-based field indices, or field names listed in field_names, for row axis.
1776
+ # data_fields: array of { fld:, name:, subtotal: } hashes ({ field: } takes a field name or index
1777
+ # in place of fld:), or field names.
1778
+ # col_fields: array of 0-based field indices, or field names, for column axis.
1773
1779
  # field_names: array of field name strings (for cache definition).
1774
1780
  # items: hash mapping field index to array of item values.
1775
- # : (untyped source_ref, row_fields: untyped, data_fields: untyped, ?col_fields: untyped, ?dest_ref: ::String, ?name: untyped?, ?field_names: untyped?, ?items: untyped?, ?sheet: untyped?, **untyped opts) -> untyped
1776
- def add_pivot_table(source_ref, row_fields:, data_fields:, col_fields: [], dest_ref: "E1", name: nil, field_names: nil, items: nil, sheet: nil, **opts)
1781
+ # : (untyped source_ref, row_fields: untyped, data_fields: untyped, ?col_fields: untyped, ?column_fields: untyped, ?dest_ref: untyped, ?destination: untyped, ?name: untyped?, ?field_names: untyped?, ?items: untyped?, ?sheet: untyped?, **untyped opts) -> untyped
1782
+ def add_pivot_table(source_ref, row_fields:, data_fields:, col_fields: nil, column_fields: nil, dest_ref: nil, destination: nil, name: nil, field_names: nil, items: nil, sheet: nil, **opts)
1777
1783
  sheet_name = sheet || @sheet_order.first
1778
1784
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @pivot_tables_data.key?(sheet_name)
1779
1785
 
1780
1786
  pt_name = name || "PivotTable#{@pivot_tables_data.values.flatten.size + 1}"
1787
+ row_fields = row_fields.map { |f| resolve_pivot_field(f, field_names) }
1788
+ c_fields = (column_fields || col_fields || []).map { |f| resolve_pivot_field(f, field_names) }
1789
+ data_fields = data_fields.map { |df| resolve_pivot_data_field(df, field_names) }
1790
+ target_dest = destination || dest_ref || "E1"
1781
1791
  @pivot_tables_data[sheet_name] << {
1782
1792
  name: pt_name, source_ref: source_ref,
1783
- row_fields: row_fields, col_fields: col_fields,
1784
- data_fields: data_fields, dest_ref: dest_ref,
1793
+ row_fields: row_fields, col_fields: c_fields, column_fields: c_fields,
1794
+ data_fields: data_fields, dest_ref: target_dest, destination: target_dest,
1785
1795
  field_names: field_names, items: items,
1786
1796
  data_caption: opts[:data_caption], data_on_rows: opts[:data_on_rows],
1787
1797
  row_grand_totals: opts[:row_grand_totals], col_grand_totals: opts[:col_grand_totals],
@@ -1798,6 +1808,7 @@ module Xlsxrb
1798
1808
  cache_created_version: opts[:cache_created_version], cache_record_count: opts[:cache_record_count],
1799
1809
  cache_optimize_memory: opts[:cache_optimize_memory],
1800
1810
  row_page_count: opts[:row_page_count], col_page_count: opts[:col_page_count],
1811
+ first_header_row: opts[:first_header_row], first_data_row: opts[:first_data_row], first_data_col: opts[:first_data_col],
1801
1812
  field_attrs: opts[:field_attrs],
1802
1813
  apply_number_formats: opts[:apply_number_formats],
1803
1814
  apply_border_formats: opts[:apply_border_formats],
@@ -1826,6 +1837,35 @@ module Xlsxrb
1826
1837
  }
1827
1838
  end
1828
1839
 
1840
+ # Resolves a pivot table field given as a 0-based index or as a name in field_names.
1841
+ # : (untyped field, untyped field_names) -> Integer
1842
+ def resolve_pivot_field(field, field_names)
1843
+ return field if field.is_a?(Integer)
1844
+ raise ArgumentError, "pivot table field #{field.inspect} is a name; pass field_names: to resolve it" unless field_names
1845
+
1846
+ index = field_names.index(field.to_s)
1847
+ raise ArgumentError, "pivot table field #{field.inspect} is not in field_names #{field_names.inspect}" unless index
1848
+
1849
+ index
1850
+ end
1851
+ private :resolve_pivot_field
1852
+
1853
+ # Normalizes a pivot table data field to a Hash with an Integer fld.
1854
+ # : (untyped data_field, untyped field_names) -> Hash[Symbol, untyped]
1855
+ def resolve_pivot_data_field(data_field, field_names)
1856
+ data_field = { field: data_field } unless data_field.is_a?(Hash)
1857
+ return data_field if data_field[:fld].is_a?(Integer) && !data_field.key?(:field)
1858
+
1859
+ field = data_field.key?(:field) ? data_field[:field] : data_field[:fld]
1860
+ raise ArgumentError, "pivot table data field #{data_field.inspect} needs fld: or field:" if field.nil?
1861
+
1862
+ fld = resolve_pivot_field(field, field_names)
1863
+ subtotal = (data_field[:subtotal] || "sum").to_s
1864
+ caption = data_field[:name] || "#{subtotal[0].upcase}#{subtotal[1..]} of #{field_names ? field_names[fld] : "Field#{fld + 1}"}"
1865
+ data_field.except(:field).merge(fld: fld, name: caption, subtotal: subtotal)
1866
+ end
1867
+ private :resolve_pivot_data_field
1868
+
1829
1869
  # Returns pivot table definitions for the first (or given) sheet.
1830
1870
  # : (?sheet: untyped?) -> untyped
1831
1871
  def pivot_tables(sheet: nil)
@@ -2303,7 +2343,8 @@ module Xlsxrb
2303
2343
  attrs << %(windowHeight="#{@workbook_views[:window_height]}") if @workbook_views[:window_height]
2304
2344
  attrs << %(tabRatio="#{@workbook_views[:tab_ratio]}") if @workbook_views[:tab_ratio]
2305
2345
  attrs << %(firstSheet="#{@workbook_views[:first_sheet]}") if @workbook_views[:first_sheet]
2306
- attrs << %(activeTab="#{@workbook_views[:active_tab]}") if @workbook_views[:active_tab]
2346
+ at = @workbook_views[:active_sheet_index] || @workbook_views[:active_tab]
2347
+ attrs << %(activeTab="#{at}") if at
2307
2348
  afdg = @workbook_views[:auto_filter_date_grouping]
2308
2349
  attrs << %(autoFilterDateGrouping="#{afdg ? 1 : 0}") unless afdg.nil?
2309
2350
  parts << "<bookViews>"
@@ -2543,8 +2584,11 @@ module Xlsxrb
2543
2584
  outline_attrs << %(showOutlineSymbols="#{sos ? 1 : 0}") unless sos.nil?
2544
2585
  sp_children << "<outlinePr #{outline_attrs.join(" ")}/>"
2545
2586
  end
2587
+ psp = sheet_props[:page_setup_properties] || sheet_props[:page_setup_pr]
2546
2588
  ftp = sheet_props[:fit_to_page]
2589
+ ftp = psp[:fit_to_page] if ftp.nil? && psp.is_a?(Hash)
2547
2590
  apb = sheet_props[:auto_page_breaks]
2591
+ apb = psp[:auto_page_breaks] if apb.nil? && psp.is_a?(Hash)
2548
2592
  unless ftp.nil? && apb.nil?
2549
2593
  psp_attrs = []
2550
2594
  psp_attrs << %(fitToPage="#{ftp ? 1 : 0}") unless ftp.nil?
@@ -2614,22 +2658,25 @@ module Xlsxrb
2614
2658
  end
2615
2659
  pane_attrs << %(activePane="#{active_pane}")
2616
2660
  parts << "<pane #{pane_attrs.join(" ")}/>"
2617
- elsif sheet_fp && (sheet_fp[:row].to_i.positive? || sheet_fp[:col].to_i.positive?)
2618
- top_left = "#{index_to_column_letter(sheet_fp[:col].to_i + 1)}#{sheet_fp[:row].to_i + 1}"
2619
- pane_attrs = []
2620
- pane_attrs << %(ySplit="#{sheet_fp[:row]}") if sheet_fp[:row].to_i.positive?
2621
- pane_attrs << %(xSplit="#{sheet_fp[:col]}") if sheet_fp[:col].to_i.positive?
2622
- pane_attrs << %(topLeftCell="#{top_left}")
2623
- active_pane = if sheet_fp[:row].to_i.positive? && sheet_fp[:col].to_i.positive?
2624
- "bottomRight"
2625
- elsif sheet_fp[:row].to_i.positive?
2626
- "bottomLeft"
2627
- else
2628
- "topRight"
2629
- end
2630
- pane_attrs << %(activePane="#{active_pane}")
2631
- pane_attrs << 'state="frozen"'
2632
- parts << "<pane #{pane_attrs.join(" ")}/>"
2661
+ elsif sheet_fp
2662
+ fp_col = sheet_fp[:column] || sheet_fp[:col] || 0
2663
+ if sheet_fp[:row].to_i.positive? || fp_col.to_i.positive?
2664
+ top_left = "#{index_to_column_letter(fp_col.to_i + 1)}#{sheet_fp[:row].to_i + 1}"
2665
+ pane_attrs = []
2666
+ pane_attrs << %(ySplit="#{sheet_fp[:row]}") if sheet_fp[:row].to_i.positive?
2667
+ pane_attrs << %(xSplit="#{fp_col}") if fp_col.to_i.positive?
2668
+ pane_attrs << %(topLeftCell="#{top_left}")
2669
+ active_pane = if sheet_fp[:row].to_i.positive? && fp_col.to_i.positive?
2670
+ "bottomRight"
2671
+ elsif sheet_fp[:row].to_i.positive?
2672
+ "bottomLeft"
2673
+ else
2674
+ "topRight"
2675
+ end
2676
+ pane_attrs << %(activePane="#{active_pane}")
2677
+ pane_attrs << 'state="frozen"'
2678
+ parts << "<pane #{pane_attrs.join(" ")}/>"
2679
+ end
2633
2680
  end
2634
2681
 
2635
2682
  if sheet_sel
@@ -2987,8 +3034,8 @@ module Xlsxrb
2987
3034
  ps_attrs << %(cellComments="#{sheet_ps[:cell_comments]}") if sheet_ps[:cell_comments]
2988
3035
  ps_attrs << %(firstPageNumber="#{sheet_ps[:first_page_number]}") if sheet_ps[:first_page_number] && sheet_ps[:first_page_number].to_i >= 0
2989
3036
  ps_attrs << 'useFirstPageNumber="1"' if sheet_ps[:use_first_page_number]
2990
- ps_attrs << %(horizontalDpi="#{sheet_ps[:horizontal_dpi]}") if sheet_ps[:horizontal_dpi]
2991
- ps_attrs << %(verticalDpi="#{sheet_ps[:vertical_dpi]}") if sheet_ps[:vertical_dpi]
3037
+ ps_attrs << %(horizontalDpi="#{sheet_ps[:horizontal_dpi]}") if sheet_ps[:horizontal_dpi].to_i.positive?
3038
+ ps_attrs << %(verticalDpi="#{sheet_ps[:vertical_dpi]}") if sheet_ps[:vertical_dpi].to_i.positive?
2992
3039
  ps_attrs << %(copies="#{sheet_ps[:copies]}") if sheet_ps[:copies]
2993
3040
  ps_attrs << %(paperHeight="#{sheet_ps[:paper_height]}") if sheet_ps[:paper_height]
2994
3041
  ps_attrs << %(paperWidth="#{sheet_ps[:paper_width]}") if sheet_ps[:paper_width]
@@ -3017,7 +3064,15 @@ module Xlsxrb
3017
3064
 
3018
3065
  # Emit <rowBreaks> if defined.
3019
3066
  unless sheet_rb.empty?
3020
- manual_count = sheet_rb.count { |r| r.is_a?(Hash) || r.respond_to?(:fetch) ? r.fetch(:man, true) : true }
3067
+ manual_count = sheet_rb.count do |r|
3068
+ if r.is_a?(Elements::PageBreak)
3069
+ r.manual?
3070
+ elsif r.is_a?(Hash)
3071
+ r[:man] != false
3072
+ else
3073
+ true
3074
+ end
3075
+ end
3021
3076
  parts << %(<rowBreaks count="#{sheet_rb.size}" manualBreakCount="#{manual_count}">)
3022
3077
  sheet_rb.each { |r| parts << emit_brk_xml(r, default_max: 16_383) }
3023
3078
  parts << "</rowBreaks>"
@@ -3025,7 +3080,15 @@ module Xlsxrb
3025
3080
 
3026
3081
  # Emit <colBreaks> if defined.
3027
3082
  unless sheet_cb.empty?
3028
- manual_count = sheet_cb.count { |c| c.is_a?(Hash) || c.respond_to?(:fetch) ? c.fetch(:man, true) : true }
3083
+ manual_count = sheet_cb.count do |c|
3084
+ if c.is_a?(Elements::PageBreak)
3085
+ c.manual?
3086
+ elsif c.is_a?(Hash)
3087
+ c[:man] != false
3088
+ else
3089
+ true
3090
+ end
3091
+ end
3029
3092
  parts << %(<colBreaks count="#{sheet_cb.size}" manualBreakCount="#{manual_count}">)
3030
3093
  sheet_cb.each { |c| parts << emit_brk_xml(c, default_max: 1_048_575) }
3031
3094
  parts << "</colBreaks>"
@@ -3117,7 +3180,7 @@ module Xlsxrb
3117
3180
  parts << if entry[:type] == :rt
3118
3181
  "<si>#{rich_text_xml(entry[:value])}</si>"
3119
3182
  else
3120
- "<si><t>#{xml_escape(entry[:value])}</t></si>"
3183
+ "<si><t>#{xml_escape_text(entry[:value])}</t></si>"
3121
3184
  end
3122
3185
  end
3123
3186
  parts << "</sst>"
@@ -3164,7 +3227,7 @@ module Xlsxrb
3164
3227
  col_attrs = %(id="#{i + 1}" name="#{xml_escape(col_name)}")
3165
3228
  if col.is_a?(Hash) || col.is_a?(Elements::TableColumn)
3166
3229
  calc_formula = col[:calculated_column_formula] || col[:data_formula] || col[:formula]
3167
- tot_formula = col[:totals_row_formula] || col[:total_row_formula] || col[:total_formula]
3230
+ tot_formula = col[:totals_row_formula]
3168
3231
  trf = col[:totals_row_function] || ("custom" if tot_formula)
3169
3232
  col_attrs << %( totalsRowFunction="#{trf}") if trf
3170
3233
  col_attrs << %( totalsRowLabel="#{xml_escape(col[:totals_row_label])}") if col[:totals_row_label]
@@ -3185,7 +3248,8 @@ module Xlsxrb
3185
3248
  end
3186
3249
  end
3187
3250
  parts << "</tableColumns>"
3188
- raw_style = tbl[:style]
3251
+ raw_style = tbl[:style] || tbl[:style_info]
3252
+ raw_style = raw_style.to_h if raw_style.respond_to?(:to_h)
3189
3253
  style = if raw_style.is_a?(Hash)
3190
3254
  raw_style
3191
3255
  elsif raw_style
@@ -118,6 +118,24 @@ module Xlsxrb
118
118
  str.match?(ESCAPE_RE) ? str.gsub(ESCAPE_RE, ESCAPE_MAP) : str
119
119
  end
120
120
 
121
+ XSTRING_ENCODE_RE = /_(?=x\h{4}_)|[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/
122
+ private_constant :XSTRING_ENCODE_RE
123
+
124
+ # Encodes cell text as ISO/IEC 29500-1 ST_Xstring, the inverse of the _xHHHH_ part
125
+ # of unescape: an underscore that starts an _xHHHH_ sequence becomes _x005F_, and a
126
+ # character that XML 1.0 cannot hold, such as U+0001 or U+FFFE, becomes _xHHHH_.
127
+ # Excel and unescape read the original text back. The value must be UTF-8.
128
+ #
129
+ # @param value [String]
130
+ # @return [String]
131
+ #: (String value) -> String
132
+ def self.encode_xstring(value)
133
+ return value unless value.match?(XSTRING_ENCODE_RE)
134
+
135
+ # The underscore is U+005F, so the same format gives _x005F_.
136
+ value.gsub(XSTRING_ENCODE_RE) { |char| format("_x%04X_", char.ord) }
137
+ end
138
+
121
139
  NUM_ENTITY_RE = /&#(?:(\d+)|x([0-9a-fA-F]+));/
122
140
  XSTRING_RE = /_x([0-9A-Fa-f]{4})_/
123
141
  private_constant :NUM_ENTITY_RE, :XSTRING_RE