class Object

Constants

DEFAULT_CONFIG_FILENAME
PREDEF_FILE
REVIEW_EPUBMAKER
REVIEW_PDFMAKER

Public Instance Methods

_main() click to toggle source
# File ../../../../../bin/review-compile, line 36
def _main
  mode = :files
  basedir = nil
  if /\Areview2/ =~ File.basename($0)
    target = File.basename($0, '.rb').sub(/review2/, '')
  else
    target = nil
  end
  check_only = false
  output_filename = nil

  config = ReVIEW::Configure.values

  opts = OptionParser.new
  opts.version = ReVIEW::VERSION
  opts.banner = "Usage: #{File.basename($0)} [--target=FMT]"
  opts.on('--yaml=YAML', 'Read configurations from YAML file.') {|yaml| config["yaml"] = yaml}
  opts.on('-c', '--check', 'Check manuscript') { check_only = true }
  opts.on('--level=LVL', 'Section level to append number.') {|lvl| config["secnolevel"] = lvl.to_i }
  opts.on('--toclevel=LVL', 'Section level to append number.') {|lvl| config["toclevel"] = lvl.to_i }
  opts.on('--structuredxml', 'Produce XML with structured sections. (idgxml)') { config["structuredxml"] = true }
  opts.on('--table=WIDTH', 'Default table width. (idgxml)') {|tbl| config["tableopt"] = tbl }
  opts.on('--listinfo', 'Append listinfo tag to lists to indicate begin/end. (idgxml)') { config["listinfo"] = true }
  opts.on('--chapref="before,middle,after"', 'Chapref decoration. (idgxml)') {|cdec| config["chapref"] = cdec }
  opts.on('--chapterlink', 'make chapref hyperlink') { config["chapterlink"] = true }
  opts.on('--stylesheet=file', 'Stylesheet file for HTML (comma separated)') {|files| config["stylesheet"] = files.split(/\s*,\s*/) }
  opts.on('--mathml', 'Use MathML for TeX equation in HTML') do
    config["mathml"] = true
  end
  opts.on('--htmlversion=VERSION', 'HTML version.') do |v|
    v = v.to_i
    config["htmlversion"] = v if v == 4 || v == 5
  end
  opts.on('--epubversion=VERSION', 'EPUB version.') do |v|
    v = v.to_i
    config["epubversion"] = v if v == 2 || v == 3
  end
  opts.on('--target=FMT', 'Target format.') {|fmt| target = fmt } unless target
  opts.on('--footnotetext',
          'Use footnotetext and footnotemark instead of footnote (latex)') {
    config["footnotetext"] = true
  }
  opts.on('--draft', 'use draft mode(inline comment)') { config["draft"] = true }
  opts.on('--directory=DIR', 'Compile all chapters in DIR.') do |path|
    mode = :dir
    basedir = path
  end
  opts.on('--output-file=FILENAME', 'Write all results into file instead of stdout.') do |filename|
    output_filename = filename
  end
  opts.on('--tabwidth=WIDTH', 'tab width') {|width| config["tabwidth"] = width.to_i }
  opts.on('--catalogfile=FILENAME', 'Set catalog file') do |catalogfile|
    config["catalogfile"] = catalogfile
  end
  opts.on('--help', 'Prints this message and quit.') do
    puts opts.help
    exit 0
  end
  begin
    opts.parse!
    unless target
      if check_only
        target = 'html'
      else
        raise OptionParser::ParseError, "no target given"
      end
    end
  rescue OptionParser::ParseError => err
    error err.message
    $stderr.puts opts.help
    exit 1
  end

  begin
    loader = ReVIEW::YAMLLoader.new
    if config["yaml"]
      config.deep_merge!(loader.load_file(config["yaml"]))
    else
      if File.exist?(DEFAULT_CONFIG_FILENAME)
        config.deep_merge!(loader.load_file(DEFAULT_CONFIG_FILENAME))
      end
    end

    config["builder"] = target
    ReVIEW::I18n.setup(config["language"])
    begin
      config.check_version(ReVIEW::VERSION)
    rescue ReVIEW::ConfigError => e
      warn e.message
    end

    if ARGV.blank?
      mode = :dir
    end

    case mode
    when :files
      if ARGV.empty?
        error 'no input'
        exit 1
      end

      basedir = File.dirname(ARGV[0])
      book = ReVIEW::Book::Base.load(basedir)
      book.config = config # needs only at the first time
      ARGV.each do |item|
        chap_name = File.basename(item, '.*')
        chap = book.chapter(chap_name)
        compiler = ReVIEW::Compiler.new(load_strategy_class(target, check_only))
        result = compiler.compile(chap)
        if output_filename
          write output_filename, result
        else
          puts result unless check_only
        end
      end
    when :dir
      book = basedir ? ReVIEW::Book.load(basedir) : ReVIEW::Book::Base.load
      book.config = config
      compiler = ReVIEW::Compiler.new(load_strategy_class(target, check_only))
      book.chapters.each do |chap|
        str = compiler.compile(chap)
        write "#{chap.name}#{compiler.strategy.extname}", str unless check_only
      end
      # PART
      book.parts_in_file.each do |part|
        str = compiler.compile(part)
        write "#{part.name}#{compiler.strategy.extname}", str unless check_only
      end
    else
      raise "must not happen: #{mode}"
    end
  rescue ReVIEW::ApplicationError => err
    raise if $DEBUG
    error err.message
    exit 1
  end
end
_parse(str, header) click to toggle source
# File ../../../../../bin/review-catalog-converter, line 87
def _parse(str, header)
  if str.present?
    header + str.split("\n").map{|i| "  - #{i}\n" }.join
  else
    header
  end
end
assets_dir() click to toggle source
# File ../../../../../test/test_helper.rb, line 9
def assets_dir
  File.join(File.dirname(__FILE__), "assets")
end
blank?() click to toggle source
# File ../../../../../lib/review/extentions/object.rb, line 2
def blank?
  respond_to?(:empty?) ? empty? : !self
end
chapnumstr(n) click to toggle source
# File ../../../../../bin/review-vol, line 95
def chapnumstr(n)
  n ? sprintf('%2d.', n) : '   '
end
check_text(files) click to toggle source
# File ../../../../../bin/review-check, line 80
def check_text(files)
  re, neg = words_re("#{@book.basedir}/#{@book.reject_file}")
  files.each do |path|
    File.open(path) {|f|
      each_paragraph(f) do |para, lineno|
        s = para.join('')
        if m = re.match(s)
          next if m[0] == @review_utils_word_ok
          next if neg and neg =~ s
          str, offset = find_line(para, re)
          out = sprintf("%s:%d: %s\n", path, lineno + offset, str)
          print out
        end
      end
    }
  end
end
compile_block(text) click to toggle source
# File ../../../../../test/test_helper.rb, line 23
def compile_block(text)
  method_name = "compile_block_#{@builder.target_name}"
  if !self.respond_to?(method_name, true)
    method_name = "compile_block_default"
  end
  self.__send__(method_name, text)
end
compile_block_default(text) click to toggle source
# File ../../../../../test/test_helper.rb, line 31
def compile_block_default(text)
  @chapter.content = text
  @compiler.compile(@chapter)
end
compile_block_html(text) click to toggle source
# File ../../../../../test/test_helper.rb, line 36
def compile_block_html(text)
  @chapter.content = text
  matched = @compiler.compile(@chapter).match(/<body>\n(.+)<\/body>/m)
  if matched && matched.size > 1
    matched[1]
  else
    ""
  end
end
compile_block_idgxml(text) click to toggle source
# File ../../../../../test/test_helper.rb, line 46
def compile_block_idgxml(text)
  @chapter.content = text
  @compiler.compile(@chapter).gsub(/.*<doc xmlns:aid="http:\/\/ns.adobe.com\/AdobeInDesign\/4.0\/">/m,"").gsub(/<\/doc>\n/, "")
end
compile_inline(text) click to toggle source
# File ../../../../../test/test_helper.rb, line 19
def compile_inline(text)
  @builder.compile_inline(text)
end
each_paragraph(f) { |[$1], filename, lineno| ... } click to toggle source
# File ../../../../../bin/review-check, line 130
def each_paragraph(f)
  @review_utils_word_ok = nil
  while line = f.gets
    case line
    when /\A\#@ok\((.*)\)/
      @review_utils_word_ok = $1
    when /\A\#@/
      # do nothing
    when %r[\A//caption\{(.*?)//\}]
      yield [$1], f.filename, f.lineno
    when %r<\A//\w.*\{\s*\z>
      while line = f.gets
        break if %r<//\}> === line
      end
    when /\A=/
      yield [line.slice(/\A=+(?:\[.*?\])?\s+(.*)/, 1).strip], f.lineno
    when /\A\s*\z/
      # skip
    else
      buf = [line.strip]
      lineno = f.lineno
      while line = f.gets
        break if line.strip.empty?
        break if %r<\A(?:=|//[\w\}])> =~ line
        next if %r<\A\#@> =~ line
        buf.push line.strip
      end
      yield buf, lineno
      @review_utils_word_ok = nil
    end
  end
end
each_paragraph_line(f, &block) click to toggle source
# File ../../../../../bin/review-check, line 163
def each_paragraph_line(f, &block)
  each_paragraph(f) do |para, *|
    para.each(&block)
  end
end
error(msg) click to toggle source
# File ../../../../../bin/review-compile, line 175
def error(msg)
  $stderr.puts "#{File.basename($0, '.*')}: error: #{msg}"
end
error_exit(msg) click to toggle source
# File ../../../../../bin/review-index, line 103
def error_exit(msg)
  $stderr.puts "#{File.basename($0)}: #{msg}"
  exit 1
end
find_line(lines, re) click to toggle source
# File ../../../../../bin/review-check, line 98
def find_line(lines, re)
  # single line?
  lines.each_with_index do |line, idx|
    return line.gsub(re, '<<<\&>>>'), idx if re =~ line
  end

  # multiple lines?
  i = 0
  while i < lines.size - 1
    str = lines[i] + lines[i+1]
    return str.gsub(re, '<<<\&>>>'), i if re =~ str
    i += 1
  end

  raise 'must not happen'
end
generate_catalog_file(dir) click to toggle source
# File ../../../../../bin/review-init, line 89
def generate_catalog_file(dir)
  File.open(dir + "/catalog.yml", "w") do |file|
    file.write <<-EOS
PREDEF:

CHAPS:
  - #{File.basename(dir)}.re

APPENDIX:

POSTDEF:

EOS
  end
end
generate_config(dir) click to toggle source
# File ../../../../../bin/review-init, line 113
def generate_config(dir)
  today = Time.now.strftime("%Y-%m-%d")
  content = File.read(@review_dir + "/doc/config.yml.sample", {:encoding => 'utf-8'})
  content.gsub!(/^#\s*coverimage:.*$/, 'coverimage: cover.jpg')
  content.gsub!(/^#\s*date:.*$/, "date: #{today}")
  content.gsub!(/^#\s*history:.*$/, %Q|history: [["#{today}"]]|)
  content.gsub!(/^#\s*texstyle:.*$/, "texstyle: reviewmacro")
  content.gsub!(/^(#\s*)?stylesheet:.*$/, %Q|stylesheet: ["style.css"]|)
  if @epub_version.to_i == 2
    content.gsub!(/^#.*epubversion:.*$/,'epubversion: 2')
    content.gsub!(/^#.*htmlversion:.*$/,'htmlversion: 4')
  end
  File.open(File.join(dir, "config.yml"), "w"){|f| f.write(content) }
end
generate_cover_image(dir) click to toggle source
# File ../../../../../bin/review-init, line 109
def generate_cover_image(dir)
  FileUtils.cp @review_dir + "/test/sample-book/src/images/cover.jpg", dir + '/images/'
end
generate_dir(dir) { |dir| ... } click to toggle source
# File ../../../../../bin/review-init, line 68
def generate_dir(dir)
  if File.exist?(dir) && !@force
    puts "#{dir} already exists."
    exit
  end
  FileUtils.mkdir_p dir
  yield dir
end
generate_gemfile(dir) click to toggle source
# File ../../../../../bin/review-init, line 149
def generate_gemfile(dir)
  File.open(dir + "/Gemfile", "w") do |file|
    file.write <<-EOS
source 'https://rubygems.org'

gem 'rake'
gem 'review', '#{ReVIEW::VERSION}'
EOS
  end
end
generate_images_dir(dir) click to toggle source
# File ../../../../../bin/review-init, line 105
def generate_images_dir(dir)
  FileUtils.mkdir_p dir + '/images'
end
generate_layout(dir) click to toggle source
# File ../../../../../bin/review-init, line 85
def generate_layout(dir)
  FileUtils.mkdir_p dir + '/layouts'
end
generate_locale(dir) click to toggle source
# File ../../../../../bin/review-init, line 145
def generate_locale(dir)
  FileUtils.cp @review_dir + '/lib/review/i18n.yml', dir + '/locale.yml'
end
generate_rakefile(dir) click to toggle source
# File ../../../../../bin/review-init, line 141
def generate_rakefile(dir)
  FileUtils.cp @review_dir + "/test/sample-book/src/Rakefile", dir
end
generate_sample(dir) click to toggle source
# File ../../../../../bin/review-init, line 77
def generate_sample(dir)
  if !@force
    File.open("#{dir}/#{File.basename(dir)}.re", "w") do |file|
      file.write("= ")
    end
  end
end
generate_style(dir) click to toggle source
# File ../../../../../bin/review-init, line 128
def generate_style(dir)
  FileUtils.cp @review_dir + "/test/sample-book/src/style.css", dir
end
generate_texmacro(dir) click to toggle source
# File ../../../../../bin/review-init, line 132
def generate_texmacro(dir)
  texmacrodir = dir + '/sty'
  FileUtils.mkdir_p texmacrodir
  FileUtils.cp [
    @review_dir + "/test/sample-book/src/sty/reviewmacro.sty",
    @review_dir + "/test/sample-book/src/sty/jumoline.sty"
  ], texmacrodir
end
load_strategy_class(target, strict) click to toggle source
# File ../../../../../bin/review-compile, line 179
def load_strategy_class(target, strict)
  require "review/#{target}builder"
  ReVIEW.const_get("#{target.upcase}Builder").new(strict)
end
location() click to toggle source
# File ../../../../../bin/review-checkdep, line 59
def location
  "#{ARGF.filename}:#{ARGF.file.lineno}"
end
main() click to toggle source
# File ../../../../../bin/review-catalog-converter, line 19
def main
  opts = OptionParser.new
  opts.version = ReVIEW::VERSION
  opts.banner = "Usage: #{File.basename($0)} dirname"
  opts.on('-h', '--help', 'print this message and quit.') do
    puts opts.help
    exit 0
  end

  begin
    opts.parse!
  rescue OptionParser::ParseError => err
    $stderr.puts err.message
    $stderr.puts opts.help
    exit 1
  end

  dir = Dir.pwd

  # confirmation
  if File.exist?("#{dir}/catalog.yml")
    loop do
      print "The catalog.yml already exists. Do you want to overwrite it? [y/n]"
      case gets
      when /^[yY]/
        puts "Start writing..."
        break
      when /^[nN]/, /^$/
        puts "bye."
        exit
      end
    end
  end

  File.open("#{dir}/catalog.yml", "w") do |catalog|
    # predef
    if File.exist?("#{dir}/PREDEF")
      catalog << parse_predef(File.open("#{dir}/PREDEF").read)
    end
    # chaps and parts
    if File.exist?("#{dir}/CHAPS")
      if File.exist?("#{dir}/PART")
        catalog << parse_parts(File.open("#{dir}/PART").read,
                               File.open("#{dir}/CHAPS").read)
      else
        catalog << parse_chaps(File.open("#{dir}/CHAPS").read)
      end
    end
    # postdef
    if File.exist?("#{dir}/POSTDEF")
      postdef = File.open("#{dir}/POSTDEF").read
      loop do
        print "Do you want to convert POSTDEF into APPENDIX? [y/n]"
        case gets
        when /^[yY]/
          catalog << parse_postdef(postdef, true)
          break
        when /^[nN]/, /^$/
          catalog << parse_postdef(postdef)
          break
        end
      end
    end
  end

  puts File.open("#{dir}/catalog.yml").read
end
parse_chaps(str) click to toggle source
# File ../../../../../bin/review-catalog-converter, line 100
def parse_chaps(str)
  header = "CHAPS:\n"
  _parse(str, header) + "\n"
end
parse_parts(parts_str, chaps_str) click to toggle source
# File ../../../../../bin/review-catalog-converter, line 114
def parse_parts(parts_str, chaps_str)
  if parts_str.blank? or chaps_str.blank?
    return "CHAPS:\n\n"
  end

  parts = parts_str.split("\n")
  chaps = chaps_str.split("\n\n")
  "CHAPS:\n" + parts.zip(chaps).map{|k, vs|
    "  - #{k}:\n" + vs.split("\n").map{|i| "    - #{i}\n"}.join
  }.join + "\n"
end
parse_postdef(str, to_appendix = false) click to toggle source
# File ../../../../../bin/review-catalog-converter, line 105
def parse_postdef(str, to_appendix = false)
  if to_appendix
    header = "APPENDIX:\n"
  else
    header = "POSTDEF:\n"
  end
  _parse(str, header) + "\n"
end
parse_predef(str) click to toggle source
# File ../../../../../bin/review-catalog-converter, line 95
def parse_predef(str)
  header = "PREDEF:\n"
  _parse(str, header) + "\n"
end
parse_predefined() click to toggle source
# File ../../../../../bin/review-checkdep, line 49
def parse_predefined
  result = {}
  File.foreach(PREDEF_FILE) do |line|
    result[line.strip] = '(predefined)'
  end
  result
rescue Errno::ENOENT
  return {}
end
prepare_samplebook(srcdir) click to toggle source
# File ../../../../../test/test_helper.rb, line 13
def prepare_samplebook(srcdir)
  samplebook_dir = File.expand_path("sample-book/src/", File.dirname(__FILE__))
  FileUtils.cp_r(Dir.glob(samplebook_dir + "/*"), srcdir)
  YAML.load(File.open(srcdir + "/config.yml"))
end
preproc(pp, path) click to toggle source
# File ../../../../../bin/review-preproc, line 126
def preproc(pp, path)
  buf = StringIO.new
  File.open(path) {|f|
    pp.process f, buf
  }
  buf.string
end
present?() click to toggle source
# File ../../../../../lib/review/extentions/object.rb, line 6
def present?
  !blank?
end
print_chapter_volume(chap) click to toggle source
print_volume(vol) click to toggle source
provide(kw) click to toggle source
# File ../../../../../bin/review-checkdep, line 41
def provide(kw)
  @provided[kw] ||= location()
  if @unprovided[kw]
    reqpos = @unprovided.delete(kw)
    puts "#{location()}: provided now: #{kw} (#{reqpos})"
  end
end
sigmain() click to toggle source
# File ../../../../../bin/review-check, line 23
def sigmain
  Signal.trap(:INT) { exit 1 }
  if RUBY_PLATFORM !~ /mswin(?!ce)|mingw|cygwin|bccwin/
    Signal.trap(:PIPE, 'IGNORE')
  end
  main
rescue Errno::EPIPE
  exit 0
end
touch_file(path) click to toggle source
# File ../../../../../test/test_helper.rb, line 4
def touch_file(path)
  File.open(path, "w").close
  path
end
usage() click to toggle source
# File ../../../../../bin/review, line 13
def usage
  message = <<-EOB
usage: review <command> [<args>]

ReVIEW commands are:
  init
  preproc
  compile
  epubmaker
  pdfmaker
  vol
  check
  index
  validate
EOB
  print message
  exit 1
end
words_re(rc) click to toggle source
# File ../../../../../bin/review-check, line 115
def words_re(rc)
  words = []
  nega = []
  File.foreach(rc) do |line|
    next if line[0,1] == '#'
    if / !/ =~ line
      line, n = *line.split(/!/, 2)
      nega.push n.strip
    end
    words.push line.strip
  end
  return Regexp.compile(words.join('|')),
         nega.empty?() ? nil : Regexp.compile(nega.join('|'))
end
write(path, str) click to toggle source
# File ../../../../../bin/review-compile, line 184
def write(path, str)
  File.open(path, 'w') {|f|
    f.puts str
  }
end