• Stars
    star
    2,377
  • Rank 19,355 (Top 0.4 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 5 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A fast and flexible Markdown parser written in Swift.

โ€œ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!

More Repositories

1

Publish

A static site generator for Swift developers
Swift
4,840
star
2

SwiftTips

A collection of Swift tips & tricks that I've shared on Twitter
3,971
star
3

Files

A nicer way to handle files & folders in Swift
Swift
2,456
star
4

Plot

A DSL for writing type-safe HTML, XML and RSS in Swift.
Swift
1,979
star
5

Unbox

[Deprecated] The easy to use Swift JSON decoder
Swift
1,956
star
6

Marathon

[DEPRECATED] Marathon makes it easy to write, run and manage your Swift scripts ๐Ÿƒ
Swift
1,863
star
7

ImagineEngine

A project to create a blazingly fast Swift game engine that is a joy to use ๐Ÿš€
Swift
1,825
star
8

SwiftPlate

Easily generate cross platform Swift framework projects from the command line
Swift
1,766
star
9

Splash

A fast, lightweight and flexible Swift syntax highlighter for blogs, tools and fun!
Swift
1,758
star
10

TestDrive

Quickly try out any Swift pod or framework in a playground
Swift
1,597
star
11

Codextended

Extensions giving Swift's Codable API type inference super powers ๐Ÿฆธโ€โ™‚๏ธ๐Ÿฆนโ€โ™€๏ธ
Swift
1,495
star
12

ShellOut

Easily run shell commands from a Swift script or command line tool
Swift
836
star
13

Wrap

[DEPRECATED] The easy to use Swift JSON encoder
Swift
732
star
14

CollectionConcurrencyKit

Async and concurrent versions of Swiftโ€™s forEach, map, flatMap, and compactMap APIs.
Swift
730
star
15

Sweep

Fast and powerful Swift string scanning made simple
Swift
531
star
16

Playground

Instantly create Swift playgrounds from the command line
Swift
439
star
17

Require

Require optional values to be non-nil, or crash gracefully
Swift
414
star
18

XcodeTheme

My Xcode theme - Sundell's Colors
Swift
408
star
19

AsyncCompatibilityKit

iOS 13-compatible backports of commonly used async/await-based system APIs that are only available from iOS 15 by default.
Swift
378
star
20

Shapeshift

Quickly convert a folder containing Swift files into an iPad-compatible Playground
Swift
338
star
21

Identity

๐Ÿ†” Type-safe identifiers in Swift
Swift
298
star
22

SwiftBySundell

Code samples from the Swift by Sundell website & podcast
Swift
289
star
23

SwiftScripting

A list of Swift scripting tools, frameworks & examples
235
star
24

SuperSpriteKit

Extensions to Apple's SpriteKit game engine
Objective-C
224
star
25

Flow

Operation Oriented Programming in Swift
Swift
217
star
26

Xgen

A Swift package for generating Xcode workspaces & playgrounds
Swift
189
star
27

IndieSupportWeeks

A two-week effort to help support indie developers shipping apps on Apple's platforms who have been financially impacted by the COVID-19 pandemic.
182
star
28

CGOperators

Easily manipulate CGPoints, CGSizes and CGVectors using math operators
Swift
148
star
29

Animate

Declarative UIView animations without nested closures
Swift
129
star
30

SplashPublishPlugin

A Splash plugin for the Publish static site generator
Swift
92
star
31

Assert

A collection of convenient assertions for Swift testing
Swift
69
star
32

UITestingExample

Example code from my blog post about UI testing
Swift
67
star
33

Marathon-Examples

A collection of example Swift scripts that can easily be run using Marathon
Swift
55
star
34

Releases

A Swift package for resolving released versions from a Git repository
Swift
51
star
35

BlockSnippets

Xcode snippets that are very handy when working with blocks in various contexts
51
star
36

PlotPlayground

A Swift playground that comes pre-loaded with Plot, that can be used to explore the new component API.
Swift
49
star
37

SwiftKit

A collection of Swift utilities that I share across my Swift-based projects
Swift
38
star
38

UnitTestingWorkshop

Project used during my workshop "Getting started with unit testing in Swift"
Swift
36
star
39

JSUpdateLookup

A lightweight, easy to use Objective-C class to check if your iOS app has an update available
Objective-C
28
star
40

SwiftAveiro

Skeleton project for my Swift Aveiro workshop "Everyone is an API designer"
Swift
15
star
41

CloudKitChat

A demo chat application powered by CloudKit
Objective-C
14
star
42

swiftbysundell-beta-feedback

Submit your feedback on the Swift by Sundell 2.0 beta
9
star
43

JSGeometry

A set of utility functions that enables easy one-line manipulation of CoreGraphics geometry structs like CGPoint, CGSize & CGRect.
Objective-C
6
star
44

JSAutoCopy

An Objective-C category that enables automatic copying of any object
Objective-C
4
star
45

UnboxDemoPlayground

A Swift Playground that comes setup with Unbox & Wrap, used in my CocoaHeads Stockholm presentation
Swift
3
star
46

JSAutoEncodedObject

Automatically encode or decode any Objective-C object
Objective-C
3
star
47

JSLocalization

An Objective-C class that enables dynamic localization of an iOS app.
Objective-C
3
star
48

MarathonTestScriptWithDependencies

A test script with dependencies - used for Marathon's tests
Swift
2
star
49

JSObservableObject

Easily add protocol-based observation to any Objective-C class
Objective-C
2
star
50

MarathonTestScript

A Swift script that's used in Marathon's tests
Swift
1
star
51

MarathonTestPackage

A Swift package that's used in Marathon's tests
Swift
1
star