-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
asciidoc.rb
executable file
·1127 lines (1001 loc) · 35.5 KB
/
asciidoc.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'cgi'
require 'erb'
require 'tilt'
# REFERENCE
# TODO:
# * Nexted section blocks (eg. olist with listing blocks in git-cvsserver)
# * paragraph/block titles
# * captions
# * example blocks
# * list items with +\n<moar things>
# * escaped attributes
# * single-line titles, eg. === TITLE
# * optional paragraph titles
# * passthrough block
# * unordered lists, nested [uod]lists
# * tables
# Public: Methods for parsing Asciidoc input files and rendering documents
# using Tilt-compatible templates.
#
# Asciidoc documents are comprised of a header followed by zero or more
# sections, and sections are comprised of blocks of content. For example:
#
# Doc Title
# =========
#
# SECTION 1
# ---------
#
# This is a paragraph block in the first section.
#
# SECTION 2
#
# This section has a paragraph block and an olist block.
#
# 1. Item 1
# 2. Item 2
#
# Examples:
#
# lines = File.readlines(filename)
#
# doc = Asciidoc.new(lines)
# html = doc.render(template_path)
module Asciidoc
REGEXP = {
:name => /^([A-Za-z].*)\s*$/,
:line => /^([=\-~^\+])+\s*$/,
:verse => /^\[verse\]\s*$/,
:note => /^\[NOTE\]\s*$/,
:dlist => /^(.*)(::|;;)\s*$/,
:olist => /^(\d+\.|\. )(.*)$/,
:ulist => /^\s*[\*\-]\s+(.*)$/,
:title => /^\.(\S.*)\s*$/,
:quote => /^_{4,}\s*$/,
:colist => /^\<\d+\>\s*(.*)/,
:oblock => /^\-\-\s*$/,
:anchor => /^\[(\[.+\])\]\s*$/,
:biblio => /\[\[\[([^\]]+)\]\]\]/,
:comment => /^\/\/\s/,
:listing => /^\-+\s*$/,
:example => /^=+\s*$/,
:literal => /^([ \t]+.*)$/,
:caption => /^\[caption=\"([^\"]+)\"\]/,
:continue => /^\+\s*$/
}
# Public: Methods for rendering Asciidoc Documents, Sections, and Blocks
# using Tile-compatible templates.
class Renderer
# Public: Initialize an Asciidoc::Renderer object.
#
# template_dir - the String pathname of the directory containing template
# files that should be used for subsequent render requests.
def initialize(template_dir, options={})
@debug = !!options[:debug]
files = Dir.glob(File.join(template_dir, '*')).select{|f| File.stat(f).file?}
@views = files.inject({}) do |view_hash, view|
name = File.basename(view).split('.').first
view_hash.merge!(name => Tilt.new(view, nil, :trim => '<>'))
end
@render_stack = []
end
# Public: Render an Asciidoc object with a specified view template.
#
# view - the String view template name.
# object - the Object to be passed to Tilt as an evaluation scope.
# locals - the optional Hash of locals to be passed to Tile (default {})
def render(view, object, locals={})
@render_stack.push([view, object])
ret = @views[view].render(object, locals)
if @debug
prefix = ''
STDERR.puts '=' * 80
STDERR.puts "Rendering:"
@render_stack.each do |stack_view, stack_obj|
obj_info = case stack_obj
when Section; "SECTION #{stack_obj.name}"
when Block;
if stack_obj.context == :dlist
dt_list = stack_obj.buffer.map{|dt,dd| dt.content.strip}.join(', ')
"BLOCK :dlist (#{dt_list})"
else
"BLOCK #{stack_obj.context.inspect}"
end
else stack_obj.class
end
STDERR.puts "#{prefix}#{stack_view}: #{obj_info}"
prefix << ' '
end
STDERR.puts '-' * 80
STDERR.puts ret.inspect
STDERR.puts '=' * 80
STDERR.puts
end
@render_stack.pop
ret
end
end
# Public: Methods for managing items for Asciidoc olists, ulist, and dlists.
class ListItem
# Public: Get the Array of Blocks from the list item's continuation.
attr_reader :blocks
# Public: Get/Set the String content.
attr_accessor :content
# Public: Initialize an Asciidoc::ListItem object.
#
# content - the String content (default '')
def initialize(content='')
@content = content
@blocks = []
end
end
# Public: Methods for managing blocks of Asciidoc content in a section.
#
# Examples
#
# block = Asciidoc::Block.new(:paragraph, ["`This` is a <test>"])
# block.content
# => ["<em>This</em> is a <test>"]
class Block
# Public: Get the Symbol context for this section block.
attr_reader :context
# Public: Get the Array of sub-blocks for this section block.
attr_reader :blocks
# Public: Get/Set the original Array content for this section block.
attr_accessor :buffer
# Public: Get/Set the String section anchor name.
attr_accessor :anchor
# Public: Get/Set the String block title.
attr_accessor :title
# Public: Get/Set the String block caption.
attr_accessor :caption
# Public: Initialize an Asciidoc::Block object.
#
# parent - The parent Asciidoc Object.
# context - The Symbol context name for the type of content.
# buffer - The Array buffer of source data.
def initialize(parent, context, buffer=nil)
@parent = parent
@context = context
@buffer = buffer.join.gsub(/\n\s*\\/m,'').lines.to_a unless buffer.nil?
@blocks = []
end
# Public: Get the Asciidoc::Document instance to which this Block belongs
def document
@parent.is_a?(Document) ? @parent : @parent.document
end
# Public: Get the Asciidoc::Renderer instance being used for the ancestor
# Asciidoc::Document instance.
def renderer
@parent.renderer
end
# Public: Get the rendered String content for this Block and all its child
# Blocks.
def render
rendered_blocks = [renderer.render("section_#{context}", self)]
rendered_blocks += blocks.map do |block|
view = "section_#{block.context}"
renderer.render(view, block)
end
rendered_blocks.join
end
# Public: Get an HTML-ified version of the source buffer, with special
# Asciidoc characters and entities converted to their HTML equivalents.
#
# Examples
#
# block = Block.new(:paragraph, ['`This` is what happens when you <meet> a stranger in the <alps>!']
# block.content
# => ["<em>This</em> is what happens when you <meet> a stranger in the <alps>!"]
#
# TODO:
# * forced line breaks
# * bold, mono
# * double/single quotes
# * super/sub script
def content
case @context
when :dlist
@buffer.map do |dt, dd|
html_dt = htmlify(dt.content)
if dd.content.empty?
html_dd = ''
else
html_dd = "<p>#{htmlify(dd.content)}</p>"
end
html_dd += dd.blocks.map{|block| block.render}.join
[html_dt, html_dd]
end
when :oblock
''
when :olist, :ulist, :colist
@buffer.map do |li|
htmlify(li.content) + li.blocks.map{|block| block.render}.join
end
when :listing
@buffer.map{|l| CGI.escapeHTML(l).gsub(/(<\d+>)/,'<b>\1</b>')}.join
when :literal
leading_ws = @buffer.first.match(/^(\s+)/)[1]
@buffer.map{|l| htmlify(l.sub(/#{leading_ws}/,''))}.join
when :verse
@buffer.map{|l| htmlify(l.strip)}.join("\n")
else
@buffer.map{|l| htmlify(l.lstrip)}.join # ("\n")
end
end
private
# Private: Return a String HTML version of the source string, with
# Asciidoc characters converted and HTML entities escaped.
#
# string - The String source string in Asciidoc format.
#
# Examples
#
# asciidoc_string = "Make 'this' <emphasized>"
# htmlify(asciidoc_string)
# => "Make <em>this</em> <emphasized>"
def htmlify(string)
intrinsics = {
'startsb' => '[',
'endsb' => ']'
}
unless string.nil?
html = string.dup
# Convert reference links to "link:" asciidoc for later HTMLification.
# This ensures that eg. "<<some reference>>" is turned into a link but
# "`<<<<<` and `>>>>>` are conflict markers" is not. This is much
# easier before the HTML is escaped and <> are turned into entities.
html.gsub!( /(^|[^<])<<([^<>,]+)(,([^>]*))?>>/ ) { "#{$1}link:##{$2}[" + ($4.nil?? document.references[$2] : $4).to_s + "]" }
# Do the same with URLs
html.gsub!(/(https?:\/\/[^\[ ]+)(\[.*)?/) do
if $2.nil?
"link:#{$1}[$1]$'"
else
link, rest = linkify($2[1..-1])
"link:#{$1}[#{link}]#{rest}"
end
end
CGI.escapeHTML(html).
gsub(REGEXP[:biblio], '<a name="\1">[\1]</a>').
gsub(/``(.*?)''/, '“\1”').
gsub(/(^|\W)'([^']+)'/, '\1<em>\2</em>').
gsub(/`([^`]+)`/, '<tt>\1</tt>').
gsub(/\*([^\*]+)\*/, '<strong>\1</strong>').
gsub(/\{([^\}]+)\}/) { intrinsics[$1] }.
gsub(/linkgit:([^\]]+)\[(\d+)\]/, '<a href="\1.html">\1(\2)</a>').
gsub(/link:([^\[]+)\[(.*)$/) { link,rest = linkify($2); "<a href=\"#{$1}\">#{link}</a>#{rest}" }
end
end
# Private: Extract the link text from a string, allowing for the link text to have zero
# or more levels of '[]' characters.
#
# string - the String input following the leading '[' character after an Asciidoc link: tag
#
# Returns the Array of [String link, String rest_of_string]
#
# Examples
#
# linkify( '1] lorem ipsum dolor' )
# => ["1", " lorem ipsum dolor"]
#
# linkify( '[1]] lorem ipsum dolor' )
# => ["[1]", " lorem ipsum dolor"]
#
# linkify( '[[1]]] lorem ipsum dolor' )
# => ["[[1]]", " lorem ipsum dolor"]
#
def linkify(string)
chars = string.chars.to_a
i = 0
level = 1
while chars.any? && level > 0
case chars.shift
when '['; level += 1
when ']'; level -= 1
end
i += 1 unless level == 0
end
raise "Unable to find link in #{string.inspect}" unless level == 0
[string[0..i-1], string[i+1..-1]]
end
end
# Public: Methods for managing sections of Asciidoc content in a document.
# The section responds as an Array of content blocks by delegating
# block-related methods to its @blocks Array.
#
# Examples
#
# section = Asciidoc::Section.new
# section.name = 'DESCRIPTION'
# section.anchor = 'DESCRIPTION'
#
# section.size
# => 0
#
# section.section_id
# => "_description"
#
# section << new_block
# section.size
# => 1
class Section
# Public: Get/Set the Integer section level.
attr_accessor :level
# Public: Get/Set the String section name.
attr_accessor :name
# Public: Get/Set the String section title.
attr_accessor :title
# Public: Get/Set the String section caption.
attr_accessor :caption
# Public: Get/Set the String section anchor name.
attr_accessor :anchor
# Public: Get the Array of section blocks.
attr_reader :blocks
# Public: Initialize an Asciidoc::Section object.
#
# parent - The parent Asciidoc Object.
def initialize(parent)
@parent = parent
@blocks = []
end
# Public: Get the String section id
#
# Examples
#
# section = Section.new
# section.name = "Foo"
# section.section_id
# => "_foo"
def section_id
"_#{name && name.downcase.gsub(' ','_')}"
end
# Public: Get the Asciidoc::Document instance to which this Block belongs
def document
@parent.is_a?(Document) ? @parent : @parent.document
end
# Public: Get the Asciidoc::Renderer instance being used for the ancestor
# Asciidoc::Document instance.
def renderer
@parent.renderer
end
# Public: Get the rendered String content for this Section and all its child
# Blocks.
def render
renderer.render('section', self)
end
# Public: Get the String section content by aggregating rendered section blocks.
#
# Examples
#
# section = Section.new
# section << 'foo'
# section << 'bar'
# section << 'baz'
# section.content
# "<div class=\"paragraph\"><p>foo</p></div>\n<div class=\"paragraph\"><p>bar</p></div>\n<div class=\"paragraph\"><p>baz</p></div>"
def content
@blocks.map{|block| block.render}.join
end
# Public: Get the Integer number of blocks in the section.
#
# Examples
#
# section = Section.new
#
# section.size
# => 0
#
# section << 'foo'
# section << 'bar'
# section.size
# => 2
def size
@blocks.size
end
# Public: Get the element at i in the array of section blocks.
#
# i - The Integer array index number.
#
# section = Section.new
#
# section << 'foo'
# section << 'bar'
# section[1]
# => "bar"
def [](i)
@blocks[i]
end
# Public: Delete the element at i in the array of section blocks,
# returning that element or nil if i is out of range.
#
# i - The Integer array index number.
#
# section = Section.new
#
# section << 'foo'
# section << 'bar'
# section.delete_at(1)
# => "bar"
#
# section.blocks
# => ["foo"]
def delete_at(i)
@blocks.delete_at(i)
end
# Public: Append a content block to this section's list of blocks.
#
# block - The new section block.
#
# section = Section.new
#
# section << 'foo'
# section << 'bar'
# section.blocks
# => ["foo", "bar"]
def <<(block)
@blocks << block
end
# Public: Insert a content block at the specified index in this section's
# list of blocks.
#
# i - The Integer array index number.
# val = The content block to insert.
#
# section = Section.new
#
# section << 'foo'
# section << 'baz'
# section.insert(1, 'bar')
# section.blocks
# ["foo", "bar", "baz"]
def insert(i, block)
@blocks.insert(i, block)
end
# Public: Get the Integer index number of the first content block element
# for which the provided block returns true. Returns nil if no match is
# found.
#
# block - A block that can be used to determine whether a supplied element
# is a match.
#
# section = Section.new
#
# section << 'foo'
# section << 'bar'
# section << 'baz'
# section.index{|el| el =~ /^ba/}
# => 1
def index(&block)
@blocks.index(&block)
end
end
# Public: Methods for parsing Asciidoc documents and rendering them
# using Tilt-compatible templates.
class Document
# Public: Get the String document source.
attr_reader :source
# Public: Get the Asciidoc::Renderer instance currently being used
# to render this Document.
attr_reader :renderer
# Public: Get the Hash of document references
attr_reader :references
# Public: Initialize an Asciidoc object.
#
# data - The String Asciidoc source document.
# block - A block that can be used to retrieve external Asciidoc
# data to include in this document.
#
# Examples
#
# base = File.dirname(filename)
# data = File.readlines(filename)
# doc = Asciidoc.new(data) do |inc|
# incfile = File.join(base, inc)
# File.read(incfile)
# end
def initialize(name, data, &block)
raw_source = data.dup
@defines = {}
@references = {}
include_regexp = /^include::([^\[]+)\[\]\s*\n/
while inc = raw_source.match(include_regexp)
raw_source.sub!(include_regexp){|st| yield inc[1]}
end
ifdef_regexp = /^(ifdef|ifndef)::([^\[]+)\[\]/
endif_regexp = /^endif::/
defattr_regexp = /^:([^:]+):\s*(.*)\s*$/
conditional_regexp = /^\s*\{([^\?]+)\?\s*([^\}]+)\s*\}/
skip_to = nil
@lines = raw_source.each_line.inject([]) do |lines, line|
if !skip_to.nil?
skip_to = nil if line.match(skip_to)
elsif match = line.match(ifdef_regexp)
attr = match[2]
skip = case match[1]
when 'ifdef'; !@defines.has_key?(attr)
when 'ifndef'; @defines.has_key?(attr)
end
skip_to = /^endif::#{attr}\[\]\s*\n/ if skip
elsif match = line.match(defattr_regexp)
@defines[match[1]] = match[2]
elsif !line.match(endif_regexp)
while match = line.match(conditional_regexp)
value = @defines.has_key?(match[1]) ? match[2] : ''
line.sub!(conditional_regexp, value)
end
lines << line unless line.match(REGEXP[:comment])
end
lines
end
# Process bibliography references, so they're available when text
# before the reference is being rendered.
@lines.each do |line|
if biblio = line.match(REGEXP[:biblio])
references[biblio[1]] = "[#{biblio[1]}]"
end
end
# link: tags and xrefs (and maybe other things?) can span multiple lines.
# eg. the SEE ALSO section of git-branch or the shallow_repository
# definition in glossary-content.
i = 0
while i < @lines.size
while link = @lines[i].match(/link:[^\[]+(\[.*)$/) && $1.count('[') > $1.count(']')
@lines[i].sub!(/\n$/,' ')
next_line = @lines.delete_at(i+1)
break if next_line.nil?
@lines[i] << next_line
end
while xref = @lines[i].match(/<</) && $' !~ />>/
@lines[i].sub!(/\n$/,' ')
next_line = @lines.delete_at(i+1)
break if next_line.nil?
@lines[i] << next_line
end
i += 1
end
@source = @lines.join
@root = next_section(@lines)
if @root.blocks.first.is_a?(Section)
@header = @root.blocks.shift
else
@preamble = Section.new(self)
while @root.blocks.first.is_a?(Block)
@preamble << @root.blocks.shift
end
end
end
# Public: Render the Asciidoc document using Tilt-compatible templates in
# the specified path.
#
# template_base - The String pathname of the directory containing templates.
#
# Examples
#
# Dir.entries(template_dir)
# => ['.', '..', 'document.html.erb', 'section.html.erb', 'section_paragraph.html.erb', ...]
#
# doc.render(template_dir)
# => "<h1>Doc Title</h1>\n<div class=\"section\">\n <div class=\"paragraph\"><p>Foo</p></div>\n</div>\n"
def render(template_dir)
@renderer = Renderer.new(template_dir)
html = @renderer.render('document', @root, :header => @header, :preamble => @preamble)
@renderer = nil
html
end
private
# Private: Strip off leading blank lines in the Array of lines.
#
# lines - the Array of String lines.
#
# Returns nil.
#
# Examples
#
# content
# => ["\n", "\t\n", "Foo\n", "Bar\n", "\n"]
#
# skip_blank(content)
# => nil
#
# lines
# => ["Foo\n", "Bar\n"]
def skip_blank(lines)
while lines.any? && lines.first.strip.empty?
lines.shift
end
nil
end
# Private: Strip off and return the next segment (one or more contiguous blocks) from the Array of lines.
#
# lines - the Array of String lines.
# options - an optional Hash of processing options:
# * :alt_ending may be used to specify a regular expression match other than
# a blank line to signify the end of the segment.
# Returns the Array of lines from the next segment.
#
# Examples
#
# content
# => ["First paragraph\n", "+\n", "Second paragraph\n", "--\n", "Open block\n", "\n", "Can have blank lines\n", "--\n", "\n", "In a different segment\n"]
#
# next_segment(content)
# => ["First paragraph\n", "+\n", "Second paragraph\n", "--\n", "Open block\n", "\n", "Can have blank lines\n", "--\n"]
#
# content
# => ["In a different segment\n"]
def next_segment(lines, options={})
alternate_ending = options[:alt_ending]
segment = []
skip_blank(lines)
# Grab lines until the first blank line not inside an open block
in_oblock = false
while lines.any?
this_line = lines.shift
in_oblock = !in_oblock if this_line.match(REGEXP[:oblock])
if !in_oblock
if this_line.strip.empty?
break
elsif !alternate_ending.nil? && this_line.match(alternate_ending)
lines.unshift this_line
break
end
end
segment << this_line
end
segment
end
# Private: Return the next block from the section.
#
# * Skip over blank lines to find the start of the next content block.
# * Use defined regular expressions to determine the type of content block.
# * Based on the type of content block, grab lines to the end of the block.
# * Return a new Asciidoc::Block or Asciidoc::Section instance with the
# content set to the grabbed lines.
def next_block(lines, parent=self)
# Skip ahead to the block content
while lines.any? && lines.first.strip.empty?
lines.shift
end
return nil if lines.empty?
if match = lines.first.match(REGEXP[:anchor])
anchor = match[1].match(/^\[(.*)\]/) ? $1 : match[1]
@references[anchor] = match[1]
lines.shift
else
anchor = nil
end
block = nil
title = nil
caption = nil
buffer = []
while lines.any? && block.nil?
buffer.clear
this_line = lines.shift
next_line = lines.first || ''
if this_line.match(REGEXP[:comment])
next
elsif match = this_line.match(REGEXP[:title])
title = match[1]
elsif match = this_line.match(REGEXP[:caption])
caption = match[1]
elsif this_line.match(REGEXP[:name]) && next_line.match(REGEXP[:line]) && (this_line.size - next_line.size).abs <= 1
lines.unshift(this_line)
lines.unshift(anchor) unless anchor.nil?
block = next_section(lines)
elsif this_line.match(REGEXP[:oblock])
# oblock is surrounded by '--' lines and has zero or more blocks inside
this_line = lines.shift
while !this_line.nil? && !this_line.match(REGEXP[:oblock])
buffer << this_line
this_line = lines.shift
end
while buffer.any? && buffer.last.strip.empty?
buffer.pop
end
block = Block.new(parent, :oblock, [])
while buffer.any?
block.blocks << next_block(buffer, block)
end
elsif this_line.match(REGEXP[:olist])
# olist is a series of blank-line-separated list items terminated by something that isn't an olist item
items = []
block = Block.new(parent, :olist)
while !this_line.nil? && match = this_line.match(REGEXP[:olist])
item = ListItem.new
item_blocks = []
item_buffer = [match[2]]
while lines.any? && !lines.first.strip.empty? && !lines.first.match(REGEXP[:olist])
this_line = lines.shift
if this_line.match(REGEXP[:listing])
item_buffer << this_line
this_line = lines.shift
while !this_line.nil? && !this_line.match(REGEXP[:listing])
item_buffer << this_line
this_line = lines.shift
end
item_buffer << this_line unless this_line.nil?
elsif this_line.match(REGEXP[:continue])
item_blocks << item_buffer.dup if item_buffer.any?
item_buffer.clear
else
item_buffer << this_line
end
end
item_blocks << item_buffer.dup if item_buffer.any?
item.content = item_blocks.shift.join
while item_block = item_blocks.shift
while item_block.any?
item.blocks << next_block(item_block)
end
end
items << item
while lines.any? && lines.first.strip.empty?
lines.shift
end
this_line = lines.shift
end
lines.unshift(this_line) unless this_line.nil?
block.buffer = items
elsif this_line.match(REGEXP[:ulist])
# ulist is a series of blank-line-separated list items terminated by something that isn't an ulist item
items = []
block = Block.new(parent, :ulist)
while !this_line.nil? && match = this_line.match(REGEXP[:ulist])
item = ListItem.new
item_blocks = []
item_buffer = [match[1]]
while lines.any? && !lines.first.strip.empty? && !lines.first.match(REGEXP[:ulist])
this_line = lines.shift
if this_line.match(REGEXP[:listing])
item_buffer << this_line
this_line = lines.shift
while !this_line.nil? && !this_line.match(REGEXP[:listing])
item_buffer << this_line
this_line = lines.shift
end
item_buffer << this_line unless this_line.nil?
elsif this_line.match(REGEXP[:continue])
item_blocks << item_buffer.dup if item_buffer.any?
item_buffer.clear
else
item_buffer << this_line
end
end
item_blocks << item_buffer.dup if item_buffer.any?
item.content = item_blocks.shift.join
while item_block = item_blocks.shift
while item_block.any?
item.blocks << next_block(item_block)
end
end
items << item
while lines.any? && lines.first.strip.empty?
lines.shift
end
this_line = lines.shift
end
lines.unshift(this_line) unless this_line.nil?
block.buffer = items
elsif this_line.match(REGEXP[:colist])
# colist is a series of blank-line-separated list items terminated by something that isn't an colist item
items = []
block = Block.new(parent, :colist)
while !this_line.nil? && match = this_line.match(REGEXP[:colist])
item = ListItem.new
item_blocks = []
item_buffer = [match[1]]
while lines.any? && !lines.first.strip.empty? && !lines.first.match(REGEXP[:colist])
this_line = lines.shift
if this_line.match(REGEXP[:listing])
item_buffer << this_line
this_line = lines.shift
while !this_line.nil? && !this_line.match(REGEXP[:listing])
item_buffer << this_line
this_line = lines.shift
end
item_buffer << this_line unless this_line.nil?
elsif this_line.match(REGEXP[:continue])
item_blocks << item_buffer.dup if item_buffer.any?
item_buffer.clear
else
item_buffer << this_line
end
end
item_blocks << item_buffer.dup if item_buffer.any?
item.content = item_blocks.shift.join
while item_block = item_blocks.shift
while item_block.any?
item.blocks << next_block(item_block)
end
end
items << item
while lines.any? && lines.first.strip.empty?
lines.shift
end
this_line = lines.shift
end
lines.unshift(this_line) unless this_line.nil?
block.buffer = items
elsif this_line.match(REGEXP[:dlist])
pairs = []
block = Block.new(parent, :dlist)
while !this_line.nil? && match = this_line.match(REGEXP[:dlist])
dt = ListItem.new(match[1])
dd = ListItem.new
lines.shift if lines.any? && lines.first.strip.empty? # workaround eg. git-config OPTIONS --get-colorbool
dd_segment = next_segment(lines, :alt_ending => REGEXP[:dlist])
while dd_segment.any?
dd.blocks << next_block(dd_segment, block)
end
if dd.blocks.any? && dd.blocks.first.is_a?(Block) && (dd.blocks.first.context == :paragraph || dd.blocks.first.context == :literal)
dd.content = dd.blocks.shift.buffer.map{|l| l.strip}.join("\n")
end
pairs << [dt, dd]
skip_blank(lines)
this_line = lines.shift
end
lines.unshift(this_line) unless this_line.nil?
block.buffer = pairs
elsif this_line.match(REGEXP[:verse])
# verse is preceded by [verse] and lasts until a blank line
this_line = lines.shift
while !this_line.nil? && !this_line.strip.empty?
buffer << this_line
this_line = lines.shift
end
block = Block.new(parent, :verse, buffer)
elsif this_line.match(REGEXP[:note])
# note is an admonition preceded by [NOTE] and lasts until a blank line
this_line = lines.shift
while !this_line.nil? && !this_line.strip.empty?
buffer << this_line
this_line = lines.shift
end
block = Block.new(parent, :note, buffer)
elsif this_line.match(REGEXP[:listing])
# listing is surrounded by '----' (3 or more dashes) lines
this_line = lines.shift
while !this_line.nil? && !this_line.match(REGEXP[:listing])
buffer << this_line
this_line = lines.shift
end
block = Block.new(parent, :listing, buffer)
elsif this_line.match(REGEXP[:example])
# example is surrounded by '====' (3 or more '=' chars) lines
this_line = lines.shift
while !this_line.nil? && !this_line.match(REGEXP[:example])
buffer << this_line
this_line = lines.shift
end
block = Block.new(parent, :example, buffer)
elsif this_line.match(REGEXP[:quote])
# quote is surrounded by '____' (4 or more '_' chars) lines
this_line = lines.shift
while !this_line.nil? && !this_line.match(REGEXP[:quote])
buffer << this_line
this_line = lines.shift
end
block = Block.new(parent, :quote, buffer)
elsif this_line.match(REGEXP[:literal])
# literal is contiguous lines starting with 4 spaces
while !this_line.nil? && this_line.match(REGEXP[:literal])
buffer << this_line
this_line = lines.shift
end
block = Block.new(parent, :literal, buffer)
else
# paragraph is contiguous nonblank/noncontinuation lines
while !this_line.nil? && !this_line.strip.empty?