Convert Figma logo to code with AI

JohnSundell logoInk

A fast and flexible Markdown parser written in Swift.

2,383
194
2,383
20

Top Related Projects

5,853

Determines which markup library to use to render a content file (e.g. README) on GitHub

12,482

Static site generator that supports Markdown and reST syntax. Powered by Python.

75,317

The world’s fastest framework for building websites.

48,920

:globe_with_meridians: Jekyll is a blog-aware static site generator in Ruby

16,839

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.

13,601

A fast static site generator in a single binary with everything built-in. https://www.getzola.org

Quick Overview

Ink is a lightweight and flexible Markdown parsing and rendering library for Swift. It provides a simple API for converting Markdown to HTML, with support for custom parsing and rendering rules. Ink is designed to be fast, efficient, and easy to integrate into Swift projects.

Pros

  • Fast and lightweight, with minimal dependencies
  • Customizable parsing and rendering rules
  • Supports CommonMark syntax and GitHub Flavored Markdown
  • Easy to integrate into Swift projects

Cons

  • Limited built-in support for advanced Markdown features
  • May require additional customization for complex use cases
  • Not as feature-rich as some other Markdown libraries
  • Limited documentation compared to more established libraries

Code Examples

  1. Basic Markdown to HTML conversion:
import Ink

let markdown = "# Hello, world!"
let parser = MarkdownParser()
let result = parser.html(from: markdown)
print(result) // Outputs: <h1>Hello, world!</h1>
  1. Custom parsing rule:
import Ink

let parser = MarkdownParser(modifiers: [
    Modifier(target: .codeBlocks) { html, _ in
        return "<pre><code>\(html)</code></pre>"
    }
])

let markdown = "```\nprint(\"Hello, world!\")\n```"
let result = parser.html(from: markdown)
print(result) // Outputs: <pre><code>print("Hello, world!")</code></pre>
  1. Extracting metadata from Markdown:
import Ink

let markdown = """
---
title: My Article
author: John Doe
---
# Article content
"""

let parser = MarkdownParser()
let result = parser.parse(markdown)

print(result.metadata["title"]) // Outputs: Optional("My Article")
print(result.metadata["author"]) // Outputs: Optional("John Doe")
print(result.html) // Outputs: <h1>Article content</h1>

Getting Started

To use Ink in your Swift project, follow these steps:

  1. Add Ink as a dependency in your Package.swift file:
dependencies: [
    .package(url: "https://github.com/JohnSundell/Ink.git", from: "0.5.0")
]
  1. Import Ink in your Swift file:
import Ink
  1. Create a MarkdownParser instance and use it to convert Markdown to HTML:
let parser = MarkdownParser()
let markdown = "# Hello, Ink!"
let html = parser.html(from: markdown)
print(html) // Outputs: <h1>Hello, Ink!</h1>

Competitor Comparisons

5,853

Determines which markup library to use to render a content file (e.g. README) on GitHub

Pros of Markup

  • Supports multiple markup languages (Markdown, reStructuredText, textile, etc.)
  • Integrates well with GitHub's ecosystem and rendering pipeline
  • Actively maintained by GitHub with regular updates

Cons of Markup

  • More complex setup and usage compared to Ink
  • Heavier dependency footprint
  • Primarily designed for GitHub's specific use cases

Code Comparison

Markup (Ruby):

GitHub::Markup.render('README.md', File.read('README.md'))

Ink (Swift):

try Ink(markdown: "# Hello").html()

Summary

Markup is a versatile tool supporting multiple markup languages, making it ideal for GitHub's diverse ecosystem. However, it comes with a more complex setup and heavier dependencies. Ink, on the other hand, focuses solely on Markdown, offering a simpler, lightweight solution with easy integration into Swift projects. Markup's Ruby-based implementation contrasts with Ink's Swift code, reflecting their different target environments and use cases.

12,482

Static site generator that supports Markdown and reST syntax. Powered by Python.

Pros of Pelican

  • More mature and feature-rich, with a larger ecosystem of themes and plugins
  • Supports multiple content formats (Markdown, reStructuredText, AsciiDoc)
  • Built-in internationalization support for multilingual sites

Cons of Pelican

  • Steeper learning curve, especially for users new to Python
  • Slower build times for large sites compared to Ink
  • More complex configuration and setup process

Code Comparison

Pelican (Python):

from pelican import Pelican
from pelican.settings import read_settings

settings = read_settings('pelicanconf.py')
pelican = Pelican(settings)
pelican.run()

Ink (Swift):

import Ink

let markdown = "# Hello, world!"
let parser = MarkdownParser()
let html = parser.html(from: markdown)

Summary

Pelican is a more comprehensive static site generator with a wider range of features and customization options. It's well-suited for complex projects and multilingual sites. Ink, on the other hand, is a lightweight Markdown parser and HTML generator, offering simplicity and speed for Swift developers. Pelican requires more setup but provides greater flexibility, while Ink focuses on quick and easy Markdown processing within Swift applications.

75,317

The world’s fastest framework for building websites.

Pros of Hugo

  • More feature-rich and mature static site generator
  • Extensive theme ecosystem and community support
  • Faster build times for large sites

Cons of Hugo

  • Steeper learning curve, especially for non-technical users
  • More complex configuration and setup process
  • Requires Go installation for local development

Code Comparison

Ink (Swift):

struct Article: Codable {
    let title: String
    let content: String
    let date: Date
}

Hugo (Go):

type Page struct {
    Title   string    `json:"title"`
    Content string    `json:"content"`
    Date    time.Time `json:"date"`
}

Summary

Hugo is a more powerful and feature-rich static site generator compared to Ink. It offers faster build times, extensive theming options, and strong community support. However, Hugo has a steeper learning curve and requires more setup. Ink, being Swift-based, is simpler and more accessible for iOS developers but lacks the advanced features and ecosystem of Hugo. The code comparison shows similar structure for content types in both projects, with Hugo using Go and Ink using Swift.

48,920

:globe_with_meridians: Jekyll is a blog-aware static site generator in Ruby

Pros of Jekyll

  • Mature and widely adopted static site generator with a large community
  • Extensive plugin ecosystem for added functionality
  • Built-in support for GitHub Pages, making deployment seamless

Cons of Jekyll

  • Requires Ruby knowledge for advanced customization
  • Can be slower for large sites due to its build process
  • Less flexible for non-blog content types compared to modern alternatives

Code Comparison

Jekyll (Liquid templating):

{% for post in site.posts %}
  <h2>{{ post.title }}</h2>
  <p>{{ post.excerpt }}</p>
{% endfor %}

Ink (Swift):

for page in site.pages {
    HTML(
        .h2(.text(page.title)),
        .p(.text(page.body))
    )
}

Jekyll uses Liquid templating language, which is easy to learn but less powerful than Swift. Ink leverages Swift's type safety and expressiveness, allowing for more complex logic in templates. However, Jekyll's approach may be more accessible to non-programmers.

Both projects serve different needs: Jekyll is a full-featured static site generator, while Ink is a lightweight Swift-based templating engine. Jekyll is better suited for traditional websites and blogs, whereas Ink is ideal for Swift developers looking for a flexible, type-safe templating solution.

16,839

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.

Pros of Eleventy

  • More flexible with multiple templating languages supported
  • Larger community and ecosystem
  • Better suited for complex, multi-page websites

Cons of Eleventy

  • Steeper learning curve
  • More configuration required
  • Potentially slower build times for large sites

Code Comparison

Ink (Swift):

struct MyWebsite: Website {
    var url = URL(string: "https://mywebsite.com")!
    var name = "My Website"
    var description = "A website built using Ink"
    var language: Language { .english }
    var imagePath: Path? { "images/icon.png" }
}

Eleventy (JavaScript):

module.exports = function(eleventyConfig) {
  return {
    dir: {
      input: "src",
      output: "dist"
    }
  };
};

The code snippets show basic configuration for both static site generators. Ink uses a Swift struct to define website properties, while Eleventy uses a JavaScript configuration file to set input and output directories.

Eleventy offers more flexibility in terms of templating languages and configuration options, making it suitable for complex projects. However, this flexibility comes at the cost of a steeper learning curve and potentially more setup time.

Ink, being Swift-based, provides a more streamlined experience for iOS and macOS developers, but may be less versatile for web-focused projects.

13,601

A fast static site generator in a single binary with everything built-in. https://www.getzola.org

Pros of Zola

  • Written in Rust, offering better performance and memory safety
  • Supports more advanced features like taxonomies and multilingual sites
  • Has a built-in search functionality and live reload for development

Cons of Zola

  • Steeper learning curve due to more complex configuration options
  • Less flexible for custom build processes or integrations
  • Requires Rust installation for building from source

Code Comparison

Zola (config.toml):

base_url = "https://example.com"
title = "My Site"
compile_sass = true
build_search_index = true

Ink (main.swift):

try Publish(using: [
    .addMarkdownFiles(),
    .generateHTML(withTheme: .foundation),
    .generateRSSFeed(including: [.posts]),
    .generateSiteMap()
]).deploy(using: .gitHub("username/repo"))

Both Zola and Ink are static site generators, but they cater to different user preferences. Zola offers more built-in features and performance benefits, while Ink provides a simpler, Swift-based approach that may be more appealing to iOS and macOS developers. The choice between them depends on the specific project requirements and the developer's familiarity with Rust or Swift ecosystems.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

“Ink”

Swift Package Manager Mac + Linux Twitter: @johnsundell

Welcome to Ink, a fast and flexible Markdown parser written in Swift. It can be used to convert Markdown-formatted strings into HTML, and also supports metadata parsing, as well as powerful customization options for fine-grained post-processing. It was built with a focus on Swift-based web development and other HTML-centered workflows.

Ink is used to render all articles on swiftbysundell.com.

Converting Markdown into HTML

To get started with Ink, all you have to do is to import it, and use its MarkdownParser type to convert any Markdown string into efficiently rendered HTML:

import Ink

let markdown: String = ...
let parser = MarkdownParser()
let html = parser.html(from: markdown)

That’s it! The resulting HTML can then be displayed as-is, or embedded into some other context — and if that’s all you need Ink for, then no more code is required.

Automatic metadata parsing

Ink also comes with metadata support built-in, meaning that you can define key/value pairs at the top of any Markdown document, which will then be automatically parsed into a Swift dictionary.

To take advantage of that feature, call the parse method on MarkdownParser, which gives you a Markdown value that both contains any metadata found within the parsed Markdown string, as well as its HTML representation:

let markdown: String = ...
let parser = MarkdownParser()
let result = parser.parse(markdown)

let dateString = result.metadata["date"]
let html = result.html

To define metadata values within a Markdown document, use the following syntax:

---
keyA: valueA
keyB: valueB
---

Markdown text...

The above format is also supported by many different Markdown editors and other tools, even though it’s not part of the original Markdown spec.

Powerful customization

Besides its built-in parsing rules, which aims to cover the most common features found in the various flavors of Markdown, you can also customize how Ink performs its parsing through the use of modifiers.

A modifier is defined using the Modifier type, and is associated with a given Target, which determines the kind of Markdown fragments that it will be used for. For example, here’s how an H3 tag could be added before each code block:

var parser = MarkdownParser()

let modifier = Modifier(target: .codeBlocks) { html, markdown in
    return "<h3>This is a code block:</h3>" + html
}

parser.addModifier(modifier)

let markdown: String = ...
let html = parser.html(from: markdown)

Modifiers are passed both the HTML that Ink generated for the given fragment, and its raw Markdown representation as well — both of which can be used to determine how each fragment should be customized.

Performance built-in

Ink was designed to be as fast and efficient as possible, to enable hundreds of full-length Markdown articles to be parsed in a matter of seconds, while still offering a fully customizable API as well. Two key characteristics make this possible:

  1. Ink aims to get as close to O(N) complexity as possible, by minimizing the amount of times it needs to read the Markdown strings that are passed to it, and by optimizing its HTML rendering to be completely linear. While true O(N) complexity is impossible to achieve when it comes to Markdown parsing, because of its very flexible syntax, the goal is to come as close to that target as possible.
  2. A high degree of memory efficiency is achieved thanks to Swift’s powerful String API, which Ink makes full use of — by using string indexes, ranges and substrings, rather than performing unnecessary string copying between its various operations.

System requirements

To be able to successfully use Ink, make sure that your system has Swift version 5.2 (or later) installed. If you’re using a Mac, also make sure that xcode-select is pointed at an Xcode installation that includes the required version of Swift, and that you’re running macOS Catalina (10.15) or later.

Please note that Ink does not officially support any form of beta software, including beta versions of Xcode and macOS, or unreleased versions of Swift.

Installation

Ink is distributed using the Swift Package Manager. To install it into a project, simply add it as a dependency within your Package.swift manifest:

let package = Package(
    ...
    dependencies: [
        .package(url: "https://github.com/johnsundell/ink.git", from: "0.1.0")
    ],
    ...
)

Then import Ink wherever you’d like to use it:

import Ink

For more information on how to use the Swift Package Manager, check out this article, or its official documentation.

Command line tool

Ink also ships with a simple but useful command line tool that lets you convert Markdown to HTML directly from the command line.

To install it, clone the project and run make:

$ git clone https://github.com/johnsundell/Ink.git
$ cd Ink
$ make

The command line tool will be installed as ink, and can be passed Markdown text for conversion into HTML in several ways.

Calling it without arguments will start reading from stdin until terminated with Ctrl+D:

$ ink

Markdown text can be piped in when ink is called without arguments:

$ echo "*Hello World*" | ink

A single argument is treated as a filename, and the corresponding file will be parsed:

$ ink file.md

A Markdown string can be passed directly using the -m or --markdown flag:

$ ink -m "*Hello World*"

You can of course also build your own command line tools that utilizes Ink in more advanced ways by importing it as a package.

Markdown syntax supported

Ink supports the following Markdown features:

  • Headings (H1 - H6), using leading pound signs, for example ## H2.
  • Italic text, by surrounding a piece of text with either an asterisk (*), or an underscore (_). For example *Italic text*.
  • Bold text, by surrounding a piece of text with either two asterisks (**), or two underscores (__). For example **Bold text**.
  • Text strikethrough, by surrounding a piece of text with two tildes (~~), for example ~~Strikethrough text~~.
  • Inline code, marked with a backtick on either site of the code.
  • Code blocks, marked with three or more backticks both above and below the block.
  • Links, using the following syntax: [Title](url).
  • Images, using the following syntax: ![Alt text](image-url).
  • Both images and links can also use reference URLs, which can be defined anywhere in a Markdown document using this syntax: [referenceName]: url.
  • Both ordered lists (using numbers followed by a period (.) or right parenthesis ()) as bullets) and unordered lists (using either a dash (-), plus (+), or asterisk (*) as bullets) are supported.
  • Ordered lists start from the index of the first entry
  • Nested lists are supported as well, by indenting any part of a list that should be nested within its parent.
  • Horizontal lines can be placed using either three asterisks (***) or three dashes (---) on a new line.
  • HTML can be inlined both at the root level, and within text paragraphs.
  • Blockquotes can be created by placing a greater-than arrow at the start of a line, like this: > This is a blockquote.
  • Tables can be created using the following syntax (the line consisting of dashes (-) can be omitted to create a table without a header row):
| Header | Header 2 |
| ------ | -------- |
| Row 1  | Cell 1   |
| Row 2  | Cell 2   |

Please note that, being a very young implementation, Ink does not fully support all Markdown specs, such as CommonMark. Ink definitely aims to cover as much ground as possible, and to include support for the most commonly used Markdown features, but if complete CommonMark compatibility is what you’re looking for — then you might want to check out tools like CMark.

Internal architecture

Ink uses a highly modular rule-based internal architecture, to enable new rules and formatting options to be added without impacting the system as a whole.

Each Markdown fragment is individually parsed and rendered by a type conforming to the internal Readable and HTMLConvertible protocols — such as FormattedText, List, and Image.

To parse a part of a Markdown document, each fragment type uses a Reader instance to read the Markdown string, and to make assertions about its structure. Errors are used as control flow to signal whether a parsing operation was successful or not, which in turn enables the parent context to decide whether to advance the current Reader instance, or whether to rewind it.

A good place to start exploring Ink’s implementation is to look at the main MarkdownParser type’s parse method, and to then dive deeper into the various Fragment implementations, and the Reader type.

Credits

Ink was originally written by John Sundell as part of the Publish suite of static site generation tools, which is used to build and generate Swift by Sundell. The other tools that make up the Publish suite will also be open sourced soon.

The Markdown format was created by John Gruber. You can find more information about it here.

Contributions and support

Ink is developed completely in the open, and your contributions are more than welcome.

Before you start using Ink in any of your projects, it’s highly recommended that you spend a few minutes familiarizing yourself with its documentation and internal implementation, so that you’ll be ready to tackle any issues or edge cases that you might encounter.

Since this is a very young project, it’s likely to have many limitations and missing features, which is something that can really only be discovered and addressed as more people start using it. While Ink is used in production to render all of Swift by Sundell, it’s recommended that you first try it out for your specific use case, to make sure it supports the features that you need.

This project does not come with GitHub Issues-based support, and users are instead encouraged to become active participants in its continued development — by fixing any bugs that they encounter, or by improving the documentation wherever it’s found to be lacking.

If you wish to make a change, open a Pull Request — even if it just contains a draft of the changes you’re planning, or a test that reproduces an issue — and we can discuss it further from there.

Hope you’ll enjoy using Ink!