Class: Markita::Markdown

Inherits:
Object
  • Object
show all
Defined in:
lib/markita/markdown.rb

Constant Summary collapse

ROUGE =
Rouge::Formatters::HTML.new
PARSERS =
[]
Ux =
/_([^_]+)_/
U =
->(m){"<u>#{m[1]}</u>"}
Sx =
/~([^~]+)~/
S =
->(m){"<s>#{m[1]}</s>"}
Ix =
/"([^"]+)"/
I =
->(m){"<i>#{m[1]}</i>"}
Bx =
/\*([^*]+)\*/
B =
->(m){"<b>#{m[1]}</b>"}
CODEx =
/`([^`]+)`/
CODE =
->(m){"<code>#{m[1].gsub('<','&lt;')}</code>"}
Ax =
/\[([^\[\]]+)\]\(([^()]+)\)/
URLx =
%r{(https?://[\w./&+?%-]+)}
URL =
->(m){%(<a href="#{m[1]}">#{m[1]}</a>)}
EMOJIx =
/:(\w+):/
EMOJI =
->(m){(_=EMOJIS[m[1]])? "&#x#{_};" : m[0]}
FOOTNOTEx =
/\[\^(\d+)\](:)?/
FOOTNOTE =
lambda do |m|
  if m[2]
    %(<a id="fn:#{m[1]}" href="#fnref:#{m[1]}">#{m[1]}:</a>)
  else
    %(<a id="fnref:#{m[1]}" href="#fn:#{m[1]}"><sup>#{m[1]}</sup></a>)
  end
end
EMPTY =

Empty

/^$/
ORDERED =

Ordered list

/^( {0,3})\d+\. (\S.*)$/
PARAGRAPHS =

Paragraph

/^[\[(*`'"~_]?:?\w/
UNORDERED =

Unordered list

/^( {0,3})[*] (\S.*)$/
BALLOTS =

Ballot box

/^- \[(x| )\] (.*)$/
DEFINITIONS =

Definition list

/^[+] (.*)$/
HEADERS =

Headers

/^(\#{1,6}) (.*)$/
BLOCKQS =

Block-quote

/^( {0,3})> (.*)$/
CODES =

Code

/^[`~]{3}\s*(\w+)?$/
SCRIPT =

Script

/^<script/
PREFORMS =

Preform

/^ {4}(.*)$/
METADATAS =

Meta-data

/^(\w+): (.*)$/
HRS =

Horizontal rule or Meta-data

/^---+$/
TABLES =

Table

/^\|.+\|$/
SPLITS =

Splits

/^:?\|:?$/
IMAGES =

Image

/^!\[([^\[\]]+)\]\(([^()]+)\)$/
FIELD =

Forms

'(\w+:)?\[(\*)?(\w+)(=("[^"]+")(,"[^"]+")*)?\]'
FIELDS =
Regexp.new FIELD
FORMS =
Regexp.new "^!( #{FIELD})+"
EMBED_TEXTS =

Embed text

/^!> (#{PAGE_KEY}\.\w+)$/
FOOTNOTES =

Footnotes

/^\[\^\d+\]:/
ATTRIBUTES =

Attributes

/^\{:( .*)\}/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(title) ⇒ Markdown

Returns a new instance of Markdown.



6
7
8
9
10
# File 'lib/markita/markdown.rb', line 6

def initialize(title)
  @title = title
  @line=@html=@file=@opt=nil
  @metadata = {}
end

Class Method Details

.tag(entry, regx, m2string, &block) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/markita/markdown.rb', line 88

def self.tag(entry, regx, m2string, &block)
  if (m=regx.match entry)
    string = ''
    while m
      pre_match = (block ? block.call(m.pre_match) : m.pre_match)
      string << pre_match + m2string[m]
      post_match = m.post_match
      m = regx.match(post_match)
    end
    string << (block ? block.call(post_match) : post_match)
    return string
  end
  block ? block.call(entry) : entry
end

Instance Method Details

#anchor(m) ⇒ Object



67
68
69
70
71
# File 'lib/markita/markdown.rb', line 67

def anchor(m)
  href = ((_=m[2]).match?(/^\d+$/) and @metadata[_] or _)
  text = Markdown.tag(m[1], EMOJIx, EMOJI)
  %(<a href="#{href}">#{text}</a>)
end

#attributesObject



514
515
516
517
518
519
# File 'lib/markita/markdown.rb', line 514

def attributes
  md = ATTRIBUTES.match(@line) or return false
  @opt[:attributes] = md[1]
  @line = md.post_match
  true
end

#ballotsObject



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/markita/markdown.rb', line 185

def ballots
  md = BALLOTS.match(@line) or return false
  @html << "<ul#{@opt[:attributes]}>\n"
  @opt.delete(:attributes)
  while md
    x,t = md[1],md[2]
    li = x=='x' ?
      %q(<li style="list-style-type: '&#9745; '">) :
      %q(<li style="list-style-type: '&#9744; '">)
    @html << "  #{li}#{inline(t)}</li>\n"
    md = (@line=@file.gets)&.match BALLOTS
  end
  @html << "</ul>\n"
  true
end

#blockqs(md = nil) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/markita/markdown.rb', line 242

def blockqs(md=nil)
  md ||= BLOCKQS.match(@line) or return false
  level = md[1].length
  @html << "<blockquote#{@opt[:attributes]}>\n"
  @opt.delete(:attributes)
  while md && level==md[1].length
    @html << inline(md[2])
    @html << "\n"
    next unless (md=(@line=@file.gets)&.match BLOCKQS) && level<md[1].length
    blockqs(md)
    md = @line&.match(BLOCKQS)
  end
  @html << "</blockquote>\n"
  true
end

#codesObject



261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/markita/markdown.rb', line 261

def codes
  md = CODES.match(@line) or return false
  lang = Rouge::Lexer.find md[1]
  klass = lang ? ' class="highlight"' : nil
  @html << "<pre#{klass}#{@opt[:attributes]}><code>\n"
  @opt.delete(:attributes)
  code = ''
  code << @line while (@line=@file.gets) && !CODES.match?(@line)
  @html << (lang ? ROUGE.format(lang.new.lex(code)) : code)
  @html << "</code></pre>\n"
  @line = @file.gets if @line # then it's code close and thus need next @line.
  true
end

#defaultObject



25
26
27
28
# File 'lib/markita/markdown.rb', line 25

def default
  @html << @line
  @line = @file.gets
end

#definitionsObject



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/markita/markdown.rb', line 204

def definitions
  md = DEFINITIONS.match(@line) or return false
  @html << "<dl#{@opt[:attributes]}>\n"
  @opt.delete(:attributes)
  while md
    case md[1]
    when /(.*): (.*)$/
      @html << "<dt>#{inline $1.strip}</dt>\n"
      @html << "<dd>#{inline $2.strip}</dd>\n"
    when /(.*):$/
      @html << "<dt>#{inline $1.strip}</dt>\n"
    else
      @html << "<dd>#{inline md[1].strip}</dd>\n"
    end
    md = (@line=@file.gets)&.match DEFINITIONS
  end
  @html << "</dl>\n"
  true
end

#embed_textsObject



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
# File 'lib/markita/markdown.rb', line 471

def embed_texts
  md = EMBED_TEXTS.match(@line) or return false
  if File.exist?(filename=File.join(ROOT, md[1]))
    extension,lang = filename.split('.').last,nil
    unless extension=='html'
      lang = Rouge::Lexer.find(extension) unless extension=='txt'
      klass = lang ? ' class="highlight"' : nil
      @html << "<pre#{klass}#{@opt[:attributes]}>"
      @opt.delete(:attributes)
      @html << '<code>' if lang
      @html << "\n"
    end
    code = File.read(filename)
    @html << (lang ? ROUGE.format(lang.new.lex(code)) : code)
    unless extension=='html'
      @html << '</code>' if lang
      @html << '</pre>'
      @html << "\n"
    end
  else
    @html << @line
  end
  @line = @file.gets
  true
end

#emptyObject



122
123
124
125
126
# File 'lib/markita/markdown.rb', line 122

def empty
  EMPTY.match?(@line) or return false
  @line = @file.gets
  true
end

#filepath(filepath) ⇒ Object



46
47
48
49
# File 'lib/markita/markdown.rb', line 46

def filepath(filepath)
  File.open(filepath, 'r'){|fh| parse fh}
  @html
end

#finishObject



17
18
19
20
21
22
23
# File 'lib/markita/markdown.rb', line 17

def finish
  if (title=@metadata['Title'])
    @html << %(<script> document.title = "#{title}" </script>\n)
  end
  @html << HTML.footer
  @line = nil
end

#footnotesObject



500
501
502
503
504
505
506
507
508
509
# File 'lib/markita/markdown.rb', line 500

def footnotes
  md = FOOTNOTES.match(@line) or return false
  @html << "<small>\n"
  while md
    @html << inline(@line.chomp)+"<br>\n"
    md = (@line=@file.gets)&.match FOOTNOTES
  end
  @html << "</small>\n"
  true
end

#formsObject



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
# File 'lib/markita/markdown.rb', line 420

def forms
  md = FORMS.match(@line) or return false
  fields,nl,submit = 0,false,nil
  action = (_=/\(([^()]*)\)!?$/.match(@line))? %( action="#{_[1]}") : nil
  method = @line.match?(/!$/) ? ' method="post"' : nil
  @html << %(<form#{action}#{method}#{@opt[:attributes]}>\n)
  @opt.delete(:attributes)
  while md
    @html << "  <br>\n" if nl
    @line.scan(FIELDS).each do |field, pwd, name, value|
      field &&= field[0...-1]
      value &&= value[2...-1]
      if field
        type = pwd ? 'password' : 'text'
        if value
          if (values = value.split('","')).length > 1
            @html << %(#{field}:<select name="#{name}">\n)
            values.each do |value|
              fields += 1
              @html << %(  <option value="#{value}">#{value}</option>\n)
            end
            @html << "</select>\n"
          else
            fields += 1
            @html << %(  #{field}:<input type="#{type}" name="#{name}")
            @html << %( value="#{value}">\n)
          end
        else
          fields += 1
          @html << %(  #{field}:<input type="#{type}" name="#{name}">\n)
        end
      elsif name=='submit'
        submit = value
      else
        @html << %(  <input type="hidden" name="#{name}" value="#{value}">\n)
      end
    end
    md=(@line=@file.gets)&.match(FORMS) and nl=true
  end
  if submit || fields!=1
    submit ||= 'Submit'
    @html << "  <br>\n" if nl
    @html << %(  <input type="submit" value="#{submit}">\n)
  end
  @html << %(</form>\n)
  true
end

#headersObject



227
228
229
230
231
232
233
234
235
236
237
# File 'lib/markita/markdown.rb', line 227

def headers
  md = HEADERS.match(@line) or return false
  i,header = md[1].length,md[2]
  id = header.gsub(/\([^()]*\)/,'').scan(/\w+/).join('+')
  @html << %(<a id="#{id}">\n)
  @html << "  <h#{i}#{@opt[:attributes]}>#{inline(header)}</h#{i}>\n"
  @html << "</a>\n"
  @opt.delete(:attributes)
  @line = @file.gets
  true
end

#hrsObject



319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/markita/markdown.rb', line 319

def hrs
  HRS.match? @line or return false
  @line = @file.gets
  if 
    # Optional closing HRS
    @line = @file.gets if @line&.match? HRS
  else
    # Display HR
    @html << "<hr#{@opt[:attributes]}>\n"
    @opt.delete(:attributes)
  end
  true
end

#imagesObject



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/markita/markdown.rb', line 390

def images
  md = IMAGES.match(@line) or return false
  alt,src,href=md[1],*md[2].strip.split(/\s+/,2)
  style = ' '
  case alt
  when /^:.*:$/
    style =
    %( style="display: block; margin-left: auto; margin-right: auto;" )
  when /:$/
    style = %( style="float:left;" )
  when /^:/
    style = %( style="float:right;" )
  end
  if /(\d+)x(\d+)/.match alt
    style << %(width="#{$1}" height="#{$2}" )
  end
  @html << %(<a href="#{href}">\n) if href
  @html <<
    %(<img src="#{src}"#{style}alt="#{alt.strip}"#{@opt[:attributes]}>\n)
  @html << %(</a>\n) if href
  @opt.delete(:attributes)
  @line = @file.gets
  true
end

#init(fh) ⇒ Object



30
31
32
# File 'lib/markita/markdown.rb', line 30

def init(fh)
  @file,@html,@opt = Preprocess.new(fh),'',{}
end

#inline(entry) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/markita/markdown.rb', line 103

def inline(entry)
  string = Markdown.tag(entry, CODEx, CODE) do |entry|
    Markdown.tag(entry, Ax, method(:anchor)) do |entry|
      Markdown.tag(entry, URLx, URL) do |entry|
        entry = Markdown.tag(entry, EMOJIx, EMOJI)
        entry = Markdown.tag(entry, Bx, B)
        entry = Markdown.tag(entry, Ix, I)
        entry = Markdown.tag(entry, Sx, S)
        entry = Markdown.tag(entry, Ux, U)
        Markdown.tag(entry, FOOTNOTEx, FOOTNOTE)
      end
    end
  end
  string.sub(/  $/,'<br>')
end

#markdown(string) ⇒ Object



41
42
43
44
# File 'lib/markita/markdown.rb', line 41

def markdown(string)
  parse StringIO.new string
  @html
end

#metadataObject



307
308
309
310
311
312
313
314
# File 'lib/markita/markdown.rb', line 307

def 
  md = METADATAS.match(@line) or return false
  while md
    @metadata[md[1]] = md[2]
    md = (@line=@file.gets)&.match METADATAS
  end
  true
end

#ordered(md = nil) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/markita/markdown.rb', line 131

def ordered(md=nil)
  md ||= ORDERED.match(@line) or return false
  level = md[1].length
  @html << "<ol#{@opt[:attributes]}>\n"
  @opt.delete(:attributes)
  while md && level==md[1].length
    @html << "  <li>#{inline(md[2])}</li>\n"
    next unless (md=(@line=@file.gets)&.match ORDERED) && level<md[1].length
    ordered(md)
    md = @line&.match(ORDERED)
  end
  @html << "</ol>\n"
  true
end

#paragraphsObject



149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/markita/markdown.rb', line 149

def paragraphs
  md = PARAGRAPHS.match(@line) or return false
  @html << "<p#{@opt[:attributes]}>\n"
  @opt.delete(:attributes)
  while md
    @html << inline(@line)
    while (@line=@file.gets)&.start_with?('<')
      @html << @line # Exceptional HTML injection into the paragraph
    end
    md = @line&.match PARAGRAPHS
  end
  @html << "</p>\n"
  true
end

#parse(fh) ⇒ Object



34
35
36
37
38
39
# File 'lib/markita/markdown.rb', line 34

def parse(fh)
  init(fh)
  start
  PARSERS.detect{method(_1).call} or default while @line
  finish
end

#preformsObject



292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/markita/markdown.rb', line 292

def preforms
  md = PREFORMS.match(@line) or return false
  @html << "<pre#{@opt[:attributes]}>\n"
  @opt.delete(:attributes)
  while md
    @html << md[1]
    @html << "\n"
    md = (@line=@file.gets)&.match PREFORMS
  end
  @html << "</pre>\n"
  true
end

#scriptObject



278
279
280
281
282
283
284
285
286
287
# File 'lib/markita/markdown.rb', line 278

def script
  SCRIPT.match(@line) or return false
  @html << @line
  while (@line=@file.gets)
    @html << @line
    break if %r{^</script>}.match?(@line)
  end
  @line = @file.gets if @line
  true
end

#splitsObject



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/markita/markdown.rb', line 370

def splits
  SPLITS.match? @line or return false
  case @line.chomp
  when '|:'
    @html << %(<table><tr><td#{@opt[:attributes]}>\n)
  when '|'
    @html << %(</td><td#{@opt[:attributes]}>\n)
  when ':|:'
    @html << %(</td></tr><tr><td#{@opt[:attributes]}>\n)
  when ':|'
    @html << %(</td></tr></table>\n)
  end
  @opt.delete(:attributes)
  @line = @file.gets
  true
end

#startObject



12
13
14
15
# File 'lib/markita/markdown.rb', line 12

def start
  @html << HTML.header(@title)
  @line = HTML.navigation
end

#tablesObject



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
# File 'lib/markita/markdown.rb', line 336

def tables
  TABLES.match? @line or return false
  @html << "<table#{@opt[:attributes]}>\n"
  @opt.delete(:attributes)
  @html << '<thead><tr><th>'
  @html << @line[1...-1].split('|').map{inline(_1.strip)}.join('</th><th>')
  @html << "</th></tr></thead>\n"
  align = []
  while (@line=@file.gets)&.match? TABLES
    @html << '<tr>'
    @line[1...-1].split('|').each_with_index do |cell, i|
      case cell
      when /^\s*:-+:\s*$/
        align[i] = ' align="center"'
        @html << '<td><hr></td>'
      when /^\s*-+:\s*$/
        align[i] = ' align="right"'
        @html << '<td><hr></td>'
      when /^\s*:-+\s*$/
        align[i] = ' align="left"'
        @html << '<td><hr></td>'
      else
        @html << "<td#{align[i]}>#{inline(cell.strip)}</td>"
      end
    end
    @html << "</tr>\n"
  end
  @html << "</table>\n"
  true
end

#unordered(md = nil) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/markita/markdown.rb', line 167

def unordered(md=nil)
  md ||= UNORDERED.match(@line) or return false
  level = md[1].length
  @html << "<ul#{@opt[:attributes]}>\n"
  @opt.delete(:attributes)
  while md && level==md[1].length
    @html << "  <li>#{inline(md[2])}</li>\n"
    next unless (md=(@line=@file.gets)&.match UNORDERED) && level<md[1].length
    unordered(md)
    md = @line&.match(UNORDERED)
  end
  @html << "</ul>\n"
  true
end