Markdown to create pages and table of contents?

后端 未结 30 2648
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-12 08:49

I started to use markdown to take notes.

I use marked to view my markdown notes and its beautiful.

But as my notes get longer I find it diff

30条回答
  •  攒了一身酷
    2020-12-12 09:18

    Based on albertodebortoli answer created the function with additional checks and substitution of punctuation marks.

    # @fn       def generate_table_of_contents markdown # {{{
    # @brief    Generates table of contents for given markdown text
    #
    # @param    [String]  markdown Markdown string e.g. File.read('README.md')
    #
    # @return   [String]  Table of content in markdown format.
    #
    def generate_table_of_contents markdown
      table_of_contents = ""
      i_section = 0
      # to track markdown code sections, because e.g. ruby comments also start with #
      inside_code_section = false
      markdown.each_line do |line|
        inside_code_section = !inside_code_section if line.start_with?('```')
    
        forbidden_words = ['Table of contents', 'define', 'pragma']
        next if !line.start_with?('#') || inside_code_section || forbidden_words.any? { |w| line =~ /#{w}/ }
    
        title = line.gsub("#", "").strip
        href = title.gsub(/(^[!.?:\(\)]+|[!.?:\(\)]+$)/, '').gsub(/[!.,?:; \(\)-]+/, "-").downcase
    
        bullet = line.count("#") > 1 ? " *" : "#{i_section += 1}."
        table_of_contents << "  " * (line.count("#") - 1) + "#{bullet} [#{title}](\##{href})\n"
      end
      table_of_contents
    end
    

提交回复
热议问题