Skip to content

Instantly share code, notes, and snippets.

@satour
Last active February 14, 2019 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satour/16f6d657bb82a5b0f7cf2ad9859724d2 to your computer and use it in GitHub Desktop.
Save satour/16f6d657bb82a5b0f7cf2ad9859724d2 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require 'fileutils'
require 'find'
require 'uri'
@level1 = /^[#][^#]*[^}]$/
@level2 = /^[#][#][^#]*[^}]$/
@level3 = /^[#][#][#][^#]*[^}]$/
@anchorString = /[{][#].*/
@backup = false
Find.find('.') {|fname|
if ( File.extname(fname) == '.md' || File.extname(fname) == '.markdown' )
FileUtils.copy_file(fname, fname + ".bak")
File.open(fname + ".bak", "r") { |original|
File.open(fname, "w") { |dist|
original.each_line { |line|
buffer = line
# 既存行の末尾に Gitbook書式 の anchor があれば、一度削除する
if @anchorString.match(buffer.chomp)
buffer = buffer.gsub!(@anchorString, "")
end
# 既存行の末尾に Gitbook書式 の anchor を追加する
if @level1.match(buffer)
buffer = buffer.chomp.strip
new_line = "#{buffer} {##{URI.escape(buffer.slice(2..-1))}}\n"
dist.write(new_line)
elsif @level2.match(buffer)
buffer = buffer.chomp.strip
new_line = "#{buffer} {##{URI.escape(buffer.slice(3..-1))}}\n"
dist.write(new_line)
elsif @level3.match(buffer)
buffer = buffer.chomp.strip
new_line = "#{buffer} {##{URI.escape(buffer.slice(4..-1))}}\n"
dist.write(new_line)
else
dist.write(buffer)
end
}
}
}
FileUtils.rm(fname + ".bak") unless @backup
end
}
@satour
Copy link
Author

satour commented Jan 8, 2019

TODO

  • - 行末に付与するアンカー用の文字列をURIエンコードする
  • - 行末にスペースが入っていた場合、削除してからアンカー用の文字列を作成するようにする

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment