Last active
December 25, 2015 16:59
-
-
Save pyro2927/7010361 to your computer and use it in GitHub Desktop.
Generate table of contents from 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
#!/usr/bin/env ruby | |
# sanity checks | |
if ARGV.count == 0 | |
puts "You must provide a file name" | |
return | |
elsif File.exist?(ARGV.first) == false | |
puts "That file doesn't exist" | |
return | |
end | |
toc = Array.new | |
toc << "## Table of Contents" | |
File.open(ARGV.first).each do |line| | |
if line.start_with? "##" | |
# count number of lines, figure out how many leading paces we need | |
# four spaces for each hash after the second | |
spaces = " " * (line.split(" ").first.count("#") - 2) * 4 | |
title = line.split(" ") | |
title.shift | |
# links are the title, downcased, and spaces replaced with hyphens | |
link = title.map {|w| w.downcase } .join("-") | |
toc << "#{spaces}* [#{title.join(" ")}](##{link})" | |
end | |
end | |
puts toc.join("\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Easy way to use on OS X
./toc.rb <FILENAME> | pbcopy
Then paste wherever you please