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

Class Method Details

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



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

def Markdown.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
  return (block ? block.call(entry) : entry)
end

Instance Method Details

#anchor(m) ⇒ Object



69
70
71
72
73
# File 'lib/markita/markdown.rb', line 69

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

#attributesObject



510
511
512
513
514
515
# File 'lib/markita/markdown.rb', line 510

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

#ballotsObject



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/markita/markdown.rb', line 193

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



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/markita/markdown.rb', line 250

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 and level==md[1].length
    @html << inline(md[2])
    @html << "\n"
    if md = (@line=@file.gets)&.match(BLOCKQS)
      if level < md[1].length
        blockqs(md)
        md = @line&.match(BLOCKQS)
      end
    end
  end
  @html << "</blockquote>\n"
  true
end

#codesObject



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/markita/markdown.rb', line 272

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 = ''
  while @line=@file.gets and not CODES.match(@line)
    code << @line
  end
  @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



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/markita/markdown.rb', line 212

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



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

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



124
125
126
127
128
# File 'lib/markita/markdown.rb', line 124

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

#filepath(filepath) ⇒ Object



48
49
50
51
# File 'lib/markita/markdown.rb', line 48

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 = ['Title']
    @html << %Q(<script> document.title = "#{title}" </script>\n)
  end
  @html << HTML.footer
  @line = nil
end

#footnotesObject



496
497
498
499
500
501
502
503
504
505
# File 'lib/markita/markdown.rb', line 496

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



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

def forms
  md = FORMS.match(@line) or return false
  fields,nl,submit = 0,false,nil
  action = (_=/\(([^\(\)]*)\)!?$/.match(@line))? %Q( action="#{_[1]}") : nil
  method = @line.match?(/!$/) ? ' method="post"' : nil
  @html << %Q(<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 << %Q(#{field}:<select name="#{name}">\n)
            values.each do |value|
              fields += 1
              @html << %Q(  <option value="#{value}">#{value}</option>\n)
            end
            @html << "</select>\n"
          else
            fields += 1
            @html << %Q{  #{field}:<input type="#{type}" name="#{name}" value="#{value}">\n}
          end
        else
          fields += 1
          @html << %Q{  #{field}:<input type="#{type}" name="#{name}">\n}
        end
      elsif name=='submit'
        submit = value
      else
        @html << %Q{  <input type="hidden" name="#{name}" value="#{value}">\n}
      end
    end
    md=(@line=@file.gets)&.match(FORMS) and nl=true
  end
  if submit or not fields==1
    submit ||= 'Submit'
    @html << "  <br>\n" if nl
    @html << %Q(  <input type="submit" value="#{submit}">\n)
  end
  @html << %Q(</form>\n)
  true
end

#headersObject



235
236
237
238
239
240
241
242
243
244
245
# File 'lib/markita/markdown.rb', line 235

def headers
  md = HEADERS.match(@line) or return false
  i,header = md[1].length,md[2]
  id = header.gsub(/\([^\(\)]*\)/,'').scan(/\w+/).join('+')
  @html << %Q(<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



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

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



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

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 = %Q( style="display: block; margin-left: auto; margin-right: auto;" )
  when /:$/
    style = %Q( style="float:left;" )
  when /^:/
    style = %Q( style="float:right;" )
  end
  if /(\d+)x(\d+)/.match alt
    style << %Q(width="#{$1}" height="#{$2}" )
  end
  @html << %Q(<a href="#{href}">\n) if href
  @html << %Q(<img src="#{src}"#{style}alt="#{alt.strip}"#{@opt[:attributes]}>\n)
  @html << %Q(</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



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

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)
        entry = Markdown.tag(entry, FOOTNOTEx, FOOTNOTE)
      end
    end
  end
  string.sub(/  $/,'<br>')
end

#markdown(string) ⇒ Object



43
44
45
46
# File 'lib/markita/markdown.rb', line 43

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

#metadataObject



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

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

#ordered(md = nil) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/markita/markdown.rb', line 133

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 and level==md[1].length
    @html << "  <li>#{inline(md[2])}</li>\n"
    if md = (@line=@file.gets)&.match(ORDERED)
      if level < md[1].length
        ordered(md)
        md = @line&.match(ORDERED)
      end
    end
  end
  @html << "</ol>\n"
  true
end

#paragraphsObject



154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/markita/markdown.rb', line 154

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

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

#preformsObject



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

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

#splitsObject



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

def splits
  SPLITS.match? @line or return false
  case @line.chomp
  when '|:'
    @html << %Q(<table><tr><td#{@opt[:attributes]}>\n)
  when '|'
    @html << %Q(</td><td#{@opt[:attributes]}>\n)
  when ':|:'
    @html << %Q(</td></tr><tr><td#{@opt[:attributes]}>\n)
  when ':|'
    @html << %Q(</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



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

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



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/markita/markdown.rb', line 172

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 and level==md[1].length
    @html << "  <li>#{inline(md[2])}</li>\n"
    if md = (@line=@file.gets)&.match(UNORDERED)
      if level < md[1].length
        unordered(md)
        md = @line&.match(UNORDERED)
      end
    end
  end
  @html << "</ul>\n"
  true
end