Metadata-Version: 2.1
Name: keymap-drawer
Version: 0.15.0
Summary: A module and CLI tool to help parse and draw keyboard layouts.
Home-page: https://github.com/caksoylar/keymap-drawer
License: MIT
Author: Cem Aksoylar
Author-email: caksoylar@gmail.com
Requires-Python: >=3.10,<4.0
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Requires-Dist: pcpp (>=1.30,<2.0)
Requires-Dist: platformdirs (>=3.5.1,<4.0.0)
Requires-Dist: pydantic (>=2.0.0,<3.0.0)
Requires-Dist: pydantic-settings (>=2.2.1,<3.0.0)
Requires-Dist: pyparsing (>=3.0.9,<4.0.0)
Requires-Dist: pyyaml (>=6.0,<7.0)
Project-URL: Bug Tracker, https://github.com/caksoylar/keymap-drawer/issues
Project-URL: Repository, https://github.com/caksoylar/keymap-drawer
Project-URL: Release Notes, https://github.com/caksoylar/keymap-drawer/releases
Description-Content-Type: text/markdown

# ![keymap-drawer](/site/logo_light.svg)

[![PyPI version](https://img.shields.io/pypi/v/keymap-drawer.svg)](https://pypi.org/project/keymap-drawer/)

Parse QMK & ZMK keymaps and draw them in vector graphics (SVG) format, with support for visualizing hold-taps and combos that are commonly used with smaller keyboards.

Available as a [command-line tool](#command-line-tool-installation) or a [web application](https://caksoylar.github.io/keymap-drawer).

[![Example keymap](https://caksoylar.github.io/keymap-drawer/showcase.svg)](examples/showcase.yaml)

## Features

- Draw keymap representations consisting of multiple layers, hold-tap keys and combos
  - Uses a human-editable YAML format for specifying the keymap
  - Non-adjacent or 3+ key combos can be visualized by specifying its positioning relative to the keys, with automatically drawn dendrons to keys
  - Alternatively, output a separate diagram per combo if you have tricky key position combinations
- Bootstrap the YAML representation by automatically parsing QMK or ZMK keymap files
- Arbitrary physical keyboard layouts (with rotated keys!) supported, along with parametrized ortho layouts
- Both parsing and drawing are customizable with a config file, see ["Customization" section](#customization)
- Custom glyph support: render custom SVG icons and not just unicode text

See examples in [the live web demo](https://caksoylar.github.io/keymap-drawer) for example inputs and outputs.

Compared to to visual editors like [KLE](http://www.keyboard-layout-editor.com/), `keymap-drawer` takes a more programmatic approach.
It also decouples the physical keyboard layout from the keymap (i.e., layer and combo definitions) and provides the tooling to bootstrap it quickly from existing firmware configuration.

## Usage

### Try it as a web application

You can try the keymap parsing and drawing functionalities with a [Streamlit](https://streamlit.io) web application available at https://caksoylar.github.io/keymap-drawer.
Below instructions mostly apply for the web interface, where subcommands and option flags are mapped to different widgets in the UX.

### Command-line tool installation

The recommended way to install `keymap-drawer` is through [pipx](https://pypa.github.io/pipx/), which sets up an isolated environment and installs the application with a single command:

```sh
pipx install keymap-drawer
```

This will make the `keymap` command available in your `PATH` to use:

```sh
keymap --help
```

Alternatively, you can `pip install keymap-drawer` in a virtual environment or install into your user install directory with `pip install --user keymap-drawer`.
See [the development section](#development) for instructions to install from source.

### Bootstrapping your keymap representation

**`keymap parse`** command helps to parse an existing QMK or ZMK keymap file into the keymap YAML representation the `draw` command uses to generate SVGs.
`-c`/`--columns` is an optional parameter that specifies the total number of columns in the keymap to better reorganize output layers.

- **QMK**: Only json-format keymaps are supported, which can be exported from [QMK Configurator](https://config.qmk.fm/), converted from `keymap.c` via [`qmk c2json`](https://docs.qmk.fm/#/cli_commands?id=qmk-c2json), or from a VIA backup json via [`qmk via2json`](https://docs.qmk.fm/#/cli_commands?id=qmk-via2json):

  ```sh
  # from keymap.c
  qmk c2json ~/qmk_firmware/keyboards/ferris/keymaps/username/keymap.c | keymap parse -c 10 -q - >sweep_keymap.yaml

  # from VIA backup
  qmk via2json -kb ferris/sweep sweep_via_backup.json | keymap parse -c 10 -q - >sweep_keymap.yaml
  ```

  Due to current limitations of the `keymap.json` format, combos and `#define`'d layer names will not be present in the parsing output.
  However you can manually specify layer names using the layer names parameter, e.g. `keymap parse --layer-names Base Sym Nav ...`.

- **ZMK**: `.keymap` files are used for parsing. These will be preprocessed similar to the ZMK build system, so `#define`'s and `#include`s will be expanded.

  ```sh
  keymap parse -c 10 -z ~/zmk-config/config/cradio.keymap >sweep_keymap.yaml
  ```

  Currently combos, hold-taps, mod-morphs, sticky keys and layer names can be determined via parsing.
  For layer names, the value of the `display-name` property will take precedence over the layer's node name if provided.

As an alternative to parsing, you can also check out the [examples](examples/) to find a layout similar to yours to use as a starting point.

### Tweaking the produced keymap representation

While the parsing step aims to create a decent starting point, you will likely want to make certain tweaks to the produced keymap representation.
Please refer to [the keymap schema specification](KEYMAP_SPEC.md) while making changes:

0. (If starting from a QMK keymap) Add combo definitions using key position indices.
1. Tweak the display form of parsed keys, e.g., replacing `&bootloader` with `BOOT`. (See [the customization section](#customization) to modify parser's behavior.)
2. If you have combos between non-adjacent keys or 3+ key positions, add `align` and/or `offset` properties in order to position them better
3. Add or modify `type` specifiers for certain keys, like `"ghost"` for keys optional to the layout

It might be beneficial to start by `draw`'ing the current representation and iterate over these changes, especially for tweaking combo positioning.

> #### ℹ️ Preserving manual modifications
>
> If you need to re-parse a firmware file after it was changed, you can provide the previous parse output that you tweaked to the
> parse command via `keymap parse -b old_keymap.yaml ... >new_keymap.yaml` and the tool will try to preserve your manual tweaks.

### Producing the SVG

Final step is to produce the SVG representation using the **`keymap draw`** command.
However to do that, we need to specify the _physical_ layout of the keyboard, i.e., how many keys there are, where each key is positioned etc.

If you produced your keymap YAML through `keymap parse`, it will have tried to guess the proper layout in the `layout` field of your keymap.
If you like you can tweak the field value according to the [spec](KEYMAP_SPEC.md#layout), then finally call the draw command:

```sh
keymap draw sweep_keymap.yaml >sweep_keymap.ortho.svg
```

And you are done! You can view the output SVG on your browser or use a tool like [CairoSVG](https://cairosvg.org/) or [Inkscape](https://inkscape.org/) to convert to a different format.

> #### ℹ️ Specifying layouts in the CLI
>
> If you like you can override the layout specification on the command line.
> For instance you can provide a QMK keyboard name with `-q`/`--qmk-keyboard` and layout with `-l`/`--qmk-layout`,
> or an ortho layout with `-o`/`--ortho-layout` (using YAML syntax for the value) or `-n`/`--cols-thumbs-notation`.
> See `keymap draw --help` for details.

## Customization

Both parsing and drawing can be customized using a configuration file passed to the `keymap` executable.
This allows you to, for instance, change the default keycode-to-symbol mappings while parsing, or change font sizes, colors etc. while drawing the SVG.

Start by dumping the default configuration settings to a file:

```sh
keymap dump-config >my_config.yaml
```

Then, edit the file to change the settings, referring to [CONFIGURATION.md](CONFIGURATION.md). You can delete from the file the settings you don't want to change.

You can then pass this file to either `draw` and `parse` subcommands with the `-c`/`--config` argument (note the location before the subcommand):

```sh
keymap -c my_config.yaml parse [...] >my_keymap.yaml
keymap -c my_config.yaml draw [...] my_keymap.yaml >my_keymap.svg
```

Since configuration classes are [Pydantic settings](https://docs.pydantic.dev/usage/settings/) they can also be overridden by environment variables with a `KEYMAP_` prefix:

```sh
KEYMAP_raw_binding_map='{"&bootloader": "BOOT"}' keymap parse -z zmk-config/config/cradio.keymap >cradio.yaml
```

Drawing parameters that are specified in the `draw_config` field can also be overridden in [the keymap YAML](KEYMAP_SPEC.md#draw_config).
Using this you can preserve your style customizations along with your keymap in a single file.

## Custom SVG Glyphs

`keymap-drawer` can also use SVG glyphs for legends, in addition to plain or unicode text. The easiest way to do this is
to use the `$$source:id$$` notation [certain `source`s](CONFIGURATION.md#glyph_urls), which will automatically fetch
the SVGs from a given remote `source`, e.g. using `$$mdi:volume-mute$$` will insert the
[mute icon from Material Design Icons](https://pictogrammers.com/library/mdi/icon/volume-mute/).
The following `source` values are currently supported:

- `mdi`: [Pictogrammers Material Design Icons](https://pictogrammers.com/library/mdi/) (use icon name as `id`)
- `mdil`: [Pictogrammers Material Design Icons Light](https://pictogrammers.com/library/mdil/) (use icon name as `id`)
- `material`: [Google Material Symbols](https://fonts.google.com/icons) (use value in "Android" tab as `id`)
- `tabler`: [Tabler Icons](https://tabler.io/icons) ("Outline" style, use icon name as `id`)

Fetched SVGs will be [cached by default](CONFIGURATION.md#use_local_cache) to speed up future runs.

The height of the SVG is bound by the config properties `glyph_{tap,hold,shifted}_size` and width will maintain the aspect ratio.
To allow for customization, glyphs are assigned CSS classes `glyph` and `<glyph_name>`.
SVG glyphs currently cannot be used alongside other text in the same legend field.

Instead of automatically fetching them from remote sources, you can also define custom SVG blocks under `draw_config`.
After a glyph is defined this way it can be used in key fields via the glyph name surrounded by `$$`, e.g. `$$vol_up$$`.
The provided SVG must specify a `viewBox`, given that positional or dimensional properties will be calculated by `keymap-drawer`:

```yaml
draw_config:
  # specify the size to bound the vertical dimension of your glyph, below are defaults
  glyph_tap_size: 14
  glyph_hold_size: 12
  glyph_shifted_size: 10
  glyphs: # mapping of glyph name to be used to svg definition
    vol_up: |
      <svg viewBox="2 3 34 33">
        <path style="stroke: black; fill: black;" d="M23.41,25.25a1,1,0,0,1-.54-1.85,6.21,6.21,0,0,0-.19-10.65,1,1,0,1,1,1-1.73,8.21,8.21,0,0,1,.24,14.06A1,1,0,0,1,23.41,25.25Z"/>
        <path style="stroke: black; fill: black;" d="M25.62,31.18a1,1,0,0,1-.45-1.89A12.44,12.44,0,0,0,25,6.89a1,1,0,1,1,.87-1.8,14.44,14.44,0,0,1,.24,26A1,1,0,0,1,25.62,31.18Z"/>
        <path style="stroke: black; fill: black;" d="M18.33,4,9.07,12h-6a1,1,0,0,0-1,1v9.92a1,1,0,0,0,1,1H8.88l9.46,8.24A1,1,0,0,0,20,31.43V4.72A1,1,0,0,0,18.33,4Z"/>
      </svg>
layers:
  Media:
    - ["", "$$vol_up$$", "", "", ""]
```

## Setting up an automated drawing workflow

If you use a [ZMK config repo](https://zmk.dev/docs/user-setup), you can set up an automated workflow that parses and draws your keymaps, then commits the YAML parse outputs and produced SVGs to your repo.
To do that you can add a new workflow to your repo at `.github/workflows/draw-keymaps.yml` that refers to the reusable `keymap-drawer` [workflow](.github/workflows/draw-zmk.yml):

<!-- prettier-ignore -->
```yaml
# Example for using the keymap-drawer ZMK user config workflow
name: Draw ZMK keymaps
on:
  workflow_dispatch:  # can be triggered manually
  push:               # automatically run on changes to following paths
    paths:
      - "config/*.keymap"
      - "config/*.dtsi"
      - "keymap_drawer.config.yaml"
      # - 'boards/*/*/*.keymap'

jobs:
  draw:
    uses: caksoylar/keymap-drawer/.github/workflows/draw-zmk.yml@main
    permissions:
      contents: write  # allow workflow to commit to the repo
    with:
      keymap_patterns: "config/*.keymap"        # path to the keymaps to parse
      config_path: "keymap_drawer.config.yaml"  # config file, ignored if not exists
      output_folder: "keymap-drawer"            # path to save produced SVG and keymap YAML files
      parse_args: ""  # map of extra args to pass to `keymap parse`, e.g. "corne:'-l Def Lwr Rse' cradio:''"
      draw_args: ""   # map of extra args to pass to `keymap draw`, e.g. "corne:'-k corne_rotated' cradio:'-k paroxysm'"
```

### Modifying the workflow-generated commit

The workflow will add the generated SVG and keymap representation YAML files to the `output_folder`, and generate a new commit with commit message "keymap-drawer render" by default. You can modify this commit message with the `commit_message` input param, e.g.:

```yaml
jobs:
  draw:
    uses: caksoylar/keymap-drawer/.github/workflows/draw-zmk.yml@main
    with:
      # Use the triggering commit's message, prepending the "[Draw]" tag
      commit_message: "[Draw] ${{ github.event.head_commit.message }}"
      # …other inputs
```

Alternatively, you can choose to amend the triggering commit instead of generating a new one by using the `amend_commit: true` option. In this case the triggering commit's message will be used by default, and the `commit_message` input will be ignored. E.g.:

```yaml
jobs:
  draw:
    uses: caksoylar/keymap-drawer/.github/workflows/draw-zmk.yml@main
    with:
      amend_commit: true
      # …other inputs
```

> #### ⚠️ Rewriting history
>
> You should understand the implications of rewriting history if you amend a commit that has already been published. See [remarks](https://git-scm.com/docs/git-rebase#_recovering_from_upstream_rebase) in `git-rebase` documentation.

## Community

Below are a few tools and example usages from the community that might be inspirational, whether they are doing unique things with styling, configuration or legends used, or integrate `keymap-drawer` into other workflows.

- [YellowAfterlife's Vial To Keymap Drawer](https://yal-tools.github.io/vial-to-keymap-drawer/): Parser to convert Vial .vil files to keymap YAMLs
- [minusfive's ZMK config](https://github.com/minusfive/zmk-config): Uses an [extensive config file](https://github.com/minusfive/zmk-config/blob/main/keymap_drawer.config.yaml) for great results out of the automated drawing workflow, with plenty of SVG glyphs
- [SethMilliken's ZMK config](https://github.com/SethMilliken/zmk-config): Another config using the automated workflow with a [nice configuration](https://github.com/SethMilliken/zmk-config/blob/main/keymap_drawer.config.yaml) and SVG glyphs
- [englmaxi's ZMK config](https://github.com/englmaxi/zmk-config): Using key sides setting and CSS tricks to position multiple SVG glyphs in one key
- [jbarr21's `keymap-display`](https://github.com/jbarr21/keymap-display): Uses a [converter script](https://github.com/jbarr21/keymap-display/blob/main/scripts/json2yaml) to convert QMK `keymap.c` to a keymap YAML
- [casuanoob's keymap](https://github.com/casuanoob/zmk-config-bkb): Many useful unicode and SVG glyphs in the [keymap YAML](https://github.com/casuanoob/zmk-config-bkb/blob/master/assets/split34_keymap_zmk.yaml)
- [possumvibes's keymap](https://github.com/possumvibes/keyboard-layout): Separate layer and combo diagrams
- [infused-kim's ZMK config](https://github.com/infused-kim/zmk-config): [Uses the `--base-keymap` feature](https://github.com/infused-kim/zmk-config/blob/chocofi/main/keymap_img/update_keymap_img.sh) to pre-assign held keys and combo positions
- [crides's Fissure write-up](https://github.com/crides/fissure): Custom physical layout with non-square keys and unique SVG styling

If you use `keymap-drawer`, tag your Github repo with the [`keymap-drawer` topic](https://github.com/topics/keymap-drawer) and it will show up for anyone else searching for it!

## Development

This project requires Python 3.10+ and uses [Poetry](https://python-poetry.org/) for packaging.

To get started, [install Poetry](https://python-poetry.org/docs/#installation), clone this repo, then install dependencies with the `poetry` command:

```sh
git clone https://github.com/caksoylar/keymap-drawer.git
cd keymap-drawer
poetry install  # --with dev,lsp optional dependencies
```

`poetry shell` will activate a virtual environment with the `keymap_drawer` module in Python path and `keymap` executable available.
Changes you make in the source code will be reflected when using the module or the command.

If you prefer not to use Poetry, you can get an editable install with `pip install --editable .` inside the `keymap-drawer` folder.

The source code for the Streamlit app lives in the [`keymap-drawer-web`](https://github.com/caksoylar/keymap-drawer-web) repo.

## Related projects

- [@nickcoutsos's ZMK keymap editor](https://github.com/nickcoutsos/keymap-editor)
- [The original `keymap`](https://github.com/callum-oakley/keymap/)
- [@jbarr21's keymap parser](https://github.com/jbarr21/keymap-display)
- [@leiserfg's ZMK parser](https://github.com/leiserfg/zmk-config/tree/master/parser)
- [Keymapviz](https://github.com/yskoht/keymapviz)

# Keymap YAML specification

This page documents the YAML-format keymap representation that is output by `keymap parse` and used by `keymap draw`.

At the root, four fields can be specified which are detailed in respective sections. A typical keymap will have the following structure:

```yaml
layout:      # physical layout specs, optional if used in CLI
  ...
layers:      # ordered mapping of layer name to contents
  layer_1:   # list of (lists of) key specs
    - [Q, W, ...]
    ...
  layer_2:
    ...
combos:      # list of combo specs, optional
  - ...
draw_config: # config overrides for drawing, optional
  - ...
```

## `layout`

This field provides information about the physical layout of the keyboard, i.e., the location and sizes of individual keys.
`keymap-drawer` understands three types of physical layout descriptions, with corresponding sub-fields under the `layout` field.

### QMK `info.json` specification

This is the [official QMK format](https://docs.qmk.fm/#/reference_info_json?id=layout-format) for physical key descriptions
that every `info.json` file in the QMK firmware repository uses. `keymap-drawer` only uses the `x`, `y`, `r`, `rx` and `ry` fields.
Note that `keymap-editor` utilizes [the same format](https://github.com/nickcoutsos/keymap-editor/wiki/Defining-keyboard-layouts) for `info.json`.
QMK spec also lets you specify multiple "layouts" per keyboard corresponding to different layout macros to support physical variations.

Following physical layout parameters can be specified either in the command line or under this field definition as key-value pairs:

- **`qmk_keyboard`** (equivalent to `-k`/`--qmk-keyboard` on the command line):
  Specifies the keyboard name to use with QMK `info.json` format layout definition, retrieved from following sources in order of preference:

  - `<keyboard>.json` (with `/`'s in `<keyboard>` replaced by `@`) under [`resources/qmk_layouts`](/resources/qmk_layouts/), if it exists
  - [QMK keyboard metadata API](https://docs.qmk.fm/#/configurator_architecture?id=keyboard-metadata) that [QMK Configurator](https://config.qmk.fm) also uses

  _Example:_ `layout: {qmk_keyboard: crkbd/rev1}`

- **`qmk_info_json`** (equivalent to `-j`/`--qmk-info-json` on the command line):
  Specifies the path to a local QMK format `info.json` file to use (exclusive with `qmk_keyboard`).

  _Example:_ `layout: {qmk_info_json: my_special_layout.json}`

- **`qmk_layout`** (equivalent to `-l`/`--qmk-layout` on the command line):
  Specifies the layout macro to be used for the QMK keyboard, defaults to first one specified if not used --
  should be used alongside one of the above two options.

  _Example:_ `layout: {qmk_keyboard: crkbd/rev1, qmk_layout: LAYOUT_split_3x5_3}`

**Hint**: You can use the [QMK Configurator](https://config.qmk.fm/) to search for `qmk_keyboard` and `qmk_layout` values, and preview the physical layout.

You can create your own physical layout definitions in QMK format to use with `keymap-drawer`, which accepts JSONs with the official schema that
has layouts listed under the `layout` key, or one that directly consists of a list of key specs as a shortcut. The best way to generate one is to use
the interactive [Keymap Layout Helper tool](https://nickcoutsos.github.io/keymap-layout-tools/) tool by @nickcoutsos. This web app is useful to
visualize a given JSON definition, re-order keys using the "Re-order" tool and generate one from scratch from various formats such as KLE or Kicad
PCBs using the "Import" tool.[^1]

[^1]:
    The behavior of the layout helper and `keymap-drawer` differs for rotated keys when omitting `rx`, `ry` parameters --
    `keymap-drawer` assumes rotation around the key center and layout helper assumes rotation around the top left of the key.
    For this reason it is recommended to explicitly specify `rx`, `ry` fields if `r` is specified. You might also want to omit the fields
    besides `x`, `y`, `r`, `rx` and `ry` in your final JSON since they won't be used by `keymap-drawer`.

### Parametrized ortholinear layout specification

This option lets you specify a set of parameters to automatically generate a split or non-split ortholinear layout.

Following physical layout parameter can be specified either in the command line or under this field definition as a key-value pair:

- **`ortho_layout`** (equivalent to `-o`/`--ortho-layout` on the command line):
  Specifies a mapping of parameters to values to generate an ortholinear physical layout, with schema:

  | field name   | type                     | default value | description                                                                                              |
  | ------------ | ------------------------ | ------------- | -------------------------------------------------------------------------------------------------------- |
  | `split`      | `bool`                   | `False`       | whether the layout is a split keyboard or not, affects a few other options below                         |
  | `rows`       | `int`                    | required      | how many rows are in the keyboard, excluding the thumb row if split                                      |
  | `columns`    | `int`                    | required      | how many columns are in the keyboard, only applies to one half if split                                  |
  | `thumbs`     | `int \| "MIT" \| "2x2u"` | `0`           | the number thumb keys per half if split; for non-splits can only take special values `MIT` or `2x2u`[^2] |
  | `drop_pinky` | `bool`                   | `False`       | whether the pinky (outermost) columns have one fewer key, N/A for non-splits                             |
  | `drop_inner` | `bool`                   | `False`       | whether the inner index (innermost) columns have one fewer key, N/A for non-splits                       |

  _Example:_ `layout: {ortho_layout: {split: true, rows: 3, columns: 5, thumbs: 3}}`

[^2]: Corresponding to bottom row arrangements of a single `2u` key, or two neighboring `2u` keys, respectively.

### Cols+Thumbs notation specification

Using the "cols+thumbs" notation is another way to generate a layout parametrically, but via a special syntax string that describes the
key counts in each column and thumb cluster of the keyboard. This is more flexible than the `ortho_layout` option
if special MIT/2x2u thumbs aren't needed.

Following physical layout parameter can be specified either in the command line or under this field definition as a key-value pair:

- **`cols_thumbs_notation`** (equivalent to `-n`/`--cols-thumbs-notation` on the command line):
  Specifies a specially formatted string to describe an ortholinear keyboard layout. This string is composed of a number of digits
  corresponding to each column in the keyboard, optionally augmented by a count of thumb keys. This can be repeated to specify
  split keyboards with two or more halves, separated by a space.

  _Example:_ `layout: {cols_thumbs_notation: 33333+1 2+33332}`

Above example specifies an asymmetric 32 key split keyboard with 3 rows and 5 columns on the left side, and a right-aligned thumb cluster with a single key.
The right half has a left-aligned thumb cluster with two keys, 5 columns with 3 rows but has a key dropped on the last column.

Normally each column will be centered vertically, but you can also add modifier characters after each column count to tweak this:
`v` or `d` (for ↓/"down") pushes the column down by half a key height, and `^` or `u` (for ↑/"up") pushes it up by the same amount.
These modifiers can be repeated to push further.
Similarly, you can use `>` to push a thumb row right by half a key width, or `<` to push it left.

As an advanced example, notation `2v333+2> 3<<+13332^ 33` will result in a physical layout that looks like below:

```
  x x x       x x x x   x x
x x x x     x x x x x   x x
x x x x       x x x     x x
     x x    x x x
```

> #### ℹ️ CLI+keymap YAML specification
>
> If the physical layout parameters are specified in both command line and under the `layout` section, the former will take precedence.

## `layers`

This field is an ordered mapping of layer names to a list of `LayoutKey` specs that represent the keys on that layer.
A `LayoutKey` can be defined with either a string value or with a mapping with the following fields:

| field name (alias) | type  | default value | description                                                                                                                                                                                                                                                                 |
| ------------------ | ----- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tap (t)`          | `str` | `""`          | the tap action of a key, drawn on the center of the key; spaces will be converted to line breaks[^3]                                                                                                                                                                        |
| `hold (h)`         | `str` | `""`          | the hold action of a key, drawn on the bottom of the key                                                                                                                                                                                                                    |
| `shifted (s)`      | `str` | `""`          | the "shifted" action of a key, drawn on the top of the key                                                                                                                                                                                                                  |
| `type`             | `str` | `""`          | the styling of the key that corresponds to the [SVG class](CONFIGURATION.md#svg_style)[^4]. predefined types are `held` (a red shading to denote held down keys), `ghost` (dashed outline to denote optional keys in a layout), `trans` (lighter text for transparent keys) |

[^3]: You can prevent line breaks by using double spaces `"  "` to denote a single non-breaking space.
[^4]: Text styling can be overridden in the `svg_extra_style` field under `draw_config` using the `"tap"`, `"hold"` and `"shifted"` CSS classes if desired.

Using a string value such as `"A"` for a key spec is equivalent to defining a mapping with only the tap field, i.e., `{tap: "A"}`.
It is meant to be used as a shortcut for keys that do not need `hold` or `type` fields.

You can use the special `$$..$$` syntax to refer to custom SVG glyphs in `tap`/`hold`/`shifted` fields, however note that they cannot be used with other text or glyphs inside the same field value.
See the [custom glyphs section](README.md#custom-glyphs) for more information.

`layers` field also flattens any lists that are contained in its value: This allows you to semantically divide keys to "rows," if you prefer to do so.
The two layers in the following example are functionally identical:

<!-- prettier-ignore -->
```yaml
layers:
  flat_layer: ["7", "8", "9", "4", "5", "6", "1", "2", "3", {t: "0", h: Fn}]
  nested_layer:
    - ["7", "8", "9"]
    - ["4", "5", "6"]
    - ["1", "2", "3"]
    - {t: "0", h: Fn}
```

## `combos`

This is an optional field that contains a list of `ComboSpec`s, each of which is a mapping that can have the following fields:

| field name (alias)  | type                                              | default value | description                                                                                                                                                                       |
| ------------------- | ------------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key_positions (p)` | `list[int]`                                       | required      | list of key indices that trigger the combo[^5]                                                                                                                                    |
| `key (k)`           | `LayoutKey`[^6]                                   | required      | key produced by the combo when triggered, `LayoutKey`'s `type` field will be combined with the type field of `ComboSpec`                                                          |
| `layers (l)`        | `list[str]`                                       | `[]`[^7]      | list of layers the combo can trigger on, specified using layer names in `layers` field                                                                                            |
| `align (a)`         | `"mid" \| "top" \| "bottom" \| "left" \| "right"` | `"mid"`       | where to draw the combo: `mid` draws on the mid-point of triggering keys' center coordinates, or to the `top`/`bottom`/`left`/`right` of the triggering keys                      |
| `offset (o)`        | `float`                                           | `0.0`         | additional offset to `top`/`bottom`/`left`/`right` positioning, specified in units of key width/height: useful for combos that would otherwise overlap                            |
| `dendron (d)`       | `null \| bool`                                    | `null`        | whether to draw dendrons going from combo to triggering key coordinates, default is to draw for non-`mid` alignments and draw for `mid` if key coordinates are far from the combo |
| `slide (s)`         | `null \| float (-1 <= val <= 1)`                  | `null`        | slide the combo box along an axis between keys -- can be used for moving `top`/`bottom` combo boxes left/right, `left`/`right` boxes up/down, or `mid` combos between two keys    |
| `arc_scale`         | `float`                                           | `1.0`         | scale the arcs going left/right for `top`/`bottom` or up/down for `left`/`right` aligned combos                                                                                   |
| `type`              | `str`                                             | `""`          | the styling of the key that corresponds to the [CSS class](CONFIGURATION.md#svg_style), see `LayoutKey` definition above                                                          |
| `width (w)`         | `float`                                           | `null`        | the width of the combo box (in pixels), defaults to `draw_config.combo_w` if null                                                                                                 |
| `height (h)`        | `float`                                           | `null`        | the height of the combo box (in pixels), defaults to `draw_config.combo_h` if null                                                                                                |
| `rotation (r)`      | `float`                                           | `0.0`         | the rotation of the combo box in degrees -- only applies to the box itself and not any dendrons                                                                                   |
| `draw_separate`     | `null \| bool`                                    | `null`        | whether to draw the combo separate from layers, using a dedicated diagram. defaults to `draw_config.separate_combo_diagrams` if null                                              |

All fields except `key_positions`, `key` and `type` are ignored when combo is drawn in a separate diagram using `draw_separate` or `draw_config.separate_combo_diagrams`.

[^5]: Key indices start from `0` on the first key position and increase by columns and then rows, corresponding to their ordering in the `layers` field. This matches the `key-positions` property in ZMK combo definitions.
[^6]: Just like for keys in a layer under the `layers` field, `key` field can be specified with a string value as a shortcut, or a mapping (where the `type` field will be ignored).
[^7]: The default value of empty list corresponds to all layers in the keymap, similar to the `layers` property in ZMK.

_Example:_

```yaml
combos:
  - { p: [0, 1], k: Tab, l: [Qwerty] }
  - { p: [1, 2], k: Esc, l: [Qwerty] }
```

## `draw_config`

This optional field lets you override [config parameters](README.md#customization) for SVG drawing.
This way you can specify drawing configuration for a specific layout and store in the keymap specification.
It is a mapping from field names in [`DrawConfig` class](CONFIGURATION.md#draw-configuration) to values.

_Example:_

```yaml
draw_config:
  key_h: 60
  combo_h: 22
  combo_w: 24
```

# Configuration options

This page details the configuration options available for parsing and drawing, which can be provided to the CLI or can be set in the web UI in the "Configuration" box.
Also see the [customization section](README.md#configuration) in the README for usage.

## Draw Configuration

These settings are nested under the `draw_config` field and applies to `keymap draw` subcommand in the CLI, as well as the conversion from keymap YAML input to SVG in the web app.
In addition to the configuration file, this field can also be set in the [keymap YAML](KEYMAP_SPEC.md#draw_config) which overrides the former.

#### `key_w`, `key_h`

Key dimensions. Non-ortho layouts (e.g. via `qmk_keyboard`) use `key_h` for both width and height, whereas `ortho_layout` and `cols_thumbs_notation` use both.

_Type:_ `float`

_Default:_ `60`, `56`

#### `split_gap`

The gap between two halves of a split keyboard, only used for physical layouts specified via `ortho_layout` and `cols_thumbs_notation`.

_Type:_ `float`

_Default:_ `30`

#### `combo_w`, `combo_h`

Dimensions of combo boxes that are drawn on layer diagrams.

_Type:_ `float`

_Default:_ `28`, `26`

#### `key_rx`, `key_ry`

Curvature of rounded key rectangles, used both for key and combo boxes

_Type:_ `float`

_Default:_ `6`

#### `n_columns`

Number of layer columns in the output drawing.
For example if this is set to 2, two layers will be shown side-by-side and layers will go right then down.

_Type:_ `int`

_Default:_ `1`

#### `separate_combo_diagrams`

When set, visualize combos using separate mini-layout diagrams rather than drawing them on layers.
This sets the default behavior, which can be overridden by the `draw_separate` field of the [`ComboSpec`](KEYMAP_SPEC.md#combos).

_Type:_ `bool`

_Default:_ `false`

#### `combo_diagrams_scale`

For combos visualized separate from layers, this is the scale factor for the mini-layout used to show their key positions.

_Type:_ `int`

_Default:_ `2`

#### `inner_pad_w`, `inner_pad_h`

The amount of padding between adjacent keys, in two axes.

_Type:_ `float`

_Default:_ `2`, `2`

#### `outer_pad_w`, `outer_pad_h`

Padding amount between layer diagrams, in two axes.

_Type:_ `float`

_Default:_ `30`, `56`

#### `line_spacing`

Spacing between multi-line text in key labels in units of `em`.

_Type:_ `float`

_Default:_ `1.2`

#### `arc_radius`

Radius of the curve for combo dendrons that are drawn from the combo box to the key positions.

_Type:_ `float`

_Default:_ `6`

#### `append_colon_to_layer_header`

Whether to add a colon after layer name while printing the layer header.

_Type:_ `bool`

_Default:_ `true`

#### `small_pad`

Padding from edge of a key representation to top ("shifted") and bottom ("hold") legends.

_Type:_ `float`

_Default:_ `2`

#### `legend_rel_x`, `legend_rel_y`

Position of center ("tap") key legend relative to the center of the key.
Can be useful to tweak when `draw_key_sides` is used.

_Type:_ `float`

_Default:_ `0`, `0`

#### `draw_key_sides`

Draw "key sides" on key representations, which can be made to look like keycap profiles.
The shape is determined by `key_side_pars`.

_Type:_ `bool`

_Default:_ `false`

#### `key_side_pars`

A mapping of certain field names to their values, characterizing key side drawing. Valid fields:

- **`rel_x`**, **`rel_y`** (type: `float`): Position of internal key rectangle relative to the center of the key. _Default:_ `0`, `4`
- **`rel_w`**, **`rel_y`** (type: `float`): Delta dimension between external key rectangle and internal key rectangle. _Default:_ `12`, `12`
- **`rx`**, **`ry`** (type: `float`): Curvature of the rounded internal key rectangle. _Default:_ `4`, `4`

#### `svg_style`[^1]

[^1]: Excluded from `keymap dump-config` by default, can be modified by manually adding it to the config file.

The CSS used for the SVG styling. This includes font settings, styling of key and combo rectangles and texts within them, along with some tweaks for external SVG glyphs.
Users are encouraged to not change the default value and use `svg_extra_style` to specify overrides instead.

_Type:_ `string`

_Default:_ See [`config.py`](keymap_drawer/config.py)

#### `svg_extra_style`

Extra CSS that will be appended to `svg_style`, enabling augmenting and overriding properties.

_Type:_ `string`

_Default:_ Empty

#### `shrink_wide_legends`

Shrink font size for legends wider than this many chars, set to 0 to disable.
Ideal value depends on the font size defined in `svg_style`/`svg_extra_style` and width of the boxes.

_Type:_ `int`

_Default:_ `7`

#### `glyph_tap_size`, `glyph_hold_size`, `glyph_shifted_size`

Height in `px` for SVG glyphs, in different key fields.

_Type:_ `int`

_Default:_ `14`, `12`, `10`

#### `glyphs`

Mapping of glyph names to be used in key fields to their SVG definitions.

_Type:_ `dict[str, str]`

_Default:_ Empty

#### `glyph_urls`[^1]

Mapping of sources to (possibly templated) URLs for fetching SVG glyphs.
For instance, `$$material:settings$$` will use the value for `material` and replace `{}` in the value with `settings`.

_Type:_ `dict[str, str]`

_Default:_ See [`config.py`](keymap_drawer/config.py)

#### `use_local_cache`[^1]

Use a local filesystem cache on an OS-specific location for downloaded QMK keyboard jsons and SVG glyphs.

_Type:_ `bool`

_Default:_ `true`

## Parse configuration

These settings are nested under the `parse_config` field and applies to `keymap parse` subcommand in the CLI, as well as the conversion from "Parse from..." input forms to the keymap YAML text area in the web app.

#### `preprocess`

Run C preprocessor on ZMK keymaps.

_Type:_ `bool`

_Default:_ `true`

#### `skip_binding_parsing`

Do not do any keycode/binding parsing (except as specified by `raw_binding_map`).

_Type:_ `bool`

_Default:_ `false`

#### `raw_binding_map`

Convert raw keycode/binding strings specified as keys to the representations given by their values.[^2]

[^2]: The value can be a [`LayoutKey` mapping](KEYMAP_SPEC.md#layers) or a string representing the tap legend.

If a conversion was made, shortcut any further processing.
E.g. `{"QK_BOOT": "BOOT", "&bootloader": "BOOT"}`.

_Type:_ `dict[str, str | dict]`

_Default:_ `{}`

#### `sticky_label`

Display text to place in hold field for sticky/one-shot keys.

_Type:_ `str`

_Default:_ `"sticky"`

#### `toggle_label`

Display text to place in hold field for toggled keys.

_Type:_ `str`

_Default:_ `"toggle"`

#### `trans_legend`

Legend to output for transparent keys.[^2]

_Type:_ `str | dict`

_Default:_ `{"t": "▽", "type": "trans"}`

#### `mark_alternate_layer_activators`

Rather than only marking the first sequence of key positions to reach a layer as "held",
mark all of the sequences to reach a given layer. this is disabled by default because it
creates ambiguity: you cannot tell if _all_ the marked keys need to be held down while a
layer is active (which is the default behavior) or _any_ of them (with this option).

_Type:_ `bool`

_Default:_ `false`

#### `qmk_remove_keycode_prefix`

Remove these prefixes from QMK keycodes before further processing.
Can be augmented with other locale prefixes, e.g. `"DE_"` for German locale headers.

_Type:_ `list[str]`

_Default:_ `["KC_"]`

#### `qmk_keycode_map`

Mapping to convert QMK keycodes to their display forms, applied after removing prefixes in `qmk_remove_keycode_prefix`.[^2]

_Type:_ `dict[str, str | dict]`

_Default:_ See [`config.py`](keymap_drawer/config.py)

#### `zmk_remove_keycode_prefix`

Remove these prefixes from ZMK keycodes before further processing.
Can be augmented with other locale prefixes, e.g. `"DE_"` for German locale headers generated by `zmk-locale-generator`.

_Type:_ `list[str]`

_Default:_ `[]`

#### `zmk_keycode_map`

Mapping to convert ZMK keycodes to their display forms, applied after removing prefixes in `zmk_remove_keycode_prefix`.[^2]

_Type:_ `dict[str, str | dict]`

_Default:_ See [`config.py`](keymap_drawer/config.py)

#### `zmk_combos`

Mapping to augment the output field for parsed combos. The key names are the devicetree node names for
combos in the keymap and the value is a dict containing fields from the [`ComboSpec`](KEYMAP_SPEC.md#combos).

E.g. `{"combo_esc": {"align": "top", "offset": 0.5}}` would add these two fields to the output for combo that has node name `combo_esc`.

_Type:_ `dict[str, dict]`

_Default:_ `{}`

