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
SUPERSCRIPTx =
/\\\^\(([^()]+)\)/
SUPERSCRIPT =
->(m){"<sup>#{m[1]}</sup>"}
SUBSCRIPTx =
/\\\(([^()]+)\)/
SUBSCRIPT =
->(m){"<sub>#{m[1]}</sub>"}
ENTITYx =
/\\([<>*"~`_&;:\\])/
ENTITY =
->(m){"&##{m[1].ord};"}
EMPTY =

Empty

/^$/
LIST =

List

/^(?<spaces> {0,3})(?<bullet>[*]|(\d+\.)|(- \[( |x)\])) (?<text>\S.*)$/
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

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

Embed text

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

Footnotes

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

Attributes

/^\{:( [^\{\}]+)\}/
SCRIPT =

Script

/^<script/
HTML_MARKUP =

Html

/^ {0,3}<.*>$/
FIELD =

Forms

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

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=nil
  @metadata,@attributes = {},[]
end

Class Method Details

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



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

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



77
78
79
80
81
# File 'lib/markita/markdown.rb', line 77

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



415
416
417
418
419
420
# File 'lib/markita/markdown.rb', line 415

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

#blockqs(md = nil) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/markita/markdown.rb', line 218

def blockqs(md=nil)
  md ||= BLOCKQS.match(@line) or return false
  level = md[1].length
  @html << "<blockquote#{@attributes.shift}>\n"
  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



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

def codes
  md = CODES.match(@line) or return false
  lang = Rouge::Lexer.find md[1]
  klass = lang ? ' class="highlight"' : nil
  @html << "<pre#{klass}#{@attributes.shift}><code>\n"
  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



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/markita/markdown.rb', line 36

def default
  # Defaults to paragraph
  # Let html take the original @html object and set @html to ''
  html,@html = @html,''
  html << "<p#{@attributes.shift}>\n"
  loop do
    html << inline(@line)
    break if (@line=@file.gets).nil? || PARSERS.detect{method(_1).call}
  end
  html << "</p>\n"
  html << @html
  # Give back the original object to @html
  @html = html
end

#definitionsObject



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

def definitions
  md = DEFINITIONS.match(@line) or return false
  @html << "<dl#{@attributes.shift}>\n"
  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



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/markita/markdown.rb', line 373

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}#{@attributes.shift}>"
      @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



143
144
145
146
147
# File 'lib/markita/markdown.rb', line 143

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

#filepath(filepath) ⇒ Object



56
57
58
59
# File 'lib/markita/markdown.rb', line 56

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



401
402
403
404
405
406
407
408
409
410
# File 'lib/markita/markdown.rb', line 401

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



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

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}#{@attributes.shift}>\n)
  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



204
205
206
207
208
209
210
211
212
213
# File 'lib/markita/markdown.rb', line 204

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}#{@attributes.shift}>#{inline(header)}</h#{i}>\n"
  @html << "</a>\n"
  @line = @file.gets
  true
end

#hrsObject



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

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#{@attributes.shift}>\n"
  end
  true
end

#html_markupObject



439
440
441
442
443
444
# File 'lib/markita/markdown.rb', line 439

def html_markup
  HTML_MARKUP.match(@line) or return false
  @html << @line
  @line = @file.gets
  true
end

#imagesObject



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/markita/markdown.rb', line 346

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}"#{@attributes.shift}>\n)
  @html << %(</a>\n) if href
  @line = @file.gets
  true
end

#init(fh) ⇒ Object



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

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

#inline(entry) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/markita/markdown.rb', line 121

def inline(entry)
  entry = Markdown.tag(entry, ENTITYx, ENTITY)
  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)
        entry = Markdown.tag(entry, SUPERSCRIPTx, SUPERSCRIPT)
        Markdown.tag(entry, SUBSCRIPTx, SUBSCRIPT)
      end
    end
  end
  string.sub(/ ?[ \\]$/,'<br>')
end

#list(md = nil) ⇒ Object



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

def list(md=nil)
  md ||= LIST.match(@line) or return false
  level = md[:spaces].length
  list = md[:bullet][0]=~/\d/ ? 'ol' : 'ul'
  @html << "<#{list}#{@attributes.shift}>\n"
  loop do
    style = case md[:bullet][3]
            when ' '
              %q( style="list-style-type: '&#9744; '")
            when 'x'
              %q( style="list-style-type: '&#9745; '")
            else
              ''
            end
    @html << "  <li#{style}>#{inline(md[:text])}</li>\n"
    if (md=(@line=@file.gets)&.match LIST) && level<md[:spaces].length
      list(md)
      md = @line&.match(LIST)
    end
    break unless md &&
                 (level == md[:spaces].length) &&
                 (list == (md[:bullet][0]=~/\d/ ? 'ol' : 'ul'))
  end
  @html << "</#{list}>\n"
  true
end

#markdown(string) ⇒ Object



51
52
53
54
# File 'lib/markita/markdown.rb', line 51

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

#metadataObject



266
267
268
269
270
271
272
273
# File 'lib/markita/markdown.rb', line 266

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

#parse(fh) ⇒ Object



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

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

#preformsObject



252
253
254
255
256
257
258
259
260
261
262
# File 'lib/markita/markdown.rb', line 252

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

#scriptObject



425
426
427
428
429
430
431
432
433
434
# File 'lib/markita/markdown.rb', line 425

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



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/markita/markdown.rb', line 327

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



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

def tables
  TABLES.match? @line or return false
  @html << "<table#{@attributes.shift}>\n"
  @html << "<thead#{@attributes.shift}><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