Skip to content

Instantly share code, notes, and snippets.

@pyro2927
Last active December 25, 2015 16:59
Show Gist options
  • Save pyro2927/7010361 to your computer and use it in GitHub Desktop.
Save pyro2927/7010361 to your computer and use it in GitHub Desktop.
Generate table of contents from Markdown file
#!/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")
@pyro2927
Copy link
Author

Easy way to use on OS X
./toc.rb <FILENAME> | pbcopy
Then paste wherever you please

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