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 34
def _main
  @logger = ReVIEW.logger
  mode = :files
  basedir = nil
  if /\Areview2/ =~ File.basename($PROGRAM_NAME)
    target = File.basename($PROGRAM_NAME, '.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($PROGRAM_NAME)} [--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') { config['mathml'] = true }
  opts.on('--htmlversion=VERSION', 'HTML version.') do |v|
    v = v.to_i
    config['htmlversion'] = v if [4, 5].include?(v)
  end
  opts.on('--epubversion=VERSION', 'EPUB version.') do |v|
    v = v.to_i
    config['epubversion'] = v if [2, 3].include?(v)
  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.') { |filename| output_filename = filename }
  opts.on('--tabwidth=WIDTH', 'tab width') { |width| config['tabwidth'] = width.to_i }
  opts.on('--catalogfile=FILENAME', 'Set catalog file') { |catalogfile| config['catalogfile'] = catalogfile }
  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
    @logger.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']))
    elsif File.exist?(DEFAULT_CONFIG_FILENAME)
      config.deep_merge!(loader.load_file(DEFAULT_CONFIG_FILENAME))
    end

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

    mode = :dir if ARGV.blank?

    case mode
    when :files
      if ARGV.empty?
        @logger.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
    @logger.error(err.message)
    exit 1
  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 83
def chapnumstr(n)
  n ? sprintf('%2d.', n) : '   '
end
check_text(files) click to toggle source
# File ../../../../../bin/review-check, line 77
def check_text(files)
  re, neg = words_re("#{@book.basedir}/#{@book.reject_file}")
  files.each do |path|
    File.open(path) do |f|
      each_paragraph(f) do |para, lineno|
        s = para.join
        m = re.match(s)
        next if m.nil? || 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}"
  method_name = 'compile_block_default' unless self.respond_to?(method_name, true)
  self.__send__(method_name, text)
end
compile_block_default(text) click to toggle source
# File ../../../../../test/test_helper.rb, line 29
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 34
def compile_block_html(text)
  @chapter.content = text
  matched = @compiler.compile(@chapter).match(Regexp.new(%Q(<body>\n(.+)</body>), Regexp::MULTILINE))
  if matched && matched.size > 1
    matched[1]
  else
    ''
  end
end
compile_block_idgxml(text) click to toggle source
# File ../../../../../test/test_helper.rb, line 44
def compile_block_idgxml(text)
  @chapter.content = text
  @compiler.compile(@chapter).gsub(Regexp.new(%Q(.*<doc xmlns:aid="http://ns.adobe.com/AdobeInDesign/4.0/">), Regexp::MULTILINE), '').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 123
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
      next
    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
      next
    else
      buf = [line.strip]
      lineno = f.lineno
      while line = f.gets
        break if line.strip.empty?
        break if %r{\A(?:=|//[\w\}])} =~ line
        next if /\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 158
def each_paragraph_line(f, &block)
  each_paragraph(f) { |para, *| para.each(&block) }
end
error_exit(msg) click to toggle source
# File ../../../../../bin/review-index, line 95
def error_exit(msg)
  @logger.error "#{File.basename($PROGRAM_NAME)}: #{msg}"
  exit 1
end
find_line(lines, re) click to toggle source
# File ../../../../../bin/review-check, line 94
def find_line(lines, re)
  # single line?
  lines.each_with_index { |line, idx| return line.gsub(re, '<<<\&>>>'), idx if re =~ line }

  # 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 80
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 104
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 100
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 63
def generate_dir(dir)
  if File.exist?(dir) && !@force
    @logger.error "#{dir} already exists."
    exit
  end
  FileUtils.mkdir_p dir
  yield dir
end
generate_gemfile(dir) click to toggle source
# File ../../../../../bin/review-init, line 140
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 96
def generate_images_dir(dir)
  FileUtils.mkdir_p dir + '/images'
end
generate_layout(dir) click to toggle source
# File ../../../../../bin/review-init, line 76
def generate_layout(dir)
  FileUtils.mkdir_p dir + '/layouts'
end
generate_locale(dir) click to toggle source
# File ../../../../../bin/review-init, line 136
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 132
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 72
def generate_sample(dir)
  File.open("#{dir}/#{File.basename(dir)}.re", 'w') { |file| file.write('= ') } unless @force
end
generate_style(dir) click to toggle source
# File ../../../../../bin/review-init, line 119
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 123
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 163
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 54
def location
  "#{ARGF.filename}:#{ARGF.file.lineno}"
end
main() click to toggle source
# File ../../../../../bin/review-catalog-converter, line 20
def main
  @logger = ReVIEW.logger
  opts = OptionParser.new
  opts.version = ReVIEW::VERSION
  opts.banner = "Usage: #{File.basename($PROGRAM_NAME)} dirname"
  opts.on('-h', '--help', 'print this message and quit.') do
    puts opts.help
    exit 0
  end

  begin
    opts.parse!
  rescue OptionParser::ParseError => err
    @logger.error 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 /\A[yY]/
        @logger.info 'Start writing...'
        break
      when /\A[nN]/, /\A\Z/
        @logger.info '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 /\A[yY]/
          catalog << parse_postdef(postdef, true)
          break
        when /\A[nN]/, /\A\Z/
          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 102
def parse_chaps(str)
  header = "CHAPS:\n"
  parse_internal(str, header) + "\n"
end
parse_internal(str, header) click to toggle source
# File ../../../../../bin/review-catalog-converter, line 89
def parse_internal(str, header)
  if str.present?
    header + str.split("\n").map { |i| "  - #{i}\n" }.join
  else
    header
  end
end
parse_parts(parts_str, chaps_str) click to toggle source
# File ../../../../../bin/review-catalog-converter, line 116
def parse_parts(parts_str, chaps_str)
  return "CHAPS:\n\n" if parts_str.blank? or chaps_str.blank?

  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 107
def parse_postdef(str, to_appendix = false)
  if to_appendix
    header = "APPENDIX:\n"
  else
    header = "POSTDEF:\n"
  end
  parse_internal(str, header) + "\n"
end
parse_predef(str) click to toggle source
# File ../../../../../bin/review-catalog-converter, line 97
def parse_predef(str)
  header = "PREDEF:\n"
  parse_internal(str, header) + "\n"
end
parse_predefined() click to toggle source
# File ../../../../../bin/review-checkdep, line 46
def parse_predefined
  result = {}
  File.foreach(PREDEF_FILE) { |line| result[line.strip] = '(predefined)' }
  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 110
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 38
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 22
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 12
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 109
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
  [Regexp.compile(words.join('|')), nega.empty? ? nil : Regexp.compile(nega.join('|'))]
end
write(path, str) click to toggle source
# File ../../../../../bin/review-compile, line 168
def write(path, str)
  File.open(path, 'w') { |f| f.puts str }
end