Class: Newstile::Converter::Newstile

Inherits:
Base
  • Object
show all
Includes:
Utils::HTML
Defined in:
lib/newstile/converter/newstile.rb

Overview

Converts a Newstile::Document to the newstile format.

Constant Summary collapse

ESCAPED_CHAR_RE =
/(\$\$|[\\*_`\[\]\{"'])|^[ ]{0,3}(:)/
HTML_TAGS_WITH_BODY =
['div', 'script', 'iframe', 'textarea']
TYPOGRAPHIC_SYMS =
{
  :mdash => '---', :ndash => '--', :qdash_space => '-. ', :qdash => '-.', :hellip => '...',
  :laquo_space => '<< ', :raquo_space => ' >>',
  :laquo => '<<', :raquo => '>>'
}

Constants included from Utils::HTML

Utils::HTML::ESCAPE_ALL_RE, Utils::HTML::ESCAPE_ATTRIBUTE_RE, Utils::HTML::ESCAPE_MAP, Utils::HTML::ESCAPE_RE_FROM_TYPE, Utils::HTML::ESCAPE_TEXT_RE

Instance Method Summary collapse

Methods included from Utils::HTML

#entity_to_str, #escape_html, #html_attributes

Methods inherited from Base

apply_template, convert, #generate_id, get_template

Constructor Details

#initialize(doc) ⇒ Newstile

Returns a new instance of Newstile.



36
37
38
39
40
41
42
# File 'lib/newstile/converter/newstile.rb', line 36

def initialize(doc)
  super
  @linkrefs = []
  @footnotes = []
  @abbrevs = []
  @stack = []
end

Instance Method Details

#convert(el, opts = {:indent => 0}) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/newstile/converter/newstile.rb', line 44

def convert(el, opts = {:indent => 0})
  res = send("convert_#{el.type}", el, opts)
  if el.type != :html_element && el.type != :li && el.type != :dd && (ial = ial_for_element(el))
    res << ial
    res << "\n\n" if el.options[:category] == :block
  elsif [:ul, :dl, :ol, :codeblock].include?(el.type) && opts[:next] &&
      ([el.type, :codeblock].include?(opts[:next].type) ||
       (opts[:next].type == :blank && opts[:nnext] && [el.type, :codeblock].include?(opts[:nnext].type)))
    res << "^\n\n"
  elsif el.options[:category] == :block && ![:li, :dd, :dt, :td, :th, :tr, :thead, :tbody, :tfoot, :blank].include?(el.type) &&
      (el.type != :p || !el.options[:transparent])
    res << "\n"
  end
  res
end

#convert_a(el, opts) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/newstile/converter/newstile.rb', line 281

def convert_a(el, opts)
  if el.attr['href'].empty?
    "[#{inner(el, opts)}]()"
  elsif el.attr['href'] =~ /^(?:http|ftp)/ || el.attr['href'].count("()") > 0
    index = if link_el = @linkrefs.find {|c| c.attr['href'] == el.attr['href']}
              @linkrefs.index(link_el) + 1
            else
              @linkrefs << el
              @linkrefs.size
            end
    "[#{inner(el, opts)}][#{index}]"
  else
    title = el.attr['title'].to_s.empty? ? '' : ' "' + el.attr['title'].gsub(/"/, "&quot;") + '"'
    "[#{inner(el, opts)}](#{el.attr['href']}#{title})"
  end
end

#convert_abbreviation(el, opts) ⇒ Object



363
364
365
# File 'lib/newstile/converter/newstile.rb', line 363

def convert_abbreviation(el, opts)
  el.value
end

#convert_blank(el, opts) ⇒ Object



76
77
78
# File 'lib/newstile/converter/newstile.rb', line 76

def convert_blank(el, opts)
  ""
end

#convert_blockquote(el, opts) ⇒ Object



106
107
108
109
# File 'lib/newstile/converter/newstile.rb', line 106

def convert_blockquote(el, opts)
  opts[:indent] += 2
  inner(el, opts).chomp.split(/\n/).map {|l| "> #{l}"}.join("\n") << "\n"
end

#convert_br(el, opts) ⇒ Object



277
278
279
# File 'lib/newstile/converter/newstile.rb', line 277

def convert_br(el, opts)
  "  \n"
end

#convert_codeblock(el, opts) ⇒ Object



102
103
104
# File 'lib/newstile/converter/newstile.rb', line 102

def convert_codeblock(el, opts)
  el.value.split(/\n/).map {|l| l.empty? ? "    " : "    #{l}"}.join("\n") + "\n"
end

#convert_codespan(el, opts) ⇒ Object



312
313
314
315
# File 'lib/newstile/converter/newstile.rb', line 312

def convert_codespan(el, opts)
  delim = (el.value.scan(/`+/).max || '') + '`'
  "#{delim}#{' ' if delim.size > 1}#{el.value}#{' ' if delim.size > 1}#{delim}"
end

#convert_comment(el, opts) ⇒ Object



269
270
271
272
273
274
275
# File 'lib/newstile/converter/newstile.rb', line 269

def convert_comment(el, opts)
  if el.options[:category] == :block
    "{::comment}\n#{el.value}\n{:/}\n"
  else
    "{::comment}#{el.value}{:/}"
  end
end

#convert_dd(el, opts) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/newstile/converter/newstile.rb', line 161

def convert_dd(el, opts)
  sym, width = ": ", (el.children.first.type == :codeblock ? 4 : 2)
  if ial = ial_for_element(el)
    sym += ial + " "
  end

  opts[:indent] += width
  text = inner(el, opts)
  newlines = text.scan(/\n*\Z/).first
  first, *last = text.split(/\n/)
  last = last.map {|l| " "*width + l}.join("\n")
  text = first + (last.empty? ? "" : "\n") + last + newlines
  text.chomp! if text =~ /\n\n\Z/ && opts[:next] && opts[:next].type == :dd
  text += "\n" if text !~ /\n\n\Z/ && opts[:next] && opts[:next].type == :dt
  if el.children.first.type == :p && !el.children.first.options[:transparent]
    "\n#{sym}#{text}"
  elsif el.children.first.type == :codeblock
    "#{sym}\n    #{text}"
  else
    "#{sym}#{text}"
  end
end

#convert_dt(el, opts) ⇒ Object



184
185
186
# File 'lib/newstile/converter/newstile.rb', line 184

def convert_dt(el, opts)
  inner(el, opts) << "\n"
end

#convert_em(el, opts) ⇒ Object



334
335
336
# File 'lib/newstile/converter/newstile.rb', line 334

def convert_em(el, opts)
  "*#{inner(el, opts)}*"
end

#convert_entity(el, opts) ⇒ Object



342
343
344
# File 'lib/newstile/converter/newstile.rb', line 342

def convert_entity(el, opts)
  entity_to_str(el.value, el.options[:original])
end

#convert_footnote(el, opts) ⇒ Object



317
318
319
320
# File 'lib/newstile/converter/newstile.rb', line 317

def convert_footnote(el, opts)
  @footnotes << [el.options[:name], @doc.parse_infos[:footnotes][el.options[:name]]]
  "[^#{el.options[:name]}]"
end

#convert_header(el, opts) ⇒ Object



116
117
118
119
120
121
# File 'lib/newstile/converter/newstile.rb', line 116

def convert_header(el, opts)
  res = ''
  res << "#{'!' * el.options[:level]} #{inner(el, opts)}"
  res << "   {##{el.attr['id']}}" if el.attr['id']
  res << "\n"
end

#convert_hr(el, opts) ⇒ Object



123
124
125
# File 'lib/newstile/converter/newstile.rb', line 123

def convert_hr(el, opts)
  "* * *\n"
end

#convert_html_element(el, opts) ⇒ Object



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
# File 'lib/newstile/converter/newstile.rb', line 190

def convert_html_element(el, opts)
  markdown_attr = el.options[:category] == :block && el.children.any? do |c|
    c.type != :html_element && (c.type != :p || !c.options[:transparent]) && c.options[:category] == :block
  end
  opts[:force_raw_text] = true if %w{script pre code}.include?(el.value)
  opts[:raw_text] = opts[:force_raw_text] || opts[:block_raw_text] || (el.options[:category] != :span && !markdown_attr)
  opts[:block_raw_text] = true if el.options[:category] == :block && opts[:raw_text]
  res = inner(el, opts)
  if el.options[:category] == :span
    "<#{el.value}#{html_attributes(el)}" << (!res.empty? || HTML_TAGS_WITH_BODY.include?(el.value) ? ">#{res}</#{el.value}>" : " />")
  else
    output = ''
    output << "<#{el.value}#{html_attributes(el)}"
    output << " markdown=\"1\"" if markdown_attr
    if !res.empty? && el.options[:parse_type] != :block
      output << ">#{res}</#{el.value}>"
    elsif !res.empty?
      output << ">\n#{res}"  <<  "</#{el.value}>"
    elsif HTML_TAGS_WITH_BODY.include?(el.value)
      output << "></#{el.value}>"
    else
      output << " />"
    end
    output << "\n" if @stack.last.type != :html_element || @stack.last.options[:parse_type] != :raw
    output
  end
end

#convert_img(el, opts) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/newstile/converter/newstile.rb', line 298

def convert_img(el, opts)
  if el.attr['src'].empty?
    "![#{el.attr['alt']}]()"
  else
    title = (el.attr['title'] ? ' "' + el.attr['title'].gsub(/"/, "&quot;") + '"' : '')
    link = if el.attr['src'].count("()") > 0
             "<#{el.attr['src']}>"
           else
             el.attr['src']
           end
    "![#{el.attr['alt']}](#{link}#{title})"
  end
end

#convert_li(el, opts) ⇒ Object



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
# File 'lib/newstile/converter/newstile.rb', line 133

def convert_li(el, opts)
  sym, width = if @stack.last.type == :ul
                 ['* ', el.children.first.type == :codeblock ? 4 : 2]
               else
                 ["#{opts[:index] + 1}.".ljust(4), 4]
               end
  if ial = ial_for_element(el)
    sym += ial + " "
  end

  opts[:indent] += width
  text = inner(el, opts)
  newlines = text.scan(/\n*\Z/).first
  first, *last = text.split(/\n/)
  last = last.map {|l| " "*width + l}.join("\n")
  text = first + (last.empty? ? "" : "\n") + last + newlines
  if el.children.first.type == :p && !el.children.first.options[:transparent]
    res = "#{sym}#{text}"
    res << "^\n" if el.children.size == 1 && @stack.last.children.last == el &&
      (@stack.last.children.any? {|c| c.children.first.type != :p} || @stack.last.children.size == 1)
    res
  elsif el.children.first.type == :codeblock
    "#{sym}\n    #{text}"
  else
    "#{sym}#{text}"
  end
end

#convert_math(el, opts) ⇒ Object



359
360
361
# File 'lib/newstile/converter/newstile.rb', line 359

def convert_math(el, opts)
  (@stack.last.type == :p && opts[:prev].nil? ? "\\" : '') + "$$#{el.value}$$" + (el.options[:category] == :block ? "\n" : '')
end

#convert_p(el, opts) ⇒ Object



92
93
94
95
96
97
98
99
# File 'lib/newstile/converter/newstile.rb', line 92

def convert_p(el, opts)
  w = @doc.options[:line_width] - opts[:indent].to_s.to_i
  first, second, *rest = inner(el, opts).strip.gsub(/(.{1,#{w}})( +|$\n?)/, "\\1\n").split(/\n/)
  first.gsub!(/^(?:(#)|(\d+)\.|([+-]\s))/) { $1 || $3 ? "\\#{$1 || $3}" : "#{$2}\\."}
  first.gsub!(/\|/, '\\|')
  second.gsub!(/^([=-]+\s*?)$/, "\\\1") if second
  [first, second, *rest].compact.join("\n") + "\n"
end

#convert_raw(el, opts) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
# File 'lib/newstile/converter/newstile.rb', line 322

def convert_raw(el, opts)
  attr = (el.options[:type] || []).join(' ')
  attr = " type=\"#{attr}\"" if attr.length > 0
  if @stack.last.type == :html_element
    el.value
  elsif el.options[:category] == :block
    "{::nomarkdown#{attr}}\n#{el.value}\n{:/}\n"
  else
    "{::nomarkdown#{attr}}#{el.value}{:/}"
  end
end

#convert_root(el, opts) ⇒ Object



367
368
369
370
371
372
373
# File 'lib/newstile/converter/newstile.rb', line 367

def convert_root(el, opts)
  res = inner(el, opts)
  res << create_link_defs
  res << create_footnote_defs
  res << create_abbrev_defs
  res
end

#convert_smart_quote(el, opts) ⇒ Object



355
356
357
# File 'lib/newstile/converter/newstile.rb', line 355

def convert_smart_quote(el, opts)
  el.value.to_s =~ /[rl]dquo/ ? "\"" : "'"
end

#convert_strong(el, opts) ⇒ Object



338
339
340
# File 'lib/newstile/converter/newstile.rb', line 338

def convert_strong(el, opts)
  "**#{inner(el, opts)}**"
end

#convert_summary(el, opts) ⇒ Object



111
112
113
114
# File 'lib/newstile/converter/newstile.rb', line 111

def convert_summary(el, opts)
  opts[:indent] += 2
  inner(el, opts).chomp.split(/\n/).map {|l| "//. #{l}"}.join("\n") << "\n"
end

#convert_table(el, opts) ⇒ Object



228
229
230
231
# File 'lib/newstile/converter/newstile.rb', line 228

def convert_table(el, opts)
  opts[:alignment] = el.options[:alignment]
  inner(el, opts)
end

#convert_tbody(el, opts) ⇒ Object



249
250
251
252
253
254
# File 'lib/newstile/converter/newstile.rb', line 249

def convert_tbody(el, opts)
  res = ''
  res << inner(el, opts)
  res << '|' << '-'*10 << "\n" if opts[:next] && opts[:next].type == :tbody
  res
end

#convert_td(el, opts) ⇒ Object Also known as: convert_th



264
265
266
# File 'lib/newstile/converter/newstile.rb', line 264

def convert_td(el, opts)
  inner(el, opts).gsub(/\|/, '\\|')
end

#convert_text(el, opts) ⇒ Object



82
83
84
85
86
87
88
89
90
# File 'lib/newstile/converter/newstile.rb', line 82

def convert_text(el, opts)
  if opts[:raw_text]
    el.value
  else
    el.value.gsub(/\A\n/) do
      opts[:prev] && opts[:prev].type == :br ? '' : "\n"
    end.gsub(/\s+/, ' ').gsub(ESCAPED_CHAR_RE) { "\\#{$1 || $2}" }
  end
end

#convert_tfoot(el, opts) ⇒ Object



256
257
258
# File 'lib/newstile/converter/newstile.rb', line 256

def convert_tfoot(el, opts)
  "|" + "="*10 + "\n#{inner(el, opts)}"
end

#convert_thead(el, opts) ⇒ Object



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/newstile/converter/newstile.rb', line 233

def convert_thead(el, opts)
  rows = inner(el, opts)
  if opts[:alignment].all? {|a| a == :default}
    "#{rows}|" + "-"*10 + "\n"
  else
    "#{rows}| " + opts[:alignment].map do |a|
      case a
      when :left then ":-"
      when :right then "-:"
      when :center then ":-:"
      when :default then "-"
      end
    end.join(' ') + "\n"
  end
end

#convert_tr(el, opts) ⇒ Object



260
261
262
# File 'lib/newstile/converter/newstile.rb', line 260

def convert_tr(el, opts)
  "| " + el.children.map {|c| convert(c, opts)}.join(" | ") + " |\n"
end

#convert_typographic_sym(el, opts) ⇒ Object



351
352
353
# File 'lib/newstile/converter/newstile.rb', line 351

def convert_typographic_sym(el, opts)
  TYPOGRAPHIC_SYMS[el.value]
end

#convert_ul(el, opts) ⇒ Object Also known as: convert_ol, convert_dl



127
128
129
# File 'lib/newstile/converter/newstile.rb', line 127

def convert_ul(el, opts)
  inner(el, opts).sub(/\n+\Z/, "\n")
end

#convert_xml_comment(el, opts) ⇒ Object Also known as: convert_xml_pi, convert_html_doctype



218
219
220
221
222
223
224
# File 'lib/newstile/converter/newstile.rb', line 218

def convert_xml_comment(el, opts)
  if el.options[:category] == :block && (@stack.last.type != :html_element || @stack.last.options[:parse_type] != :raw)
    el.value + "\n"
  else
    el.value
  end
end

#create_abbrev_defsObject



394
395
396
397
398
399
400
401
# File 'lib/newstile/converter/newstile.rb', line 394

def create_abbrev_defs
  return '' unless @doc.parse_infos[:abbrev_defs]
  res = ''
  @doc.parse_infos[:abbrev_defs].each do |name, text|
    res << "*[#{name}]: #{text}\n"
  end
  res
end

#create_footnote_defsObject



385
386
387
388
389
390
391
392
# File 'lib/newstile/converter/newstile.rb', line 385

def create_footnote_defs
  res = ''
  @footnotes.each do |name, data|
    res << "[^#{name}]:\n"
    res << inner(data[:content]).chomp.split(/\n/).map {|l| "    #{l}"}.join("\n") + "\n\n"
  end
  res
end


375
376
377
378
379
380
381
382
383
# File 'lib/newstile/converter/newstile.rb', line 375

def create_link_defs
  res = ''
  res << "\n\n" if @linkrefs.size > 0
  @linkrefs.each_with_index do |el, i|
    title = el.attr['title']
    res << "[#{i+1}]: #{el.attr['href']} #{title ? '"' + title.gsub(/"/, "&quot;") + '"' : ''}\n"
  end
  res
end

#ial_for_element(el) ⇒ Object

Return the IAL containing the attributes of the element el.



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/newstile/converter/newstile.rb', line 404

def ial_for_element(el)
  res = el.attr.map do |k,v|
    next if [:img, :a].include?(el.type) && ['href', 'src', 'alt', 'title'].include?(k)
    next if el.type == :header && k == 'id'
    if v.nil?
      ''
    elsif k == 'class'
      " " + v.split(/\s+/).map {|w| ".#{w}"}.join(" ")
    elsif k == 'id'
      " ##{v}"
    else
      " #{k}=\"#{v.to_s}\""
    end
  end.compact.join('')
  res = "toc" + (res.strip.empty? ? '' : " #{res}") if (el.type == :ul || el.type == :ol) &&
    (el.options[:ial][:refs].include?('toc') rescue nil)
  res.strip.empty? ? nil : "{:#{res}}"
end

#inner(el, opts = {:indent => 0}) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/newstile/converter/newstile.rb', line 60

def inner(el, opts = {:indent => 0})
  @stack.push(el)
  result = ''
  el.children.each_with_index do |inner_el, index|
    options = opts.dup
    options[:index] = index
    options[:prev] = (index == 0 ? nil : el.children[index-1])
    options[:pprev] = (index <= 1 ? nil : el.children[index-2])
    options[:next] = (index == el.children.length - 1 ? nil : el.children[index+1])
    options[:nnext] = (index >= el.children.length - 2 ? nil : el.children[index+2])
    result << convert(inner_el, options)
  end
  @stack.pop
  result
end