llm-docs-builder 1.0.0 → 1.1.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.
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmDocsBuilder
4
+ # Finds the source markdown files in a documentation directory
5
+ #
6
+ # Shared by `generate` and `bulk-transform` so both pick the same files: hidden directories
7
+ # are pruned unless `include_hidden` is set, hidden files and bulk-transformed files (ending
8
+ # with the suffix, e.g. README.llm.md) are skipped, and files matching `excludes` are left out.
9
+ #
10
+ # @api private
11
+ class MarkdownFinder
12
+ # Flags used for every exclude pattern match
13
+ FNMATCH_FLAGS = File::FNM_PATHNAME | File::FNM_DOTMATCH
14
+ private_constant :FNMATCH_FLAGS
15
+
16
+ # Matches a path whose last component starts with a dot
17
+ HIDDEN_PATH_PATTERN = %r{(?:\A|/)\.[^/]*\z}
18
+ private_constant :HIDDEN_PATH_PATTERN
19
+
20
+ # @return [String] path to documentation directory
21
+ attr_reader :docs_path
22
+
23
+ # @return [Hash] finder options
24
+ attr_reader :options
25
+
26
+ # Initialize a new finder
27
+ #
28
+ # @param docs_path [String] path to documentation directory
29
+ # @param options [Hash] finder options
30
+ # @option options [String] :suffix suffix of bulk-transformed files to skip (default: '.llm')
31
+ # @option options [Array<String>] :excludes glob patterns for files to exclude
32
+ # @option options [Boolean] :include_hidden include files in hidden directories
33
+ def initialize(docs_path, options = {})
34
+ @docs_path = docs_path
35
+ @options = options
36
+ @docs_prefix = docs_path.end_with?('/') ? docs_path : "#{docs_path}/"
37
+ @exclude_patterns = Array(options[:excludes]).map { |pattern| normalize_pattern(pattern) }
38
+ end
39
+
40
+ # Recursively finds the source markdown files in docs_path
41
+ #
42
+ # @return [Array<String>] paths to markdown files, in directory traversal order
43
+ def files
44
+ files = []
45
+ output_ending = "#{options.fetch(:suffix, '.llm')}.md".downcase
46
+
47
+ Find.find(docs_path) do |path|
48
+ if hidden_directory?(path)
49
+ Find.prune
50
+ next
51
+ end
52
+
53
+ next unless File.file?(path)
54
+ next unless path.match?(/\.md$/i)
55
+ next if path.match?(HIDDEN_PATH_PATTERN)
56
+ next if output_ending != '.md' && path.downcase.end_with?(output_ending)
57
+ next if excluded?(path)
58
+
59
+ files << path
60
+ end
61
+
62
+ files
63
+ end
64
+
65
+ # Tests if file matches any exclusion pattern from options
66
+ #
67
+ # Checks both the given path and the path relative to docs_path. A trailing `/**` matches
68
+ # files at any depth below the directory.
69
+ #
70
+ # @param file_path [String] path to check
71
+ # @return [Boolean] true if file should be excluded
72
+ def excluded?(file_path)
73
+ return false if @exclude_patterns.empty?
74
+
75
+ relative = relative_path(file_path)
76
+
77
+ @exclude_patterns.any? do |pattern|
78
+ File.fnmatch(pattern, file_path, FNMATCH_FLAGS) || File.fnmatch(pattern, relative, FNMATCH_FLAGS)
79
+ end
80
+ end
81
+
82
+ private
83
+
84
+ # Converts an exclude pattern into the fnmatch pattern that implements it
85
+ #
86
+ # @param pattern [String] exclude pattern from options
87
+ # @return [String] fnmatch pattern
88
+ def normalize_pattern(pattern)
89
+ # fnmatch requires /** to be followed by at least one component
90
+ pattern.end_with?('/**') ? "#{pattern}/*" : pattern
91
+ end
92
+
93
+ # Tests if path is a hidden directory to skip
94
+ #
95
+ # The root docs_path itself is never skipped (even if it's ".")
96
+ #
97
+ # @param path [String] path to check
98
+ # @return [Boolean] true if path is a hidden directory and include_hidden is not set
99
+ def hidden_directory?(path)
100
+ return false if options[:include_hidden] || path == docs_path
101
+
102
+ path.match?(HIDDEN_PATH_PATTERN) && File.directory?(path)
103
+ end
104
+
105
+ # Computes the path of a file relative to docs_path
106
+ #
107
+ # Paths from Find.find start with docs_path, so the prefix is stripped without Pathname.
108
+ #
109
+ # @param file_path [String] path to a file inside docs_path
110
+ # @return [String] relative path, or the basename if it can't be made relative
111
+ def relative_path(file_path)
112
+ return file_path.delete_prefix(@docs_prefix) if file_path.start_with?(@docs_prefix)
113
+
114
+ @expanded_docs_path ||= Pathname.new(File.expand_path(docs_path))
115
+ Pathname.new(File.expand_path(file_path)).relative_path_from(@expanded_docs_path).to_s
116
+ rescue ArgumentError
117
+ File.basename(file_path)
118
+ end
119
+ end
120
+ end
@@ -47,9 +47,9 @@ module LlmDocsBuilder
47
47
  #
48
48
  # Processes content through specialized transformers in order:
49
49
  # 1. ContentCleanupTransformer - Removes unwanted elements
50
- # 2. LinkTransformer - Processes links
51
- # 3. HeadingTransformer - Normalizes heading hierarchy (if enabled)
52
- # 4. TextCompressor - Advanced compression (if enabled)
50
+ # 2. LinkTransformer - Processes links, on the code detection of step 1
51
+ # 3. HeadingTransformer - Normalizes heading hierarchy (if enabled), on the code detection of step 1
52
+ # 4. TextCompressor - Advanced compression (if enabled), on the code detection of step 1
53
53
  # 5. EnhancementTransformer - Adds TOC and instructions
54
54
  # 6. WhitespaceTransformer - Normalizes whitespace
55
55
  #
@@ -58,10 +58,11 @@ module LlmDocsBuilder
58
58
  content = load_content
59
59
 
60
60
  # Build and execute transformation pipeline
61
- content = cleanup_transformer.transform(content, options)
62
- content = link_transformer.transform(content, options)
63
- content = heading_transformer.transform(content, options)
64
- content = compress_content(content) if should_compress?
61
+ content = cleanup_transformer.transform(content, options) do |text|
62
+ text = link_transformer.transform_outside_code(text, options)
63
+ text = heading_transformer.transform(text, options)
64
+ should_compress? ? compress_content(text) : text
65
+ end
65
66
  content = enhancement_transformer.transform(content, options)
66
67
  whitespace_transformer.transform(content, options)
67
68
  end
@@ -112,15 +113,15 @@ module LlmDocsBuilder
112
113
 
113
114
  # Compress content using TextCompressor
114
115
  #
115
- # @param content [String] markdown content
116
- # @return [String] compressed content
116
+ # @param content [String] content with code replaced by {Transformers::CodeBlocks} placeholders
117
+ # @return [String] compressed content, still with placeholders
117
118
  def compress_content(content)
118
119
  compressor = TextCompressor.new
119
120
  compression_methods = {
120
121
  remove_stopwords: options[:remove_stopwords],
121
122
  remove_duplicates: options[:remove_duplicates]
122
123
  }
123
- compressor.compress(content, compression_methods)
124
+ compressor.compress_outside_code(content, compression_methods)
124
125
  end
125
126
 
126
127
  # Load source content either from provided string or file path
@@ -128,7 +128,7 @@ module LlmDocsBuilder
128
128
  puts ' llm-docs-builder bulk-transform --docs ./docs --config llm-docs-builder.yml'
129
129
  puts ''
130
130
  puts '2. Configure your web server to serve .md files to AI bots:'
131
- puts ' See: https://github.com/mensfeld/llm-docs-builder#serving-optimized-docs'
131
+ puts ' See: https://github.com/mensfeld/llm-docs-builder#serving-optimized-docs-to-ai-bots'
132
132
  puts ''
133
133
  puts '3. Measure your actual savings:'
134
134
  puts ' llm-docs-builder compare --url <your-url> --file <local-md>'
@@ -12,6 +12,8 @@ module LlmDocsBuilder
12
12
  #
13
13
  # @api public
14
14
  class TextCompressor
15
+ include Transformers::CodeBlocks
16
+
15
17
  # Common English stopwords that can be safely removed from documentation
16
18
  # Excludes words that might be important in technical contexts (like "not", "no")
17
19
  STOPWORDS = %w[
@@ -35,6 +37,11 @@ module LlmDocsBuilder
35
37
  throughout under until up upon within without
36
38
  ].freeze
37
39
 
40
+ # Word, or a code placeholder or bare URL that stopword removal leaves unchanged
41
+ WORD_PATTERN = %r{#{CODE_PLACEHOLDER_PATTERN}|https?://\S+|(?:(?!https?://)[[:word:]])+}
42
+
43
+ private_constant :WORD_PATTERN
44
+
38
45
  # @return [Hash] compression options
39
46
  attr_reader :options
40
47
 
@@ -57,19 +64,31 @@ module LlmDocsBuilder
57
64
  # @option methods [Boolean] :remove_stopwords remove common filler words
58
65
  # @option methods [Boolean] :remove_duplicates remove duplicate sentences/paragraphs
59
66
  # @return [String] compressed text
67
+ # @note Code (fenced and indented code blocks, inline code spans) is left unchanged
60
68
  def compress(content, methods = {})
61
- result = content.dup
69
+ return content.dup unless methods[:remove_stopwords] || methods[:remove_duplicates]
62
70
 
63
- result = remove_stopwords(result) if methods[:remove_stopwords]
64
- result = remove_duplicate_paragraphs(result) if methods[:remove_duplicates]
71
+ outside_code(content) { |text| compress_outside_code(text, methods) }
72
+ end
65
73
 
66
- result
74
+ # Compress text whose code is already replaced by placeholders
75
+ #
76
+ # @param text [String] text with code replaced by {Transformers::CodeBlocks} placeholders
77
+ # @param methods [Hash] compression methods to apply
78
+ # @option methods [Boolean] :remove_stopwords remove common filler words
79
+ # @option methods [Boolean] :remove_duplicates remove duplicate sentences/paragraphs
80
+ # @return [String] compressed text, still with placeholders
81
+ # @api private
82
+ def compress_outside_code(text, methods = {})
83
+ text = remove_stopwords_outside_code(text) if methods[:remove_stopwords]
84
+ text = remove_duplicate_paragraphs_outside_code(text) if methods[:remove_duplicates]
85
+ text
67
86
  end
68
87
 
69
88
  # Remove stopwords from text while preserving technical content
70
89
  #
71
90
  # Removes common English stopwords that don't carry significant meaning.
72
- # Preserves code blocks, inline code, and technical terms.
91
+ # Preserves code blocks, inline code, bare URLs and technical terms.
73
92
  #
74
93
  # @deprecated This is an aggressive optimization that may affect readability.
75
94
  # Use with caution and test results carefully.
@@ -77,64 +96,54 @@ module LlmDocsBuilder
77
96
  # @param content [String] text to process
78
97
  # @return [String] text with stopwords removed
79
98
  def remove_stopwords(content)
80
- # Preserve code blocks by temporarily replacing them
81
- code_blocks = {}
82
- code_counter = 0
83
-
84
- # Extract and preserve fenced code blocks
85
- content = content.gsub(/^```.*?^```/m) do |match|
86
- placeholder = "___CODE_BLOCK_#{code_counter}___"
87
- code_blocks[placeholder] = match
88
- code_counter += 1
89
- placeholder
90
- end
99
+ outside_code(content) { |text| remove_stopwords_outside_code(text) }
100
+ end
91
101
 
92
- # Extract and preserve inline code
93
- content = content.gsub(/`[^`]+`/) do |match|
94
- placeholder = "___INLINE_CODE_#{code_counter}___"
95
- code_blocks[placeholder] = match
96
- code_counter += 1
97
- placeholder
98
- end
102
+ # Remove duplicate paragraphs from text
103
+ #
104
+ # Detects and removes paragraphs that are the same after whitespace and case normalization.
105
+ # Documentation often repeats concepts across different sections. Paragraphs with code are always kept.
106
+ #
107
+ # @param content [String] text to process
108
+ # @return [String] text with duplicate paragraphs removed
109
+ def remove_duplicate_paragraphs(content)
110
+ outside_code(content) { |text| remove_duplicate_paragraphs_outside_code(text) }
111
+ end
112
+
113
+ private
99
114
 
115
+ # Remove stopwords from text whose code is replaced by placeholders
116
+ #
117
+ # @param content [String] text with code replaced by {Transformers::CodeBlocks} placeholders
118
+ # @return [String] text with stopwords removed
119
+ def remove_stopwords_outside_code(content)
100
120
  # Get combined stopwords list
101
121
  stopwords_list = STOPWORDS + options[:custom_stopwords]
102
122
 
103
123
  # Process each line
104
- content = content.split("\n").map do |line|
124
+ content.split("\n").map do |line|
105
125
  # Skip markdown headers, lists, and links
106
126
  if line.match?(/^#+\s/) || line.match?(/^[\*\-]\s/) || line.match?(/\[[^\]]+\]\([^)]+\)/)
107
127
  line
108
128
  else
109
129
  # Remove stopwords from regular text
110
- words = line.split(/\b/)
111
- words.map do |word|
130
+ line.gsub(WORD_PATTERN) do |word|
112
131
  # Preserve the word if it's not a stopword or if we should preserve technical terms
113
132
  if stopwords_list.include?(word.downcase) && !word.match?(/^[A-Z]/) # Don't remove capitalized words
114
133
  ''
115
134
  else
116
135
  word
117
136
  end
118
- end.join
137
+ end
119
138
  end
120
139
  end.join("\n")
121
-
122
- # Restore code blocks
123
- code_blocks.each do |placeholder, original|
124
- content = content.gsub(placeholder, original)
125
- end
126
-
127
- content
128
140
  end
129
141
 
130
- # Remove duplicate paragraphs from text
131
- #
132
- # Detects and removes paragraphs that are duplicates or near-duplicates.
133
- # Documentation often repeats concepts across different sections.
142
+ # Remove duplicate paragraphs from text whose code is replaced by placeholders
134
143
  #
135
- # @param content [String] text to process
144
+ # @param content [String] text with code replaced by {Transformers::CodeBlocks} placeholders
136
145
  # @return [String] text with duplicate paragraphs removed
137
- def remove_duplicate_paragraphs(content)
146
+ def remove_duplicate_paragraphs_outside_code(content)
138
147
  # Split into paragraphs (separated by blank lines)
139
148
  paragraphs = content.split(/\n\s*\n/)
140
149
 
@@ -149,7 +158,7 @@ module LlmDocsBuilder
149
158
  # Skip empty paragraphs
150
159
  next if normalized.empty?
151
160
 
152
- # Check if we've seen this or similar paragraph
161
+ # Code placeholders are unique, so a paragraph with code is never a duplicate
153
162
  unless seen[normalized]
154
163
  seen[normalized] = true
155
164
  unique_paragraphs << para
@@ -158,6 +167,5 @@ module LlmDocsBuilder
158
167
 
159
168
  unique_paragraphs.join("\n\n")
160
169
  end
161
-
162
170
  end
163
171
  end
@@ -0,0 +1,226 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmDocsBuilder
4
+ module Transformers
5
+ # Detection of code shared by transformers
6
+ #
7
+ # Finds fenced and indented code blocks and inline code spans, and runs transformations on content with the
8
+ # code replaced by placeholders, optionally leaving backticks inside HTML comments in place.
9
+ #
10
+ # @api private
11
+ module CodeBlocks
12
+ # Opening line of a fenced code block
13
+ FENCE_OPENING_PATTERN = /\A[ \t]*(`{3,}|~{3,})/
14
+
15
+ # Blockquote markers at the start of a line
16
+ BLOCKQUOTE_PREFIX_PATTERN = /\A(?: {0,3}> ?)*/
17
+
18
+ # Line that starts a list item
19
+ LIST_ITEM_PATTERN = /\A {0,3}(?:[-+*]|\d{1,9}[.)])(?:[ \t]|\s*\z)/
20
+
21
+ # ATX heading line
22
+ ATX_HEADING_PATTERN = /\A\#{1,6}(?:[ \t]|\s*\z)/
23
+
24
+ # Placeholder that stands in for a protected code fragment; a code block's ends with `b`
25
+ CODE_PLACEHOLDER_PATTERN = /\u0000(\d+)b?\u0000/
26
+
27
+ # Placeholder standing in for a protected code block, the one carrying the `b` marker
28
+ CODE_BLOCK_PLACEHOLDER_PATTERN = /\u0000\d+b\u0000/
29
+
30
+ # Placeholder standing in for protected inline code, the one without a marker
31
+ INLINE_CODE_PLACEHOLDER_PATTERN = /\u0000\d+\u0000/
32
+
33
+ # Inline code span: a backtick run closed by a run of the same length, within one paragraph
34
+ INLINE_CODE_PATTERN = /(?<![`\\])(`+)(?!`)(?:(?!\n[ \t]*\n)[^\u0000])+?(?<!`)\1(?!`)/m
35
+
36
+ # Start of an HTML comment or of an inline code span
37
+ COMMENT_OR_BACKTICK_PATTERN = /<!--|`/
38
+
39
+ # Start of an inline code span
40
+ BACKTICK_PATTERN = /`/
41
+
42
+ # Byte of a backtick
43
+ BACKTICK_BYTE = '`'.ord
44
+
45
+ # End of an HTML comment
46
+ COMMENT_END_PATTERN = /-->/
47
+
48
+ private_constant :FENCE_OPENING_PATTERN, :BLOCKQUOTE_PREFIX_PATTERN, :LIST_ITEM_PATTERN, :ATX_HEADING_PATTERN,
49
+ :CODE_PLACEHOLDER_PATTERN, :CODE_BLOCK_PLACEHOLDER_PATTERN, :INLINE_CODE_PLACEHOLDER_PATTERN,
50
+ :INLINE_CODE_PATTERN, :COMMENT_OR_BACKTICK_PATTERN, :BACKTICK_PATTERN, :BACKTICK_BYTE, :COMMENT_END_PATTERN
51
+
52
+ private
53
+
54
+ # Run a transformation on content with code replaced by placeholders, then restore the code
55
+ #
56
+ # @param content [String] markdown content
57
+ # @param block_code [Proc, nil] maps each code block before it is protected
58
+ # @param comments_first [Boolean, nil] leave backticks inside HTML comments in place, as a comment that starts
59
+ # first hides them
60
+ # @yieldparam text [String] content with code fragments replaced by placeholders
61
+ # @yieldreturn [String] transformed content
62
+ # @return [String] transformed content with the original code restored
63
+ def outside_code(content, block_code: nil, comments_first: false)
64
+ codes = []
65
+ protect = lambda do |code, block: false|
66
+ codes << code
67
+ "\u0000#{codes.size - 1}#{'b' if block}\u0000"
68
+ end
69
+
70
+ text = replace_code_blocks(content) do |code|
71
+ protect.call(block_code ? block_code.call(code) : code, block: true)
72
+ end
73
+ text = if comments_first
74
+ replace_inline_code_outside_comments(text) { |span| protect.call(span) }
75
+ else
76
+ text.gsub(INLINE_CODE_PATTERN) { protect.call(::Regexp.last_match(0)) }
77
+ end
78
+
79
+ yield(text).gsub(CODE_PLACEHOLDER_PATTERN) { codes[::Regexp.last_match(1).to_i] }
80
+ end
81
+
82
+ # Replace inline code spans that do not start inside an HTML comment
83
+ #
84
+ # Scans once: a comment is skipped up to its first `-->`, and an unclosed comment ends the search for
85
+ # comments, as no later `<!--` can be closed either.
86
+ #
87
+ # @param text [String] markdown content
88
+ # @yieldparam span [String] inline code span
89
+ # @yieldreturn [String] replacement for the span
90
+ # @return [String] content with inline code spans replaced
91
+ def replace_inline_code_outside_comments(text)
92
+ scanner = StringScanner.new(text, fixed_anchor: true)
93
+ out = +''
94
+ copied = 0
95
+ start_pattern = COMMENT_OR_BACKTICK_PATTERN
96
+
97
+ while scanner.skip_until(start_pattern)
98
+ if text.getbyte(scanner.pos - 1) == BACKTICK_BYTE
99
+ start = scanner.pos -= 1
100
+ length = scanner.skip(INLINE_CODE_PATTERN)
101
+ next scanner.pos += 1 unless length
102
+
103
+ out << text.byteslice(copied, start - copied) << yield(text.byteslice(start, length))
104
+ copied = scanner.pos
105
+ elsif !scanner.skip_until(COMMENT_END_PATTERN)
106
+ start_pattern = BACKTICK_PATTERN
107
+ end
108
+ end
109
+
110
+ out << text.byteslice(copied, text.bytesize - copied)
111
+ end
112
+
113
+ # Replace fenced and indented code blocks
114
+ #
115
+ # Indented lines count as code only after a blank line and outside lists, where they would otherwise be
116
+ # paragraph or list item continuations. Code inside blockquotes is detected after the `>` markers.
117
+ #
118
+ # @param content [String] markdown content
119
+ # @yieldparam code [String] code block lines without the final line break
120
+ # @yieldreturn [String] replacement for the code block
121
+ # @return [String] content with code blocks replaced
122
+ def replace_code_blocks(content, &replacement)
123
+ out = +''
124
+ code = +''
125
+ fence = nil
126
+ fence_depth = 0
127
+ depth = 0
128
+ in_list = false
129
+ prev_blank = true
130
+
131
+ content.each_line do |line|
132
+ quote = line.start_with?('>', ' ') ? line[BLOCKQUOTE_PREFIX_PATTERN] : ''
133
+ body = quote.empty? ? line : line.delete_prefix(quote)
134
+ prev_blank ||= quote.count('>') > depth
135
+ depth = quote.count('>')
136
+ fence = nil if depth < fence_depth
137
+
138
+ if fence
139
+ code << line
140
+ fence = nil if depth == fence_depth && closing_fence?(body, fence)
141
+ prev_blank = true
142
+ next
143
+ end
144
+
145
+ if !in_list && (prev_blank || !code.empty?) && indented_code?(body)
146
+ code << line
147
+ next
148
+ end
149
+
150
+ if (fence = fence_opening(body))
151
+ fence_depth = depth
152
+ in_list = in_list_after?(body, in_list, prev_blank)
153
+ code << line
154
+ next
155
+ end
156
+
157
+ out << replace_lines(code, &replacement) << line
158
+ code = +''
159
+ in_list = in_list_after?(body, in_list, prev_blank)
160
+ prev_blank = body.strip.empty?
161
+ end
162
+
163
+ out << replace_lines(code, &replacement)
164
+ end
165
+
166
+ # Fence of a line that opens a fenced code block
167
+ #
168
+ # @param line [String] markdown line
169
+ # @return [String, nil] the opening fence, or nil when the line does not open a block
170
+ def fence_opening(line)
171
+ opening = line.match(FENCE_OPENING_PATTERN)
172
+ return unless opening
173
+ return if opening[1].start_with?('`') && opening.post_match.include?('`')
174
+
175
+ opening[1]
176
+ end
177
+
178
+ # Check whether a line closes a fenced code block
179
+ #
180
+ # @param line [String] markdown line without blockquote markers
181
+ # @param fence [String] the opening fence
182
+ # @return [Boolean] true when the line holds only a fence at least as long as the opening one
183
+ def closing_fence?(line, fence)
184
+ marker = line.strip
185
+ marker.length >= fence.length && marker.count(fence[0]) == marker.length
186
+ end
187
+
188
+ # Check whether a line is indented enough to be code
189
+ #
190
+ # @param line [String] markdown line
191
+ # @return [Boolean] true for a non-blank line indented by four spaces or a tab
192
+ def indented_code?(line)
193
+ line.match?(/\A(?: {4}|\t)\s*\S/)
194
+ end
195
+
196
+ # Check whether content after a line is still inside a list
197
+ #
198
+ # A line that is not indented ends the list after a blank line, or right away when it is a heading or a fence.
199
+ #
200
+ # @param line [String] markdown line
201
+ # @param in_list [Boolean] whether the previous line was inside a list
202
+ # @param prev_blank [Boolean] whether the previous line was blank
203
+ # @return [Boolean] true when the list continues after this line
204
+ def in_list_after?(line, in_list, prev_blank)
205
+ return true if line.match?(LIST_ITEM_PATTERN)
206
+ return in_list if !in_list || line.strip.empty? || line.match?(/\A[ \t]/)
207
+ return in_list unless prev_blank || line.match?(ATX_HEADING_PATTERN) || fence_opening(line)
208
+
209
+ false
210
+ end
211
+
212
+ # Replace collected code lines, keeping the final line break
213
+ #
214
+ # @param code [String] collected code lines
215
+ # @yieldparam code [String] code lines without the final line break
216
+ # @yieldreturn [String] replacement for the code lines
217
+ # @return [String] replacement, or an empty string when there is no code
218
+ def replace_lines(code)
219
+ return '' if code.empty?
220
+
221
+ body = code.chomp
222
+ "#{yield(body)}#{code.delete_prefix(body)}"
223
+ end
224
+ end
225
+ end
226
+ end