Class: Asciidoctor::PDF::FormattedText::Formatter

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/asciidoctor/pdf/formatted_text/formatter.rb

Constant Summary collapse

FormattingSnifferPattern =
/[<&]/
WHITESPACE =
%( \t\n)
NORMALIZE_TO_SPACE =
%(\t\n)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Formatter

Returns a new instance of Formatter.



15
16
17
18
19
# File 'lib/asciidoctor/pdf/formatted_text/formatter.rb', line 15

def initialize options = {}
  @parser = MarkupParser.new
  @transform = Transform.new merge_adjacent_text_nodes: true, theme: options[:theme]
  @scratch = false
end

Instance Attribute Details

#scratchObject

Returns the value of attribute scratch.



9
10
11
# File 'lib/asciidoctor/pdf/formatted_text/formatter.rb', line 9

def scratch
  @scratch
end

Instance Method Details

#array_paragraphs(fragments) ⇒ Object

The original purpose of this method is to split paragraphs, but our formatter only works on paragraphs that have been presplit. Therefore, we just need to wrap the fragments in a single-element array (representing a single paragraph) and return them.



40
41
42
# File 'lib/asciidoctor/pdf/formatted_text/formatter.rb', line 40

def array_paragraphs fragments
  [fragments]
end

#format(string, *args) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/asciidoctor/pdf/formatted_text/formatter.rb', line 21

def format string, *args
  options = args[0] || {}
  inherited = options[:inherited]
  if FormattingSnifferPattern.match? string
    string = string.tr NORMALIZE_TO_SPACE, ' ' if (normalize_space = options[:normalize])
    if (parsed = @parser.parse string)
      return @transform.apply parsed.content, [], inherited, normalize_space: normalize_space
    end
    reason = @parser.failure_reason.sub %r/ at line \d+, column \d+ \(byte (\d+)\)(.*)/, '\2 at byte \1'
    logger.error %(failed to parse formatted text: #{string} (reason: #{reason})) unless @scratch
  elsif options[:normalize]
    string = string.tr_s WHITESPACE, ' '
  end
  [inherited ? (inherited.merge text: string) : { text: string }]
end