From: "Shirai,Kaoru" Date: 2004-01-22T19:01:55+09:00 Subject: [ruby-list:39066] rdhtml-toc.rb: RD HTMLの目次・節番号の生成 ----Next_Part(Thu_Jan_22_19_01_51_2004_907)-- Content-Type: Text/Plain; charset=iso-2022-jp Content-Transfer-Encoding: 7bit 白井です。 rd2が出力したHTMLに目次や節番号を付けるスクリプトを書きました。RD自体 を拡張したり、RDのソースを整形するアプローチの方が一般的だとは思います が…。 RDを使ってHTMLのREADMEやHOWTOを書いている人は、使ってみて下さい。 使い方: usage: rdhtml-toc.rb [OPTIONS] - < HTMLFILE usage: rdhtml-toc.rb [OPTIONS] HTMLFILE Options -n: Assign section number. RDが出力したHTMLの見出しを解析し、

...

の直後に目次を出力します。 1行目の書式では、標準入力からHTMLを読み込み、標準出力へ結果を出力します。 2行目の書式では、指定されたHTMLファイルを処理し、処理結果で置き換えます。 -nオプションを付けると、各見出しに節番号(1.1, 1.2, ...) を振ります。 -- Shirai,Kaoru Korinkan Ltd. - http://www.korinkan.co.jp/ ----Next_Part(Thu_Jan_22_19_01_51_2004_907)-- Content-Type: Text/Plain; charset=us-ascii Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="rdhtml-toc.rb" #!/usr/bin/env ruby #-*-ruby-*- require "getopts" def usage STDERR.puts("\ usage: #{File.basename($0)} [OPTIONS] - < HTMLFILE usage: #{File.basename($0)} [OPTIONS] HTMLFILE Options -n: Assign section number. ") exit 1 end getopts("n") || usage file = ARGV.shift || usage does_assign_section_number = $OPT_n html = nil if file == "-" html = STDIN.read else html = IO.read(file) end $KCODE="EUC" prev_level = 1 toc = "" shift_level = proc { |level| shift = level - prev_level toc << ("\n" * -shift) if shift < 0 prev_level = level } def ensure_array_size(array, size, filled_value = nil) delta = size - array.size if delta > 0 array.concat([filled_value] * delta) elsif delta < 0 array.slice!(-1..delta) end array end Headline = Struct.new(:level, :id, :title) sectnums = [] headlines = [] html.gsub!(%r'()(.+?)()') { match = $~.to_a pre_title, post_title = match.values_at(1, 5) headline = Headline.new(match[2].to_i, match[3], match[4]) headlines << headline if does_assign_section_number sectlevel = headline.level - 1 ensure_array_size(sectnums, sectlevel, 0) sectnums[sectlevel - 1] += 1 headline.title.gsub!(%r"^", sectnums.join(".") + " ") end pre_title + headline.title + post_title } headlines.each { |head| shift_level[head.level] toc << %Q'
  • #{head.title}
  • \n' } shift_level[1] html.sub!(%r'

    ') { |h2| %Q'
    #{toc}
    #{h2}' } if file == "-" STDOUT.print(html) else tmp = file + ".rdhtmltoc-tmp" File.open(tmp, "w") { |io| io.write(html); } File.rename(tmp, file) end ----Next_Part(Thu_Jan_22_19_01_51_2004_907)----