Zum Inhalt

mdtab

Blog --- mdtab


Created: 2024-05-28

mdtab - a small tool to create markdown tables in Vim

:.!mdtab 2 5

Will create inside Vim a markdown table with 2 columns and 5 rows.

The final formatting of the table is done with help of the tabular Plugin: https://github.com/godlygeek/tabular and this mapping:

nmap __ }v{:Tab /<bar><cr>}

mdtab is written in Golang:

package main

import (
    "fmt"
    "os"
    "strconv"
    "strings"
)

func generateMarkdownTable(columns, rows int) string {
    if columns <= 0 || rows <= 0 {
        return "The number of columns and rows must be greater than 0."
    }

    var builder strings.Builder

    // header
    for i := 1; i <= columns; i++ {
        // builder.WriteString(fmt.Sprintf("| Header%d ", i))
        builder.WriteString(fmt.Sprintf("|  "))
    }
    builder.WriteString("|\n")

    // separator
    for i := 1; i <= columns; i++ {
        builder.WriteString("|---")
    }
    builder.WriteString("|\n")

    // rows
    for r := 1; r <= rows; r++ {
        for c := 1; c <= columns; c++ {
            // builder.WriteString(fmt.Sprintf("| Row%dCol%d ", r, c))
            builder.WriteString(fmt.Sprintf("|  "))
        }
        builder.WriteString("|\n")
    }

    return builder.String()
}

func main() {
    if len(os.Args) != 3 {
        fmt.Println("Usage: go run main.go <number of columns> <number of rows>")
        return
    }

    columns, err := strconv.Atoi(os.Args[1])
    if err != nil {
        fmt.Println("Invalid number of columns:", os.Args[1])
        return
    }

    rows, err := strconv.Atoi(os.Args[2])
    if err != nil {
        fmt.Println("Invalid number of rows:", os.Args[2])
        return
    }

    table := generateMarkdownTable(columns, rows)
    fmt.Println(table)
}

You can pipe the output also to your clipboard:

mdtab 2 5 | pbcopy