Created
April 9, 2012 12:58
-
-
Save codeincontext/2343241 to your computer and use it in GitHub Desktop.
Print the headers from a markdown document into 1.2.3 format
This file contains hidden or 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
| file = '/Users/skattyadz/Dropbox/PlainText/FYP.txt' | |
| toc = '' | |
| number_stack = [0] | |
| File.readlines(file).each do |line| | |
| if line[0] == '#' | |
| hash_count = line.count('#') | |
| if hash_count > number_stack.length | |
| # down a level | |
| number_stack << 1 | |
| else | |
| if hash_count < number_stack.length | |
| # up a level | |
| levels_up = number_stack.length - hash_count | |
| levels_up.times do | |
| number_stack.pop | |
| end | |
| end | |
| subheader_number = number_stack.pop + 1 | |
| number_stack << subheader_number | |
| end | |
| spacing = if hash_count == 1 | |
| "\n" | |
| else | |
| "\t" * (hash_count - 1) | |
| end | |
| header_number = number_stack * '.' | |
| line_without_hashes = line.delete! '#' | |
| toc << spacing + '- ' + header_number + line_without_hashes | |
| end | |
| end | |
| puts toc |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output (markdown)