vbasortingms-wordmarkdowneditor

How to sort sections of markdown by heading?


Given a large markdown file with a structure like:

# Main

## Sub main Z
### Title Z
Content Z
### Title B
Content B

## Sub main A
### Title A
Content A

How would one sort its sections so that they are in alphabetical order by heading?

# Main

## Sub main A
### Title A
Content A

## Sub main Z
### Title B
Content B
### Title Z
Content Z

Solution

  • I tried to use pandoc, but in step from AST to markdown was lost many formatting like new line and etc.

    I found another way to do that. We need only MS Word.

    1. Open markdown file thought Word
    2. Create new macro with the next code. We find all headers (#) and apply style Title 1, Title 2 and so on. Change the name of style for you.
    Sub insertStyleHeaders()
        Dim hashCount As Integer
        Dim styleStr As String
        
        Set oRng = ActiveDocument.Range
        With oRng.Find
            .text = "#"
            While .Execute
                oRng.MoveEnd wdParagraph
                If InStr(oRng.text, "# ") Then
                    hashCount = Len(oRng.text) - Len(Replace(oRng.text, "#", ""))
                    styleStr = "Title " + CStr(hashCount)
                    oRng.Select
                    oRng.Style = ActiveDocument.Styles(styleStr)
                End If
                oRng.Collapse wdCollapseEnd
            Wend
        End With
    End Sub
    
    1. After run macros, right mouse click to: Expand/Collapse -> Collapse All Headings
    2. Now we have next doc. You need to select by mouse group of items and call sort by headings.

    enter image description here enter image description here

    1. After end of sort, select all doc (Ctrl + A) and apply plain text/default style in order to remove header styles.
    2. And last, use ruler to shift indents and save file.

    enter image description here