forked from asciidoctor/docbookrx
/
docbookrx.rb
987 lines (874 loc) · 25 KB
/
docbookrx.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
# docbookrx - A script to convert DocBook to AsciiDoc
require 'nokogiri'
infile = ARGV.first || 'sample.xml'
unless infile
warn 'Please specify a DocBook file to convert'
exit
end
docbook = File.read infile
class DocBookVisitor
ENTITY_TABLE = {
169 => '(C)',
174 => '(R)',
8201 => ' ',
8212 => '--',
8216 => '`',
8217 => '\'',
8220 => '``',
8221 => '\'\'',
8230 => '...',
8482 => '(TM)',
8592 => '<-',
8594 => '->',
8656 => '<=',
8658 => '=>'
}
REPLACEMENT_TABLE = {
':: ' => '{two-colons} '
}
PARA_TAG_NAMES = ['para', 'simpara']
#COMPLEX_PARA_TAG_NAMES = ['formalpara', 'para']
ADMONITION_NAMES = ['note', 'tip', 'warning', 'caution', 'important']
SECTION_NAMES = ['abstract', 'appendix', 'glossary', 'bibliography']
LITERAL_NAMES = ['interfacename', 'classname', 'methodname', 'constant', 'filename']
LITERAL_NAMES_UNNAMED = ['application', 'command', 'guibutton', 'guimenu', 'guilabel', 'keycap']
attr_reader :lines
def initialize opts = {}
@lines = []
@level = 1
@skip = {}
@requires_index = false
@list_index = 0
@continuation = false
@adjoin_next = false
@idprefix = opts[:idprefix] || '_'
@idseparator = opts[:idseparator] || '_'
@em_char = opts[:em_char] || '_'
@attributes = opts[:attributes] || {}
@preserve_line_wrap = opts.fetch(:preserve_line_wrap, true)
@sentence_per_line = opts.fetch(:sentence_per_line, true)
@delimit_source = opts.fetch(:delimit_source, true)
end
## Traversal methods
# Main processor loop
def visit node
return if node.type == Nokogiri::XML::Node::COMMENT_NODE
if (at_root = (node == node.document.root))
before_traverse if respond_to? :before_traverse
end
name = node.name
if node.type == Nokogiri::XML::Node::PI_NODE
visit_method_name = :visit_pi
#elsif ADMONITION_NAMES.include?(name)
# visit_method_name = :process_admonition
#elsif SECTION_NAMES.include?(name)
# visit_method_name = :process_section
else
visit_method_name = "visit_#{name}".to_sym
end
if respond_to? visit_method_name
result = send(visit_method_name, node)
elsif ADMONITION_NAMES.include?(name) && (respond_to? :process_admonition)
result = send(:process_admonition, node, name)
elsif SECTION_NAMES.include?(name) && (respond_to? :process_section)
result = send(:process_section, node, name)
elsif LITERAL_NAMES.include?(name) && (respond_to? :process_literal)
result = send(:process_literal, node, name)
elsif LITERAL_NAMES_UNNAMED.include?(name) && (respond_to? :process_literal)
result = send(:process_literal, node)
elsif node.type == 5 && (respond_to? :passthru_entity_node) # html entity node
result = send(:passthru_entity_node, node)
elsif respond_to? :default_visit
result = send(:default_visit, node)
end
if result == true
traverse_children node
end
if at_root
after_traverse if respond_to? :after_traverse
end
end
def traverse_children node, opts = {}
(opts[:using_elements] ? node.elements : node.children).each do |child|
child.accept self
end
end
alias :proceed :traverse_children
## Text extraction and processing methods
def text node, unsub = true
if node
if node.is_a? Nokogiri::XML::Node
unsub ? reverse_subs(node.text) : node.text
elsif node.is_a? Nokogiri::XML::NodeSet && (first = node.first)
unsub ? reverse_subs(first.text) : first.text
else
nil
end
else
nil
end
end
def text_at_css node, css, unsub = true
text(node.at_css css, unsub)
end
def format_text node
if node && (node.is_a? Nokogiri::XML::NodeSet)
node = node.first
end
if node.is_a? Nokogiri::XML::Node
append_blank_line
proceed node
@lines.pop
else
nil
end
end
def format_text_at_css node, css
format_text(node.at_css css)
end
def entity number
[number].pack('U*')
end
# Replaces XML entities, and other encoded forms that AsciiDoc automatically
# applies, with their plain-text equivalents.
#
# This method effectively undoes the inline substitutions that AsciiDoc performs.
#
# str - The String to processes
#
# Examples
#
# reverse_subs "© Acme, Inc."
# # => "(C) Acme, Inc."
#
# Returns The processed String
def reverse_subs str
ENTITY_TABLE.each do |num, text|
str = str.gsub(entity(num), text)
end
REPLACEMENT_TABLE.each do |original, replacement|
str = str.gsub(original, replacement)
end
str
end
## Writer methods
def append_line line, unsub = false
line = reverse_subs line if unsub
@lines << line
end
def append_blank_line
if @continuation
@continuation = false
elsif @adjoin_next
@adjoin_next = false
else
@lines << ''
end
end
alias :start_new_line :append_blank_line
def append_block_title node
if (title = (format_text_at_css node, '> title'))
# special case for <itemizedlist role="see-also-list"><title> -- omit the prefix "." as we want simple text on a bullet, not a heading
if (node.attr('role') == "see-also-list")
append_line %(#{title.gsub(/\n[[:blank:]\t]*/, ' ')})
else
append_line %(.#{title.gsub(/\n[[:blank:]\t]*/, ' ')})
end
@adjoin_next = true
true
else
false
end
end
def append_block_role node
if (role = node.attr('role'))
append_line %([.#{role}])
#@adjoin_next = true
true
else
false
end
end
def append_text text, unsub = false
text = reverse_subs text if unsub
@lines[-1] = %(#{@lines[-1]}#{text})
end
## Lifecycle callbacks
#def before_traverse
#end
def after_traverse
if @requires_index
append_blank_line
append_line 'ifdef::backend-docbook[]'
append_line '[index]'
append_line '== Index'
append_line '// Generated automatically by the DocBook toolchain.'
append_line 'endif::backend-docbook[]'
end
end
## Node visitor callbacks
# pass thru HTML entities unchanged, eg., for →
def passthru_entity_node node
# warn %(Pass through #{node} unchanged)
append_text %(#{node})
false
end
def default_visit node
warn %(No visitor defined for <#{node.name}> element, type = #{node.type}! Skipping.)
false
end
# Skip title as it's always handled by the parent visitor
def visit_title node
false
end
def visit_toc node
false
end
### Document node (article | book | chapter) & header node (articleinfo | bookinfo | info) visitors
def visit_book node
process_doc node
end
def visit_bookinfo node
process_info node
end
def visit_article node
process_doc node
end
def visit_articleinfo node
process_info node
end
# treat chapters as books, and number their sections
def visit_chapter node
append_line ':numbered:'
append_line ':doctype: book'
append_line ':toc: left'
append_line ':icons: font'
append_blank_line
process_doc node
end
def process_doc node
@level += 1
proceed node, :using_elements => true
@level -= 1
false
end
def process_info node
title = text_at_css node, '> title'
append_line %(= #{title})
author_line = nil
if (author_node = node.at_css('author'))
author_line = [(text_at_css author_node, 'firstname'), (text_at_css author_node, 'surname')].compact * ' '
if (email_node = author_node.at_css('email'))
author_line = %(#{author_line} <#{text email_node}>)
end
end
append_line author_line if author_line
date_line = nil
if (revnumber_node = node.at_css('revhistory revnumber', 'releaseinfo'))
date_line = %(v#{revnumber_node.text}, )
end
if (date_node = node.at_css('> date', '> pubdate'))
append_line %(#{date_line}#{date_node.text})
end
if node.name == 'bookinfo' || node.parent.name == 'book' || node.parent.name == 'chapter'
append_line ':doctype: book'
append_line ':numbered:'
append_line ':toc2:'
end
if @idprefix != '_'
append_line ":idprefix: #{@idprefix}".rstrip
end
if @idseparator != '_'
append_line ":idseparator: #{@idseparator}".rstrip
end
@attributes.each do |name, val|
append_line %(:#{name}: #{val}).rstrip
end
false
end
# Very rough first pass at processing xi:include
def visit_include node
# QUESTION should we reuse this instance to traverse the new tree?
include_infile = node.attr 'href'
include_outfile = include_infile.sub '.xml', '.ad'
if File.readable? include_infile
doc = Nokogiri::XML::Document.parse(File.read include_infile)
# TODO pass in options that were passed to this visitor
visitor = self.class.new
doc.root.accept visitor
result = visitor.lines
result.shift while result.size > 0 && result.first.empty?
File.open(include_outfile, 'w') {|f| f.write(visitor.lines * "\n") }
else
warn %(Include file not readable: #{href})
end
append_blank_line
# TODO make leveloffset more context-aware
append_line %(:leveloffset: #{@level - 1}) if @level > 1
append_line %(include::#{include_outfile}[])
append_line %(:leveloffset: 0) if @level > 1
false
end
### Section node (part | section | <special>) visitors
def visit_section node
process_section node
end
def visit_bridgehead node
level = node.attr('renderas').sub('sect', '').to_i + 1
append_blank_line
append_line '[float]'
title = format_text node
auto_id = generate_id title
# anchor links should be lower-case-with-dashes, not Title_Case_With_Underscores
if (id = node.attr('id').downcase.gsub("_","-")) && id != auto_id
append_line %([[#{id}]])
end
append_line %(#{'=' * level} #{title.gsub(/\n[[:blank:]]*/, ' ')})
false
end
def process_section node, special = nil
append_blank_line
if special
append_line ':numbered!:'
append_blank_line
append_line %([#{special}])
end
title = format_text_at_css node, '> title'
auto_id = generate_id title
# anchor links should be lower-case-with-dashes, not Title_Case_With_Underscores
if (id = node.attr('id').downcase.gsub("_","-"))
if id != (generate_id title)
append_line %([[#{id}]])
end
end
append_line %(#{'=' * @level} #{title.gsub(/\n[[:blank:]\t]*/, ' ')})
@level += 1
proceed node, :using_elements => true
@level -= 1
if special
append_blank_line
append_line ':numbered:'
end
false
end
def generate_id title
sep = @idseparator
pre = @idprefix
illegal_sectid_chars = /&(?:[[:alpha:]]+|#[[:digit:]]+|#x[[:alnum:]]+);|\W+?/
id = %(#{pre}#{title.downcase.gsub(illegal_sectid_chars, sep).tr_s(sep, sep).chomp(sep)})
if pre.empty? && id.start_with?(sep)
id = id[1..-1]
id = id[1..-1] while id.start_with?(sep)
end
id
end
### Block node visitors
def visit_formalpara node
append_blank_line
append_block_title node
true
end
def visit_para node
append_blank_line
append_block_role node
append_blank_line
true
end
def visit_simpara node
append_blank_line
append_block_role node
append_blank_line
true
end
def process_admonition node, name
elements = node.elements
append_blank_line
append_block_title node
append_line %([#{name.upcase}])
append_line '===='
if elements.size == 1 && PARA_TAG_NAMES.include?((child = elements.first).name)
append_line %(#{format_text child})
else
@adjoin_next = true
proceed node
@adjoin_next = false
end
append_line '===='
false
end
def visit_itemizedlist node
append_blank_line
append_block_title node
true
end
def visit_procedure node
append_line %(.Procedure: #{node.at_css('title').text})
append_blank_line
visit_orderedlist node
end
def visit_substeps node
visit_orderedlist node
end
def visit_stepalternatives node
visit_orderedlist node
end
def visit_orderedlist node
@list_index = 1
append_blank_line
numeration = node.attr('numeration')
if (numeration && numeration != 'arabic')
append_line %([#{numeration}])
end
true
end
def visit_variablelist node
append_blank_line
append_block_title node
true
end
def visit_step node
visit_listitem node
end
def visit_listitem node
elements = node.elements.to_a
item_text = format_text elements.shift
# do we want variable depths of bullets?
depth = (node.ancestors.length - 4)
# or static bullet depths
depth = 1
marker = (node.parent.name == 'orderedlist' || node.parent.name == 'procedure' ? '.' * depth :
(node.parent.name == 'stepalternatives' ? 'a.' : '*' * depth))
didbullet=false
item_text.split("\n").each_with_index do |line, i|
line = line.gsub("^[[:blank:]\t]*","")
if line.length > 0
if (line == "====")
append_line %(#{line})
elsif (!didbullet)
append_line %(#{marker} #{line})
didbullet=true
else
append_line %( #{line})
end
end
end
unless elements.empty?
elements.each_with_index do |child, i|
unless i == 0 && child.name == 'literallayout'
append_line '+'
@continuation = true
end
child.accept self
end
append_blank_line
end
false
end
def visit_varlistentry node
append_blank_line unless (previous = node.previous_element) && previous.name == 'title'
append_line %(#{format_text(node.at_css node, '> term')};;)
item_text = format_text(node.at_css node, '> listitem > para', '> listitem > simpara')
if item_text
item_text.split("\n").each do |line|
append_line %( #{line})
end
end
# support listitem figures in a listentry
if node.at_css('listitem figure')
# warn %(#{node.at_css('listitem figure')})
visit_figure node.at_css('listitem figure')
end
# FIXME this doesn't catch complex children
false
end
def visit_glossentry node
append_blank_line
if !(previous = node.previous_element) || previous.name != 'glossentry'
append_line '[glossary]'
end
true
end
def visit_glossterm node
append_line %(#{format_text node}::)
false
end
def visit_glossdef node
append_line %( #{text node.elements.first})
false
end
def visit_bibliodiv node
append_blank_line
append_line '[bibliography]'
true
end
def visit_bibliomisc node
true
end
def visit_bibliomixed node
append_blank_line
proceed node
append_line @lines.pop.sub(/^\[(.*?)\]/, '* [[[\\1]]]')
false
end
def visit_literallayout node
append_blank_line
source_lines = node.text.rstrip.split("\n")
if (source_lines.detect{|line| line.rstrip.empty?})
append_line '....'
append_line node.text.rstrip
append_line '....'
else
source_lines.each do |line|
append_line %( #{line})
end
end
false
end
def visit_screen node
append_blank_line unless node.parent.name == 'para'
source_lines = node.text.rstrip.split("\n")
if source_lines.detect {|line| line.match(/^-{4,}/) }
append_line '[listing]'
append_line '....'
append_line node.text.rstrip
append_line '....'
else
append_line '----'
append_line node.text.rstrip
append_line '----'
end
false
end
def visit_programlisting node
language = node.attr('language') || @attributes['language']
language = %(,#{language.downcase}) if language
linenums = node.attr('linenumbering') == 'numbered'
append_blank_line unless node.parent.name == 'para'
append_line %([source#{language}#{linenums ? ',linenums' : nil}])
source_lines = node.text.rstrip.split("\n")
if @delimit_source || (source_lines.detect {|line| line.rstrip.empty?})
append_line '----'
append_line (source_lines * "\n")
append_line '----'
else
append_line (source_lines * "\n")
end
false
end
# FIXME wrap this up in a process_block method
def visit_example node
append_blank_line
append_block_title node
elements = node.elements.to_a
if elements.size > 0 && elements.first.name == 'title'
elements.shift
end
if elements.size == 1 && PARA_TAG_NAMES.include?((child = elements.first).name)
append_line '[example]'
append_line format_text child
else
append_line '===='
@adjoin_next = true
proceed node
@adjoin_next = false
append_line '===='
end
false
end
# FIXME wrap this up in a process_block method
def visit_sidebar node
append_blank_line
append_block_title node
elements = node.elements.to_a
# TODO make skipping title a part of append_block_title perhaps?
if elements.size > 0 && elements.first.name == 'title'
elements.shift
end
if elements.size == 1 && PARA_TAG_NAMES.include?((child = elements.first).name)
append_line '[sidebar]'
append_line format_text child
else
append_line '****'
@adjoin_next = true
proceed node
@adjoin_next = false
append_line '****'
end
false
end
def visit_blockquote node
append_blank_line
append_block_title node
elements = node.elements.to_a
# TODO make skipping title a part of append_block_title perhaps?
if elements.size > 0 && elements.first.name == 'title'
elements.shift
end
if elements.size == 1 && PARA_TAG_NAMES.include?((child = elements.first).name)
append_line '[quote]'
append_line format_text child
else
append_line '____'
@adjoin_next = true
proceed node
@adjoin_next = false
append_line '____'
end
false
end
def visit_table node
append_blank_line
append_block_title node
process_table node
false
end
def visit_informaltable node
append_blank_line
process_table node
false
end
def process_table node
numcols = (node.at_css '> tgroup').attr('cols').to_i
cols = ('1' * numcols).split('')
body = node.at_css '> tgroup > tbody'
row1 = body.at_css '> row'
row1_cells = row1.elements
numcols.times do |i|
next if !(element = row1_cells[i].elements.first)
case element.name
when 'literallayout'
cols[i] = %(#{cols[i]}*l)
end
end
if (frame = node.attr('frame'))
frame = %(, frame="#{frame}")
else
frame = nil
end
options = []
if (head = node.at_css '> tgroup > thead')
options << 'header'
end
if (foot = node.at_css '> tgroup > tfoot')
options << 'footer'
end
options = (options.empty? ? nil : %(, options="#{options * ','}"))
append_line %([cols="#{cols * ','}"#{frame}#{options}])
append_line '|==='
if head
(head.css '> row > entry').each do |cell|
append_line %(| #{text cell})
end
end
(node.css '> tgroup > tbody > row').each do |row|
append_blank_line
row.elements.each do |cell|
next if !(element = cell.elements.first)
if element.text.empty?
append_line '|'
else
append_line %(| #{text cell})
#case element.name
#when 'literallayout'
# append_line %(|`#{text cell}`)
#else
# append_line %(|#{text cell})
#end
end
end
end
if foot
(foot.css '> row > entry').each do |cell|
# FIXME needs inline formatting like body
append_line %(| #{text cell})
end
end
append_line '|==='
false
end
### Inline node visitors
def visit_text node
in_para = PARA_TAG_NAMES.include?(node.parent.name) || node.parent.name == 'phrase'
# drop text if empty unless we're processing a paragraph
unless node.text.rstrip.empty? && !in_para
text = node.text
if in_para
# strip leading indent for normal paragraph
# TODO may want to factor out this whitespace processing
text = text.gsub(/\n[[:blank:]\t]*/, @preserve_line_wrap ? "\n" : ' ')
if @sentence_per_line
text = text.gsub(/(^|[^A-Z])\. /, "\\1.\n")
end
end
append_text text, true
end
false
end
def visit_anchor node
# anchor links should be lower-case-with-dashes, not Title_Case_With_Underscores
id = node.attr('id').downcase.gsub("_","-")
append_text %([[#{id}]])
false
end
def visit_link node
linkend = node.attr('linkend')
label = format_text node
if label.include? ','
label = %("#{label}")
end
append_text %(<<#{linkend},#{label}>>)
false
end
def visit_ulink node
url = node.attr('url')
prefix = 'link:'
if url.start_with?('http://') || url.start_with?('https://')
prefix = nil
end
label = text node
if url != label
if (ref = @attributes.key(url))
url = %({#{ref}})
end
append_text %(#{prefix}#{url}[#{label}])
else
if (ref = @attributes.key(url))
url = %({#{ref}})
end
append_text %(#{prefix}#{url})
end
false
end
def visit_xref node
linkend = node.attr('linkend')
label = linkend.gsub("_"," ")
# anchor links should be lower-case-with-dashes, not Title_Case_With_Underscores
linkend = linkend.downcase.gsub("_","-")
append_text %(<<#{linkend},#{label}>>)
false
end
def visit_phrase node
# FIXME for now, double up the marks to be sure we catch it
#append_text %([#{node.attr 'role'}]##{format_text node}#)
if node.attr 'role'
append_text %([#{node.attr 'role'}]###{format_text node}##)
else
append_text %(#{format_text node})
end
false
end
def visit_emphasis node
quote_char = node.attr('role') == 'strong' ? '*' : @em_char
append_text %(#{quote_char}#{format_text node}#{quote_char})
false
end
def visit_literal node
process_literal node
end
def visit_code node
process_literal node
end
def process_literal node, name = nil
unless name.nil?
shortname = name.sub('name', '')
append_text %([#{shortname}])
end
node_text = node.text
if node_text == '`'
append_text '+`+'
# FIXME be smarter about when to use + vs `
# FIXME know when to use ++
elsif node_text.include? '`'
append_text %(+#{node_text}+)
else
append_text %(`#{node_text}`)
end
false
end
def visit_inlinemediaobject node
src = node.at_css('imageobject imagedata').attr('fileref')
alt = text_at_css node, 'textobject phrase'
generated_alt = File.basename(src)[0...-(File.extname(src).length)]
if alt == generated_alt
alt = nil
end
append_text %(image:#{src}["#{alt}"])
false
end
def visit_mediaobject node
visit_figure node
end
# FIXME share logic w/ visit_inlinemediaobject, which is the same here except no block_title and uses append_text, not append_line
def visit_figure node
append_blank_line
append_block_title node
src = node.at_css('imageobject imagedata').attr('fileref')
alt = text_at_css node, 'textobject phrase'
#title = node.at_css('title').text
generated_alt = File.basename(src)[0...-(File.extname(src).length)]
if alt == generated_alt
alt = nil
end
#append_line %(.#{title})
append_blank_line
append_line %(image::#{src}["#{alt}"])
false
end
def visit_footnote node
append_text %(footnote:[#{text_at_css node, '> para', '> simpara'}])
# FIXME not sure a blank line is always appropriate
append_blank_line
false
end
def visit_indexterm node
previous_skipped = false
if @skip.has_key? :indexterm
skip_count = @skip[:indexterm]
if skip_count > 0
@skip[:indexterm] -= 1
return false
else
@skip.delete(:indexterm)
previous_skipped = true
end
end
@requires_index = true
entries = [(text_at_css node, 'primary'), (text_at_css node, 'secondary'), (text_at_css node, 'tertiary')].compact
if previous_skipped && (previous = node.previous_element) && previous.name == 'indexterm'
append_blank_line
end
@skip[:indexterm] = entries.size - 1 if entries.size > 1
append_text %|(((#{entries * ','})))|
# Only if next word matches the index term do we use double-bracket form
#if entries.size == 1
# append_text %|((#{entries.first}))|
#else
# @skip[:indexterm] = entries.size - 1
# append_text %|(((#{entries * ','})))|
#end
false
end
def visit_pi node
case node.name
when 'asciidoc-br'
append_text ' +'
when 'asciidoc-hr'
# <?asciidoc-hr?> will be wrapped in a para/simpara
append_text '\'' * 3
end
false
end
end
doc = Nokogiri::XML::Document.parse(docbook)
options = {
# :idprefix => '',
# :idseparator => '-',
# :em_char => '\'',
# :attributes => {
# 'ref-contribute' => 'http://beanvalidation.org/contribute/',
# 'ref-jsr-317' => 'http://jcp.org/en/jsr/detail?id=317'
# }
}
visitor = DocBookVisitor.new options
doc.root.accept visitor
puts visitor.lines * "\n"