Last active
February 12, 2016 14:21
-
-
Save dmigous/c4b17eddcba410f6df11 to your computer and use it in GitHub Desktop.
Ruby script that maybe used in rake task to add Table Of Contents section into Markdown file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @fn def generate_table_of_contents markdown # {{{ | |
# @brief Generates table of contents for given markdown text | |
# | |
# @param [String] markdown Markdown string e.g. File.read('README.md') | |
# | |
# @return [String] Table of content in markdown format. | |
# | |
def generate_table_of_contents markdown | |
table_of_contents = "" | |
i_section = 0 | |
# to track markdown code sections, because e.g. ruby comments also start with # | |
inside_code_section = false | |
markdown.each_line do |line| | |
inside_code_section = !inside_code_section if line.start_with?('```') | |
forbidden_words = ['Table of contents', 'define', 'pragma'] | |
next if !line.start_with?('#') || inside_code_section || forbidden_words.any? { |w| line =~ /#{w}/ } | |
title = line.gsub("#", "").strip | |
href = title.gsub(/(^[!.?:\(\)]+|[!.?:\(\)]+$)/, '').gsub(/[!.,?:; \(\)-]+/, "-").downcase | |
bullet = line.count("#") > 1 ? " *" : "#{i_section += 1}." | |
table_of_contents << " " * (line.count("#") - 1) + "#{bullet} [#{title}](\##{href})\n" | |
end | |
table_of_contents | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment