Method: RubyRTF::Parser#parse

Defined in:
lib/ruby-rtf/parser.rb

#parse(src) ⇒ RubyRTF::Document

Parses a given string into an RubyRTF::Document

Parameters:

  • src (String)

    The document to parse

Returns:

Raises:



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ruby-rtf/parser.rb', line 29

def parse(src)
  raise RubyRTF::InvalidDocument.new("Opening \\rtf1 missing") unless src =~ /\{\\rtf1/

  current_pos = 0
  len = src.length

  group_level = 0
  while (current_pos < len)
    char = src[current_pos]
    current_pos += 1

    case(char)
    when '\\' then
      name, val, current_pos = parse_control(src, current_pos)
      current_pos = handle_control(name, val, src, current_pos)

    when '{' then
      add_section!
      group_level += 1

    when '}' then
      pop_formatting!
      add_section!
      group_level -= 1

    when *["\r", "\n"] then ;
    else current_section[:text] << char
    end
  end

  unless current_section[:text].empty?
    current_context << current_section
  end

  raise RubyRTF::InvalidDocument.new("Unbalanced {}s") unless group_level == 0
  @doc
end