Skip to content

Instantly share code, notes, and snippets.

@leesei
Forked from pyro2927/toc.rb
Last active November 1, 2017 10:04
Show Gist options
  • Save leesei/7194859 to your computer and use it in GitHub Desktop.
Save leesei/7194859 to your computer and use it in GitHub Desktop.
#ruby #markdown Generate TOC for 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("#") - 1) * 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