) : ''
# NOTE kindlegen seems to mangle the element, so we wrap its content in a div
lines = [%(
#{doctitle_sanitized}
#{icon_css_head}
#{header}
#{content})]
unless (fns = node.document.footnotes - @footnotes).empty?
@footnotes += fns
# NOTE kindlegen seems to mangle the
'
chapter_item.add_content postprocess_xhtml lines * LF
epub_properties = node.attr 'epub-properties'
chapter_item.add_property 'svg' if epub_properties&.include? 'svg'
# # QUESTION reenable?
# #linear 'yes' if i == 0
chapter_item
end
def convert_section node
if add_chapter(node).nil?
hlevel = node.level
epub_type_attr = node.special ? %( epub:type="#{node.sectname}") : ''
div_classes = [%(sect#{node.level}), node.role].compact
title = node.title
title_sanitized = xml_sanitize title
%(#{title}#{(content = node.content).empty? ? '' : %(
#{content})}
)
end
end
# NOTE embedded is used for AsciiDoc table cell content
def convert_embedded node
node.content
end
# TODO: support use of quote block as abstract
def convert_preamble node
if add_chapter(node).nil?
if (first_block = node.blocks[0]) && first_block.style == 'abstract'
convert_abstract first_block
# REVIEW: should we treat the preamble as an abstract in general?
elsif first_block && node.blocks.size == 1
convert_abstract first_block
else
node.content
end
end
end
def convert_open node
id_attr = node.id ? %( id="#{node.id}") : nil
class_attr = node.role ? %( class="#{node.role}") : nil
if id_attr || class_attr
%(
#{output_content node}
)
else
output_content node
end
end
def convert_abstract node
%(
#{output_content node}
)
end
def convert_paragraph node
role = node.role
# stack-head is the alternative to the default, inline-head (where inline means "run-in")
head_stop = node.attr 'head-stop', (role && (node.has_role? 'stack-head') ? nil : '.')
head = node.title? ? %(#{title = node.title}#{head_stop && title !~ TrailingPunctRx ? head_stop : ''} ) : ''
if role
node.set_option 'hardbreaks' if node.has_role? 'signature'
%(
#{head}#{node.content}
)
else
%(
#{head}#{node.content}
)
end
end
def convert_pass node
content = node.content
if content == ''
''
else
content
end
end
def convert_admonition node
id_attr = node.id ? %( id="#{node.id}") : ''
if node.title?
title = node.title
title_sanitized = xml_sanitize title
title_attr = %( title="#{node.caption}: #{title_sanitized}")
title_el = %(
#{title}
)
else
title_attr = %( title="#{node.caption}")
title_el = ''
end
type = node.attr 'name'
epub_type = case type
when 'tip'
'help'
when 'note'
'note'
when 'important', 'warning', 'caution'
'warning'
else
logger.warn %(unknown admonition type: #{type})
'note'
end
%()
end
def convert_example node
id_attr = node.id ? %( id="#{node.id}") : ''
title_div = node.title? ? %(
#{node.title}
) : ''
%(
#{title_div}
#{output_content node}
)
end
def convert_floating_title node
tag_name = %(h#{node.level + 1})
id_attribute = node.id ? %( id="#{node.id}") : ''
%(<#{tag_name}#{id_attribute} class="#{['discrete', node.role].compact * ' '}">#{node.title}#{tag_name}>)
end
def convert_listing node
figure_classes = ['listing']
figure_classes << 'coalesce' if node.option? 'unbreakable'
pre_classes = node.style == 'source' ? ['source', %(language-#{node.attr 'language'})] : ['screen']
title_div = node.title? ? %(#{node.captioned_title}
) : ''
%()
end
# TODO: implement proper stem support. See https://github.com/asciidoctor/asciidoctor-epub3/issues/10
alias convert_stem convert_listing
# QUESTION should we wrap the
in either
or
?
def convert_literal node
%(
#{node.content}
)
end
def convert_page_break _node
''
end
def convert_thematic_break _node
''
end
def convert_quote node
id_attr = node.id ? %( id="#{node.id}") : ''
class_attr = (role = node.role) ? %( class="blockquote #{role}") : ' class="blockquote"'
footer_content = []
if (attribution = node.attr 'attribution')
footer_content << attribution
end
if (citetitle = node.attr 'citetitle')
citetitle_sanitized = xml_sanitize citetitle
footer_content << %(#{citetitle})
end
footer_content << %(#{node.title}) if node.title?
footer_tag = footer_content.empty? ? '' : %(
)
content = (output_content node).strip
%(
']
num = CalloutStartNum
node.items.each_with_index do |item, i|
lines << %(
#{num} #{item.text}
)
num = num.next
end
lines << '
'
end
# TODO: add complex class if list has nested blocks
def convert_dlist node
lines = []
case (style = node.style)
when 'itemized', 'ordered'
list_tag_name = style == 'itemized' ? 'ul' : 'ol'
role = node.role
subject_stop = node.attr 'subject-stop', (role && (node.has_role? 'stack') ? nil : ':')
# QUESTION should we just use itemized-list and ordered-list as the class here? or just list?
div_classes = [%(#{style}-list), role].compact
list_class_attr = (node.option? 'brief') ? ' class="brief"' : ''
lines << %(
<#{list_tag_name}#{list_class_attr}#{list_tag_name == 'ol' && (node.option? 'reversed') ? ' reversed="reversed"' : ''}>)
node.items.each do |subjects, dd|
# consists of one term (a subject) and supporting content
subject = [*subjects].first.text
subject_plain = xml_sanitize subject, :plain
subject_element = %(#{subject}#{subject_stop && subject_plain !~ TrailingPunctRx ? subject_stop : ''})
lines << '
'
if dd
# NOTE: must wrap remaining text in a span to help webkit justify the text properly
lines << %(#{subject_element}#{dd.text? ? %( #{dd.text}) : ''})
lines << dd.content if dd.blocks?
else
lines << %(#{subject_element})
end
lines << '
'
end
lines << %(#{list_tag_name}>
)
else
lines << '
'
node.items.each do |terms, dd|
[*terms].each do |dt|
lines << %(
#{dt.text}
)
end
next unless dd
lines << '
'
if dd.blocks?
lines << %(#{dd.text}) if dd.text?
lines << dd.content
else
lines << %(#{dd.text})
end
lines << '
)
else
lines << (nav_level child_sections, depth - 1, state)
lines << ''
end
state.delete :content_doc_href unless chapter_name.nil?
end
lines << ''
lines * LF
end
def ncx_doc doc, items
# TODO: populate docAuthor element based on unique authors in work
lines = [%(
%{depth}
#{sanitize_doctitle_xml doc, :cdata})]
lines << (ncx_level items, [(doc.attr 'toclevels', 1).to_i, 0].max, state = {})
lines[0] = lines[0].sub '%{depth}', %()
lines << %()
lines * LF
end
def ncx_level items, depth, state = {}
lines = []
state[:max_depth] = (state.fetch :max_depth, 0) + 1
items.each do |item|
index = (state[:index] = (state.fetch :index, 0) + 1)
item_id = %(nav_#{index})
if (chapter_name = get_chapter_name item).nil?
item_label = sanitize_xml item.title, :cdata
item_href = %(#{state[:content_doc_href]}##{item.id})
else
if item.context == :document
item_label = sanitize_doctitle_xml item, :cdata
else
item_label = sanitize_xml item.title, :cdata
end
item_href = (state[:content_doc_href] = %(#{chapter_name}.xhtml))
end
lines << %()
lines << %(#{item_label})
lines << %()
unless depth == 0 || (child_sections = item.sections).empty?
lines << (ncx_level child_sections, depth - 1, state)
end
lines << %()
state.delete :content_doc_href unless chapter_name.nil?
end
lines * LF
end
# Swap fonts in CSS based on the value of the document attribute 'scripts',
# then return the list of fonts as well as the font CSS.
def select_fonts filename, scripts = 'latin'
font_css = ::File.read filename
font_css = font_css.gsub(/(?<=-)latin(?=\.ttf\))/, scripts) unless scripts == 'latin'
# match CSS font urls in the forms of:
# src: url(../fonts/notoserif-regular-latin.ttf);
# src: url(../fonts/notoserif-regular-latin.ttf) format("truetype");
font_list = font_css.scan(/url\(\.\.\/([^)]+\.ttf)\)/).flatten
[font_list, font_css.to_ios]
end
def postprocess_css_file filename, format
return filename unless format == :kf8
postprocess_css ::File.read(filename), format
end
def postprocess_css content, format
return content.to_ios unless format == :kf8
# TODO: convert regular expressions to constants
content
.gsub(/^ -webkit-column-break-.*\n/, '')
.gsub(/^ max-width: .*\n/, '')
.to_ios
end
# NOTE Kindle requires that
#
# be converted to
#
def postprocess_xhtml content
return content.to_ios unless @format == :kf8
# TODO: convert regular expressions to constants
content
.gsub(//, '')
.gsub(/]+) style="width: (\d\d)%;"/, '.*?<\/script>\n?/m, '')
.to_ios
end
def get_kindlegen_command kindlegen_path
unless kindlegen_path.nil?
logger.debug %(Using ebook-kindlegen-path attribute: #{kindlegen_path})
return [kindlegen_path]
end
unless (result = ENV['KINDLEGEN']).nil?
logger.debug %(Using KINDLEGEN env variable: #{result})
return [result]
end
begin
require 'kindlegen' unless defined? ::Kindlegen
result = ::Kindlegen.command.to_s
logger.debug %(Using KindleGen from gem: #{result})
[result]
rescue LoadError => e
logger.debug %(#{e}; Using KindleGen from PATH)
[%(kindlegen#{::Gem.win_platform? ? '.exe' : ''})]
end
end
def distill_epub_to_mobi epub_file, target, compress, kindlegen_path
mobi_file = ::File.basename target.sub(EpubExtensionRx, '.mobi')
compress_flag = KindlegenCompression[compress ? (compress.empty? ? '1' : compress.to_s) : '0']
argv = get_kindlegen_command(kindlegen_path) + ['-dont_append_source', compress_flag, '-o', mobi_file, epub_file].compact
begin
# This duplicates Kindlegen.run, but we want to override executable
out, err, res = Open3.capture3(*argv) do |r|
r.force_encoding 'UTF-8' if ::Gem.win_platform? && r.respond_to?(:force_encoding)
end
rescue Errno::ENOENT => e
raise 'Unable to run KindleGen. Either install the kindlegen gem or place `kindlegen` executable on PATH or set KINDLEGEN environment variable with path to it', cause: e
end
out.each_line do |line|
log_line line
end
err.each_line do |line|
log_line line
end
output_file = ::File.join ::File.dirname(epub_file), mobi_file
if res.success?
logger.debug %(Wrote MOBI to #{output_file})
else
logger.error %(KindleGen failed to write MOBI to #{output_file})
end
end
def get_epubcheck_command epubcheck_path
unless epubcheck_path.nil?
logger.debug %(Using ebook-epubcheck-path attribute: #{epubcheck_path})
return [epubcheck_path]
end
unless (result = ENV['EPUBCHECK']).nil?
logger.debug %(Using EPUBCHECK env variable: #{result})
return [result]
end
begin
result = ::Gem.bin_path 'epubcheck-ruby', 'epubcheck'
logger.debug %(Using EPUBCheck from gem: #{result})
[::Gem.ruby, result]
rescue ::Gem::Exception => e
logger.debug %(#{e}; Using EPUBCheck from PATH)
['epubcheck']
end
end
def validate_epub epub_file, epubcheck_path
argv = get_epubcheck_command(epubcheck_path) + ['-w', epub_file]
begin
out, err, res = Open3.capture3(*argv)
rescue Errno::ENOENT => e
raise 'Unable to run EPUBCheck. Either install epubcheck-ruby gem or place `epubcheck` executable on PATH or set EPUBCHECK environment variable with path to it', cause: e
end
out.each_line do |line|
logger.info line
end
err.each_line do |line|
log_line line
end
logger.error %(EPUB validation failed: #{epub_file}) unless res.success?
end
def log_line line
line = line.strip
if line =~ /^fatal/i
logger.fatal line
elsif line =~ /^error/i
logger.error line
elsif line =~ /^warning/i
logger.warn line
else
logger.info line
end
end
private
def class_string node
role = node.role
return '' unless role_valid_class? role
%( class="#{role}")
end
# Handles asciidoctor 1.5.6 quirk when role can be parent
def role_valid_class? role
role.is_a? String
end
end
class DocumentIdGenerator
ReservedIds = %w(cover nav ncx)
CharRefRx = /&(?:([a-zA-Z][a-zA-Z]+\d{0,2})|#(\d\d\d{0,4})|#x([\da-fA-F][\da-fA-F][\da-fA-F]{0,3}));/
if defined? __dir__
InvalidIdCharsRx = /[^\p{Word}]+/
LeadingDigitRx = /^\p{Nd}/
else
InvalidIdCharsRx = /[^[:word:]]+/
LeadingDigitRx = /^[[:digit:]]/
end
class << self
def generate_id doc, pre = nil, sep = nil
synthetic = false
unless (id = doc.id)
# NOTE we assume pre is a valid ID prefix and that pre and sep only contain valid ID chars
pre ||= '_'
sep = sep ? sep.chr : '_'
if doc.header?
id = doc.doctitle sanitize: true
id = id.gsub CharRefRx do
$1 ? ($1 == 'amp' ? 'and' : sep) : ((d = $2 ? $2.to_i : $3.hex) == 8217 ? '' : ([d].pack 'U*'))
end if id.include? '&'
id = id.downcase.gsub InvalidIdCharsRx, sep
if id.empty?
id, synthetic = nil, true
else
unless sep.empty?
if (id = id.tr_s sep, sep).end_with? sep
if id == sep
id, synthetic = nil, true
else
id = (id.start_with? sep) ? id[1..-2] : id.chop
end
elsif id.start_with? sep
id = id[1..-1]
end
end
unless synthetic
if pre.empty?
id = %(_#{id}) if LeadingDigitRx =~ id
elsif !(id.start_with? pre)
id = %(#{pre}#{id})
end
end
end
elsif (first_section = doc.first_section)
id = first_section.id
else
synthetic = true
end
id = %(#{pre}document#{sep}#{doc.object_id}) if synthetic
end
logger.error %(chapter uses a reserved ID: #{id}) if !synthetic && (ReservedIds.include? id)
id
end
end
end
Extensions.register do
if (document = @document).backend == 'epub3'
document.set_attribute 'listing-caption', 'Listing'
# pygments.rb hangs on JRuby for Windows, see https://github.com/asciidoctor/asciidoctor-epub3/issues/253
if !(::RUBY_ENGINE == 'jruby' && Gem.win_platform?) && (Gem.try_activate 'pygments.rb')
if document.set_attribute 'source-highlighter', 'pygments'
document.set_attribute 'pygments-css', 'style'
document.set_attribute 'pygments-style', 'bw'
end
end
case (ebook_format = document.attributes['ebook-format'])
when 'epub3', 'kf8'
# all good
when 'mobi'
ebook_format = document.attributes['ebook-format'] = 'kf8'
else
# QUESTION should we display a warning?
ebook_format = document.attributes['ebook-format'] = 'epub3'
end
document.attributes[%(ebook-format-#{ebook_format})] = ''
treeprocessor do
process do |doc|
doc.id = DocumentIdGenerator.generate_id doc, (doc.attr 'idprefix'), (doc.attr 'idseparator')
nil
end
end
end
end
end
end