wp2txt 2.3.4 → 2.5.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.
Files changed (83) hide show
  1. checksums.yaml +4 -4
  2. data/.dockerignore +0 -4
  3. data/.github/workflows/ci.yml +16 -1
  4. data/.github/workflows/publish-image.yml +8 -4
  5. data/.gitignore +3 -6
  6. data/CHANGELOG.md +32 -0
  7. data/DEVELOPMENT.md +63 -93
  8. data/DEVELOPMENT_ja.md +61 -93
  9. data/Dockerfile +1 -1
  10. data/README.md +93 -8
  11. data/README_ja.md +84 -8
  12. data/Rakefile +10 -21
  13. data/bin/wp2txt +84 -15
  14. data/bin/wp2txt-mcp +1 -1
  15. data/docs/INDEXES.md +61 -1
  16. data/lib/wp2txt/article.rb +2 -3
  17. data/lib/wp2txt/bz2_stream.rb +63 -0
  18. data/lib/wp2txt/cli.rb +90 -26
  19. data/lib/wp2txt/config.rb +2 -11
  20. data/lib/wp2txt/constants.rb +13 -1
  21. data/lib/wp2txt/corpus.rb +10 -23
  22. data/lib/wp2txt/data/template_aliases.json +4 -1
  23. data/lib/wp2txt/data/template_patterns.json +61643 -0
  24. data/lib/wp2txt/dump_snapshot.rb +99 -0
  25. data/lib/wp2txt/extraction_run.rb +272 -0
  26. data/lib/wp2txt/extractor.rb +481 -327
  27. data/lib/wp2txt/formatter.rb +14 -12
  28. data/lib/wp2txt/fts_index.rb +1 -1
  29. data/lib/wp2txt/index_cache.rb +144 -55
  30. data/lib/wp2txt/index_commands.rb +109 -18
  31. data/lib/wp2txt/langlinks_importer.rb +19 -35
  32. data/lib/wp2txt/lead_terms.rb +228 -0
  33. data/lib/wp2txt/link_counter.rb +171 -0
  34. data/lib/wp2txt/magic_words.rb +44 -28
  35. data/lib/wp2txt/metadata_index.rb +82 -13
  36. data/lib/wp2txt/multistream.rb +911 -824
  37. data/lib/wp2txt/output_writer.rb +3 -1
  38. data/lib/wp2txt/page_props_importer.rb +170 -0
  39. data/lib/wp2txt/parser_functions.rb +23 -5
  40. data/lib/wp2txt/ractor_worker.rb +6 -4
  41. data/lib/wp2txt/regex.rb +24 -4
  42. data/lib/wp2txt/site_info.rb +123 -0
  43. data/lib/wp2txt/sql_dump_reader.rb +57 -0
  44. data/lib/wp2txt/stream_processor.rb +9 -2
  45. data/lib/wp2txt/stream_store.rb +91 -0
  46. data/lib/wp2txt/template_args.rb +111 -0
  47. data/lib/wp2txt/template_expander.rb +110 -124
  48. data/lib/wp2txt/template_patterns.rb +182 -0
  49. data/lib/wp2txt/utils.rb +164 -127
  50. data/lib/wp2txt/version.rb +1 -1
  51. data/lib/wp2txt/wikitext_regions.rb +66 -0
  52. data/spec/auto_download_spec.rb +9 -6
  53. data/spec/category_fetcher_spec.rb +135 -463
  54. data/spec/cli_targeted_spec.rb +60 -0
  55. data/spec/config_spec.rb +2 -15
  56. data/spec/constants_spec.rb +0 -4
  57. data/spec/docs_sync_spec.rb +3 -3
  58. data/spec/dump_fetch_spec.rb +293 -0
  59. data/spec/extraction_run_spec.rb +520 -0
  60. data/spec/index_build_spec.rb +113 -0
  61. data/spec/index_commands_version_spec.rb +17 -0
  62. data/spec/langlinks_importer_spec.rb +27 -0
  63. data/spec/lead_terms_edge_cases_spec.rb +194 -0
  64. data/spec/lead_terms_links_qids_spec.rb +204 -0
  65. data/spec/multistream_reader_spec.rb +140 -0
  66. data/spec/multistream_spec.rb +8 -214
  67. data/spec/output_integrity_spec.rb +45 -2
  68. data/spec/p1_correctness_spec.rb +12 -9
  69. data/spec/page_properties_spec.rb +161 -0
  70. data/spec/regex_spec.rb +30 -0
  71. data/spec/region_semantics_spec.rb +71 -0
  72. data/spec/spec_helper.rb +3 -3
  73. data/spec/support/dump_status.rb +34 -0
  74. data/spec/support/multistream_fixture.rb +26 -8
  75. data/spec/template_args_spec.rb +133 -0
  76. data/spec/template_expander_spec.rb +29 -111
  77. data/spec/template_passthrough_spec.rb +58 -0
  78. data/spec/template_patterns_spec.rb +253 -0
  79. data/spec/tracked_paths_spec.rb +168 -0
  80. data/spec/utils_spec.rb +7 -1
  81. metadata +45 -5
  82. data/lib/wp2txt/category_cache.rb +0 -313
  83. data/spec/category_cache_spec.rb +0 -226
@@ -0,0 +1,228 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "wikitext_regions"
4
+
5
+ module Wp2txt
6
+ # Finds the terms an article introduces in its lead: bold spans in the first
7
+ # paragraph that has one, the parenthesized notes written right after each,
8
+ # and reading (ruby) templates. Nothing is judged — which note is a reading,
9
+ # a native spelling, or a date is left to the caller.
10
+ #
11
+ # Positions are character offsets [start, end) into the article's wikitext
12
+ # as stored in the dump, XML entities decoded, before any other processing
13
+ # (comments included), so a caller holding the same text can cut out and
14
+ # hash exactly the span a term came from.
15
+ module LeadTerms
16
+ MAX_TERMS = 5
17
+ HEADING = /^={2,6}[^=\n].*?={2,6}[ \t]*$/
18
+ OPENERS = { "(" => ")", "(" => ")" }.freeze
19
+ SEPARATORS = ["、", ",", ",", ";", ";"].freeze
20
+ PARAGRAPH_BREAK = /\n[ \t\r]*\n/
21
+ # Regions whose bold text is not the article's own lead prose
22
+ SKIP_OPEN = { "{{" => "}}", "{|" => "|}", "<!--" => "-->" }.freeze
23
+ REF_OPEN = /\A<ref(?:\s[^>]*)?>/i
24
+ REF_SELF_CLOSING = /\A<ref(?:\s[^>]*)?\/>/i
25
+ FILE_LINK = /\A\[\[\s*(?:file|image|ファイル|画像|media)\s*:/i
26
+
27
+ module_function
28
+
29
+ # @param wikitext [String] decoded article wikitext
30
+ # @param render [#call] turns a wikitext fragment into clean text
31
+ # @return [Array<Hash>] terms in order of appearance, at most MAX_TERMS
32
+ def extract(wikitext, render:)
33
+ return [] if wikitext.nil? || wikitext.empty?
34
+
35
+ visible = WikitextRegions.mask_lead(wikitext)
36
+ bolds, rubies, lead_end = scan(visible, visible.length, source: wikitext)
37
+ original_render = render
38
+ render = ->(fragment) { original_render.call(fragment.gsub(WikitextRegions::COMMENT, "")) }
39
+ terms = []
40
+
41
+ if (first = bolds.first)
42
+ paragraph = paragraph_bounds(visible, first[0], lead_end)
43
+ bolds.select { |s, e| s >= paragraph[0] && e <= paragraph[1] }.first(MAX_TERMS).each do |s, e|
44
+ terms << bold_term(wikitext, s, e, paragraph[1], render)
45
+ end
46
+ end
47
+ rubies.each do |s, e, parts|
48
+ terms << { "text" => render.call(parts[1].to_s).strip, "reading" => render.call(parts[2].to_s).strip,
49
+ "source" => parts[0].strip, "span" => { "template" => [s, e] } }
50
+ end
51
+
52
+ terms.sort_by { |t| t["span"].values.first.first }.first(MAX_TERMS)
53
+ .each_with_index.map { |t, i| { "index" => i }.merge(t) }
54
+ end
55
+
56
+ # Top-level bold spans [start, end) including the quote marks, and ruby
57
+ # templates [start, end, [name, text, reading]] found in the lead
58
+ def scan(text, limit, source: text)
59
+ bolds = []
60
+ rubies = []
61
+ i = 0
62
+ open_bold = nil
63
+ while i < limit
64
+ if (i.zero? || text[i - 1] == "\n") && text[i] == "=" &&
65
+ HEADING.match?(text[i...(text.index("\n", i) || limit)])
66
+ limit = i
67
+ break
68
+ elsif text[i] == "\n"
69
+ open_bold = nil # bold does not continue across lines
70
+ i += 1
71
+ elsif (close = SKIP_OPEN[text[i, 4] == "<!--" ? "<!--" : text[i, 2]])
72
+ opener = text[i, 4] == "<!--" ? "<!--" : text[i, 2]
73
+ stop = matching_end(text, i, opener, close)
74
+ if opener == "{{" && (ruby = ruby_template(source[(i + 2)...(stop - 2)]))
75
+ rubies << [i, stop, ruby]
76
+ end
77
+ i = stop
78
+ elsif text[i, 2] == "[[" && FILE_LINK.match?(text[i, 40])
79
+ i = matching_end(text, i, "[[", "]]")
80
+ elsif text[i] == "<" && (m = REF_SELF_CLOSING.match(text[i, 200]))
81
+ i += m[0].length
82
+ elsif text[i] == "<" && (m = REF_OPEN.match(text[i, 200]))
83
+ close_at = text.index(%r{</ref\s*>}i, i + m[0].length)
84
+ i = close_at ? text.index(">", close_at) + 1 : limit
85
+ elsif text[i, 3] == "'''"
86
+ run = text[i..][/\A'+/].length
87
+ if open_bold
88
+ bolds << [open_bold, i + run]
89
+ open_bold = nil
90
+ else
91
+ open_bold = i
92
+ end
93
+ i += run
94
+ else
95
+ i += 1
96
+ end
97
+ end
98
+ [bolds, rubies, limit]
99
+ end
100
+
101
+ # End index (exclusive) of the construct opened at start, honouring nesting
102
+ def matching_end(text, start, opener, closer)
103
+ depth = 0
104
+ i = start
105
+ while i < text.length
106
+ if text[i, opener.length] == opener
107
+ depth += 1
108
+ i += opener.length
109
+ elsif text[i, closer.length] == closer
110
+ depth -= 1
111
+ i += closer.length
112
+ return i if depth.zero?
113
+ else
114
+ i += 1
115
+ end
116
+ end
117
+ text.length
118
+ end
119
+
120
+ def ruby_template(content)
121
+ parts = split_top_level(content, ["|"])
122
+ name = parts.first.to_s
123
+ return nil unless ruby_name?(name)
124
+
125
+ [name, parts[1], parts[2]]
126
+ end
127
+
128
+ # Same name rule as the cleaner: "_" and " " alike, case-insensitive
129
+ def ruby_name?(name)
130
+ @ruby_names ||= Wp2txt::RUBY_TEXT_TEMPLATES.to_set { |t| t.tr("_", " ").strip.downcase }
131
+ @ruby_names.include?(name.to_s.tr("_", " ").strip.downcase)
132
+ end
133
+
134
+ def paragraph_bounds(text, pos, limit)
135
+ start = 0
136
+ text[0...pos].to_enum(:scan, PARAGRAPH_BREAK).each { start = Regexp.last_match.end(0) }
137
+ stop = text.index(PARAGRAPH_BREAK, pos) || limit
138
+ [start, [stop, limit].min]
139
+ end
140
+
141
+ def bold_term(text, s, e, limit, render)
142
+ inner = text[s...e].sub(/\A'+/, "").sub(/'+\z/, "")
143
+ term = { "text" => render.call(plain_ruby(inner)).strip, "notes" => [], "notes_text" => nil,
144
+ "source" => "bold", "span" => { "bold" => [s, e] } }
145
+ j = e
146
+ j += 1 while j < limit && [" ", "\t", " ", "\r", "\n"].include?(text[j])
147
+ return term if j >= limit
148
+ closer = OPENERS[text[j]]
149
+ return term unless closer
150
+
151
+ pe = paren_end(text, j, text[j], closer, limit)
152
+ return term unless pe
153
+
154
+ raw = text[(j + 1)...(pe - 1)]
155
+ term["notes_text"] = render.call(raw).strip
156
+ term["notes"] = split_top_level(raw, SEPARATORS).map { |part| render.call(part).strip }.reject(&:empty?)
157
+ term["span"]["paren"] = [j, pe]
158
+ term
159
+ end
160
+
161
+ # Index after the bracket closing the one at start, or nil if unclosed
162
+ def paren_end(text, start, opener, closer, limit)
163
+ depth = 0
164
+ i = start
165
+ while i < limit
166
+ two = text[i, 2]
167
+ if text[i] == "<" && (stop = WikitextRegions.end_at(text, i, lead: true))
168
+ i = stop
169
+ next
170
+ elsif ["{{", "[["].include?(two)
171
+ i = matching_end(text, i, two, two == "{{" ? "}}" : "]]")
172
+ next
173
+ end
174
+ if [opener, "(", "("].include?(text[i])
175
+ depth += 1
176
+ elsif [closer, ")", ")"].include?(text[i])
177
+ depth -= 1
178
+ return i + 1 if depth.zero?
179
+ elsif text[i] == "\n" && /\A\n[ \t\r]*\n/.match?(text[i..])
180
+ return nil
181
+ end
182
+ i += 1
183
+ end
184
+ nil
185
+ end
186
+
187
+ # Split at separators that sit outside brackets, templates, and links
188
+ def split_top_level(text, separators)
189
+ parts = [+""]
190
+ depth = 0
191
+ i = 0
192
+ while i < text.length
193
+ two = text[i, 2]
194
+ if text[i] == "<" && (stop = WikitextRegions.end_at(text, i, lead: true))
195
+ parts.last << text[i...stop]
196
+ i = stop
197
+ elsif ["{{", "[["].include?(two)
198
+ depth += 1
199
+ parts.last << two
200
+ i += 2
201
+ elsif ["}}", "]]"].include?(two)
202
+ depth -= 1
203
+ parts.last << two
204
+ i += 2
205
+ else
206
+ ch = text[i]
207
+ depth += 1 if ["(", "("].include?(ch)
208
+ depth -= 1 if [")", ")"].include?(ch)
209
+ if depth <= 0 && separators.include?(ch)
210
+ parts << +""
211
+ else
212
+ parts.last << ch
213
+ end
214
+ i += 1
215
+ end
216
+ end
217
+ parts
218
+ end
219
+
220
+ # In a bold headword, a ruby template stands for its base text; the
221
+ # reading is reported separately as its own term
222
+ def plain_ruby(fragment)
223
+ fragment.gsub(/\{\{([^{}]*)\}\}/) do |whole|
224
+ (ruby = ruby_template(Regexp.last_match(1))) ? ruby[1].to_s : whole
225
+ end
226
+ end
227
+ end
228
+ end
@@ -0,0 +1,171 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "parallel"
4
+ require "sqlite3"
5
+ require "time"
6
+ require_relative "metadata_index"
7
+ require_relative "version"
8
+ require_relative "text_processing"
9
+ require_relative "wikitext_regions"
10
+
11
+ module Wp2txt
12
+ # Counts, for every article, how many other articles link to it, and stores
13
+ # the result in the metadata index as page_inlinks(page_id, inlinks,
14
+ # via_redirects).
15
+ #
16
+ # Rules (recorded as RULE_VERSION so counts from different rules are never
17
+ # compared unknowingly):
18
+ # - sources are articles (namespace 0) that are not redirects
19
+ # - each source counts once per target, however many times it links there
20
+ # - a link to a redirect counts for the redirect's target (one hop);
21
+ # via_redirects is how many sources reached the target only that way
22
+ # - only links written in the article's own wikitext count; links that
23
+ # templates add when rendered (navigation boxes) are not in the dump text
24
+ # - commented-out links do not count
25
+ class LinkCounter
26
+ include Wp2txt
27
+
28
+ RULE_VERSION = "2"
29
+ STREAMS_PER_BATCH = 50
30
+ LINK_REGEX = /\[\[([^\[\]|<>{}\n]+)(?=\||\]\])/
31
+ COMMENT_REGEX = /<!--.*?-->/m
32
+
33
+ def initialize(multistream_path, stream_offsets, db_path:, num_processes: 4)
34
+ @multistream_path = multistream_path
35
+ @stream_offsets = stream_offsets
36
+ @db_path = db_path
37
+ @num_processes = num_processes
38
+ end
39
+
40
+ # @return [Hash] { articles:, with_inlinks:, rule_version: }
41
+ def count!(&progress)
42
+ titles, redirects = load_titles
43
+ # Inherited by the forked workers (copy-on-write); they only read it
44
+ @redirects = redirects
45
+
46
+ direct = Hash.new(0)
47
+ via = Hash.new(0)
48
+ pairs = @stream_offsets.zip(@stream_offsets[1..].to_a + [nil])
49
+ batches = pairs.each_slice(STREAMS_PER_BATCH).to_a
50
+ done = 0
51
+
52
+ Parallel.each(
53
+ batches,
54
+ in_processes: @num_processes,
55
+ finish: lambda { |_item, _idx, result|
56
+ result[:direct].each { |t, n| direct[t] += n }
57
+ result[:via].each { |t, n| via[t] += n }
58
+ done += 1
59
+ progress&.call(done, batches.size)
60
+ }
61
+ ) do |batch|
62
+ scan_batch(batch)
63
+ end
64
+
65
+ write(titles, direct, via)
66
+ end
67
+
68
+ private
69
+
70
+ # Articles (title => page_id) and redirects (title => target title)
71
+ def load_titles
72
+ db = SQLite3::Database.new(@db_path, readonly: true)
73
+ @case_rule = db.get_first_value("SELECT value FROM metadata WHERE key = 'case_rule'") || "first-letter"
74
+ titles = {}
75
+ redirects = {}
76
+ db.execute("SELECT page_id, title, redirect_to FROM pages WHERE namespace = 0") do |id, title, target|
77
+ if target
78
+ redirects[title] = normalize_target(target)
79
+ else
80
+ titles[title] = id
81
+ end
82
+ end
83
+ [titles, redirects]
84
+ ensure
85
+ db&.close
86
+ end
87
+
88
+ # Runs in a worker: returns per-target counts for this batch of streams
89
+ def scan_batch(offset_pairs)
90
+ direct = Hash.new(0)
91
+ via = Hash.new(0)
92
+ File.open(@multistream_path, "rb") do |f|
93
+ offset_pairs.each do |offset, next_offset|
94
+ f.seek(offset)
95
+ data = next_offset ? f.read(next_offset - offset) : f.read
96
+ xml = Wp2txt.decompress_bz2(data)
97
+ xml.scan(MetadataIndexBuilder::PAGE_BLOCK_REGEX) do
98
+ count_page(::Regexp.last_match(1), direct, via)
99
+ end
100
+ end
101
+ end
102
+ { direct: direct, via: via }
103
+ end
104
+
105
+ def count_page(block, direct, via)
106
+ return unless Wp2txt.namespace_id(block[MetadataIndexBuilder::NS_REGEX, 1]).zero?
107
+
108
+ text = MetadataIndexBuilder.unescape_xml(block[MetadataIndexBuilder::TEXT_REGEX, 1] || "")
109
+ return if Wp2txt::REDIRECT_REGEX.match?(text)
110
+
111
+ reached = {} # target => true if reached directly at least once
112
+ WikitextRegions.remove_literal(text).scan(LINK_REGEX) do |(raw)|
113
+ name = normalize_target(raw)
114
+ next if name.empty?
115
+
116
+ if (target = @redirects[name])
117
+ reached[target] ||= false
118
+ else
119
+ reached[name] = true
120
+ end
121
+ end
122
+ reached.each do |target, directly|
123
+ direct[target] += 1
124
+ via[target] += 1 unless directly
125
+ end
126
+ end
127
+
128
+ def normalize_target(raw)
129
+ # Decode each reference in the original input, never references created
130
+ # by decoding another one (special_chr has two decoding stages).
131
+ decoded = raw.gsub(/&(?:#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);/) { |entity| special_chr(entity) }
132
+ title = decoded.split("#", 2).first.to_s.strip.sub(/\A:/, "")
133
+ MetadataIndex.normalize_title(title, case_rule: @case_rule || "first-letter")
134
+ end
135
+
136
+ def write(titles, direct, via)
137
+ db = SQLite3::Database.new(@db_path)
138
+ db.busy_timeout = 5000
139
+ db.execute("DROP TABLE IF EXISTS page_inlinks")
140
+ db.execute("DELETE FROM metadata WHERE key LIKE 'links\\_%' ESCAPE '\\'")
141
+ db.execute(<<~SQL)
142
+ CREATE TABLE page_inlinks (
143
+ page_id INTEGER PRIMARY KEY,
144
+ inlinks INTEGER NOT NULL,
145
+ via_redirects INTEGER NOT NULL
146
+ )
147
+ SQL
148
+ with_inlinks = 0
149
+ db.transaction do
150
+ stmt = db.prepare("INSERT INTO page_inlinks (page_id, inlinks, via_redirects) VALUES (?, ?, ?)")
151
+ titles.each do |title, page_id|
152
+ n = direct[title]
153
+ with_inlinks += 1 if n.positive?
154
+ stmt.execute([page_id, n, via[title]])
155
+ end
156
+ stmt.close
157
+ end
158
+ db.execute("CREATE INDEX idx_page_inlinks_count ON page_inlinks(inlinks)")
159
+ {
160
+ links_counted_at: Time.now.utc.iso8601,
161
+ links_rule_version: RULE_VERSION,
162
+ links_wp2txt_version: Wp2txt::VERSION,
163
+ links_article_count: titles.size,
164
+ links_with_inlinks: with_inlinks
165
+ }.each { |k, v| db.execute("INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)", [k.to_s, v.to_s]) }
166
+ { articles: titles.size, with_inlinks: with_inlinks, rule_version: RULE_VERSION }
167
+ ensure
168
+ db&.close
169
+ end
170
+ end
171
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "regex"
4
+ require_relative "template_args"
4
5
 
5
6
  module Wp2txt
6
7
  # Expands MediaWiki magic words to their actual values
@@ -91,7 +92,10 @@ module Wp2txt
91
92
  Sunday Monday Tuesday Wednesday Thursday Friday Saturday
92
93
  ].freeze
93
94
 
94
- def initialize(title, namespace: "", dump_date: nil)
95
+ # @param literal_equals [String, nil] put in place of "=" in a page name
96
+ # (see TemplateArgs.literal_equals)
97
+ def initialize(title, namespace: "", dump_date: nil, literal_equals: nil)
98
+ @literal_equals = literal_equals
95
99
  @title = title || ""
96
100
  @namespace = namespace || ""
97
101
  @dump_date = dump_date || Time.now
@@ -126,7 +130,7 @@ module Wp2txt
126
130
  text.gsub(/\{\{\s*([A-Z][A-Z0-9]*)\s*\}\}/i) do |match|
127
131
  word = $1.upcase
128
132
  if PAGE_CONTEXT_WORDS.key?(word)
129
- expand_page_context(PAGE_CONTEXT_WORDS[word])
133
+ TemplateArgs.literal_equals(expand_page_context(PAGE_CONTEXT_WORDS[word]), @literal_equals)
130
134
  elsif DATETIME_WORDS.key?(word)
131
135
  expand_datetime(DATETIME_WORDS[word])
132
136
  else
@@ -233,35 +237,37 @@ module Wp2txt
233
237
  result = text.dup
234
238
 
235
239
  # Simple string case functions (no nesting issues)
236
- result.gsub!(/\{\{\s*lc\s*:\s*([^}]*)\}\}/i) { $1.downcase }
237
- result.gsub!(/\{\{\s*uc\s*:\s*([^}]*)\}\}/i) { $1.upcase }
240
+ # Each function reads its argument with "=" as written, and what it
241
+ # shows has its "=" held again (see TemplateArgs.literal_equals)
242
+ result.gsub!(/\{\{\s*lc\s*:\s*([^}]*)\}\}/i) { shown(plain($1).downcase) }
243
+ result.gsub!(/\{\{\s*uc\s*:\s*([^}]*)\}\}/i) { shown(plain($1).upcase) }
238
244
  result.gsub!(/\{\{\s*lcfirst\s*:\s*([^}]*)\}\}/i) do
239
- s = $1
240
- s.empty? ? s : s[0].downcase + s[1..]
245
+ s = plain($1)
246
+ shown(s.empty? ? s : s[0].downcase + s[1..])
241
247
  end
242
248
  result.gsub!(/\{\{\s*ucfirst\s*:\s*([^}]*)\}\}/i) do
243
- s = $1
244
- s.empty? ? s : s[0].upcase + s[1..]
249
+ s = plain($1)
250
+ shown(s.empty? ? s : s[0].upcase + s[1..])
245
251
  end
246
252
 
247
253
  # URL encoding
248
254
  result.gsub!(/\{\{\s*urlencode\s*:\s*([^}|]*?)(?:\s*\|\s*[^}]*)?\}\}/i) do
249
- url_encode($1.strip)
255
+ url_encode(plain($1).strip)
250
256
  end
251
257
  result.gsub!(/\{\{\s*anchorencode\s*:\s*([^}]*)\}\}/i) do
252
- anchor_encode($1.strip)
258
+ shown(anchor_encode(plain($1).strip))
253
259
  end
254
260
 
255
261
  # Padding functions: {{padleft:string|length|pad}}
256
262
  result.gsub!(/\{\{\s*padleft\s*:\s*([^}|]*)\s*\|\s*(\d+)(?:\s*\|\s*([^}]*))?\}\}/i) do
257
- str, len, pad = $1, $2.to_i, ($3 || "0")
263
+ str, len, pad = plain($1), $2.to_i, ($3 || "0")
258
264
  pad = "0" if pad.empty?
259
- str.rjust(len, pad)
265
+ shown(str.rjust(len, pad))
260
266
  end
261
267
  result.gsub!(/\{\{\s*padright\s*:\s*([^}|]*)\s*\|\s*(\d+)(?:\s*\|\s*([^}]*))?\}\}/i) do
262
- str, len, pad = $1, $2.to_i, ($3 || "0")
268
+ str, len, pad = plain($1), $2.to_i, ($3 || "0")
263
269
  pad = "0" if pad.empty?
264
- str.ljust(len, pad)
270
+ shown(str.ljust(len, pad))
265
271
  end
266
272
 
267
273
  # formatnum - format number with thousand separators
@@ -279,21 +285,30 @@ module Wp2txt
279
285
  end
280
286
 
281
287
  # plural, grammar, gender - just return first argument (proper handling would need language rules)
282
- result.gsub!(/\{\{\s*plural\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { $1 }
283
- result.gsub!(/\{\{\s*grammar\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { $1 }
284
- result.gsub!(/\{\{\s*gender\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { $1 }
288
+ result.gsub!(/\{\{\s*plural\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { shown(plain($1)) }
289
+ result.gsub!(/\{\{\s*grammar\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { shown(plain($1)) }
290
+ result.gsub!(/\{\{\s*gender\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { shown(plain($1)) }
285
291
 
286
292
  # int - internationalization, just return the message name
287
- result.gsub!(/\{\{\s*int\s*:\s*([^}|]*)[^}]*\}\}/i) { $1.strip }
293
+ result.gsub!(/\{\{\s*int\s*:\s*([^}|]*)[^}]*\}\}/i) { shown(plain($1).strip) }
288
294
 
289
295
  result
290
296
  end
291
297
 
292
298
  # Expand #titleparts parser function
293
299
  # {{#titleparts:pagename|number of segments|first segment}}
300
+ # Text with each "=" held as a placeholder given back as written
301
+ def plain(text)
302
+ @literal_equals ? text.tr(@literal_equals, "=") : text
303
+ end
304
+
305
+ def shown(text)
306
+ TemplateArgs.literal_equals(text, @literal_equals)
307
+ end
308
+
294
309
  def expand_titleparts(text)
295
310
  text.gsub(/\{\{\s*#titleparts\s*:\s*([^}|]+)(?:\s*\|\s*([^}|]*))?(?:\s*\|\s*([^}]*))?\}\}/i) do
296
- pagename = $1.strip
311
+ pagename = plain($1.strip)
297
312
  num_segments = $2&.strip&.to_i
298
313
  first_segment = ($3&.strip&.to_i || 1)
299
314
 
@@ -301,15 +316,16 @@ module Wp2txt
301
316
  first_segment = 1 if first_segment < 1
302
317
  first_idx = first_segment - 1
303
318
 
304
- if num_segments && num_segments > 0
305
- parts[first_idx, num_segments]&.join("/") || ""
306
- elsif num_segments && num_segments < 0
307
- # Negative means "all but last N"
308
- end_idx = parts.length + num_segments
309
- end_idx > first_idx ? parts[first_idx...end_idx].join("/") : ""
310
- else
311
- parts[first_idx..]&.join("/") || ""
312
- end
319
+ shown_parts = if num_segments && num_segments > 0
320
+ parts[first_idx, num_segments]&.join("/") || ""
321
+ elsif num_segments && num_segments < 0
322
+ # Negative means "all but last N"
323
+ end_idx = parts.length + num_segments
324
+ end_idx > first_idx ? parts[first_idx...end_idx].join("/") : ""
325
+ else
326
+ parts[first_idx..]&.join("/") || ""
327
+ end
328
+ shown(shown_parts)
313
329
  end
314
330
  end
315
331