Skip to content

Instantly share code, notes, and snippets.

@ykst
Created November 4, 2013 02:10
Show Gist options
  • Save ykst/7297120 to your computer and use it in GitHub Desktop.
Save ykst/7297120 to your computer and use it in GitHub Desktop.
Generate markdown TOC for [Qiita](http://qiita.com/)
module Main where
import System.Environment (getArgs)
main = getArgs >>= \(f:_) -> readFile f >>= putStrLn . fromString
fromString = unlines . reverse . tocStr . lines
tocStr input = tocStr' input (repeat 0) []
where
tocStr' [] _ rs = rs
tocStr' (l:ls) counts rs
| marks == 0 = tocStr' ls counts rs
| otherwise = let title = drop marks l in
tocStr' ls (upd marks counts) (concat [ replicate (marks - 1) ' ', "- [", title, "](#",show marks, "-", show ((counts !! marks) + 1), ")"]:rs)
where
marks = length (takeWhile ('#' ==) l)
upd m cs = let (a, (b:bs)) = splitAt m cs in a ++ ((b+1):bs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment