-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhikidoc.rb
912 lines (779 loc) · 19.1 KB
/
hikidoc.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
# -*- coding: utf-8 -*-
# Copyright (c) 2005, Kazuhiko <[email protected]>
# Copyright (c) 2007 Minero Aoki
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the HikiDoc nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
require "stringio"
require "strscan"
require "uri"
begin
require "syntax/convertors/html"
rescue LoadError
end
class HikiDoc
VERSION = "0.1.0"
class Error < StandardError
end
class UnexpectedError < Error
end
def HikiDoc.to_html(src, options = {})
new(HTMLOutput.new(">"), options).compile(src)
end
def HikiDoc.to_xhtml(src, options = {})
new(HTMLOutput.new(" />"), options).compile(src)
end
def initialize(output, options = {})
@output = output
@options = default_options.merge(options)
@header_re = nil
@level = options[:level] || 1
@plugin_syntax = options[:plugin_syntax] || method(:valid_plugin_syntax?)
end
def compile(src)
@output.reset
escape_plugin_blocks(src) {|escaped|
compile_blocks escaped
@output.finish
}
end
# for backward compatibility
def to_html
$stderr.puts("warning: HikiDoc#to_html is deprecated. Please use HikiDoc.to_html or HikiDoc.to_xhtml instead.")
self.class.to_html(@output, @options)
end
private
def default_options
{
allow_bracket_inline_image: true,
use_wiki_name: true,
use_not_wiki_name: true,
}
end
#
# Plugin
#
def valid_plugin_syntax?(code)
/['"]/ !~ code.gsub(/\\\\/, "").gsub(/\\['"]/,"").gsub(/'[^']*'|"[^"]*"/m, "")
end
def escape_plugin_blocks(text)
s = StringScanner.new(text)
buf = ""
@plugin_blocks = []
while chunk = s.scan_until(/\{\{/)
chunk[-2, 2] = ""
buf << chunk
if block = extract_plugin_block(s)
@plugin_blocks.push block
buf << "\0#{@plugin_blocks.size - 1}\0"
else
buf << "{{"
end
end
buf << s.rest
yield(buf)
end
def restore_plugin_block(str)
str.gsub(/\0(\d+)\0/) {
"{{" + plugin_block($1.to_i) + "}}"
}
end
def evaluate_plugin_block(str, buf = nil)
buf ||= @output.container
str.split(/(\0\d+\0)/).each do |s|
if s[0, 1] == "\0" and s[-1, 1] == "\0"
buf << @output.inline_plugin(plugin_block(s[1..-2].to_i))
else
buf << @output.text(s)
end
end
buf
end
def plugin_block(id)
@plugin_blocks[id] or raise UnexpectedError, "must not happen: #{id.inspect}"
end
def extract_plugin_block(s)
pos = s.pos
buf = ""
while chunk = s.scan_until(/\}\}/)
buf << chunk
buf.chomp!("}}")
if @plugin_syntax.call(buf)
return buf
end
buf << "}}"
end
s.pos = pos
nil
end
#
# Block Level
#
def compile_blocks(src)
f = LineInput.new(StringIO.new(src))
while line = f.peek
case line
when COMMENT_RE
f.gets
when HEADER_RE
compile_header f.gets
when HRULE_RE
f.gets
compile_hrule
when LIST_RE
compile_list f
when DLIST_RE
compile_dlist f
when TABLE_RE
compile_table f
when BLOCKQUOTE_RE
compile_blockquote f
when INDENTED_PRE_RE
compile_indented_pre f
when BLOCK_PRE_OPEN_RE
compile_block_pre f
else
if /^$/ =~ line
f.gets
next
end
compile_paragraph f
end
end
end
COMMENT_RE = %r<\A//>
def skip_comments(f)
f.while_match(COMMENT_RE) do |line|
end
end
HEADER_RE = /\A!+/
def compile_header(line)
@header_re ||= /\A!{1,#{7 - @level}}/
level = @level + (line.slice!(@header_re).size - 1)
title = strip(line)
@output.headline level, compile_inline(title)
end
HRULE_RE = /\A----$/
def compile_hrule
@output.hrule
end
ULIST = "*"
OLIST = "#"
LIST_RE = /\A#{Regexp.union(ULIST, OLIST)}+/
def compile_list(f)
typestack = []
level = 0
@output.list_begin
f.while_match(LIST_RE) do |line|
list_type = (line[0,1] == ULIST ? "ul" : "ol")
new_level = line.slice(LIST_RE).size
item = strip(line.sub(LIST_RE, ""))
if new_level > level
(new_level - level).times do
typestack.push list_type
@output.list_open list_type
@output.listitem_open
end
@output.listitem compile_inline(item)
elsif new_level < level
(level - new_level).times do
@output.listitem_close
@output.list_close typestack.pop
end
@output.listitem_close
@output.listitem_open
@output.listitem compile_inline(item)
elsif list_type == typestack.last
@output.listitem_close
@output.listitem_open
@output.listitem compile_inline(item)
else
@output.listitem_close
@output.list_close typestack.pop
@output.list_open list_type
@output.listitem_open
@output.listitem compile_inline(item)
typestack.push list_type
end
level = new_level
skip_comments f
end
level.times do
@output.listitem_close
@output.list_close typestack.pop
end
@output.list_end
end
DLIST_RE = /\A:/
def compile_dlist(f)
@output.dlist_open
f.while_match(DLIST_RE) do |line|
dt, dd = split_dlitem(line.sub(DLIST_RE, ""))
@output.dlist_item compile_inline(dt), compile_inline(dd)
skip_comments f
end
@output.dlist_close
end
def split_dlitem(line)
re = /\A((?:#{BRACKET_LINK_RE}|.)*?):/o
if m = re.match(line)
return m[1], m.post_match
else
return line, ""
end
end
TABLE_RE = /\A\|\|/
def compile_table(f)
lines = []
f.while_match(TABLE_RE) do |line|
lines.push line
skip_comments f
end
@output.table_open
lines.each do |line|
@output.table_record_open
split_columns(line.sub(TABLE_RE, "")).each do |col|
mid = col.sub!(/\A!/, "") ? "table_head" : "table_data"
span = col.slice!(/\A[\^>]*/)
rs = span_count(span, "^")
cs = span_count(span, ">")
@output.__send__(mid, compile_inline(col), rs, cs)
end
@output.table_record_close
end
@output.table_close
end
def split_columns(str)
cols = str.split(/\|\|/)
cols.pop if cols.last.chomp.empty?
cols
end
def span_count(str, ch)
c = str.count(ch)
c == 0 ? nil : c + 1
end
BLOCKQUOTE_RE = /\A""[ \t]?/
def compile_blockquote(f)
@output.blockquote_open
lines = []
f.while_match(BLOCKQUOTE_RE) do |line|
lines.push line.sub(BLOCKQUOTE_RE, "")
skip_comments f
end
compile_blocks lines.join("")
@output.blockquote_close
end
INDENTED_PRE_RE = /\A[ \t]/
def compile_indented_pre(f)
lines = f.span(INDENTED_PRE_RE)\
.map {|line| rstrip(line.sub(INDENTED_PRE_RE, "")) }
text = restore_plugin_block(lines.join("\n"))
@output.preformatted(@output.text(text))
end
BLOCK_PRE_OPEN_RE = /\A<<<\s*(\w+)?/
BLOCK_PRE_CLOSE_RE = /\A>>>/
def compile_block_pre(f)
m = BLOCK_PRE_OPEN_RE.match(f.gets) or raise UnexpectedError, "must not happen"
str = restore_plugin_block(f.break(BLOCK_PRE_CLOSE_RE).join.chomp)
f.gets
@output.block_preformatted(str, m[1])
end
BLANK = /\A$/
PARAGRAPH_END_RE = Regexp.union(BLANK,
HEADER_RE, HRULE_RE, LIST_RE, DLIST_RE,
BLOCKQUOTE_RE, TABLE_RE,
INDENTED_PRE_RE, BLOCK_PRE_OPEN_RE)
def compile_paragraph(f)
lines = f.break(PARAGRAPH_END_RE)\
.reject {|line| COMMENT_RE =~ line }
if lines.size == 1 and /\A\0(\d+)\0\z/ =~ strip(lines[0])
@output.block_plugin plugin_block($1.to_i)
else
line_buffer = @output.container(:paragraph)
lines.each_with_index do |line, i|
buffer = @output.container
line_buffer << buffer
compile_inline(lstrip(line).chomp, buffer)
end
@output.paragraph(line_buffer)
end
end
#
# Inline Level
#
BRACKET_LINK_RE = /\[\[.+?\]\]/
URI_RE = /(?:https?|ftp|file|mailto):[A-Za-z0-9;\/?:@&=+$,\-_.!~*\'()#%]+/
WIKI_NAME_RE = /\b(?:[A-Z]+[a-z\d]+){2,}\b/
def inline_syntax_re
if @options[:use_wiki_name]
if @options[:use_not_wiki_name]
/ (#{BRACKET_LINK_RE})
| (#{URI_RE})
| (#{MODIFIER_RE})
| (\^?#{WIKI_NAME_RE})
/xo
else
/ (#{BRACKET_LINK_RE})
| (#{URI_RE})
| (#{MODIFIER_RE})
| (#{WIKI_NAME_RE})
/xo
end
else
/ (#{BRACKET_LINK_RE})
| (#{URI_RE})
| (#{MODIFIER_RE})
/xo
end
end
def compile_inline(str, buf = nil)
buf ||= @output.container
re = inline_syntax_re
pending_str = ""
while m = re.match(str)
str = m.post_match
link, uri, mod, wiki_name = m[1, 4]
if wiki_name and wiki_name.start_with? "^"
pending_str += m.pre_match + wiki_name[1..-1]
next
end
pre_str = "#{pending_str}#{m.pre_match}"
pending_str = ""
evaluate_plugin_block(pre_str, buf)
compile_inline_markup(buf, link, uri, mod, wiki_name)
end
evaluate_plugin_block(pending_str + str, buf)
buf
end
def compile_inline_markup(buf, link, uri, mod, wiki_name)
case
when link
buf << compile_bracket_link(link[2...-2])
when uri
buf << compile_uri_autolink(uri)
when mod
buf << compile_modifier(mod)
when wiki_name
buf << @output.wiki_name(wiki_name)
else
raise UnexpectedError, "must not happen"
end
end
def compile_bracket_link(link)
if m = /\A(.*)\|/.match(link)
title = m[0].chop
uri = m.post_match
fixed_uri = fix_uri(uri)
if can_image_link?(uri)
@output.image_hyperlink(fixed_uri, title)
else
@output.hyperlink(fixed_uri, compile_modifier(title))
end
else
fixed_link = fix_uri(link)
if can_image_link?(link)
@output.image_hyperlink(fixed_link)
else
@output.hyperlink(fixed_link, @output.text(link))
end
end
end
def can_image_link?(uri)
image?(uri) and @options[:allow_bracket_inline_image]
end
def compile_uri_autolink(uri)
if image?(uri)
@output.image_hyperlink(fix_uri(uri))
else
@output.hyperlink(fix_uri(uri), @output.text(uri))
end
end
def fix_uri(uri)
if /\A(?:https?|ftp|file):(?!\/\/)/ =~ uri
uri.sub(/\A\w+:/, "")
else
uri
end
end
IMAGE_EXTS = %w(.jpg .jpeg .gif .png)
def image?(uri)
IMAGE_EXTS.include?(uri[/\.[^.]+\z/].to_s.downcase)
end
STRONG = "'''"
EM = "''"
DEL = "=="
TT = "``"
STRONG_RE = /'''.+?'''/
EM_RE = /''.+?''/
DEL_RE = /==.+?==/
TT_RE = /``.+?``/
MODIFIER_RE = Regexp.union(STRONG_RE, EM_RE, DEL_RE, TT_RE)
MODTAG = {
STRONG => "strong",
EM => "em",
DEL => "del",
TT => 'tt'
}
def compile_modifier(str)
buf = @output.container
while m = / (#{MODIFIER_RE})
/xo.match(str)
evaluate_plugin_block(m.pre_match, buf)
case
when chunk = m[1]
mod, s = split_mod(chunk)
mid = MODTAG[mod]
buf << @output.__send__(mid, compile_inline(s))
else
raise UnexpectedError, "must not happen"
end
str = m.post_match
end
evaluate_plugin_block(str, buf)
buf
end
def split_mod(str)
case str
when /\A'''/
return str[0, 3], str[3...-3]
when /\A''/
return str[0, 2], str[2...-2]
when /\A==/
return str[0, 2], str[2...-2]
when /\A``/
return str[0, 2], str[2...-2]
else
raise UnexpectedError, "must not happen: #{str.inspect}"
end
end
def strip(str)
rstrip(lstrip(str))
end
def rstrip(str)
str.sub(/[ \t\r\n\v\f]+\z/, "")
end
def lstrip(str)
str.sub(/\A[ \t\r\n\v\f]+/, "")
end
class HTMLOutput
def initialize(suffix = " />")
@suffix = suffix
@f = nil
end
def reset
@f = StringIO.new
end
def finish
@f.string
end
def container(_for=nil)
case _for
when :paragraph
[]
else
""
end
end
#
# Procedures
#
def headline(level, title)
@f.puts "<h#{level}>#{title}</h#{level}>"
end
def hrule
@f.puts "<hr#{@suffix}"
end
def list_begin
end
def list_end
@f.puts
end
def list_open(type)
@f.puts "<#{type}>"
end
def list_close(type)
@f.print "</#{type}>"
end
def listitem_open
@f.print "<li>"
end
def listitem_close
@f.puts "</li>"
end
def listitem(item)
@f.print item
end
def dlist_open
@f.puts "<dl>"
end
def dlist_close
@f.puts "</dl>"
end
def dlist_item(dt, dd)
case
when dd.empty?
@f.puts "<dt>#{dt}</dt>"
when dt.empty?
@f.puts "<dd>#{dd}</dd>"
else
@f.puts "<dt>#{dt}</dt>"
@f.puts "<dd>#{dd}</dd>"
end
end
def table_open
@f.puts %Q(<table border="1">)
end
def table_close
@f.puts "</table>"
end
def table_record_open
@f.print "<tr>"
end
def table_record_close
@f.puts "</tr>"
end
def table_head(item, rs, cs)
@f.print "<th#{tdattr(rs, cs)}>#{item}</th>"
end
def table_data(item, rs, cs)
@f.print "<td#{tdattr(rs, cs)}>#{item}</td>"
end
def tdattr(rs, cs)
buf = ""
buf << %Q( rowspan="#{rs}") if rs
buf << %Q( colspan="#{cs}") if cs
buf
end
private :tdattr
def blockquote_open
@f.print "<blockquote>"
end
def blockquote_close
@f.puts "</blockquote>"
end
def block_preformatted(str, info)
syntax = info ? info.downcase : nil
if syntax
begin
convertor = Syntax::Convertors::HTML.for_syntax(syntax)
@f.puts convertor.convert(str)
return
rescue NameError, RuntimeError
@f.puts %Q|<pre class="prettyprint">#{text(str)}</pre>|
return
end
end
preformatted(text(str))
end
def preformatted(str)
@f.print "<pre>"
@f.print str
@f.puts "</pre>"
end
def paragraph(lines)
@f.puts "<p>#{lines.join("\n")}</p>"
end
def block_plugin(str)
@f.puts %Q(<div class="plugin">{{#{escape_html(str)}}}</div>)
end
#
# Functions
#
def hyperlink(uri, title)
%Q(<a href="#{escape_html_param(uri)}">#{title}</a>)
end
def wiki_name(name)
hyperlink(name, text(name))
end
def image_hyperlink(uri, alt = nil)
alt ||= uri.split(/\//).last
alt = escape_html(alt)
%Q(<img src="#{escape_html_param(uri)}" alt="#{alt}"#{@suffix})
end
def strong(item)
"<strong>#{item}</strong>"
end
def em(item)
"<em>#{item}</em>"
end
def del(item)
"<del>#{item}</del>"
end
def tt(item)
"<tt>#{item}</tt>"
end
def text(str)
escape_html(str)
end
def inline_plugin(src)
%Q(<span class="plugin">{{#{escape_html(src)}}}</span>)
end
#
# Utilities
#
def escape_html_param(str)
escape_quote(escape_html(str))
end
def escape_html(text)
text.gsub(/&/, "&").gsub(/</, "<").gsub(/>/, ">")
end
def unescape_html(text)
text.gsub(/>/, ">").gsub(/</, "<").gsub(/&/, "&")
end
def escape_quote(text)
text.gsub(/"/, """)
end
end
class LineInput
def initialize(f)
@input = f
@buf = []
@lineno = 0
@eof_p = false
end
def inspect
"\#<#{self.class} file=#{@input.inspect} line=#{lineno()}>"
end
def eof?
@eof_p
end
def lineno
@lineno
end
def gets
unless @buf.empty?
@lineno += 1
return @buf.pop
end
return nil if @eof_p # to avoid ARGF blocking.
line = @input.gets
line = line.sub(/\r\n/, "\n") if line
@eof_p = line.nil?
@lineno += 1
line
end
def ungets(line)
return unless line
@lineno -= 1
@buf.push line
line
end
def peek
line = gets()
ungets line if line
line
end
def next?
peek() ? true : false
end
def skip_blank_lines
n = 0
while line = gets()
unless line.strip.empty?
ungets line
return n
end
n += 1
end
n
end
def gets_if(re)
line = gets()
if not line or not (re =~ line)
ungets line
return nil
end
line
end
def gets_unless(re)
line = gets()
if not line or re =~ line
ungets line
return nil
end
line
end
def each
while line = gets()
yield line
end
end
def while_match(re)
while line = gets()
unless re =~ line
ungets line
return
end
yield line
end
nil
end
def getlines_while(re)
buf = []
while_match(re) do |line|
buf.push line
end
buf
end
alias span getlines_while # from Haskell
def until_match(re)
while line = gets()
if re =~ line
ungets line
return
end
yield line
end
nil
end
def getlines_until(re)
buf = []
until_match(re) do |line|
buf.push line
end
buf
end
alias break getlines_until # from Haskell
def until_terminator(re)
while line = gets()
return if re =~ line # discard terminal line
yield line
end
nil
end
def getblock(term_re)
buf = []
until_terminator(term_re) do |line|
buf.push line
end
buf
end
end
end
if __FILE__ == $0
puts HikiDoc.to_html(ARGF.read(nil))
end