Compare commits

..

No commits in common. "master" and "v0.9.0" have entirely different histories.

146 changed files with 8210 additions and 14614 deletions

1
.github/FUNDING.yml vendored
View File

@ -1 +0,0 @@
github: mfontanini

View File

@ -16,12 +16,11 @@ jobs:
- name: Checkout code
uses: actions/checkout@v3
- name: Install cargo-binstall
uses: cargo-bins/cargo-binstall@v1.10.22
- name: Install mdbook
- name: Install mdBook
run: |
cargo binstall -y mdbook@0.4.44 mdbook-alerts@0.7.0
curl -sSL -o /tmp/mdbook.tar.gz https://github.com/rust-lang/mdBook/releases/download/v0.4.36/mdbook-v0.4.36-x86_64-unknown-linux-gnu.tar.gz
tar -xf /tmp/mdbook.tar.gz -C /usr/local/bin
mdbook --version
- name: Build the book
run: |

View File

@ -8,54 +8,48 @@ name: Merge checks
jobs:
check:
name: Checks
name: Check
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Install rust toolchain
uses: dtolnay/rust-toolchain@1.78.0
with:
components: clippy
uses: dtolnay/rust-toolchain@1.74.0
- name: Run cargo check
run: cargo check --features sixel
test:
name: Tests
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Install rust toolchain
uses: dtolnay/rust-toolchain@1.74.0
- name: Run cargo test
run: cargo test
- name: Run cargo clippy
run: cargo clippy -- -D warnings
lints:
name: Lints
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Install nightly toolchain
- name: Install stable toolchain
uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
components: rustfmt, clippy
- name: Run cargo fmt
run: cargo +nightly fmt --all -- --check
run: cargo fmt --all -- --check
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Install weasyprint
run: |
uv venv
source ./.venv/bin/activate
uv pip install weasyprint
- name: Export demo presentation as PDF and HTML
run: |
cat >/tmp/config.yaml <<EOL
export:
dimensions:
rows: 35
columns: 135
EOL
source ./.venv/bin/activate
cargo run -- --export-pdf -c /tmp/config.yaml examples/demo.md
cargo run -- --export-html -c /tmp/config.yaml examples/demo.md
- name: Run cargo clippy
run: cargo clippy -- -D warnings
nix-flake:
name: Validate nix flake

View File

@ -1,102 +0,0 @@
name: Nightly build
on:
schedule:
- cron: "0 0 * * *"
env:
RELEASE_VERSION: nightly
jobs:
vars:
name: Set release variables
runs-on: ubuntu-latest
outputs:
timestamp: ${{ steps.set.outputs.timestamp }}
git_hash: ${{ steps.set.outputs.git_hash }}
steps:
- name: Checkout the repository
uses: actions/checkout@v4
- name: Set variables
id: set
shell: bash
run: |
set -euo pipefail
timestamp=$(date -u)
git_hash=$(git rev-parse HEAD)
echo "timestamp=$timestamp" >> "$GITHUB_OUTPUT"
echo "git_hash=$git_hash" >> "$GITHUB_OUTPUT"
publish-github:
name: Publish on GitHub
runs-on: ${{ matrix.config.OS }}
needs: vars
strategy:
fail-fast: false
matrix:
config:
- { OS: ubuntu-latest, TARGET: "x86_64-unknown-linux-gnu" }
- { OS: ubuntu-latest, TARGET: "x86_64-unknown-linux-musl" }
- { OS: ubuntu-latest, TARGET: "i686-unknown-linux-gnu" }
- { OS: ubuntu-latest, TARGET: "i686-unknown-linux-musl" }
- { OS: ubuntu-latest, TARGET: "armv5te-unknown-linux-gnueabi" }
- { OS: ubuntu-latest, TARGET: "armv7-unknown-linux-gnueabihf" }
- { OS: ubuntu-latest, TARGET: "aarch64-unknown-linux-gnu" }
- { OS: ubuntu-latest, TARGET: "aarch64-unknown-linux-musl" }
- { OS: macos-latest, TARGET: "x86_64-apple-darwin" }
- { OS: macos-latest, TARGET: "aarch64-apple-darwin" }
- { OS: windows-latest, TARGET: "x86_64-pc-windows-msvc" }
- { OS: windows-latest, TARGET: "i686-pc-windows-msvc" }
steps:
- name: Checkout the repository
uses: actions/checkout@v4
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: ${{ matrix.config.TARGET }}
override: true
- name: Build
uses: actions-rs/cargo@v1
with:
use-cross: true
command: build
args: --release --locked --target ${{ matrix.config.TARGET }}
- name: Prepare release assets
shell: bash
run: |
mkdir release/
cp {LICENSE,README.md} release/
cp target/${{ matrix.config.TARGET }}/release/presenterm release/
mv release/ presenterm-${{ env.RELEASE_VERSION }}/
- name: Create release artifacts
shell: bash
run: |
if [ "${{ matrix.config.OS }}" = "windows-latest" ]; then
7z a -tzip "presenterm-${{ env.RELEASE_VERSION }}-${{ matrix.config.TARGET }}.zip" \
presenterm-${{ env.RELEASE_VERSION }}
sha512sum "presenterm-${{ env.RELEASE_VERSION }}-${{ matrix.config.TARGET }}.zip" \
> presenterm-${{ env.RELEASE_VERSION }}-${{ matrix.config.TARGET }}.zip.sha512
else
tar -czvf presenterm-${{ env.RELEASE_VERSION }}-${{ matrix.config.TARGET }}.tar.gz \
presenterm-${{ env.RELEASE_VERSION }}/
shasum -a 512 presenterm-${{ env.RELEASE_VERSION }}-${{ matrix.config.TARGET }}.tar.gz \
> presenterm-${{ env.RELEASE_VERSION }}-${{ matrix.config.TARGET }}.tar.gz.sha512
fi
- name: Upload the release
uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
tag: nightly
file: presenterm-${{ env.RELEASE_VERSION }}-${{ matrix.config.TARGET }}.*
file_glob: true
overwrite: true
prerelease: true
release_name: Nightly
body: |
This is a nightly build based on ref [${{ needs.vars.outputs.git_hash }}](https://github.com/mfontanini/presenterm/commit/${{ needs.vars.outputs.git_hash }})
Generated on `${{ needs.vars.outputs.timestamp }}`

View File

@ -1,171 +1,4 @@
# v0.13.0 - 2025-04-25
## Breaking changes
* The CLI parameter to generate the JSON schema for the config file (`--generate-config-file-schema`) is now hidden behind a `json-schema` feature flag. The JSON schema file for the latest version is already publicly available at `https://github.com/mfontanini/presenterm/blob/${VERSION}/config-file-schema.json`, so anyone can use it without having to generate it by hand. This allows cutting down the number of dependencies in this project quite a bit ([#563](https://github.com/mfontanini/presenterm/issues/563)).
## New features
* Support for [slide transitions](https://mfontanini.github.io/presenterm/features/slide-transitions.html) is now available ([#530](https://github.com/mfontanini/presenterm/issues/530)):
* Add fade slide transition ([#534](https://github.com/mfontanini/presenterm/issues/534)).
* Add slide horizontally slide transition animation ([#528](https://github.com/mfontanini/presenterm/issues/528)).
* Add `collapse_horizontal` slide transition ([#560](https://github.com/mfontanini/presenterm/issues/560)).
* Add `--output` option to specify the path where the output file is written to during an export ([#526](https://github.com/mfontanini/presenterm/issues/526)) - thanks @marianozunino.
* Allow specifying [start/end lines](https://mfontanini.github.io/presenterm/features/code/highlighting.html#including-external-code-snippets) in file snippet type ([#565](https://github.com/mfontanini/presenterm/issues/565)).
* Allow letting [pauses become new slides](https://mfontanini.github.io/presenterm/configuration/settings.html#pause-behavior) when exporting ([#557](https://github.com/mfontanini/presenterm/issues/557)).
* Allow [using images on right in footer](https://mfontanini.github.io/presenterm/features/themes/definition.html#footer-images) ([#554](https://github.com/mfontanini/presenterm/issues/554)).
* Add [`max_rows` configuration](https://mfontanini.github.io/presenterm/configuration/settings.html#maximum-presentation-height) to cap vertical size ([#531](https://github.com/mfontanini/presenterm/issues/531)).
* Add julia language highlighting and execution support ([#561](https://github.com/mfontanini/presenterm/issues/561)).
## Fixes
* Center overflow lines when using centered text ([#546](https://github.com/mfontanini/presenterm/issues/546)).
* Don't add extra space before heading if prefix in theme is empty ([#542](https://github.com/mfontanini/presenterm/issues/542)).
* Use no typst background in terminal-* built in themes ([#535](https://github.com/mfontanini/presenterm/issues/535)).
* Use `std::env::temp_dir` in the `external_snippet` test ([#533](https://github.com/mfontanini/presenterm/issues/533)) - thanks @Medovi.
* Respect `extends` in a theme set via `path` in front matter ([#532](https://github.com/mfontanini/presenterm/issues/532)).
## Misc
* Refactor async renders (e.g. mermaid/typst/latex `+render` blocks, `+exec` blocks, etc) to work truly asynchronously. This causes the output to be polled faster, and causes jumping to a slide that contains an async render to take a likely negligible (but maybe noticeable) amount of time to be jumped to. This was needed for slide transitions to work seemlessly ([#556](https://github.com/mfontanini/presenterm/issues/556)).
* Get rid of `textproperties` ([#529](https://github.com/mfontanini/presenterm/issues/529)).
* Add links to presentations using presenterm ([#544](https://github.com/mfontanini/presenterm/issues/544)) - thanks @orhun.
## Performance improvements
* A few performance improvements had to be done for slide transitions to work seemlessly:
* Pre-scale ASCII images when transitions are enabled ([#550](https://github.com/mfontanini/presenterm/issues/550)).
* Pre-scale generated images ([#553](https://github.com/mfontanini/presenterm/issues/553)).
* Cache resized ASCII images ([#547](https://github.com/mfontanini/presenterm/issues/547)).
## ❤️ Sponsors
Thanks to the following users who supported _presenterm_ via a [github sponsorship](https://github.com/sponsors/mfontanini) in this release:
* [@0atman](https://github.com/0atman)
* [@orhun](https://github.com/orhun)
* [@fipoac](https://github.com/fipoac)
# v0.12.0 - 2025-03-24
## Breaking changes
* Using incremental lists now adds an extra pause before and after a list. Use the `defaults.incremental_lists` [configuration parameter](https://mfontanini.github.io/presenterm/features/commands.html#incremental-lists-behavior) to go back to the previous behavior ([#487](https://github.com/mfontanini/presenterm/issues/487)) ([#498](https://github.com/mfontanini/presenterm/issues/498)).
## New features
* [PDF exports](https://mfontanini.github.io/presenterm/features/pdf-export.html) are now generated by invoking [weasyprint](https://pypi.org/project/weasyprint/) rather than by using the now deprecated _presenterm-export_. This gets rid of the need for _tmux_ and opens up the door for other export formats ([#509](https://github.com/mfontanini/presenterm/issues/509)) ([#517](https://github.com/mfontanini/presenterm/issues/517)).
* PDF export dimensions can now also be [specified in the config file](https://mfontanini.github.io/presenterm/configuration/settings.html#pdf-export-size) rather than always having them inferred by the terminal size ([#511](https://github.com/mfontanini/presenterm/issues/511)).
* Allow specifying path for temporary files generated during presentation export ([#518](https://github.com/mfontanini/presenterm/issues/518)).
* Respect font sizes in generated PDF ([#510](https://github.com/mfontanini/presenterm/issues/510)).
* Add [`skip_slide` comment command](https://mfontanini.github.io/presenterm/features/commands.html#skip-slide) to avoid including a slide in the final presentation ([#505](https://github.com/mfontanini/presenterm/issues/505)).
* Add [`alignment` comment](https://mfontanini.github.io/presenterm/features/commands.html#text-alignment) command to specify text alignment for the remainder of a slide ([#493](https://github.com/mfontanini/presenterm/issues/493)) ([#522](https://github.com/mfontanini/presenterm/issues/522)).
* Add `--current-theme` CLI parameter to display the theme being used ([#489](https://github.com/mfontanini/presenterm/issues/489)).
* Add gruvbox dark theme ([#483](https://github.com/mfontanini/presenterm/issues/483)) - thanks @ret2src.
## Fixes
* Fix broken ANSI escape code parsing which would cause command output to sometimes be incorrectly parsed and therefore led to its colors/attributes not being respected ([#500](https://github.com/mfontanini/presenterm/issues/500)).
* Center lists correctly ([#512](https://github.com/mfontanini/presenterm/issues/512)) ([#520](https://github.com/mfontanini/presenterm/issues/520)).
* Respect end slide shorthand in speaker notes mode ([#494](https://github.com/mfontanini/presenterm/issues/494)).
* Use more visible colors in snippet execution output in terminal-light/dark themes ([#485](https://github.com/mfontanini/presenterm/issues/485)).
* Show error if sixel mode is selected but disabled ([#525](https://github.com/mfontanini/presenterm/issues/525)).
## CI
* Add nightly build job ([#496](https://github.com/mfontanini/presenterm/issues/496)).
## Docs
* Fix typo in README.md ([#490](https://github.com/mfontanini/presenterm/issues/490)) - thanks @eltociear.
* Correctly include layout pic ([#495](https://github.com/mfontanini/presenterm/issues/495)) - thanks @Tuxified.
## Misc
* Cleanup text attributes ([#519](https://github.com/mfontanini/presenterm/issues/519)).
* Refactor snippet processing ([#484](https://github.com/mfontanini/presenterm/issues/484)).
## Sponsors
It is now possible to sponsor this project via [github sponsors](https://github.com/sponsors/mfontanini).
Thanks to [@0atman](https://github.com/0atman) for being the first project sponsor!
# v0.11.0 - 2025-03-08
## Breaking changes
* Footer templates are now sanitized, and any variables surrounded in braces that aren't supported (e.g. `{potato}`) will now cause _presenterm_ to display an error. If you'd like to use braces in contexts where you're not trying to reference a variable you can use double braces, e.g. `live at {{PotatoConf}}` ([#442](https://github.com/mfontanini/presenterm/issues/442)) ([#467](https://github.com/mfontanini/presenterm/issues/467)) ([#469](https://github.com/mfontanini/presenterm/issues/469)) ([#471](https://github.com/mfontanini/presenterm/issues/471)).
## New features
* [Add support for kitty's font size protocol](https://mfontanini.github.io/presenterm/features/introduction.html#font-sizes). This is now used by default in built in themes in a few components such as the intro slide's title and slide titles. See the [example presentation gif](https://github.com/mfontanini/presenterm/blob/master/docs/src/assets/demo.gif) to check out how this looks like. Terminal suport for this feature is detected on startup and will be ignored if unsupported. This requires _kitty_ >= 0.40.0 ([#438](https://github.com/mfontanini/presenterm/issues/438)) ([#460](https://github.com/mfontanini/presenterm/issues/460)) ([#470](https://github.com/mfontanini/presenterm/issues/470)).
* [Allow specifying font size in a comment command](https://mfontanini.github.io/presenterm/features/commands.html#font-size), which causes any subsequent text in a slide to use the specified font size. Just like the above, only supported in _kitty_ >= 0.40.0 for now ([#458](https://github.com/mfontanini/presenterm/issues/458)).
* [Footers can now contain images](https://mfontanini.github.io/presenterm/features/themes/definition.html#footer-images) in the left and center components. This allows including some form of branding/company logo to your presentations ([#450](https://github.com/mfontanini/presenterm/issues/450)) ([#476](https://github.com/mfontanini/presenterm/issues/476)).
* [Footers can now contain inline markdown](https://mfontanini.github.io/presenterm/features/themes/definition.html#template-footers), which allows using bold, italics, `<span>` tags for colors, etc ([#466](https://github.com/mfontanini/presenterm/issues/466)).
* [Presentation titles can now contain inline markdown](https://mfontanini.github.io/presenterm/features/introduction.html#introduction-slide) ([#464](https://github.com/mfontanini/presenterm/issues/464)).
* [Introduce palette.classes in themes](https://mfontanini.github.io/presenterm/features/themes/definition.html#color-palette) to allow specifying combinations of foreground/background colors that can be referenced via the `class` attribute in `<span>` tags ([#468](https://github.com/mfontanini/presenterm/issues/468)).
* It's now possible to [configure the alignment](https://mfontanini.github.io/presenterm/configuration/settings.html#maximum-presentation-width) to use when `max_columns` is configured and the terminal width is larger than it ([#475](https://github.com/mfontanini/presenterm/issues/475)).
* Add support for wikilinks ([#448](https://github.com/mfontanini/presenterm/issues/448)).
## Fixes
* Don't get stuck if tmux doesn't passthrough ([#456](https://github.com/mfontanini/presenterm/issues/456)).
* Don't squash image if terminal's font aspect ratio is not 2:1 ([#446](https://github.com/mfontanini/presenterm/issues/446)).
* Fail if `--config-file` points to non existent file ([#474](https://github.com/mfontanini/presenterm/issues/474)).
* Use right script name for kotlin files when executing ([#462](https://github.com/mfontanini/presenterm/issues/462)).
* Respect lists that start at non 1 indexes ([#459](https://github.com/mfontanini/presenterm/issues/459)).
* Jump to right slide on code attribute change ([#478](https://github.com/mfontanini/presenterm/issues/478)).
## Improvements
* Remove `result` return type from builder fns that don't need it ([#465](https://github.com/mfontanini/presenterm/issues/465)).
* Refactor theme code ([#463](https://github.com/mfontanini/presenterm/issues/463)).
* Restructure `terminal` code and add test for margins/layouts ([#443](https://github.com/mfontanini/presenterm/issues/443)).
* Use `fastrand` instead of `rand` ([#441](https://github.com/mfontanini/presenterm/issues/441)).
* Avoid cloning strings when styling them ([#440](https://github.com/mfontanini/presenterm/issues/440)).
# v0.10.1 - 2025-02-14
## Fixes
* Don't error out if `options` in front matter doesn't include `auto_render_languages` ([#454](https://github.com/mfontanini/presenterm/pull/454)).
* Bump sixel-rs to 0.4.1 to fix build in aarch64 and riscv64 ([#452](https://github.com/mfontanini/presenterm/pull/452)) - thanks @Xeonacid.
# v0.10.0 - 2025-02-02
## New features
* Support for presentation speaker notes ([#389](https://github.com/mfontanini/presenterm/issues/389)) ([#419](https://github.com/mfontanini/presenterm/issues/419)) ([#421](https://github.com/mfontanini/presenterm/issues/421)) ([#425](https://github.com/mfontanini/presenterm/issues/425)) - thanks @dmackdev.
* Add support for colored text via inline `span` HTML tags ([#390](https://github.com/mfontanini/presenterm/issues/390)).
* Add a color palette in themes to allow reusing colors across the theme and using predefined colors inside `span` tags ([#427](https://github.com/mfontanini/presenterm/issues/427)).
* Add support for github/gitlab style markdown alerts ([#423](https://github.com/mfontanini/presenterm/issues/423)) ([#430](https://github.com/mfontanini/presenterm/issues/430)).
* Allow using `+image` on code blocks to consume their output as an image ([#429](https://github.com/mfontanini/presenterm/issues/429)).
* Allow multiline comment commands ([#424](https://github.com/mfontanini/presenterm/issues/424)).
* Allow auto rendering mermaid/typst/latex code blocks ([#418](https://github.com/mfontanini/presenterm/issues/418)).
* Allow capping max columns on presentation ([#417](https://github.com/mfontanini/presenterm/issues/417)).
* Automatically detect kitty support, including when running inside tmux ([#406](https://github.com/mfontanini/presenterm/issues/406)).
* Use kitty image protocol in ghostty ([#405](https://github.com/mfontanini/presenterm/issues/405)).
* Force color output in rust, c, and c++ compiler executions ([#401](https://github.com/mfontanini/presenterm/issues/401)).
* Add graphql code highlighting ([#385](https://github.com/mfontanini/presenterm/issues/385)) - thanks @GV14982.
* Add tcl code highlighting ([#387](https://github.com/mfontanini/presenterm/issues/387)) - thanks @jtplaarj.
* Add Haskell executor ([#414](https://github.com/mfontanini/presenterm/issues/414)) - thanks @feature-not-a-bug.
* Add C# to code executors ([#399](https://github.com/mfontanini/presenterm/issues/399)) - thanks @giggio.
* Add R to executors ([#393](https://github.com/mfontanini/presenterm/issues/393)) - thanks @jonocarroll.
## Fixes
* Check for `term_program` before `term` to determine emulator ([#420](https://github.com/mfontanini/presenterm/issues/420)).
* Allow jumping back to column in column layout ([#396](https://github.com/mfontanini/presenterm/issues/396)).
* Ignore comments that start with `vim:` prefix ([#395](https://github.com/mfontanini/presenterm/issues/395)).
* Respect `+no_background` on a `+exec_replace` block ([#383](https://github.com/mfontanini/presenterm/issues/383)).
## Docs
* Document tmux active session bug ([#402](https://github.com/mfontanini/presenterm/issues/402)).
* Add notes on running `bat` directly ([#397](https://github.com/mfontanini/presenterm/issues/397)).
# v0.9.0 - 2024-10-06
# v0.9.0 - 2024-10-04
## Breaking changes

943
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -4,47 +4,50 @@ authors = ["Matias Fontanini"]
description = "A terminal slideshow presentation tool"
repository = "https://github.com/mfontanini/presenterm"
license = "BSD-2-Clause"
version = "0.13.0"
version = "0.9.0"
edition = "2021"
[dependencies]
anyhow = "1"
ansi-parser = "0.9"
base64 = "0.22"
bincode = "1.3"
clap = { version = "4.4", features = ["derive", "string"] }
comrak = { version = "0.36", default-features = false }
crossterm = { version = "0.28", features = ["serde"] }
directories = "6.0"
comrak = { version = "0.26", default-features = false }
crossterm = { version = "0.27", features = ["serde"] }
directories = "5.0"
hex = "0.4"
fastrand = "2.3"
flate2 = "1.0"
image = { version = "0.25", features = ["gif", "jpeg", "png"], default-features = false }
sixel-rs = { version = "0.4.1", optional = true }
image = { version = "0.25", features = ["gif", "jpeg", "rayon", "png", "webp"], default-features = false }
sixel-rs = { version = "0.3.3", optional = true }
merge-struct = "0.1.0"
itertools = "0.14"
itertools = "0.13"
once_cell = "1.19"
schemars = { version = "0.8", optional = true }
rand = "0.8.5"
schemars = "0.8"
semver = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.9"
serde_json = "1.0"
syntect = { version = "5.2", features = ["parsing", "default-themes", "regex-onig", "plist-load"], default-features = false }
socket2 = "0.5.8"
strum = { version = "0.27", features = ["derive"] }
tempfile = { version = "3.10", default-features = false }
tl = "0.7"
thiserror = "2"
unicode-width = "0.2"
serde_with = "3.6"
strum = { version = "0.26", features = ["derive"] }
tempfile = "3.10"
console = "0.15.8"
thiserror = "1"
unicode-width = "0.1"
os_pipe = "1.1.5"
libc = "0.2"
vte = "0.15"
libc = "0.2.155"
[dependencies.syntect]
version = "5.2"
default-features = false
features = ["parsing", "default-themes", "regex-onig", "plist-load"]
[dev-dependencies]
rstest = { version = "0.25", default-features = false }
rstest = { version = "0.21", default-features = false }
[features]
default = []
sixel = ["sixel-rs"]
json-schema = ["dep:schemars"]
[profile.dev]
opt-level = 0

View File

@ -16,9 +16,8 @@ presenterm
[scoop-package]: https://scoop.sh/#/apps?q=presenterm&id=a462290f824b50f180afbaa6d8c7c1e6e0952e3a
_presenterm_ lets you create presentations in markdown format and run them from your terminal, with support for image
and animated gifs, highly customizable themes, code highlighting, exporting presentations into PDF format, and plenty of
other features. This is how the [demo presentation](/examples/demo.md) looks like when running in the [kitty
terminal](https://sw.kovidgoyal.net/kitty/):
and animated gifs, highly customizable themes, code highlighting, exporting presentations into PDF format, and
plenty of other features. This is how the [demo presentation](/examples/demo.md) looks like:
![](/docs/src/assets/demo.gif)
@ -26,68 +25,51 @@ Check the rest of the example presentations in the [examples directory](/example
# Documentation
Visit the [documentation][docs-introduction] to get started.
Visit the [documentation][guide-introduction] to get started.
# Features
* Define your presentation in a single markdown file.
* [Images and animated gifs][docs-images] on terminals like _kitty_, _iterm2_, and _wezterm_.
* [Customizable themes][docs-themes] including colors, margins, layout (left/center aligned content), footer for every
slide, etc. Several [built-in themes][docs-builtin-themes] can give your presentation the look you want without
* [Images and animated gifs][guide-images] on terminals like _kitty_, _iterm2_, and _wezterm_.
* [Customizeable themes][guide-themes] including colors, margins, layout (left/center aligned content), footer for every
slide, etc. Several [built-in themes][guide-builtin-themes] can give your presentation the look you want without
having to define your own.
* Code highlighting for a [wide list of programming languages][docs-code-highlight].
* [Font sizes][docs-font-sizes] for terminals that support them.
* [Selective/dynamic][docs-selective-highlight] code highlighting that only highlights portions of code at a time.
* [Column layouts][docs-layout].
* [mermaid graph rendering][docs-mermaid].
* [_LaTeX_ and _typst_ formula rendering][docs-latex].
* [Introduction slide][docs-intro-slide] that displays the presentation title and your name.
* [Slide titles][docs-slide-titles].
* [Snippet execution][docs-code-execute] for various programming languages.
* [Export presentations to PDF][docs-pdf-export].
* [Slide transitions][docs-slide-transitions].
* [Pause][docs-pauses] portions of your slides.
* [Custom key bindings][docs-key-bindings].
* [Automatically reload your presentation][docs-hot-reload] every time it changes for a fast development loop.
* [Define speaker notes][docs-speaker-notes] to aid you during presentations.
* Code highlighting for a [wide list of programming languages][guide-code-highlight].
* [Selective/dynamic][guide-selective-highlight] code highlighting that only highlights portions of code at a time.
* [Column layouts][guide-layout].
* [mermaid graph rendering][guide-mermaid].
* [_LaTeX_ and _typst_ formula rendering][guide-latex].
* [Introduction slide][guide-intro-slide] that displays the presentation title and your name.
* [Slide titles][guide-slide-titles].
* [Snippet execution][guide-code-execute] for various programming languages.
* [Export presentations to PDF][guide-pdf-export].
* [Pause][guide-pauses] portions of your slides.
* [Custom key bindings][guide-key-bindings].
* [Automatically reload your presentation][guide-hot-reload] every time it changes for a fast development loop.
See the [introduction page][docs-introduction] to learn more.
# Presenterm in action
Here are some talks and demos that feature _presenterm_:
- [Bringing Terminal Aesthetics to the Web With Rust][bringing-terminal-aesthetics] by [Orhun Parmaksız][orhun-github]
- [7 Rust Terminal Tools That You Should Use][rust-terminal-tools] by [Orhun Parmaksız][orhun-github]
- [Renaissance of Terminal User Interfaces with Rust][renaissance-tui] by [Orhun Parmaksız][orhun-github]
Gave a talk using _presenterm_? We would love to feature it here! Open a PR or issue to get it added.
See the [introduction page][guide-introduction] to learn more.
<!-- links -->
[docs-introduction]: https://mfontanini.github.io/presenterm/
[docs-basics]: https://mfontanini.github.io/presenterm/features/introduction.html
[docs-intro-slide]: https://mfontanini.github.io/presenterm/features/introduction.html#introduction-slide
[docs-slide-titles]: https://mfontanini.github.io/presenterm/features/introduction.html#slide-titles
[docs-font-sizes]: https://mfontanini.github.io/presenterm/features/introduction.html#font-sizes
[docs-pauses]: https://mfontanini.github.io/presenterm/features/commands.html#pauses
[docs-images]: https://mfontanini.github.io/presenterm/features/images.html
[docs-themes]: https://mfontanini.github.io/presenterm/features/themes/introduction.html
[docs-builtin-themes]: https://mfontanini.github.io/presenterm/features/themes/introduction.html#built-in-themes
[docs-code-highlight]: https://mfontanini.github.io/presenterm/features/code/highlighting.html
[docs-code-execute]: https://mfontanini.github.io/presenterm/features/code/execution.html
[docs-selective-highlight]: https://mfontanini.github.io/presenterm/features/code/highlighting.html#selective-highlighting
[docs-slide-transitions]: https://mfontanini.github.io/presenterm/features/slide-transitons.html
[docs-layout]: https://mfontanini.github.io/presenterm/features/layout.html
[docs-mermaid]: https://mfontanini.github.io/presenterm/features/code/mermaid.html
[docs-latex]: https://mfontanini.github.io/presenterm/features/code/latex.html
[docs-pdf-export]: https://mfontanini.github.io/presenterm/features/pdf-export.html
[docs-key-bindings]: https://mfontanini.github.io/presenterm/configuration/settings.html#key-bindings
[docs-hot-reload]: https://mfontanini.github.io/presenterm/features/introduction.html#hot-reload
[docs-speaker-notes]: https://mfontanini.github.io/presenterm/features/speaker-notes.html
[guide-introduction]: https://mfontanini.github.io/presenterm/
[guide-installation]: https://mfontanini.github.io/presenterm/guides/installation.html
[guide-basics]: https://mfontanini.github.io/presenterm/guides/basics.html
[guide-intro-slide]: https://mfontanini.github.io/presenterm/guides/basics.html#introduction-slide
[guide-slide-titles]: https://mfontanini.github.io/presenterm/guides/basics.html#slide-titles
[guide-pauses]: https://mfontanini.github.io/presenterm/guides/basics.html#pauses
[guide-images]: https://mfontanini.github.io/presenterm/guides/basics.html#images
[guide-themes]: https://mfontanini.github.io/presenterm/guides/themes.html
[guide-builtin-themes]: https://mfontanini.github.io/presenterm/guides/themes.html#built-in-themes
[guide-code-highlight]: https://mfontanini.github.io/presenterm/guides/code-highlight.html
[guide-code-execute]: https://mfontanini.github.io/presenterm/guides/code-highlight.html#executing-code
[guide-selective-highlight]: https://mfontanini.github.io/presenterm/guides/code-highlight.html#selective-highlighting
[guide-layout]: https://mfontanini.github.io/presenterm/guides/layout.html
[guide-mermaid]: https://mfontanini.github.io/presenterm/guides/mermaid.html
[guide-latex]: https://mfontanini.github.io/presenterm/guides/latex.html
[guide-pdf-export]: https://mfontanini.github.io/presenterm/guides/pdf-export.html
[guide-key-bindings]: https://mfontanini.github.io/presenterm/guides/configuration.html#key-bindings
[guide-hot-reload]: https://mfontanini.github.io/presenterm/guides/basics.html#hot-reload
[bat]: https://github.com/sharkdp/bat
[syntect]: https://github.com/trishume/syntect
[bringing-terminal-aesthetics]: https://www.youtube.com/watch?v=iepbyYrF_YQ
[rust-terminal-tools]: https://www.youtube.com/watch?v=ATiKwUiqnAU
[renaissance-tui]: https://www.youtube.com/watch?v=hWG51Mc1DlM
[orhun-github]: https://github.com/orhun

View File

@ -14,9 +14,6 @@
}
]
},
"export": {
"$ref": "#/definitions/ExportConfig"
},
"mermaid": {
"$ref": "#/definitions/MermaidConfig"
},
@ -26,19 +23,6 @@
"snippet": {
"$ref": "#/definitions/SnippetConfig"
},
"speaker_notes": {
"$ref": "#/definitions/SpeakerNotesConfig"
},
"transition": {
"anyOf": [
{
"$ref": "#/definitions/SlideTransitionConfig"
},
{
"type": "null"
}
]
},
"typst": {
"$ref": "#/definitions/TypstConfig"
}
@ -56,44 +40,6 @@
}
]
},
"incremental_lists": {
"description": "The configuration for lists when incremental lists are enabled.",
"allOf": [
{
"$ref": "#/definitions/IncrementalListsConfig"
}
]
},
"max_columns": {
"description": "A max width in columns that the presentation must always be capped to.",
"default": 65535,
"type": "integer",
"format": "uint16",
"minimum": 0.0
},
"max_columns_alignment": {
"description": "The alignment the presentation should have if `max_columns` is set and the terminal is larger than that.",
"allOf": [
{
"$ref": "#/definitions/MaxColumnsAlignment"
}
]
},
"max_rows": {
"description": "A max height in rows that the presentation must always be capped to.",
"default": 65535,
"type": "integer",
"format": "uint16",
"minimum": 0.0
},
"max_rows_alignment": {
"description": "The alignment the presentation should have if `max_rows` is set and the terminal is larger than that.",
"allOf": [
{
"$ref": "#/definitions/MaxRowsAlignment"
}
]
},
"terminal_font_size": {
"description": "Override the terminal font size when in windows or when using sixel.",
"default": 16,
@ -119,55 +65,6 @@
},
"additionalProperties": false
},
"ExportConfig": {
"description": "The export configuration.",
"type": "object",
"properties": {
"dimensions": {
"description": "The dimensions to use for presentation exports.",
"anyOf": [
{
"$ref": "#/definitions/ExportDimensionsConfig"
},
{
"type": "null"
}
]
},
"pauses": {
"description": "Whether pauses should create new slides.",
"allOf": [
{
"$ref": "#/definitions/PauseExportPolicy"
}
]
}
},
"additionalProperties": false
},
"ExportDimensionsConfig": {
"description": "The dimensions to use for presentation exports.",
"type": "object",
"required": [
"columns",
"rows"
],
"properties": {
"columns": {
"description": "The number of columns.",
"type": "integer",
"format": "uint16",
"minimum": 0.0
},
"rows": {
"description": "The number of rows.",
"type": "integer",
"format": "uint16",
"minimum": 0.0
}
},
"additionalProperties": false
},
"ImageProtocol": {
"oneOf": [
{
@ -214,29 +111,6 @@
}
]
},
"IncrementalListsConfig": {
"description": "The configuration for lists when incremental lists are enabled.",
"type": "object",
"properties": {
"pause_after": {
"description": "Whether to pause after a list ends.",
"default": null,
"type": [
"boolean",
"null"
]
},
"pause_before": {
"description": "Whether to pause before a list begins.",
"default": null,
"type": [
"boolean",
"null"
]
}
},
"additionalProperties": false
},
"KeyBinding": {
"type": "string"
},
@ -383,58 +257,6 @@
}
}
},
"MaxColumnsAlignment": {
"description": "The alignment to use when `defaults.max_columns` is set.",
"oneOf": [
{
"description": "Align the presentation to the left.",
"type": "string",
"enum": [
"left"
]
},
{
"description": "Align the presentation on the center.",
"type": "string",
"enum": [
"center"
]
},
{
"description": "Align the presentation to the right.",
"type": "string",
"enum": [
"right"
]
}
]
},
"MaxRowsAlignment": {
"description": "The alignment to use when `defaults.max_rows` is set.",
"oneOf": [
{
"description": "Align the presentation to the top.",
"type": "string",
"enum": [
"top"
]
},
{
"description": "Align the presentation on the center.",
"type": "string",
"enum": [
"center"
]
},
{
"description": "Align the presentation to the bottom.",
"type": "string",
"enum": [
"bottom"
]
}
]
},
"MermaidConfig": {
"type": "object",
"properties": {
@ -451,13 +273,6 @@
"OptionsConfig": {
"type": "object",
"properties": {
"auto_render_languages": {
"description": "Assume snippets for these languages contain `+render` and render them automatically.",
"type": "array",
"items": {
"$ref": "#/definitions/SnippetLanguage"
}
},
"command_prefix": {
"description": "The prefix to use for commands.",
"type": [
@ -503,108 +318,6 @@
},
"additionalProperties": false
},
"PauseExportPolicy": {
"description": "The policy for pauses when exporting.",
"oneOf": [
{
"description": "Whether to ignore pauses.",
"type": "string",
"enum": [
"ignore"
]
},
{
"description": "Create a new slide when a pause is found.",
"type": "string",
"enum": [
"new_slide"
]
}
]
},
"SlideTransitionConfig": {
"type": "object",
"required": [
"animation"
],
"properties": {
"animation": {
"description": "The slide transition style.",
"allOf": [
{
"$ref": "#/definitions/SlideTransitionStyleConfig"
}
]
},
"duration_millis": {
"description": "The amount of time to take to perform the transition.",
"default": 1000,
"type": "integer",
"format": "uint16",
"minimum": 0.0
},
"frames": {
"description": "The number of frames in a transition.",
"default": 30,
"type": "integer",
"format": "uint",
"minimum": 0.0
}
},
"additionalProperties": false
},
"SlideTransitionStyleConfig": {
"oneOf": [
{
"description": "Slide horizontally.",
"type": "object",
"required": [
"style"
],
"properties": {
"style": {
"type": "string",
"enum": [
"slide_horizontal"
]
}
},
"additionalProperties": false
},
{
"description": "Fade the new slide into the previous one.",
"type": "object",
"required": [
"style"
],
"properties": {
"style": {
"type": "string",
"enum": [
"fade"
]
}
},
"additionalProperties": false
},
{
"description": "Collapse the current slide into the center of the screen.",
"type": "object",
"required": [
"style"
],
"properties": {
"style": {
"type": "string",
"enum": [
"collapse_horizontal"
]
}
},
"additionalProperties": false
}
]
},
"SnippetConfig": {
"type": "object",
"properties": {
@ -668,92 +381,6 @@
},
"additionalProperties": false
},
"SnippetLanguage": {
"description": "The language of a code snippet.",
"oneOf": [
{
"type": "string",
"enum": [
"Ada",
"Asp",
"Awk",
"Bash",
"BatchFile",
"C",
"CMake",
"Crontab",
"CSharp",
"Clojure",
"Cpp",
"Css",
"DLang",
"Diff",
"Docker",
"Dotenv",
"Elixir",
"Elm",
"Erlang",
"File",
"Fish",
"Go",
"GraphQL",
"Haskell",
"Html",
"Java",
"JavaScript",
"Json",
"Julia",
"Kotlin",
"Latex",
"Lua",
"Makefile",
"Mermaid",
"Markdown",
"Nix",
"Nushell",
"OCaml",
"Perl",
"Php",
"Protobuf",
"Puppet",
"Python",
"R",
"Racket",
"Ruby",
"Rust",
"RustScript",
"Scala",
"Shell",
"Sql",
"Swift",
"Svelte",
"Tcl",
"Terraform",
"Toml",
"TypeScript",
"Typst",
"Xml",
"Yaml",
"Verilog",
"Vue",
"Zig",
"Zsh"
]
},
{
"type": "object",
"required": [
"Unknown"
],
"properties": {
"Unknown": {
"type": "string"
}
},
"additionalProperties": false
}
]
},
"SnippetRenderConfig": {
"type": "object",
"properties": {
@ -767,27 +394,6 @@
},
"additionalProperties": false
},
"SpeakerNotesConfig": {
"type": "object",
"properties": {
"always_publish": {
"description": "Whether to always publish speaker notes.",
"default": false,
"type": "boolean"
},
"listen_address": {
"description": "The address in which to listen for speaker note events.",
"default": "127.255.255.255:59418",
"type": "string"
},
"publish_address": {
"description": "The address in which to publish speaker notes events.",
"default": "127.255.255.255:59418",
"type": "string"
}
},
"additionalProperties": false
},
"TypstConfig": {
"type": "object",
"properties": {

View File

@ -41,24 +41,10 @@ snippet:
# enable code snippet execution. Use at your own risk!
enable: true
exec_replace:
# enable code snippet automatic execution + replacing the snippet with its output. Use at your own risk!
enable: true
render:
# the number of threads to use when rendering `+render` code snippets.
threads: 2
speaker_notes:
# The endpoint to listen for speaker note events.
listen_address: "127.0.0.1:59418"
# The endpoint to publish speaker note events.
publish_address: "127.0.0.1:59418"
# Whether to always publish speaker notes even when `--publish-speaker-notes` is not set.
always_publish: false
bindings:
# the keys that cause the presentation to move forwards.
next: ["l", "j", "<right>", "<page_down>", "<down>", " "]

View File

@ -7,18 +7,12 @@ title = "presenterm documentation"
[preprocessor]
[preprocessor.alerts]
[preprocessor.catppuccin]
assets_version = "2.1.0"
[output]
[output.html]
additional-css = ["./theme/catppuccin.css", "./theme/catppuccin-admonish.css"]
git-repository-url = "https://github.com/mfontanini/presenterm"
default-theme = "navy"
# Redirects for broken links after 02/02/2025 restructuring.
[output.html.redirect]
"/guides/basics.html" = "../features/introduction.html"
"/guides/installation.html" = "../install.html"
"/guides/code-highlight.html" = "../features/code/highlighting.html"
"/guides/mermaid.html" = "../features/code/mermaid.html"
default-theme = "machiatto"

View File

@ -2,25 +2,17 @@
[Introduction](./introduction.md)
# Docs
# Guides
- [Install](./install.md)
- [Features](./features/introduction.md)
- [Images](./features/images.md).
- [Commands](./features/commands.md).
- [Layout](./features/layout.md).
- [Code](./features/code/highlighting.md)
- [Execution](./features/code/execution.md)
- [Mermaid diagrams](./features/code/mermaid.md)
- [LaTeX and typst](./features/code/latex.md)
- [Themes](./features/themes/introduction.md)
- [Definition](./features/themes/definition.md)
- [PDF export](./features/pdf-export.md)
- [Slide transitions](./features/slide-transitions.md)
- [Speaker notes](./features/speaker-notes.md)
- [Configuration](./configuration/introduction.md)
- [Options](./configuration/options.md)
- [Settings](./configuration/settings.md)
- [Installation](./guides/installation.md)
- [Basics](./guides/basics.md)
- [Themes](./guides/themes.md)
- [Layout](./guides/layout.md)
- [Configuration](./guides/configuration.md)
- [Code highlighting](./guides/code-highlight.md)
- [PDF export](./guides/pdf-export.md)
- [Mermaid](./guides/mermaid.md)
- [LaTeX and typst](./guides/latex.md)
# Internals

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 655 KiB

After

Width:  |  Height:  |  Size: 450 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

View File

@ -1,28 +0,0 @@
# Configuration
_presenterm_ allows you to customize its behavior via a configuration file. This file is stored, along with all of your
custom themes, in the following directories:
* `$XDG_CONFIG_HOME/presenterm/` if that environment variable is defined, otherwise:
* `~/.config/presenterm/` in Linux.
* `~/Library/Application Support/presenterm/` in macOS.
* `~/AppData/Roaming/presenterm/config/` in Windows.
The configuration file will be looked up automatically in the directories above under the name `config.yaml`. e.g. on
Linux you should create it under `~/.config/presenterm/config.yaml`. You can also specify a custom path to this file
when running _presenterm_ via the `--config-file` parameter.
A [sample configuration file](https://github.com/mfontanini/presenterm/blob/master/config.sample.yaml) is provided in
the repository that you can use as a base.
# Configuration schema
A JSON schema that defines the configuration file's schema is available to be used with YAML language servers such as
[yaml-language-server](https://github.com/redhat-developer/yaml-language-server).
Include the following line at the beginning of your configuration file to have your editor pull in autocompletion
suggestions and docs automatically:
```yaml
# yaml-language-server: $schema=https://raw.githubusercontent.com/mfontanini/presenterm/master/config-file-schema.json
```

View File

@ -1,165 +0,0 @@
# Options
Options are special configuration parameters that can be set either in the configuration file under the `options` key,
or in a presentation's front matter under the same key. This last one allows you to customize a single presentation so
that it acts in a particular way. This can also be useful if you'd like to share the source files for your presentation
with other people.
The supported configuration options are currently the following:
## implicit_slide_ends
This option removes the need to use `<!-- end_slide -->` in between slides and instead assumes that if you use a slide
title, then you're implying that the previous slide ended. For example, the following presentation:
```markdown
---
options:
implicit_slide_ends: true
---
Tasty vegetables
================
* Potato
Awful vegetables
================
* Lettuce
```
Is equivalent to this "vanilla" one that doesn't use implicit slide ends.
```markdown
Tasty vegetables
================
* Potato
<!-- end_slide -->
Awful vegetables
================
* Lettuce
```
## end_slide_shorthand
This option allows using thematic breaks (`---`) as a delimiter between slides. When enabling this option, you can still
use `<!-- end_slide -->` but any thematic break will also be considered a slide terminator.
```
---
options:
end_slide_shorthand: true
---
this is a slide
---------------------
this is another slide
```
## command_prefix
Because _presenterm_ uses HTML comments to represent commands, it is necessary to make some assumptions on _what_ is a
command and what isn't. The current heuristic is:
* If an HTML comment is laid out on a single line, it is assumed to be a command. This means if you want to use a real
HTML comment like `<!-- remember to say "potato" here -->`, this will raise an error.
* If an HTML comment is multi-line, then it is assumed to be a comment and it can have anything inside it. This means
you can't have a multi-line comment that contains a command like `pause` inside.
Depending on how you use HTML comments personally, this may be limiting to you: you cannot use any single line comments
that are not commands. To get around this, the `command_prefix` option lets you configure a prefix that must be set in
all commands for them to be configured as such. Any single line comment that doesn't start with this prefix will not be
considered a command.
For example:
```
---
options:
command_prefix: "cmd:"
---
<!-- remember to say "potato here" -->
Tasty vegetables
================
* Potato
<!-- cmd:pause -->
**That's it!**
```
In the example above, the first comment is ignored because it doesn't start with "cmd:" and the second one is processed
because it does.
## incremental_lists
If you'd like all bullet points in all lists to show up with pauses in between you can enable the `incremental_lists`
option:
```
---
options:
incremental_lists: true
---
* pauses
* in
* between
```
Keep in mind if you only want specific bullet points to show up with pauses in between, you can use the
[`incremental_lists` comment command](../features/commands.md#incremental-lists).
## strict_front_matter_parsing
This option tells _presenterm_ you don't care about extra parameters in presentation's front matter. This can be useful
if you're trying to load a presentation made for another tool. The following presentation would only be successfully
loaded if you set `strict_front_matter_parsing` to `false` in your configuration file:
```markdown
---
potato: 42
---
# Hi
```
## image_attributes_prefix
The [image size](../features/images.md#image-size) prefix (by default `image:`) can be configured to be anything you
would want in case you don't like the default one. For example, if you'd like to set the image size by simply doing
`![width:50%](path.png)` you would need to set:
```yaml
---
options:
image_attributes_prefix: ""
---
![width:50%](path.png)
```
## auto_render_languages
This option allows indicating a list of languages for which the `+render` attribute can be omitted in their code
snippets and will be implicitly considered to be set. This can be used for languages like `mermaid` so that graphs are
always automatically rendered without the need to specify `+render` everywhere.
```yaml
---
options:
auto_render_languages:
- mermaid
---
```

View File

@ -1,305 +0,0 @@
# Settings
As opposed to options, the rest of these settings **can only be configured via the configuration file**.
## Default theme
The default theme can be configured only via the config file. When this is set, every presentation that doesn't set a
theme explicitly will use this one:
```yaml
defaults:
theme: light
```
## Terminal font size
This is a parameter that lets you explicitly set the terminal font size in use. This should not be used unless you are
in Windows, given there's no (easy) way to get the terminal window size so we use this to figure out how large the
window is and resize images properly. Some terminals on other platforms may also have this issue, but that should not be
as common.
If you are on Windows or you notice images show up larger/smaller than they should, you can adjust this setting in your
config file:
```yaml
defaults:
terminal_font_size: 16
```
## Preferred image protocol
By default _presenterm_ will try to detect which image protocol to use based on the terminal you are using. In case
detection for some reason fails in your setup or you'd like to force a different protocol to be used, you can explicitly
set this via the `--image-protocol` parameter or the configuration key `defaults.image_protocol`:
```yaml
defaults:
image_protocol: kitty-local
```
Possible values are:
* `auto`: try to detect it automatically (default).
* `kitty-local`: use the kitty protocol in "local" mode, meaning both _presenterm_ and the terminal run in the same host
and can share the filesystem to communicate.
* `kitty-remote`: use the kitty protocol in "remote" mode, meaning _presenterm_ and the terminal run in different hosts
and therefore can only communicate via terminal escape codes.
* `iterm2`: use the iterm2 protocol.
* `sixel`: use the sixel protocol. Note that this requires compiling _presenterm_ using the `--features sixel` flag.
## Maximum presentation width
The `max_columns` property can be set to specify the maximum number of columns that the presentation will stretch to. If
your terminal is larger than that, the presentation will stick to that size and will be centered, preventing it from
looking too stretched.
```yaml
defaults:
max_columns: 100
```
If you would like your presentation to be left or right aligned instead of centered when the terminal is too wide, you
can use the `max_columns_alignment` key:
```yaml
defaults:
max_columns: 100
# Valid values: left, center, right
max_columns_alignment: left
```
## Maximum presentation height
The `max_rows` and `max_rows_alignment` properties are analogous to `max_columns*` to allow capping the maximum number
of rows:
```yaml
defaults:
max_rows: 100
# Valid values: top, center, bottom
max_rows_alignment: left
```
## Incremental lists behavior
By default, [incremental lists](../features/commands.md) will pause before and after a list. If you would like to change
this behavior, use the `defaults.incremental_lists` key:
```yaml
defaults:
incremental_lists:
# The defaults, change to false if desired.
pause_before: true
pause_after: true
```
# Slide transitions
Slide transitions allow animating your presentation every time you move from a slide to the next/previous one. The
configuration for slide transitions is the following:
```yaml
transition:
# how long the transition should last.
duration_millis: 750
# how many frames should be rendered during the transition
frames: 45
# the animation to use
animation:
style: <style_name>
```
See the [slide transitions page](../features/slide-transitions.md) for more information on which animation styles are
supported.
# Key bindings
Key bindings that _presenterm_ uses can be manually configured in the config file via the `bindings` key. The following
is the default configuration:
```yaml
bindings:
# the keys that cause the presentation to move forwards.
next: ["l", "j", "<right>", "<page_down>", "<down>", " "]
# the keys that cause the presentation to move backwards.
previous: ["h", "k", "<left>", "<page_up>", "<up>"]
# the keys that cause the presentation to move "fast" to the next slide. this will ignore:
#
# * Pauses.
# * Dynamic code highlights.
# * Slide transitions, if enabled.
next_fast: ["n"]
# same as `next_fast` but jumps fast to the previous slide.
previous_fast: ["p"]
# the key binding to jump to the first slide.
first_slide: ["gg"]
# the key binding to jump to the last slide.
last_slide: ["G"]
# the key binding to jump to a specific slide.
go_to_slide: ["<number>G"]
# the key binding to execute a piece of shell code.
execute_code: ["<c-e>"]
# the key binding to reload the presentation.
reload: ["<c-r>"]
# the key binding to toggle the slide index modal.
toggle_slide_index: ["<c-p>"]
# the key binding to toggle the key bindings modal.
toggle_bindings: ["?"]
# the key binding to close the currently open modal.
close_modal: ["<esc>"]
# the key binding to close the application.
exit: ["<c-c>", "q"]
# the key binding to suspend the application.
suspend: ["<c-z>"]
```
You can choose to override any of them. Keep in mind these are overrides so if for example you change `next`, the
default won't apply anymore and only what you've defined will be used.
# Snippet configurations
The configurations that affect code snippets in presentations.
## Snippet execution
[Snippet execution](../features/code/execution.md#executing-code-blocks) is disabled by default for security reasons.
Besides passing in the `-x` command line parameter every time you run _presenterm_, you can also configure this globally
for all presentations by setting:
```yaml
snippet:
exec:
enable: true
```
**Use this at your own risk**, especially if you're running someone else's presentations!
## Snippet execution + replace
[Snippet execution + replace](../features/code/execution.md#executing-and-replacing) is disabled by default for security
reasons. Similar to `+exec`, this can be enabled by passing in the `-X` command line parameter or configuring it
globally by setting:
```yaml
snippet:
exec_replace:
enable: true
```
**Use this at your own risk**. This will cause _presenterm_ to execute code without user intervention so don't blindly
enable this and open a presentation unless you trust its origin!
## Custom snippet executors
If _presenterm_ doesn't support executing code snippets for your language of choice, please [create an
issue](https://github.com/mfontanini/presenterm/issues/new)! Alternatively, you can configure this locally yourself by
setting:
```yaml
snippet:
exec:
custom:
# The keys should be the language identifier you'd use in a code block.
c++:
# The name of the file that will be created with your snippet's contents.
filename: "snippet.cpp"
# A list of environment variables that should be set before building/running your code.
environment:
MY_FAVORITE_ENVIRONMENT_VAR: foo
# A prefix that indicates a line that starts with it should not be visible but should be executed if the
# snippet is marked with `+exec`.
hidden_line_prefix: "/// "
# A list of commands that will be ran one by one in the same directory as the snippet is in.
commands:
# Compile if first
- ["g++", "-std=c++20", "snippet.cpp", "-o", "snippet"]
# Now run it
- ["./snippet"]
```
The output of all commands will be included in the code snippet execution output so if a command (like the `g++`
invocation) was to emit any output, make sure to use whatever flags are needed to mute its output.
Also note that you can override built-in executors in case you want to run them differently (e.g. use `c++23` in the
example above).
See more examples in the [executors.yaml](https://github.com/mfontanini/presenterm/blob/master/executors.yaml) file
which defines all of the built-in executors.
## Snippet rendering threads
Because some `+render` code blocks can take some time to be rendered into an image, especially if you're using
[mermaid](https://mermaid.js.org/) charts, this is run asychronously. The number of threads used to render these, which
defaults to 2, can be configured by setting:
```yaml
snippet:
render:
threads: 2
```
## Mermaid scaling
[mermaid](https://mermaid.js.org/) graphs will use a default scaling of `2` when invoking the mermaid CLI. If you'd like
to change this use:
```yaml
mermaid:
scale: 2
```
## Enabling speaker note publishing
If you don't want to run _presenterm_ with `--publish-speaker-notes` every time you want to publish speaker notes, you
can set the `speaker_notes.always_publish` attribute to `true`.
```yaml
speaker_notes:
always_publish: true
```
# Presentation exports
The configurations that affect PDF exports.
## PDF export size
The size of exported PDFs can be configured via the `export.dimensions` key:
```yaml
export:
dimensions:
columns: 80
rows: 30
```
See [the PDF export page](../features/pdf-export.md) for more information.
## Pause behavior
By default pauses will be ignored in generated PDF files. If instead you'd like every pause to generate a new page in
the export, set the `export.pauses` attribute:
```yaml
export:
pauses: new_slide
```

View File

@ -1,180 +0,0 @@
# Code highlighting
Code highlighting is supported for the following languages:
| Language | Execution support |
| -----------|-------------------|
| ada | |
| asp | |
| awk | |
| bash | ✓ |
| batchfile | |
| C | ✓ |
| cmake | |
| crontab | |
| C# | ✓ |
| clojure | |
| C++ | ✓ |
| CSS | |
| D | |
| diff | |
| docker | |
| dotenv | |
| elixir | |
| elm | |
| erlang | |
| fish | ✓ |
| go | ✓ |
| haskell | ✓ |
| HTML | |
| java | ✓ |
| javascript | ✓ |
| json | |
| julia | ✓ |
| kotlin | ✓ |
| latex | |
| lua | ✓ |
| makefile | |
| markdown | |
| nix | |
| ocaml | |
| perl | ✓ |
| php | ✓ |
| protobuf | |
| puppet | |
| python | ✓ |
| R | ✓ |
| ruby | ✓ |
| rust | ✓ |
| scala | |
| shell | ✓ |
| sql | |
| swift | |
| svelte | |
| tcl | |
| toml | |
| terraform | |
| typescript | |
| xml | |
| yaml | |
| vue | |
| zig | |
| zsh | ✓ |
Other languages that are supported are:
* nushell, for which highlighting isn't supported but execution is.
* rust-script, which is highlighted as rust but is executed via the [rust-script](https://rust-script.org/) tool,
which lets you specify dependencies in your snippet.
If there's a language that is not in this list and you would like it to be supported, please [create an
issue](https://github.com/mfontanini/presenterm/issues/new). If you'd also like code execution support, provide details
on how to compile (if necessary) and run snippets for that language. You can also configure how to run code snippet for
a language locally in your [config file](../../configuration/settings.md#custom-snippet-executors).
## Enabling line numbers
If you would like line numbers to be shown on the left of a code block use the `+line_numbers` switch after specifying
the language in a code block:
~~~markdown
```rust +line_numbers
fn hello_world() {
println!("Hello world");
}
```
~~~
## Selective highlighting
By default, the entire code block will be syntax-highlighted. If instead you only wanted a subset of it to be
highlighted, you can use braces and a list of either individual lines, or line ranges that you'd want to highlight.
~~~markdown
```rust {1,3,5-7}
fn potato() -> u32 { // 1: highlighted
// 2: not highlighted
println!("Hello world"); // 3: highlighted
let mut q = 42; // 4: not highlighted
q = q * 1337; // 5: highlighted
q // 6: highlighted
} // 7: highlighted
```
~~~
## Dynamic highlighting
Similar to the syntax used for selective highlighting, dynamic highlighting will change which lines of the code in a
code block are highlighted every time you move to the next/previous slide.
This is achieved by using the separator `|` to indicate what sections of the code will be highlighted at a given time.
You can also use `all` to highlight all lines for a particular frame.
~~~markdown
```rust {1,3|5-7}
fn potato() -> u32 {
println!("Hello world");
let mut q = 42;
q = q * 1337;
q
}
```
~~~
In this example, lines 1 and 3 will be highlighted initially. Then once you press a key to move to the next slide, lines
1 and 3 will no longer be highlighted and instead lines 5 through 7 will. This allows you to create more dynamic
presentations where you can display sections of the code to explain something specific about each of them.
See this real example of how this looks like.
[![asciicast](https://asciinema.org/a/iCf4f6how1Ux3H8GNzksFUczI.svg)](https://asciinema.org/a/iCf4f6how1Ux3H8GNzksFUczI)
## Including external code snippets
The `file` snippet type can be used to specify an external code snippet that will be included and highlighted as usual.
~~~markdown
```file +exec +line_numbers
path: snippet.rs
language: rust
```
~~~
If you'd like to include only a subset of the file, you can use the optional fields `start_line` and `end_line`:
~~~markdown
```file +exec +line_numbers
path: snippet.rs
language: rust
# Only shot lines 5-10
start_line: 5
end_line: 10
```
~~~
## Showing a snippet without a background
Using the `+no_background` flag will cause the snippet to have no background. This is useful when combining it with the
`+exec_replace` flag described further down.
## Adding highlighting syntaxes for new languages
_presenterm_ uses the syntaxes supported by [bat](https://github.com/sharkdp/bat) to highlight code snippets, so any
languages supported by _bat_ natively can be added to _presenterm_ easily. Please create a ticket or use
[this](https://github.com/mfontanini/presenterm/pull/385) as a reference to submit a pull request to make a syntax
officially supported by _presenterm_ as well.
If a language isn't natively supported by _bat_ but you'd like to use it, you can follow
[this guide in the bat docs](https://github.com/sharkdp/bat#adding-new-syntaxes--language-definitions) and
invoke _bat_ directly in a presentation:
~~~markdown
```bash +exec_replace
bat --color always script.py
```
~~~
> [!note]
> Check the [code execution docs](execution.md#executing-and-replacing) for more details on how to allow the tool to run
> `exec_replace` blocks.

View File

@ -1,123 +0,0 @@
# Comment commands
_presenterm_ uses "comment commands" in the form of HTML comments to let the user specify certain behaviors that can't
be specified by vanilla markdown.
## Pauses
Pauses allow the sections of the content in your slide to only show up when you advance in your presentation. That is,
only after you press, say, the right arrow will a section of the slide show up. This can be done by the `pause` comment
command:
```html
<!-- pause -->
```
## Font size
The font size can be changed by using the `font_size` command:
```html
<!-- font_size: 2 -->
```
This causes the remainder of the slide to use the font size specified. The font size can range from 1 to 7, 1 being the
default.
> ![note]
> This is currently only supported in the [_kitty_](https://sw.kovidgoyal.net/kitty/) terminal and only as of version
> 0.40.0. See the notes on font sizes on the [introduction page](introduction.md#font-sizes) for more information on
> this.
## Jumping to the vertical center
The command `jump_to_middle` lets you jump to the middle of the page vertically. This is useful in combination
with slide titles to create separator slides:
```markdown
blablabla
<!-- end_slide -->
<!-- jump_to_middle -->
Farming potatoes
===
<!-- end_slide -->
```
This will create a slide with the text "Farming potatoes" in the center, rendered using the slide title style.
## Explicit new lines
The `newline`/`new_line` and `newlines`/`new_lines` commands allow you to explicitly create new lines. Because markdown
ignores multiple line breaks in a row, this is useful to create some spacing where necessary:
```markdown
hi
<!-- new_lines: 10 -->
mom
<!-- new_line -->
bye
```
## Incremental lists
Using `<!-- pause -->` in between each bullet point a list is a bit tedious so instead you can use the
`incremental_lists` command to tell _presenterm_ that **until the end of the current slide** you want each individual
bullet point to appear only after you move to the next slide:
```markdown
<!-- incremental_lists: true -->
* this
* appears
* one after
* the other
<!-- incremental_lists: false -->
* this appears
* all at once
```
## No footer
If you don't want the footer to show up in some particular slide for some reason, you can use the `no_footer` command:
```html
<!-- no_footer -->
```
## Skip slide
If you don't want a specific slide to be included in the presentation use the `skip_slide` command:
```html
<!-- skip_slide -->
```
## Text alignment
The text alignment for the remainder of the slide can be configured via the `alignment` command, which can use values:
`left`, `center`, and `right`:
```markdown
<!-- alignment: left -->
left alignment, the default
<!-- alignment: center -->
centered
<!-- alignment: right -->
right aligned
```

View File

@ -1,58 +0,0 @@
# Images
Images are supported and will render in your terminal as long as it supports either the [iterm2 image
protocol](https://iterm2.com/documentation-images.html), the [kitty graphics
protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/), or [sixel](https://saitoha.github.io/libsixel/). Some of
the terminals where at least one of these is supported are:
* [kitty](https://sw.kovidgoyal.net/kitty/)
* [iterm2](https://iterm2.com/)
* [WezTerm](https://wezfurlong.org/wezterm/index.html)
* [foot](https://codeberg.org/dnkl/foot)
Sixel support is experimental so it needs to be explicitly enabled via the `sixel` configuration flag:
```bash
cargo build --release --features sixel
```
> [!note]
> This feature flag is only needed if your terminal emulator _only_ supports sixel. Many terminals support the kitty or
> iterm2 protocols so using this flag is often not required to get images to render successfully.
---
Things you should know when using image tags in your presentation's markdown are:
* Image paths are relative to your presentation path. That is a tag like `![](food/potato.png)` will be looked up at
`$PRESENTATION_DIRECTORY/food/potato.png`.
* Images will be rendered by default in their original size. That is, if your terminal is 300x200px and your image is
200x100px, it will take up 66% of your horizontal space and 50% of your vertical space.
* The exception to the point above is if the image does not fit in your terminal, it will be resized accordingly while
preserving the aspect ratio.
* If your terminal does not support any of the graphics protocol above, images will be rendered using ascii blocks. It
ain't great but it's something!
## tmux
If you're using tmux, you will need to enable the [allow-passthrough
option](https://github.com/tmux/tmux/wiki/FAQ#what-is-the-passthrough-escape-sequence-and-how-do-i-use-it) for images to
work correctly.
## Image size
The size of each image can be set by using the `image:width` or `image:w` attributes in the image tag. For example, the
following will cause the image to take up 50% of the terminal width:
```markdown
![image:width:50%](image.png)
```
The image will always be scaled to preserve its aspect ratio and it will not be allowed to overflow vertically nor
horizontally.
## Protocol detection
By default the image protocol to be used will be automatically detected. In cases where this detection fails, you can
set it manually via the `--image-protocol` parameter or by setting it in the [config
file](../configuration/settings.md#preferred-image-protocol).

View File

@ -1,182 +0,0 @@
# Introduction
This guide teaches you how to use _presenterm_. At this point you should have already installed _presenterm_, otherwise
visit the [installation](../install.md) guide to get started.
## Quick start
Download the demo presentation and run it using:
```bash
git clone https://github.com/mfontanini/presenterm.git
cd presenterm
presenterm examples/demo.md
```
# Presentations
A presentation in _presenterm_ is a single markdown file. Every slide in the presentation file is delimited by a line
that contains a single HTML comment:
```html
<!-- end_slide -->
```
Presentations can contain most commonly used markdown elements such as ordered and unordered lists, headings, formatted
text (**bold**, _italics_, ~strikethrough~, `inline code`, etc), code blocks, block quotes, tables, etc.
## Introduction slide
By setting a front matter at the beginning of your presentation you can configure the title, sub title, author and other
metadata about your presentation. Doing so will cause _presenterm_ to create an introduction slide:
```yaml
---
title: "My _first_ **presentation**"
sub_title: (in presenterm!)
author: Myself
---
```
All of these attributes are optional and should be avoided if an introduction slide is not needed. Note that the `title`
key can contain arbitrary markdown so you can use bold, italics, `<span>` tags, etc.
### Multiple authors
If you're creating a presentation in which there's multiple authors, you can use the `authors` key instead of `author`
and list them all this way:
```yaml
---
title: Our first presentation
authors:
- Me
- You
---
```
## Slide titles
Any [setext header](https://spec.commonmark.org/0.30/#setext-headings) will be considered to be a slide title and will
be rendered in a more slide-title-looking way. By default this means it will be centered, some vertical padding will be
added and the text color will be different.
~~~markdown
Hello
===
~~~
> [!note]
> See the [themes](themes/introduction.md) section on how to customize the looks of slide titles and any other element
> in a presentation.
## Ending slides
While other applications use a thematic break (`---`) to mark the end of a slide, _presenterm_ uses a special
`end_slide` HTML comment:
```html
<!-- end_slide -->
```
This makes the end of a slide more explicit and easy to spot while you're editing your presentation. See the
[configuration](../configuration/options.md#implicit_slide_ends) if you want to customize this behavior.
If you really would prefer to use thematic breaks (`---`) to delimit slides, you can do that by enabling the
[`end_slide_shorthand`](../configuration/options.md#end_slide_shorthand) options.
## Colored text
`span` HTML tags can be used to provide foreground and/or background colors to text. There's currently two ways to
specify colors:
* Via the `style` attribute, in which only the CSS attributes `color` and `background-color` can be used to set the
foreground and background colors respectively. Colors used in both CSS attributes can refer to
[theme palette colors](themes/definition.md#color-palette) by using the `palette:<name>` or `p:<name` syntaxes.
* Via the `class` attribute, which must point to a class defined in the [theme
palette](themes/definition.md#color-palette). Classes allow configuring foreground/background color combinations to be
used across your presentation.
For example, the following will use `ff0000` as the foreground color and whatever the active theme's palette defines as
`foo`:
```markdown
<span style="color: #ff0000; background-color: palette:foo">colored text!</span>
```
Alternatively, can you can define a class that contains a foreground/background color combination in your theme's
palette and use it:
```markdown
<span class="my_class">colored text!</span>
```
> [!note]
> Keep in mind **only `span` tags are supported**.
## Font sizes
The [_kitty_](https://sw.kovidgoyal.net/kitty/) terminal added in version 0.40.0 support for a new protocol that allows
TUIs to specify the font size to be used when printing text. _presenterm_ is one of the first applications supports this
protocol in various places:
* Themes can specify it in the presentation title in the introduction slide, in slide titles, and in headers by using
the `font_size` property. All built in themes currently set font size to 2 (1 is the default) for these elements.
* Explicitly by using the `font_size` comment command:
```markdown
# Normal text
<!-- font_size: 2 -->
# Larger text
```
Terminal support for this feature is verified when _presenterm_ starts and any attempt to change the font size, be it
via the theme or via the comment command, will be ignored if it's not supported.
# Key bindings
Navigation within a presentation should be intuitive: jumping to the next/previous slide can be done by using the arrow
keys, _hjkl_, and page up/down keys.
Besides this:
* Jumping to the first slide: `gg`.
* Jumping to the last slide: `G`.
* Jumping to a specific slide: `<slide-number>G`.
* Exit the presentation: `<ctrl>c`.
You can check all the configured keybindings by pressing `?` while running _presenterm_.
## Configuring key bindings
If you don't like the default key bindings, you can override them in the [configuration
file](../configuration/settings.md#key-bindings).
# Modals
_presenterm_ currently has 2 modals that can provide some information while running the application. Modals can be
toggled using some key combination and can be hidden using the escape key by default, but these can be configured via
the [configuration file key bindings](../configuration/settings.md#key-bindings).
## Slide index modal
This modal can be toggled by default using `control+p` and lets you see an index that contains a row for every slide in
the presentation, including its title and slide index. This allows you to find a slide you're trying to jump to
quicklier rather than scanning through each of them.
[![asciicast](https://asciinema.org/a/1VgRxVIEyLrMmq6OZ3oKx4PGi.svg)](https://asciinema.org/a/1VgRxVIEyLrMmq6OZ3oKx4PGi)
## Key bindings modal
The key bindings modal displays the key bindings for each of the supported actions and can be opened by pressing `?`.
# Hot reload
Unless you run in presentation mode by passing in the `--present` parameter, _presenterm_ will automatically reload your
presentation file every time you save it. _presenterm_ will also automatically detect which specific slide was modified
and jump to it so you don't have to be jumping back and forth between the source markdown and the presentation to see
how the changes look like.
[![asciicast](https://asciinema.org/a/bu9ITs8KhaQK5OdDWnPwUYKu3.svg)](https://asciinema.org/a/bu9ITs8KhaQK5OdDWnPwUYKu3)

View File

@ -1,35 +0,0 @@
# Exporting presentations in PDF format
Presentations can be converted into PDF by using [weasyprint](https://pypi.org/project/weasyprint/). Follow their
[installation instructions](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html) since it may require you
to install extra dependencies for the tool to work.
> [!note]
> If you were using _presenterm-export_ before it was deprecated, that tool already required _weasyprint_ so it is
> already installed in whatever virtual env you were using and there's nothing to be done.
After you've installed _weasyprint_, run _presenterm_ with the `--export-pdf` parameter to generate the output PDF:
```bash
presenterm --export-pdf examples/demo.md
```
The output PDF will be placed in `examples/demo.pdf`. Alternatively you can use the `--output` flag to specify where you
want the output file to be written to.
> [!note]
> If you're using a separate virtual env to install _weasyprint_ just make sure you activate it before running
> _presenterm_ with the `--export-pdf` parameter.
## PDF page size
By default, the size of each page in the generated PDF will depend on the size of your terminal.
If you would like to instead configure the dimensions by hand, set the `export.dimensions` key in the configuration file
as described in the [settings page](../configuration/settings.md#pdf-export-size).
## Pause behavior
See the [settings page](../configuration/settings.md#pause-behavior) to learn how to configure the behavior of pauses in
generated PDFs.

View File

@ -1,24 +0,0 @@
# Slide transitions
Slide transitions allow animating your presentation every time you move from a slide to the next/previous one. See the
[configuration page](../configuration/settings.md#slide-transitions) to learn how to configure transitions.
The following animations are supported:
## `fade`
Fade the current slide into the next one.
[![asciicast](https://asciinema.org/a/RvxLw0FHOopjdF4ixWbCkWuSw.svg)](https://asciinema.org/a/RvxLw0FHOopjdF4ixWbCkWuSw)
## `slide_horizontal`
Slide horizontally to the next/previous slide.
[![asciicast](https://asciinema.org/a/T43ttxPWZ8TsM2auTqNZSWrmZ.svg)](https://asciinema.org/a/T43ttxPWZ8TsM2auTqNZSWrmZ)
## `collapse_horizontal`
Collapse the current slide into the center of the screen horizontally.
[![asciicast](https://asciinema.org/a/VB8i3kGMvbkbiYYPpaZJUl2dW.svg)](https://asciinema.org/a/VB8i3kGMvbkbiYYPpaZJUl2dW)

View File

@ -1,72 +0,0 @@
## Speaker notes
Starting on version 0.10.0, _presenterm_ allows presentations to define speaker notes. The way this works is:
* You start an instance of _presenterm_ using the `--publish-speaker-notes` parameter. This will be the main instance in
which you will present like you usually do.
* Another instance should be started using the `--listen-speaker-notes` parameter. This instance will only display
speaker notes in the presentation and will automatically change slides whenever the main instance does so.
For example:
```bash
# Start the main instance
presenterm demo.md --publish-speaker-notes
# In another shell: start the speaker notes instance
presenterm demo.md --listen-speaker-notes
```
[![asciicast](https://asciinema.org/a/ETusvlmHuHrcLKzwa0CMQRX2J.svg)](https://asciinema.org/a/ETusvlmHuHrcLKzwa0CMQRX2J)
See the [speaker notes example](https://github.com/mfontanini/presenterm/blob/master/examples/speaker-notes.md) for more
information.
### Defining speaker notes
In order to define speaker notes you can use the `speaker_notes` comment command:
```markdown
Normal text
<!-- speaker_note: this is a speaker note -->
More text
```
When running this two instance setup, the main one will show "normal text" and "more text", whereas the second one will
only show "this is a speaker note" on that slide.
### Multiline speaker notes
You can use multiline speaker notes by using the appropriate YAML syntax:
```yaml
<!--
speaker_note: |
something
something else
-->
```
### Multiple instances
On Linux and Windows, you can run multiple instances in publish mode and multiple instances in listen mode at the same
time. Each instance will only listen to events for the presentation it was started on.
On Mac this is not supported and only a single listener can be used at a time.
### Enabling publishing by default
You can use the `speaker_notes.always_publish` key in your config file to always publish speaker notes. This means you
will only ever need to use `--listen-speaker-notes` and you will never need to use `--publish-speaker-notes`:
```yaml
speaker_notes:
always_publish: true
```
### Internals
This uses UDP sockets on localhost to communicate between instances. The main instance sends events every time a slide
is shown and the listener instances listen to them and displays the speaker notes for that specific slide.

View File

@ -1,102 +0,0 @@
# Themes
_presenterm_ tries to be as configurable as possible, allowing users to create presentations that look exactly how they
want them to look like. The tool ships with a set of [built-in
themes](https://github.com/mfontanini/presenterm/tree/master/themes) but users can be created by users in their local
setup and imported in their presentations.
## Setting themes
There's various ways of setting the theme you want in your presentation:
### CLI
Passing in the `--theme` parameter when running _presenterm_ to select one of the built-in themes.
### Within the presentation
The presentation's markdown file can contain a front matter that specifies the theme to use. This comes in 3 flavors:
#### By name
Using a built-in theme name makes your presentation use that one regardless of what the default or what the `--theme`
option specifies:
```yaml
---
theme:
name: dark
---
```
#### By path
You can define a theme file in yaml format somewhere in your filesystem and reference it within the presentation:
```yaml
---
theme:
path: /home/me/Documents/epic-theme.yaml
---
```
#### Overrides
You can partially/completely override the theme in use from within the presentation:
```yaml
---
theme:
override:
default:
colors:
foreground: "beeeff"
---
```
This lets you:
1. Create a unique style for your presentation without having to go through the process of taking an existing theme,
copying somewhere, and changing it when you only expect to use it for that one presentation.
2. Iterate quickly on styles given overrides are reloaded whenever you save your presentation file.
# Built-in themes
A few built-in themes are bundled with the application binary, meaning you don't need to have any external files
available to use them. These are packed as part of the [build
process](https://github.com/mfontanini/presenterm/blob/master/build.rs) as a binary blob and are decoded on demand only
when used.
Currently, the following themes are supported:
* A set of themes based on the [catppuccin](https://github.com/catppuccin/catppuccin) color palette:
* `catppuccin-latte`
* `catppuccin-frappe`
* `catppuccin-macchiato`
* `catppuccin-mocha`
* `dark`: A dark theme.
* `gruvbox`: A theme inspired by the colors used in [gruvbox](https://github.com/morhetz/gruvbox).
* `light`: A light theme.
* `terminal-dark`: A theme that uses your terminals color and looks best if your terminal uses a dark color scheme. This
means if your terminal background is e.g. transparent, or uses an image, the presentation will inherit that.
* `terminal-light`: The same as `terminal-dark` but works best if your terminal uses a light color scheme.
* `tokyonight-storm`: A theme inspired by the colors used in [toyonight](https://github.com/folke/tokyonight.nvim).
## Trying out built-in themes
All built-in themes can be tested by using the `--list-themes` parameter:
```bash
presenterm --list-themes
```
This will run a presentation where the same content is rendered using a different theme in each slide:
[![asciicast](https://asciinema.org/a/zeV1QloyrLkfBp6rNltvX7Lle.svg)](https://asciinema.org/a/zeV1QloyrLkfBp6rNltvX7Lle)
# Loading custom themes
On startup, _presenterm_ will look into the `themes` directory under the [configuration
directory](../../configuration/introduction.md) (e.g. `~/.config/presenterm/themes` in Linux) and will load any `.yaml`
file as a theme and make it available as if it was a built-in theme. This means you can use it as an argument to the
`--theme` parameter, use it in the `theme.name` property in a presentation's front matter, etc.

252
docs/src/guides/basics.md Normal file
View File

@ -0,0 +1,252 @@
## Introduction
This guide teaches you how to use _presenterm_. At this point you should have already installed _presenterm_, otherwise
visit the [installation](installation.html) guide to get started.
### Quick start
Download the demo presentation and run it using:
```shell
git clone https://github.com/mfontanini/presenterm.git
cd presenterm
presenterm examples/demo.md
```
## Presentations
A presentation in _presenterm_ is a single markdown file. Every slide in the presentation file is delimited by a line
that contains a single HTML comment:
```html
<!-- end_slide -->
```
Presentations can contain most commonly used markdown elements such as ordered and unordered lists, headings, formatted
text (**bold**, _italics_, ~strikethrough~, `inline code`, etc), code blocks, block quotes, tables, etc.
### Images
![](../assets/demo-image.png)
Images are supported and will render in your terminal as long as it supports either the [iterm2 image
protocol](https://iterm2.com/documentation-images.html), the [kitty graphics
protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/), or [sixel](https://saitoha.github.io/libsixel/). Some of
the terminals where at least one of these is supported are:
* kitty
* iterm2
* wezterm
* foot
Note that sixel support is experimental so it needs to be explicitly enabled via the `sixel` configuration flag:
```shell
cargo build --release --features sixel
```
> **Note**: this feature flag is only needed if your terminal emulator only supports sixel. Many terminals support the
> kitty or iterm2 protocols so this isn't necessary.
---
Things you should know when using image tags in your presentation's markdown are:
* Image paths are relative to your presentation path. That is a tag like `![](food/potato.png)` will be looked up at
`$PRESENTATION_DIRECTORY/food/potato.png`.
* Images will be rendered by default in their original size. That is, if your terminal is 300x200px and your image is
200x100px, it will take up 66% of your horizontal space and 50% of your vertical space.
* The exception to the point above is if the image does not fit in your terminal, it will be resized accordingly while
preserving the aspect ratio.
* If your terminal does not support any of the graphics protocol above, images will be rendered using ascii blocks. It
ain't great but it's something!
#### Image size
The size of each image can be set by using the `image:width` or `image:w` attributes in the image tag. For example, the
following will cause the image to take up 50% of the terminal width:
```markdown
![image:width:50%](image.png)
```
The image will always be scaled to preserve its aspect ratio and it will not be allowed to overflow vertically nor
horizontally.
#### Protocol detection
By default the image protocol to be used will be automatically detected. In cases where this detection fails (e.g. when
running inside `tmux`), you can set it manually via the `--image-protocol` parameter or by setting it in the [config
file](configuration.html#preferred-image-protocol).
## Extensions
Besides the standard markdown elements, _presenterm_ supports a few extensions.
### Introduction slide
By setting a front matter at the beginning of your presentation, you can configure the title, sub title, and author of
your presentation and implicitly create an introduction slide:
```markdown
---
title: My first presentation
sub_title: (in presenterm!)
author: Myself
---
```
All of these attributes are optional so you're not forced to set them all.
#### Multiple authors
If you're creating a presentation in which there's multiple authors, you can use the `authors` key instead of `author`
and list them all this way:
```markdown
---
title: Our first presentation
authors:
- Me
- You
---
```
### Slide titles
Any [setext header](https://spec.commonmark.org/0.30/#setext-headings) will be considered to be a slide title and will
be rendered in a more slide-title-looking way. By default this means it will be centered, some vertical padding will be
added and the text color will be different.
~~~
Hello
===
~~~
> Note: see the [themes](themes.html) section on how to customize the looks of slide titles and any other element in a
> presentation.
### Pauses
Pauses allow the sections of the content in your slide to only show up when you advance in your presentation. That is,
only after you press, say, the right arrow will a section of the slide show up. This can be done by the `pause` comment
command:
```html
<!-- pause -->
```
### Ending slides
While other applications use a thematic break (`---`) to mark the end of a slide, _presenterm_ uses a special
`end_slide` HTML comment:
```html
<!-- end_slide -->
```
This makes the end of a slide more explicit and easy to spot while you're editing your presentation. See the
[configuration](/docs/config.md#implicit_slide_ends) if you want to customize this behavior.
If you really would prefer to use thematic breaks (`---`) to delimit slides, you can do that by enabling the
[`end_slide_shorthand`](configuration.html#end_slide_shorthand) options.
### Jumping to the vertical center
The command `jump_to_middle` lets you jump to the middle of the page vertically. This is useful in combination
with slide titles to create separator slides:
```markdown
blablabla
<!-- end_slide -->
<!-- jump_to_middle -->
Farming potatoes
===
<!-- end_slide -->
```
This will create a slide with the text "Farming potatoes" in the center, rendered using the slide title style.
### Explicit new lines
The `newline`/`new_line` and `newlines`/`new_lines` commands allow you to explicitly create new lines. Because markdown
ignores multiple line breaks in a row, this is useful to create some spacing where necessary:
```markdown
hi
<!-- new_lines: 10 -->
mom
<!-- new_line -->
bye
```
### Incremental lists
Using `<!-- pause -->` in between each bullet point a list is a bit tedious so instead you can use the
`incremental_lists` command to tell _presenterm_ that **until the end of the current slide** you want each individual
bullet point to appear only after you move to the next slide:
```markdown
<!-- incremental_lists: true -->
* this
* appears
* one after
* the other
<!-- incremental_lists: false -->
* this appears
* all at once
```
## Key bindings
Navigation within a presentation should be intuitive: jumping to the next/previous slide can be done by using the arrow
keys, _hjkl_, and page up/down keys.
Besides this:
* Jumping to the first slide: `gg`.
* Jumping to the last slide: `G`.
* Jumping to a specific slide: `<slide-number>G`.
* Exit the presentation: `<ctrl>c`.
### Configuring key bindings
If you don't like the default key bindings, you can override them in the [configuration
file](configuration.html#key-bindings).
## Modals
_presenterm_ currently has 2 modals that can provide some information while running the application. Modals can be
toggled using some key combination and can be hidden using the escape key by default, but these can be configured via
the [configuration file key bindings](configuration.html#key-bindings).
### Slide index modal
This modal can be toggled by default using `control+p` and lets you see an index that contains a row for every slide in
the presentation, including its title and slide index. This allows you to find a slide you're trying to jump to
quicklier rather than scanning through each of them.
[![asciicast](https://asciinema.org/a/1VgRxVIEyLrMmq6OZ3oKx4PGi.svg)](https://asciinema.org/a/1VgRxVIEyLrMmq6OZ3oKx4PGi)
### Key bindings modal
The key bindings modal displays the key bindings for each of the supported actions.
## Hot reload
Unless you run in presentation mode by passing in the `--present` parameter, _presenterm_ will automatically reload your
presentation file every time you save it. _presenterm_ will also automatically detect which specific slide was modified
and jump to it so you don't have to be jumping back and forth between the source markdown and the presentation to see
how the changes look like.
[![asciicast](https://asciinema.org/a/bu9ITs8KhaQK5OdDWnPwUYKu3.svg)](https://asciinema.org/a/bu9ITs8KhaQK5OdDWnPwUYKu3)

View File

@ -1,6 +1,137 @@
# Snippet execution
## Code highlighting
## Executing code blocks
Code highlighting is supported for the following languages:
* ada
* asp
* awk
* bash
* batchfile
* C
* cmake
* crontab
* C#
* clojure
* C++
* CSS
* D
* diff
* docker
* dotenv
* elixir
* elm
* erlang
* go
* haskell
* HTML
* java
* javascript
* json
* kotlin
* latex
* lua
* makefile
* markdown
* nix
* ocaml
* perl
* php
* protobuf
* puppet
* python
* R
* ruby
* rust
* scala
* shell
* sql
* swift
* svelte
* toml
* terraform
* typescript
* xml
* yaml
* vue
* zig
### Enabling line numbers
If you would like line numbers to be shown on the left of a code block use the `+line_numbers` switch after specifying
the language in a code block:
~~~markdown
```rust +line_numbers
fn hello_world() {
println!("Hello world");
}
```
~~~
### Selective highlighting
By default, the entire code block will be syntax-highlighted. If instead you only wanted a subset of it to be
highlighted, you can use braces and a list of either individual lines, or line ranges that you'd want to highlight.
~~~markdown
```rust {1,3,5-7}
fn potato() -> u32 { // 1: highlighted
// 2: not highlighted
println!("Hello world"); // 3: highlighted
let mut q = 42; // 4: not highlighted
q = q * 1337; // 5: highlighted
q // 6: highlighted
} // 7: highlighted
```
~~~
### Dynamic highlighting
Similar to the syntax used for selective highlighting, dynamic highlighting will change which lines of the code in a
code block are highlighted every time you move to the next/previous slide.
This is achieved by using the separator `|` to indicate what sections of the code will be highlighted at a given time.
You can also use `all` to highlight all lines for a particular frame.
~~~markdown
```rust {1,3|5-7}
fn potato() -> u32 {
println!("Hello world");
let mut q = 42;
q = q * 1337;
q
}
```
~~~
In this example, lines 1 and 3 will be highlighted initially. Then once you press a key to move to the next slide, lines
1 and 3 will no longer be highlighted and instead lines 5 through 7 will. This allows you to create more dynamic
presentations where you can display sections of the code to explain something specific about each of them.
See this real example of how this looks like.
[![asciicast](https://asciinema.org/a/iCf4f6how1Ux3H8GNzksFUczI.svg)](https://asciinema.org/a/iCf4f6how1Ux3H8GNzksFUczI)
### Including external code snippets
The `file` snippet type can be used to specify an external code snippet that will be included and highlighted as usual.
~~~markdown
```file +exec +line_numbers
path: snippet.rs
language: rust
```
~~~
### Showing a snippet without a background
Using the `+no_background` flag will cause the snippet to have no background. This is useful when combining it with the
`+exec_replace` flag described further down.
## Snippet execution
### Executing code blocks
Annotating a code block with a `+exec` attribute will make it executable. Pressing `control+e` when viewing a slide that
contains an executable block, the code in the snippet will be executed and the output of the execution will be displayed
@ -17,20 +148,42 @@ Code execution **must be explicitly enabled** by using either:
* The `-x` command line parameter when running _presenterm_.
* Setting the `snippet.exec.enable` property to `true` in your [_presenterm_ config
file](../../configuration/settings.md#snippet-execution).
Refer to [the table in the highlighting page](highlighting.md#code-highlighting) for the list of languages for which
code execution is supported.
file](configuration.html#snippet-execution).
---
The list of languages that support execution are:
* bash
* c++
* c
* fish
* go
* java
* js
* kotlin
* lua
* nushell
* perl
* php
* python
* ruby
* rust
* rust-script: this highlights as normal Rust but uses [rust-script](https://rust-script.org/) to execute the snippet so
it lets you use dependencies.
* sh
* zsh
If there's a language that is not in this list and you would like it to be supported, please [create an
issue](https://github.com/mfontanini/presenterm/issues/new) providing details on how to compile (if necessary) and run
snippets for that language. You can also configure how to run code snippet for a language locally in your [config
file](configuration.html#custom-snippet-executors).
[![asciicast](https://asciinema.org/a/BbAY817esxagCgPtnKUwgYnHr.svg)](https://asciinema.org/a/BbAY817esxagCgPtnKUwgYnHr)
> [!warning]
> Run code in presentations at your own risk! Especially if you're running someone else's presentation. Don't blindly
> enable snippet execution!
> **Note**: because this is spawning a process and executing code, you should use this at your own risk.
## Executing and replacing
### Executing and replacing
Similar to `+exec`, `+exec_replace` causes a snippet to be executable but:
@ -45,23 +198,7 @@ Because of the risk involved in `+exec_replace`, where code gets automatically e
this requires users to explicitly opt in to it. This can be done by either passing in the `-X` command line parameter
or setting the `snippet.exec_replace.enable` flag in your configuration file to `true`.
## Code to image conversions
The `+image` attribute behaves like `+exec_replace` but also assumes the output of the executed snippet will be an
image, and it will render it as such. For this to work, the code **must only emit an image in jpg/png formats** and
nothing else.
For example, this would render the demo presentation's image:
~~~markdown
```bash +image
cat examples/doge.png
```
~~~
This attribute carries the same risks as `+exec_replace` and therefore needs to be enabled via the same flags.
## Executing snippets that need a TTY
### Executing snippets that need a TTY
If you're trying to execute a program like `top` that needs to run on a TTY as it renders text, clears the screen, etc,
you can use the `+acquire_terminal` modifier on a code already marked as executable with `+exec`. Executing snippets
@ -70,7 +207,7 @@ raw terminal to do whatever it needs, and upon its completion _presenterm_ will
[![asciicast](https://asciinema.org/a/AHfuJorCNRR8ZEnfwQSDR5vPT.svg)](https://asciinema.org/a/AHfuJorCNRR8ZEnfwQSDR5vPT)
## Styled execution output
### Styled execution output
Snippets that generate output which contains escape codes that change the colors or styling of the text will be parsed
and displayed respecting those styles. Do note that you may need to force certain tools to use colored output as they
@ -86,7 +223,7 @@ ls /tmp --color=always
The parameter or way to enable this will depend on the tool being invoked.
## Hiding code lines
### Hiding code lines
When you mark a code snippet as executable via the `+exec` flag, you may not be interested in showing _all the lines_ to
your audience, as some of them may not be necessary to convey your point. For example, you may want to hide imports,
@ -114,12 +251,11 @@ basis. The languages that are supported and their prefix is:
This means that any line in a rust code snippet that starts with `# ` will be hidden, whereas all lines in, say, a
golang code snippet that starts with a `/// ` will be hidden.
## Pre-rendering
### Pre-rendering
Some languages support pre-rendering. This means the code block is transformed into something else when the presentation
is loaded. The languages that currently support this are _mermaid_, _LaTeX_, and _typst_ where the contents of the code
block is transformed into an image, allowing you to define formulas as text in your presentation. This can be done by
using the `+render` attribute on a code block.
See the [LaTeX and typst](latex.md) and [mermaid](mermaid.md) docs for more information.
See the [LaTeX and typst](latex.html) and [mermaid](mermaid.html) docs for more information.

View File

@ -0,0 +1,358 @@
## Configuration
_presenterm_ allows you to customize its behavior via a configuration file. This file is stored, along with all of your
custom themes, in the following directories:
* `$XDG_CONFIG_HOME/presenterm/` if that environment variable is defined, otherwise:
* `~/.config/presenterm/` in Linux.
* `~/Library/Application Support/presenterm/` in macOS.
* `~/AppData/Roaming/presenterm/config/` in Windows.
The configuration file will be looked up automatically in the directories above under the name `config.yaml`. e.g. on
Linux you should create it under `~/.config/presenterm/config.yaml`. You can also specify a custom path to this file
when running _presenterm_ via the `--config-path` parameter.
A [sample configuration file](https://github.com/mfontanini/presenterm/blob/master/config.sample.yaml) is provided in
the repository that you can use as a base.
## Options
Options are special configuration parameters that can be set either in the configuration file under the `options` key,
or in a presentation's front matter under the same key. This last one allows you to customize a single presentation so
that it acts in a particular way. This can also be useful if you'd like to share the source files for your presentation
with other people.
The supported configuration options are currently the following:
### implicit_slide_ends
This option removes the need to use `<!-- end_slide -->` in between slides and instead assumes that if you use a slide
title, then you're implying that the previous slide ended. For example, the following presentation:
```
---
options:
implicit_slide_ends: true
---
Tasty vegetables
================
* Potato
Awful vegetables
================
* Lettuce
```
Is equivalent to this "vanilla" one that doesn't use implicit slide ends.
```markdown
Tasty vegetables
================
* Potato
<!-- end_slide -->
Awful vegetables
================
* Lettuce
```
### end_slide_shorthand
This option allows using thematic breaks (`---`) as a delimiter between slides. When enabling this option, you can still
use `<!-- end_slide -->` but any thematic break will also be considered a slide terminator.
```
---
options:
end_slide_shorthand: true
---
this is a slide
---------------------
this is another slide
```
### command_prefix
Because _presenterm_ uses HTML comments to represent commands, it is necessary to make some assumptions on _what_ is a
command and what isn't. The current heuristic is:
* If an HTML comment is laid out on a single line, it is assumed to be a command. This means if you want to use a real
HTML comment like `<!-- remember to say "potato" here -->`, this will raise an error.
* If an HTML comment is multi-line, then it is assumed to be a comment and it can have anything inside it. This means
you can't have a multi-line comment that contains a command like `pause` inside.
Depending on how you use HTML comments personally, this may be limiting to you: you cannot use any single line comments
that are not commands. To get around this, the `command_prefix` option lets you configure a prefix that must be set in
all commands for them to be configured as such. Any single line comment that doesn't start with this prefix will not be
considered a command.
For example:
```
---
options:
command_prefix: "cmd:"
---
<!-- remember to say "potato here" -->
Tasty vegetables
================
* Potato
<!-- cmd:pause -->
**That's it!**
```
In the example above, the first comment is ignored because it doesn't start with "cmd:" and the second one is processed
because it does.
### incremental_lists
If you'd like all bullet points in all lists to show up with pauses in between you can enable the `incremental_lists`
option:
```
---
options:
incremental_lists: true
---
* pauses
* in
* between
```
Keep in mind if you only want specific bullet points to show up with pauses in between, you can use the
[`incremental_lists` comment command](basics.html#incremental-lists).
### strict_front_matter_parsing
This option tells _presenterm_ you don't care about extra parameters in presentation's front matter. This can be useful
if you're trying to load a presentation made for another tool. The following presentation would only be successfully
loaded if you set `strict_front_matter_parsing` to `false` in your configuration file:
```markdown
---
potato: 42
---
# Hi
```
### image_attributes_prefix
The [image size](basics.html#image-size) prefix (by default `image:`) can be configured to be anything you would want in
case you don't like the default one. For example, if you'd like to set the image size by simply doing
`![width:50%](path.png)` you would need to set:
```
---
options:
image_attributes_prefix: ""
---
![width:50%](path.png)
```
## Defaults
Defaults **can only be configured via the configuration file**.
### Default theme
The default theme can be configured only via the config file. When this is set, every presentation that doesn't set a
theme explicitly will use this one:
```yaml
defaults:
theme: light
```
### Terminal font size
This is a parameter that lets you explicitly set the terminal font size in use. This should not be used unless you are
in Windows, given there's no (easy) way to get the terminal window size so we use this to figure out how large the
window is and resize images properly. Some terminals on other platforms may also have this issue, but that should not be
as common.
If you are on Windows or you notice images show up larger/smaller than they should, you can adjust this setting in your
config file:
```yaml
defaults:
terminal_font_size: 16
```
### Preferred image protocol
By default _presenterm_ will try to detect which image protocol to use based on the terminal you are using. In some
cases this may fail, for example when using `tmux`. In those cases, you can explicitly set this via the
`--image-protocol` parameter or the configuration key `defaults.image_protocol`:
```yaml
defaults:
image_protocol: kitty-local
```
Possible values are:
* `auto`: try to detect it automatically (default).
* `kitty-local`: use the kitty protocol in "local" mode, meaning both _presenterm_ and the terminal run in the same host
and can share the filesystem to communicate.
* `kitty-remote`: use the kitty protocol in "remote" mode, meaning _presenterm_ and the terminal run in different hosts
and therefore can only communicate via terminal escape codes.
* `iterm2`: use the iterm2 protocol.
* `sixel`: use the sixel protocol. Note that this requires compiling _presenterm_ using the `--features sixel` flag.
## Key bindings
Key bindings that _presenterm_ uses can be manually configured in the config file via the `bindings` key. The following
is the default configuration:
```yaml
bindings:
# the keys that cause the presentation to move forwards.
next: ["l", "j", "<right>", "<page_down>", "<down>", " "]
# the keys that cause the presentation to move backwards.
previous: ["h", "k", "<left>", "<page_up>", "<up>"]
# the key binding to jump to the first slide.
first_slide: ["gg"]
# the key binding to jump to the last slide.
last_slide: ["G"]
# the key binding to jump to a specific slide.
go_to_slide: ["<number>G"]
# the key binding to execute a piece of shell code.
execute_code: ["<c-e>"]
# the key binding to reload the presentation.
reload: ["<c-r>"]
# the key binding to toggle the slide index modal.
toggle_slide_index: ["<c-p>"]
# the key binding to toggle the key bindings modal.
toggle_bindings: ["?"]
# the key binding to close the currently open modal.
close_modal: ["<esc>"]
# the key binding to close the application.
exit: ["<c-c>", "q"]
# the key binding to suspend the application.
suspend: ["<c-z>"]
```
You can choose to override any of them. Keep in mind these are overrides so if for example you change `next`, the
default won't apply anymore and only what you've defined will be used.
## Snippet configurations
### Snippet execution
[Snippet execution](code-highlight.html#executing-code-blocks) is disabled by default for security reasons. Besides
passing in the `-x` command line parameter every time you run _presenterm_, you can also configure this globally for all
presentations by setting:
```yaml
snippet:
exec:
enable: true
```
**Use this at your own risk**, especially if you're running someone else's presentations!
### Snippet execution + replace
[Snippet execution + replace](code-highlight.html#executing-and-replacing) is disabled by default for security reasons.
Similar to `+exec`, this can be enabled by passing in the `-X` command line parameter or configuring it globally by
setting:
```yaml
snippet:
exec_replace:
enable: true
```
**Use this at your own risk**. This will cause _presenterm_ to execute code without user intervention so don't blindly
enable this and open a presentation unless you trust its origin!
### Custom snippet executors
If _presenterm_ doesn't support executing code snippets for your language of choice, please [create an
issue](https://github.com/mfontanini/presenterm/issues/new)! Alternatively, you can configure this locally yourself by
setting:
```yaml
snippet:
exec:
custom:
# The keys should be the language identifier you'd use in a code block.
c++:
# The name of the file that will be created with your snippet's contents.
filename: "snippet.cpp"
# A list of environment variables that should be set before building/running your code.
environment:
MY_FAVORITE_ENVIRONMENT_VAR: foo
# A prefix that indicates a line that starts with it should not be visible but should be executed if the
# snippet is marked with `+exec`.
hidden_line_prefix: "/// "
# A list of commands that will be ran one by one in the same directory as the snippet is in.
commands:
# Compile if first
- ["g++", "-std=c++20", "snippet.cpp", "-o", "snippet"]
# Now run it
- ["./snippet"]
```
The output of all commands will be included in the code snippet execution output so if a command (like the `g++`
invocation) was to emit any output, make sure to use whatever flags are needed to mute its output.
Also note that you can override built-in executors in case you want to run them differently (e.g. use `c++23` in the
example above).
See more examples in the [executors.yaml](https://github.com/mfontanini/presenterm/blob/master/executors.yaml) file
which defines all of the built-in executors.
### Snippet rendering threads
Because some `+render` code blocks can take some time to be rendered into an image, especially if you're using
[mermaid](https://mermaid.js.org/) charts, this is run asychronously. The number of threads used to render these, which
defaults to 2, can be configured by setting:
```yaml
snippet:
render:
threads: 2
```
### Mermaid scaling
[mermaid](https://mermaid.js.org/) graphs will use a default scaling of `2` when invoking the mermaid CLI. If you'd like
to change this use:
```yaml
mermaid:
scale: 2
```

View File

@ -1,41 +1,41 @@
# Installing _presenterm_
## Installation
_presenterm_ works on Linux, macOS, and Windows and can be installed in different ways:
## Pre-built binaries (recommended)
### Pre-built binaries (recommended)
The recommended way to install _presenterm_ is to download the latest pre-built version for
your system from the [releases](https://github.com/mfontanini/presenterm/releases) page.
## Install via cargo
### Install via cargo
Alternatively, download [rust](https://www.rust-lang.org/) and run:
```bash
```shell
cargo install --locked presenterm
```
## Latest unreleased version
### Latest unreleased version
To install from the latest source code run:
```bash
```shell
cargo install --git https://github.com/mfontanini/presenterm
```
## macOS
### macOS
Install the latest version in macOS via [brew](https://formulae.brew.sh/formula/presenterm) by running:
```bash
```shell
brew install presenterm
```
## Nix
### Nix
To install _presenterm_ using the Nix package manager run:
```bash
```shell
nix-env -iA nixos.presenterm # for nixos
nix-env -iA nixpkgs.presenterm # for non-nixos
```
@ -56,13 +56,13 @@ nix run github:mfontanini/presenterm # to run from github repo
```
For more information see
[nixpkgs](https://search.nixos.org/packages?channel=unstable&show=presenterm&from=0&size=50&sort=relevance&type=packages&query=presenterm).
[nixpkgs](https://search.nixos.org/packages?channel=unstable&show=presenterm&from=0&size=50&sort=relevance&type=packages&query=presenterm)
## Arch Linux
### Arch Linux
_presenterm_ is available in the [official repositories](https://archlinux.org/packages/extra/x86_64/presenterm/). You can use [pacman](https://wiki.archlinux.org/title/pacman) to install as follows:
```bash
```shell
pacman -S presenterm
```
@ -70,17 +70,17 @@ pacman -S presenterm
Alternatively, you can use any AUR helper to install the upstream binaries:
```bash
```shell
paru/yay -S presenterm-bin
```
#### Building from git
```bash
```shell
paru/yay -S presenterm-git
```
## Windows
### Windows
Install the latest version in Scoop via [Scoop](https://scoop.sh/#/apps?q=presenterm&id=a462290f824b50f180afbaa6d8c7c1e6e0952e3a) by running:

View File

@ -1,40 +1,26 @@
# LaTeX and typst
## LaTeX and typst
`latex` and `typst` code blocks can be marked with the `+render` attribute (see [highlighting](highlighting.md)) to have
them rendered into images when the presentation is loaded. This allows you to define formulas in text rather than having
to define them somewhere else, transform them into an image, and them embed it.
`latex` and `typst` code blocks can be marked with the `+render` attribute (see [highlighting](code-highlight.html)) to
have them rendered into images when the presentation is loaded. This allows you to define formulas in text rather than
having to define them somewhere else, transform them into an image, and them embed it.
For example, the following presentation:
### Dependencies
~~~
# Formulas
```latex +render
\[ \sum_{n=1}^{\infty} 2^{-n} = 1 \]
```
~~~
Would be rendered like this:
![](../../assets/formula.png)
## Dependencies
### typst
#### typst
The engine used to render both of these languages is [typst](https://github.com/typst/typst). _typst_ is easy to
install, lightweight, and boilerplate free as compared to _LaTeX_.
### pandoc
For _LaTeX_ code rendering both _typst_ and [pandoc](https://github.com/jgm/pandoc) are required. How this works is the
_LaTeX_ code you write gets transformed into _typst_ code via _pandoc_ and then rendered by using _typst_. This lets us:
#### pandoc
For _LaTeX_ code rendering, besides _typst_ you will need to install [pandoc](https://github.com/jgm/pandoc). How this
works is the _LaTeX_ code you write gets transformed into _typst_ code via _pandoc_ and then rendered by using _typst_.
This lets us:
* Have the same look/feel on generated formulas for both languages.
* Avoid having to write lots of boilerplate _LaTeX_ to make rendering for that language work.
* Have the same logic to render formulas for both languages, except with a small preparation step for _LaTeX_.
## Controlling PPI
### Controlling PPI
_presenterm_ lets you define how many Pixels Per Inch (PPI) you want in the generated images. This is important because
as opposed to images that you manually include in your presentation, where you control the exact dimensions, the images
@ -42,7 +28,7 @@ generated on the fly will have a fixed size. Configuring the PPI used during the
higher the PPI, the larger the generated images will be.
Because as opposed to most configurations this is a very environment-specific config, the PPI parameter is not part of
the theme definition but is instead has to be set in _presenterm_'s [config file](../../configuration/introduction.md):
the theme definition but is instead has to be set in [_presenterm_'s config file](configuration.html):
```yaml
typst:
@ -51,7 +37,7 @@ typst:
The default is 300 so adjust it and see what works for you.
## Image paths
### Image paths
If you're including an image inside a _typst_ snippet, you must:
@ -61,7 +47,7 @@ at `/tmp/foo/presentation.md`, you can place images in `/tmp/foo`, and `/tmp/foo
because of the absolute path rule above: the path will be considered to be relative to the presentation file's
directory.
## Controlling the image size
### Controlling the image size
You can also set the generated image's size on a per code snippet basis by using the `+width` modifier which specifies
the width of the image as a percentage of the terminal size.
@ -72,7 +58,7 @@ $f(x) = x + 1$
```
~~~
## Customizations
### Customizations
The colors and margin of the generated images can be defined in your theme:
@ -86,3 +72,19 @@ typst:
horizontal_margin: 2
vertical_margin: 2
```
## Example
The following example:
~~~
# Formulas
```latex +render
\[ \sum_{n=1}^{\infty} 2^{-n} = 1 \]
```
~~~
Is rendered like this:
![](../assets/formula.png)

View File

@ -1,4 +1,4 @@
# Layouts
## Layouts
_presenterm_ currently supports a column layout that lets you split parts of your slides into column. This allows you to
put text on one side, and code/images on the other, or really organize markdown into columns in any way you want.
@ -6,7 +6,7 @@ put text on one side, and code/images on the other, or really organize markdown
This is done by using commands, just like `pause` and `end_slide`, in the form of HTML comments. This section describes
how to use those.
## Wait, why not HTML?
### Wait, why not HTML?
While markdown _can_ contain HTML tags (beyond comments!) and we _could_ represent this using divs with alignment, I
don't really want to:
@ -17,12 +17,12 @@ don't really want to:
Because of this, _presenterm_ doesn't let you use HTML and instead has a custom way of specifying column layouts.
## Column layout
### Column layout
The way to specify column layouts is by first creating a layout, and then telling _presenterm_ you want to enter each of
the column in it as you write your presentation.
### Defining layouts
#### Defining layouts
Defining a layout is done via the `column_layout` command, in the form of an HTML comment:
@ -39,7 +39,7 @@ This defines a layout with 2 columns where:
You can use any number of columns and with as many units you want on each of them. This lets you decide how to structure
the presentation in a fairly straightforward way.
### Using columns
#### Using columns
Once a layout is defined, you just need to specify that you want to enter a column before writing any text to it by
using the `column` command:
@ -54,7 +54,7 @@ Now all the markdown you write will be placed on the first column until you eith
* The slide ends.
* You jump into another column by using the `column` command again.
## Example
### Example
The following example puts all of this together by defining 2 columns, one with some code and bullet points, another one
with an image, and some extra text at the bottom that's not tied to any columns.
@ -95,7 +95,7 @@ This would render the following way:
![](../assets/layouts.png)
## Other uses
### Other uses
Besides organizing your slides into columns, you can use column layouts to center a piece of your slide. For example, if
you want a certain portion of your slide to be centered, you could define a column layout like `[1, 3, 1]` and then only

View File

@ -1,4 +1,4 @@
## Mermaid
# Mermaid
[mermaid](https://mermaid.js.org/) snippets can be converted into images automatically in any code snippet tagged with
the `mermaid` language and a `+render` tag:
@ -15,11 +15,11 @@ sequenceDiagram
Note that because the mermaid CLI will spin up a browser under the hood, this may not work in all environments and can
also be a bit slow (e.g. ~2 seconds to generate every image). Mermaid graphs are rendered asynchronously by a number of
threads that can be configured in the [configuration file](../../configuration/settings.md#snippet-rendering-threads).
This configuration value currently defaults to 2.
threads that can be configured in the [configuration file](configuration.html#snippet-rendering-threads). This
configuration value currently defaults to 2.
The size of the rendered image can be configured by changing:
* The `mermaid.scale` [configuration parameter](../../configuration/settings.md#mermaid-scaling).
* The `mermaid.scale` [configuration parameter](configuration.html#mermaid-scaling).
* Using the `+width:<number>%` attribute in the code snippet.
For example, this diagram will take up 50% of the width of the window and will preserve its aspect ratio:
@ -38,13 +38,7 @@ cause the image to become blurry.
## Theme
The theme of the rendered mermaid diagrams can be changed through the following
[theme](../themes/introduction.md#mermaid) parameters:
The theme of the rendered mermaid diagrams can be changed through the following [theme](themes.html#mermaid) parameters:
* `mermaid.background` the background color passed to the CLI (e.g., `transparent`, `red`, `#F0F0F0`).
* `mermaid.theme` the [mermaid theme](https://mermaid.js.org/config/theming.html#available-themes) to use.
## Always render diagrams
If you don't want to use `+render` every time, you can configure which languages get this automatically via the [config
file](../../configuration/settings.md#auto_render_languages).

View File

@ -0,0 +1,31 @@
## PDF export
Presentations can be converted into PDF by using a [helper tool](https://github.com/mfontanini/presenterm-export). You
can install it by running:
```shell
pip install presenterm-export
```
> **Note**: make sure that `presenterm-export` works by running `presenterm-export --version` before attempting to
> generate a PDF file. If you get errors related to _weasyprint_, follow their [installation
> instructions](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html) to ensure you meet all of their
> dependencies. This has otherwise caused issues in macOS.
The only external dependency you'll need is [tmux](https://github.com/tmux/tmux/). After you've installed both of these,
simply run _presenterm_ with the `--export-pdf` parameter to generate the output PDF:
```shell
presenterm --export-pdf examples/demo.md
```
The output PDF will be placed in `examples/demo.pdf`. The size of each page will depend on the size of your terminal so
make sure to adjust accordingly before running the command above.
> Note: if you're using a separate virtual env to install _presenterm-export_ just make sure you activate it before
> running _presenterm_ with the `--export-pdf` parameter.
### How it works
The conversion into PDF format is pretty convoluted. If you'd like to learn more visit
[presenterm-export](https://github.com/mfontanini/presenterm-export)'s repo.

View File

@ -1,9 +1,108 @@
# Theme definition
## Themes
This section goes through the structure of the theme files. Have a look at some of the [existing
themes](https://github.com/mfontanini/presenterm/tree/master/themes) to have an idea of how to structure themes.
Themes are defined in the form of yaml files. A few built-in themes are defined in the [themes][builtin-themes]
directory, but others can be created and referenced directly in every presentation.
## Root elements
### Setting themes
There's various ways of setting the theme you want in your presentation:
#### CLI
Passing in the `--theme` parameter when running _presenterm_ to select one of the built-in themes.
#### Within the presentation
The presentation's markdown file can contain a front matter that specifies the theme to use. This comes in 3 flavors:
##### By name
Using a built-in theme name makes your presentation use that one regardless of what the default or what the `--theme`
option specifies:
```yaml
---
theme:
name: dark
---
```
##### By path
You can define a theme file in yaml format somewhere in your filesystem and reference it within the presentation:
```yaml
---
theme:
path: /home/me/Documents/epic-theme.yaml
---
```
##### Overrides
You can partially/completely override the theme in use from within the presentation:
```yaml
---
theme:
override:
default:
colors:
foreground: "beeeff"
---
```
This lets you:
1. Create a unique style for your presentation without having to go through the process of taking an existing theme,
copying somewhere, and changing it when you only expect to use it for that one presentation.
2. Iterate quickly on styles given overrides are reloaded whenever you save your presentation file.
## Built-in themes
A few built-in themes are bundled with the application binary, meaning you don't need to have any external files
available to use them. These are packed as part of the [build process][build-rs] as a binary blob and are decoded on
demand only when used.
Currently, the following themes are supported:
* `dark`: A dark theme.
* `light`: A light theme.
* `tokyonight-storm`: A theme inspired by the colors used in [toyonight](https://github.com/folke/tokyonight.nvim).
* A set of themes based on the [catppuccin](https://github.com/catppuccin/catppuccin) color palette:
* `catppuccin-latte`
* `catppuccin-frappe`
* `catppuccin-macchiato`
* `catppuccin-mocha`
* `terminal-dark`: A theme that uses your terminals color and looks best if your terminal uses a dark color scheme. This
means if your terminal background is e.g. transparent, or uses an image, the presentation will inherit that.
* `terminal-light`: The same as `terminal-dark` but works best if your terminal uses a light color scheme.
### Trying out built-in themes
All built-in themes can be tested by using the `--list-themes` parameter:
```shell
presenterm --list-themes
```
This will run a presentation where the same content is rendered using a different theme in each slide:
[![asciicast](https://asciinema.org/a/zeV1QloyrLkfBp6rNltvX7Lle.svg)](https://asciinema.org/a/zeV1QloyrLkfBp6rNltvX7Lle)
## Loading custom themes
On startup, _presenterm_ will look into the `themes` directory under the [configuration directory](configuration.html)
(e.g. `~/.config/presenterm/themes` in Linux) and will load any `.yaml` file as a theme and make it available as if it
was a built-in theme. This means you can use it as an argument to the `--theme` parameter, use it in the `theme.name`
property in a presentation's front matter, etc.
## Theme definition
This section goes through the structure of the theme files. Have a look at some of the [existing themes][builtin-themes]
to have an idea of how to structure themes.
### Root elements
The root attributes on the theme yaml files specify either:
@ -11,7 +110,7 @@ The root attributes on the theme yaml files specify either:
etc.
* A default to be applied as a fallback if no specific style is specified for a particular element.
## Alignment
### Alignment
_presenterm_ uses the notion of alignment, just like you would have in a GUI editor, to align text to the left, center,
or right. You probably want most elements to be aligned left, _some_ to be aligned on the center, and probably none to
@ -23,14 +122,14 @@ The following elements support alignment:
* The title, subtitle, and author elements in the intro slide.
* Tables.
### Left/right alignment
#### Left/right alignment
Left and right alignments take a margin property which specifies the number of columns to keep between the text and the
left/right terminal screen borders.
The margin can be specified in two ways:
#### Fixed
##### Fixed
A specific number of characters regardless of the terminal size.
@ -40,7 +139,7 @@ margin:
fixed: 5
```
#### Percent
##### Percent
A percentage over the total number of columns in the terminal.
@ -53,7 +152,7 @@ margin:
Percent alignment tends to look a bit nicer as it won't change the presentation's look as much when the terminal size
changes.
### Center alignment
#### Center alignment
Center alignment has 2 properties:
* `minimum_size` which specifies the minimum size you want that element to have. This is normally useful for code blocks
@ -62,7 +161,7 @@ Center alignment has 2 properties:
alignment. This doesn't play very well with `minimum_size` but in isolation it specifies the minimum number of columns
you want to the left and right of your text.
## Colors
### Colors
Every element can have its own background/foreground color using hex notation:
@ -73,7 +172,7 @@ default:
background: "00ff00"
```
## Default style
### Default style
The default style specifies:
@ -89,7 +188,7 @@ default:
background: "040312"
```
## Intro slide
### Intro slide
The introductory slide will be rendered if you specify a title, subtitle, or author in the presentation's front matter.
This lets you have a less markdown-looking introductory slide that stands out so that it doesn't end up looking too
@ -122,79 +221,20 @@ intro_slide:
positioning: below_title
```
## Footer
### Footer
The footer currently comes in 3 flavors:
### Template footers
#### None
A template footer lets you put text on the left, center and/or right of the screen. The template strings
can reference `{current_slide}` and `{total_slides}` which will be replaced with the current and total number of slides.
Besides those special variables, any of the attributes defined in the front matter can also be used:
* `title`.
* `sub_title`.
* `event`.
* `location`.
* `date`.
* `author`.
Strings used in template footers can contain arbitrary markdown, including `span` tags that let you use colored text. A
`height` attribute allows specifying how tall, in terminal rows, the footer is. The text in the footer will always be
placed at the center of the footer area. The default footer height is 2.
No footer at all!
```yaml
footer:
style: template
left: "My **name** is {author}"
center: "_@myhandle_"
right: "{current_slide} / {total_slides}"
height: 3
style: empty
```
Do note that:
* Only existing attributes in the front matter can be referenced. That is, if you use `{date}` but the `date` isn't set,
an error will be shown.
* Similarly, referencing unsupported variables (e.g. `{potato}`) will cause an error to be displayed. If you'd like the
`{}` characters to be used in contexts where you don't want to reference a variable, you will need to escape them by
using another brace. e.g. `{{potato}} farms` will be displayed as `{potato} farms`.
#### Footer images
Besides text, images can also be used in the left/center/right positions. This can be done by specifying an `image` key
under each of those attributes:
```yaml
footer:
style: template
left:
image: potato.png
center:
image: banana.png
right:
image: apple.png
# The height of the footer to adjust image sizes
height: 5
```
Images will be looked up:
* First, relative to the presentation file just like any other image.
* If the image is not found, it will be looked up relative to the themes directory. e.g. `~/.config/presenterm/themes`.
This allows you to define a custom theme in your themes directory that points to a local image within that same
location.
Images will preserve their aspect ratio and expand vertically to take up as many terminal rows as `footer.height`
specifies. This parameter should be adjusted accordingly if taller-than-wider images are used in a footer.
See the [footer example](https://github.com/mfontanini/presenterm/blob/master/examples/footer.md) as a showcase of how a
footer can contain images and colored text.
![](../../assets/example-footer.png)
### Progress bar footers
#### Progress bar
A progress bar that will advance as you move in your presentation. This will by default use a block-looking character to
draw the progress bar but you can customize it:
@ -207,17 +247,29 @@ footer:
character: 🚀
```
### None
#### Template
No footer at all!
A template footer that lets you put something on the left, center and/or right of the screen. The template strings
can reference `{current_slide}` and `{total_slides}` which will be replaced with the current and total number of slides.
Besides those special variables, any of the attributes defined in the front matter can also be used:
* `title`.
* `sub_title`.
* `event`.
* `location`.
* `date`.
* `author`.
```yaml
footer:
style: empty
style: template
left: "My name is {author}"
center: @myhandle
right: "{current_slide} / {total_slides}"
```
## Slide title
### Slide title
Slide titles, as specified by using a setext header, has the following properties:
* `padding_top` which specifies the number of rows you want as padding before the text.
@ -231,7 +283,7 @@ slide_title:
separator: true
```
## Headings
### Headings
Every header type (h1 through h6) can have its own style composed of:
* The prefix you want to use.
@ -249,7 +301,7 @@ headings:
foreground: "rgb_(168,223,142)"
```
## Code blocks
### Code blocks
The syntax highlighting for code blocks is done via the [syntect](https://github.com/trishume/syntect) crate. The list
of all the supported built-in _syntect_ themes is the following:
@ -280,10 +332,10 @@ code:
#### Custom highlighting themes
Besides the built-in highlighting themes, you can drop any `.tmTheme` theme in the `themes/highlighting` directory under
your [configuration directory](../../configuration/introduction.md) (e.g. `~/.config/presenterm/themes/highlighting` in
Linux) and they will be loaded automatically when _presenterm_ starts.
your [configuration directory](configuration.html) (e.g. `~/.config/presenterm/themes/highlighting` in Linux) and they
will be loaded automatically when _presenterm_ starts.
## Block quotes
### Block quotes
For block quotes you can specify a string to use as a prefix in every line of quoted text:
@ -292,7 +344,11 @@ block_quote:
prefix: "▍ "
```
## Mermaid
<!-- links -->
[builtin-themes]: https://github.com/mfontanini/presenterm/tree/master/themes
[build-rs]: https://github.com/mfontanini/presenterm/blob/master/build.rs
### Mermaid
The [mermaid](https://mermaid.js.org/) graphs can be customized using the following parameters:
@ -305,45 +361,7 @@ mermaid:
theme: dark
```
## Alerts
GitHub style markdown alerts can be styled by setting the `alert` key:
```yaml
alert:
# the base colors used in all text in an alert
base_colors:
foreground: red
background: black
# the prefix used in every line in the alert
prefix: "▍ "
# the style for each alert type
styles:
note:
color: blue
title: Note
icon: I
tip:
color: green
title: Tip
icon: T
important:
color: cyan
title: Important
icon: I
warning:
color: orange
title: Warning
icon: W
caution:
color: red
title: Caution
icon: C
```
## Extending themes
### Extending themes
Custom themes can extend other custom or built in themes. This means it will inherit all the properties of the theme
being extended by default.
@ -359,36 +377,3 @@ default:
This theme extends the built in _dark_ theme and overrides the background color. This is useful if you find yourself
_almost_ liking a built in theme but there's only some properties you don't like.
## Color palette
Every theme can define a color palette, which includes a list of pre-defined colors and a list of background/foreground
pairs called "classes". Colors and classes can be used when styling text via `<span>` HTML tags, whereas colors can also
be used inside themes to avoid duplicating the same colors all over the theme definition.
A palette can de defined as follows:
```yaml
palette:
colors:
red: "f78ca2"
purple: "986ee2"
classes:
foo:
foreground: "ff0000"
background: "00ff00"
```
Any palette color can be referenced using either `palette:<name>` or `p:<name>`. This means now any part of the theme
can use `p:red` and `p:purple` where a color is required.
Similarly, these colors can be used in `span` tags like:
```html
<span style="color: palette:red">this is red</span>
<span class="foo">this is foo-colored</span>
```
These colors can used anywhere in your presentation as well as in other places such as in
[template footers](#template-footers) and [introduction slides](../introduction.md#introduction-slide).

View File

@ -1,10 +1,10 @@
# presenterm
## presenterm
[presenterm][github] lets you create presentations in markdown format and run them from your terminal, with support for
image and animated gif support, highly customizable themes, code highlighting, exporting presentations into PDF format,
and plenty of other features.
## Demo
### Demo
This is how the [demo presentation][demo-source] looks like:

363
docs/theme/catppuccin-admonish.css vendored Normal file
View File

@ -0,0 +1,363 @@
.mocha :is(.admonition):is(.admonish-hint, .admonish-important, .admonish-tip) {
border-color: #f9e2af;
}
.mocha :is(.admonish-hint, .admonish-important, .admonish-tip) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(249, 226, 175, 0.2);
}
.mocha :is(.admonish-hint, .admonish-important, .admonish-tip) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #f9e2af;
}
.mocha :is(.admonition):is(.admonish-abstract, .admonish-summary, .admonish-tldr) {
border-color: #f2cdcd;
}
.mocha :is(.admonish-abstract, .admonish-summary, .admonish-tldr) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(242, 205, 205, 0.2);
}
.mocha :is(.admonish-abstract, .admonish-summary, .admonish-tldr) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #f2cdcd;
}
.mocha :is(.admonition):is(.admonish-example) {
border-color: #cba6f7;
}
.mocha :is(.admonish-example) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(203, 166, 247, 0.2);
}
.mocha :is(.admonish-example) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #cba6f7;
}
.mocha :is(.admonition):is(.admonish-info, .admonish-todo) {
border-color: #89dceb;
}
.mocha :is(.admonish-info, .admonish-todo) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(137, 220, 235, 0.2);
}
.mocha :is(.admonish-info, .admonish-todo) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #89dceb;
}
.mocha :is(.admonition):is(.admonish-check, .admonish-done, .admonish-success) {
border-color: #a6e3a1;
}
.mocha :is(.admonish-check, .admonish-done, .admonish-success) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(166, 227, 161, 0.2);
}
.mocha :is(.admonish-check, .admonish-done, .admonish-success) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #a6e3a1;
}
.mocha :is(.admonition):is(.admonish-note) {
border-color: #89b4fa;
}
.mocha :is(.admonish-note) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(137, 180, 250, 0.2);
}
.mocha :is(.admonish-note) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #89b4fa;
}
.mocha :is(.admonition):is(.admonish-attention, .admonish-caution, .admonish-warning) {
border-color: #fab387;
}
.mocha :is(.admonish-attention, .admonish-caution, .admonish-warning) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(250, 179, 135, 0.2);
}
.mocha :is(.admonish-attention, .admonish-caution, .admonish-warning) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #fab387;
}
.mocha :is(.admonition):is(.admonish-faq, .admonish-help, .admonish-question) {
border-color: #94e2d5;
}
.mocha :is(.admonish-faq, .admonish-help, .admonish-question) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(148, 226, 213, 0.2);
}
.mocha :is(.admonish-faq, .admonish-help, .admonish-question) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #94e2d5;
}
.mocha :is(.admonition):is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) {
border-color: #f38ba8;
}
.mocha :is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(243, 139, 168, 0.2);
}
.mocha :is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #f38ba8;
}
.mocha :is(.admonition):is(.admonish-cite, .admonish-quote) {
border-color: #f5c2e7;
}
.mocha :is(.admonish-cite, .admonish-quote) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(245, 194, 231, 0.2);
}
.mocha :is(.admonish-cite, .admonish-quote) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #f5c2e7;
}
.macchiato :is(.admonition):is(.admonish-hint, .admonish-important, .admonish-tip) {
border-color: #eed49f;
}
.macchiato :is(.admonish-hint, .admonish-important, .admonish-tip) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(238, 212, 159, 0.2);
}
.macchiato :is(.admonish-hint, .admonish-important, .admonish-tip) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #eed49f;
}
.macchiato :is(.admonition):is(.admonish-abstract, .admonish-summary, .admonish-tldr) {
border-color: #f0c6c6;
}
.macchiato :is(.admonish-abstract, .admonish-summary, .admonish-tldr) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(240, 198, 198, 0.2);
}
.macchiato :is(.admonish-abstract, .admonish-summary, .admonish-tldr) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #f0c6c6;
}
.macchiato :is(.admonition):is(.admonish-example) {
border-color: #c6a0f6;
}
.macchiato :is(.admonish-example) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(198, 160, 246, 0.2);
}
.macchiato :is(.admonish-example) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #c6a0f6;
}
.macchiato :is(.admonition):is(.admonish-info, .admonish-todo) {
border-color: #91d7e3;
}
.macchiato :is(.admonish-info, .admonish-todo) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(145, 215, 227, 0.2);
}
.macchiato :is(.admonish-info, .admonish-todo) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #91d7e3;
}
.macchiato :is(.admonition):is(.admonish-check, .admonish-done, .admonish-success) {
border-color: #a6da95;
}
.macchiato :is(.admonish-check, .admonish-done, .admonish-success) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(166, 218, 149, 0.2);
}
.macchiato :is(.admonish-check, .admonish-done, .admonish-success) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #a6da95;
}
.macchiato :is(.admonition):is(.admonish-note) {
border-color: #8aadf4;
}
.macchiato :is(.admonish-note) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(138, 173, 244, 0.2);
}
.macchiato :is(.admonish-note) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #8aadf4;
}
.macchiato :is(.admonition):is(.admonish-attention, .admonish-caution, .admonish-warning) {
border-color: #f5a97f;
}
.macchiato :is(.admonish-attention, .admonish-caution, .admonish-warning) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(245, 169, 127, 0.2);
}
.macchiato :is(.admonish-attention, .admonish-caution, .admonish-warning) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #f5a97f;
}
.macchiato :is(.admonition):is(.admonish-faq, .admonish-help, .admonish-question) {
border-color: #8bd5ca;
}
.macchiato :is(.admonish-faq, .admonish-help, .admonish-question) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(139, 213, 202, 0.2);
}
.macchiato :is(.admonish-faq, .admonish-help, .admonish-question) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #8bd5ca;
}
.macchiato :is(.admonition):is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) {
border-color: #ed8796;
}
.macchiato :is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(237, 135, 150, 0.2);
}
.macchiato :is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #ed8796;
}
.macchiato :is(.admonition):is(.admonish-cite, .admonish-quote) {
border-color: #f5bde6;
}
.macchiato :is(.admonish-cite, .admonish-quote) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(245, 189, 230, 0.2);
}
.macchiato :is(.admonish-cite, .admonish-quote) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #f5bde6;
}
.frappe :is(.admonition):is(.admonish-hint, .admonish-important, .admonish-tip) {
border-color: #e5c890;
}
.frappe :is(.admonish-hint, .admonish-important, .admonish-tip) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(229, 200, 144, 0.2);
}
.frappe :is(.admonish-hint, .admonish-important, .admonish-tip) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #e5c890;
}
.frappe :is(.admonition):is(.admonish-abstract, .admonish-summary, .admonish-tldr) {
border-color: #eebebe;
}
.frappe :is(.admonish-abstract, .admonish-summary, .admonish-tldr) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(238, 190, 190, 0.2);
}
.frappe :is(.admonish-abstract, .admonish-summary, .admonish-tldr) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #eebebe;
}
.frappe :is(.admonition):is(.admonish-example) {
border-color: #ca9ee6;
}
.frappe :is(.admonish-example) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(202, 158, 230, 0.2);
}
.frappe :is(.admonish-example) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #ca9ee6;
}
.frappe :is(.admonition):is(.admonish-info, .admonish-todo) {
border-color: #99d1db;
}
.frappe :is(.admonish-info, .admonish-todo) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(153, 209, 219, 0.2);
}
.frappe :is(.admonish-info, .admonish-todo) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #99d1db;
}
.frappe :is(.admonition):is(.admonish-check, .admonish-done, .admonish-success) {
border-color: #a6d189;
}
.frappe :is(.admonish-check, .admonish-done, .admonish-success) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(166, 209, 137, 0.2);
}
.frappe :is(.admonish-check, .admonish-done, .admonish-success) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #a6d189;
}
.frappe :is(.admonition):is(.admonish-note) {
border-color: #8caaee;
}
.frappe :is(.admonish-note) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(140, 170, 238, 0.2);
}
.frappe :is(.admonish-note) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #8caaee;
}
.frappe :is(.admonition):is(.admonish-attention, .admonish-caution, .admonish-warning) {
border-color: #ef9f76;
}
.frappe :is(.admonish-attention, .admonish-caution, .admonish-warning) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(239, 159, 118, 0.2);
}
.frappe :is(.admonish-attention, .admonish-caution, .admonish-warning) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #ef9f76;
}
.frappe :is(.admonition):is(.admonish-faq, .admonish-help, .admonish-question) {
border-color: #81c8be;
}
.frappe :is(.admonish-faq, .admonish-help, .admonish-question) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(129, 200, 190, 0.2);
}
.frappe :is(.admonish-faq, .admonish-help, .admonish-question) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #81c8be;
}
.frappe :is(.admonition):is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) {
border-color: #e78284;
}
.frappe :is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(231, 130, 132, 0.2);
}
.frappe :is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #e78284;
}
.frappe :is(.admonition):is(.admonish-cite, .admonish-quote) {
border-color: #f4b8e4;
}
.frappe :is(.admonish-cite, .admonish-quote) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(244, 184, 228, 0.2);
}
.frappe :is(.admonish-cite, .admonish-quote) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #f4b8e4;
}
.latte :is(.admonition):is(.admonish-hint, .admonish-important, .admonish-tip) {
border-color: #df8e1d;
}
.latte :is(.admonish-hint, .admonish-important, .admonish-tip) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(223, 142, 29, 0.2);
}
.latte :is(.admonish-hint, .admonish-important, .admonish-tip) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #df8e1d;
}
.latte :is(.admonition):is(.admonish-abstract, .admonish-summary, .admonish-tldr) {
border-color: #dd7878;
}
.latte :is(.admonish-abstract, .admonish-summary, .admonish-tldr) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(221, 120, 120, 0.2);
}
.latte :is(.admonish-abstract, .admonish-summary, .admonish-tldr) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #dd7878;
}
.latte :is(.admonition):is(.admonish-example) {
border-color: #8839ef;
}
.latte :is(.admonish-example) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(136, 57, 239, 0.2);
}
.latte :is(.admonish-example) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #8839ef;
}
.latte :is(.admonition):is(.admonish-info, .admonish-todo) {
border-color: #04a5e5;
}
.latte :is(.admonish-info, .admonish-todo) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(4, 165, 229, 0.2);
}
.latte :is(.admonish-info, .admonish-todo) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #04a5e5;
}
.latte :is(.admonition):is(.admonish-check, .admonish-done, .admonish-success) {
border-color: #40a02b;
}
.latte :is(.admonish-check, .admonish-done, .admonish-success) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(64, 160, 43, 0.2);
}
.latte :is(.admonish-check, .admonish-done, .admonish-success) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #40a02b;
}
.latte :is(.admonition):is(.admonish-note) {
border-color: #1e66f5;
}
.latte :is(.admonish-note) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(30, 102, 245, 0.2);
}
.latte :is(.admonish-note) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #1e66f5;
}
.latte :is(.admonition):is(.admonish-attention, .admonish-caution, .admonish-warning) {
border-color: #fe640b;
}
.latte :is(.admonish-attention, .admonish-caution, .admonish-warning) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(254, 100, 11, 0.2);
}
.latte :is(.admonish-attention, .admonish-caution, .admonish-warning) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #fe640b;
}
.latte :is(.admonition):is(.admonish-faq, .admonish-help, .admonish-question) {
border-color: #179299;
}
.latte :is(.admonish-faq, .admonish-help, .admonish-question) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(23, 146, 153, 0.2);
}
.latte :is(.admonish-faq, .admonish-help, .admonish-question) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #179299;
}
.latte :is(.admonition):is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) {
border-color: #d20f39;
}
.latte :is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(210, 15, 57, 0.2);
}
.latte :is(.admonish-bug, .admonish-danger, .admonish-error, .admonish-fail, .admonish-failure, .admonish-missing) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #d20f39;
}
.latte :is(.admonition):is(.admonish-cite, .admonish-quote) {
border-color: #ea76cb;
}
.latte :is(.admonish-cite, .admonish-quote) > :is(.admonition-title, summary.admonition-title) {
background-color: rgba(234, 118, 203, 0.2);
}
.latte :is(.admonish-cite, .admonish-quote) > :is(.admonition-title, summary.admonition-title)::before {
background-color: #ea76cb;
}

787
docs/theme/catppuccin.css vendored Normal file
View File

@ -0,0 +1,787 @@
.mocha.hljs {
color: #cdd6f4;
background: #1e1e2e;
}
.mocha .hljs-keyword {
color: #cba6f7;
}
.mocha .hljs-built_in {
color: #f38ba8;
}
.mocha .hljs-type {
color: #f9e2af;
}
.mocha .hljs-literal {
color: #fab387;
}
.mocha .hljs-number {
color: #fab387;
}
.mocha .hljs-operator {
color: #94e2d5;
}
.mocha .hljs-punctuation {
color: #bac2de;
}
.mocha .hljs-property {
color: #94e2d5;
}
.mocha .hljs-regexp {
color: #f5c2e7;
}
.mocha .hljs-string {
color: #a6e3a1;
}
.mocha .hljs-char.escape_ {
color: #a6e3a1;
}
.mocha .hljs-subst {
color: #a6adc8;
}
.mocha .hljs-symbol {
color: #f2cdcd;
}
.mocha .hljs-variable {
color: #cba6f7;
}
.mocha .hljs-variable.language_ {
color: #cba6f7;
}
.mocha .hljs-variable.constant_ {
color: #fab387;
}
.mocha .hljs-title {
color: #89b4fa;
}
.mocha .hljs-title.class_ {
color: #f9e2af;
}
.mocha .hljs-title.function_ {
color: #89b4fa;
}
.mocha .hljs-params {
color: #cdd6f4;
}
.mocha .hljs-comment {
color: #585b70;
}
.mocha .hljs-doctag {
color: #f38ba8;
}
.mocha .hljs-meta {
color: #fab387;
}
.mocha .hljs-section {
color: #89b4fa;
}
.mocha .hljs-tag {
color: #a6adc8;
}
.mocha .hljs-name {
color: #cba6f7;
}
.mocha .hljs-attr {
color: #89b4fa;
}
.mocha .hljs-attribute {
color: #a6e3a1;
}
.mocha .hljs-bullet {
color: #94e2d5;
}
.mocha .hljs-code {
color: #a6e3a1;
}
.mocha .hljs-emphasis {
color: #f38ba8;
font-style: italic;
}
.mocha .hljs-strong {
color: #f38ba8;
font-weight: bold;
}
.mocha .hljs-formula {
color: #94e2d5;
}
.mocha .hljs-link {
color: #74c7ec;
font-style: italic;
}
.mocha .hljs-quote {
color: #a6e3a1;
font-style: italic;
}
.mocha .hljs-selector-tag {
color: #f9e2af;
}
.mocha .hljs-selector-id {
color: #89b4fa;
}
.mocha .hljs-selector-class {
color: #94e2d5;
}
.mocha .hljs-selector-attr {
color: #cba6f7;
}
.mocha .hljs-selector-pseudo {
color: #94e2d5;
}
.mocha .hljs-template-tag {
color: #f2cdcd;
}
.mocha .hljs-template-variable {
color: #f2cdcd;
}
.mocha .hljs-addition {
color: #a6e3a1;
background: rgba(166, 227, 161, 0.15);
}
.mocha .hljs-deletion {
color: #f38ba8;
background: rgba(243, 139, 168, 0.15);
}
.mocha code {
color: #cdd6f4;
background: #181825;
}
.mocha blockquote blockquote {
border-top: 0.1em solid #585b70;
border-bottom: 0.1em solid #585b70;
}
.mocha hr {
color: #585b70;
}
.mocha del {
color: #9399b2;
}
.mocha .ace_gutter {
color: #7f849c;
background: #181825;
}
.mocha .ace_gutter-active-line.ace_gutter-cell {
color: #f5c2e7;
background: #181825;
}
.macchiato.hljs {
color: #cad3f5;
background: #24273a;
}
.macchiato .hljs-keyword {
color: #c6a0f6;
}
.macchiato .hljs-built_in {
color: #ed8796;
}
.macchiato .hljs-type {
color: #eed49f;
}
.macchiato .hljs-literal {
color: #f5a97f;
}
.macchiato .hljs-number {
color: #f5a97f;
}
.macchiato .hljs-operator {
color: #8bd5ca;
}
.macchiato .hljs-punctuation {
color: #b8c0e0;
}
.macchiato .hljs-property {
color: #8bd5ca;
}
.macchiato .hljs-regexp {
color: #f5bde6;
}
.macchiato .hljs-string {
color: #a6da95;
}
.macchiato .hljs-char.escape_ {
color: #a6da95;
}
.macchiato .hljs-subst {
color: #a5adcb;
}
.macchiato .hljs-symbol {
color: #f0c6c6;
}
.macchiato .hljs-variable {
color: #c6a0f6;
}
.macchiato .hljs-variable.language_ {
color: #c6a0f6;
}
.macchiato .hljs-variable.constant_ {
color: #f5a97f;
}
.macchiato .hljs-title {
color: #8aadf4;
}
.macchiato .hljs-title.class_ {
color: #eed49f;
}
.macchiato .hljs-title.function_ {
color: #8aadf4;
}
.macchiato .hljs-params {
color: #cad3f5;
}
.macchiato .hljs-comment {
color: #5b6078;
}
.macchiato .hljs-doctag {
color: #ed8796;
}
.macchiato .hljs-meta {
color: #f5a97f;
}
.macchiato .hljs-section {
color: #8aadf4;
}
.macchiato .hljs-tag {
color: #a5adcb;
}
.macchiato .hljs-name {
color: #c6a0f6;
}
.macchiato .hljs-attr {
color: #8aadf4;
}
.macchiato .hljs-attribute {
color: #a6da95;
}
.macchiato .hljs-bullet {
color: #8bd5ca;
}
.macchiato .hljs-code {
color: #a6da95;
}
.macchiato .hljs-emphasis {
color: #ed8796;
font-style: italic;
}
.macchiato .hljs-strong {
color: #ed8796;
font-weight: bold;
}
.macchiato .hljs-formula {
color: #8bd5ca;
}
.macchiato .hljs-link {
color: #7dc4e4;
font-style: italic;
}
.macchiato .hljs-quote {
color: #a6da95;
font-style: italic;
}
.macchiato .hljs-selector-tag {
color: #eed49f;
}
.macchiato .hljs-selector-id {
color: #8aadf4;
}
.macchiato .hljs-selector-class {
color: #8bd5ca;
}
.macchiato .hljs-selector-attr {
color: #c6a0f6;
}
.macchiato .hljs-selector-pseudo {
color: #8bd5ca;
}
.macchiato .hljs-template-tag {
color: #f0c6c6;
}
.macchiato .hljs-template-variable {
color: #f0c6c6;
}
.macchiato .hljs-addition {
color: #a6da95;
background: rgba(166, 218, 149, 0.15);
}
.macchiato .hljs-deletion {
color: #ed8796;
background: rgba(237, 135, 150, 0.15);
}
.macchiato code {
color: #cad3f5;
background: #1e2030;
}
.macchiato blockquote blockquote {
border-top: 0.1em solid #5b6078;
border-bottom: 0.1em solid #5b6078;
}
.macchiato hr {
color: #5b6078;
}
.macchiato del {
color: #939ab7;
}
.macchiato .ace_gutter {
color: #8087a2;
background: #1e2030;
}
.macchiato .ace_gutter-active-line.ace_gutter-cell {
color: #f5bde6;
background: #1e2030;
}
.frappe.hljs {
color: #c6d0f5;
background: #303446;
}
.frappe .hljs-keyword {
color: #ca9ee6;
}
.frappe .hljs-built_in {
color: #e78284;
}
.frappe .hljs-type {
color: #e5c890;
}
.frappe .hljs-literal {
color: #ef9f76;
}
.frappe .hljs-number {
color: #ef9f76;
}
.frappe .hljs-operator {
color: #81c8be;
}
.frappe .hljs-punctuation {
color: #b5bfe2;
}
.frappe .hljs-property {
color: #81c8be;
}
.frappe .hljs-regexp {
color: #f4b8e4;
}
.frappe .hljs-string {
color: #a6d189;
}
.frappe .hljs-char.escape_ {
color: #a6d189;
}
.frappe .hljs-subst {
color: #a5adce;
}
.frappe .hljs-symbol {
color: #eebebe;
}
.frappe .hljs-variable {
color: #ca9ee6;
}
.frappe .hljs-variable.language_ {
color: #ca9ee6;
}
.frappe .hljs-variable.constant_ {
color: #ef9f76;
}
.frappe .hljs-title {
color: #8caaee;
}
.frappe .hljs-title.class_ {
color: #e5c890;
}
.frappe .hljs-title.function_ {
color: #8caaee;
}
.frappe .hljs-params {
color: #c6d0f5;
}
.frappe .hljs-comment {
color: #626880;
}
.frappe .hljs-doctag {
color: #e78284;
}
.frappe .hljs-meta {
color: #ef9f76;
}
.frappe .hljs-section {
color: #8caaee;
}
.frappe .hljs-tag {
color: #a5adce;
}
.frappe .hljs-name {
color: #ca9ee6;
}
.frappe .hljs-attr {
color: #8caaee;
}
.frappe .hljs-attribute {
color: #a6d189;
}
.frappe .hljs-bullet {
color: #81c8be;
}
.frappe .hljs-code {
color: #a6d189;
}
.frappe .hljs-emphasis {
color: #e78284;
font-style: italic;
}
.frappe .hljs-strong {
color: #e78284;
font-weight: bold;
}
.frappe .hljs-formula {
color: #81c8be;
}
.frappe .hljs-link {
color: #85c1dc;
font-style: italic;
}
.frappe .hljs-quote {
color: #a6d189;
font-style: italic;
}
.frappe .hljs-selector-tag {
color: #e5c890;
}
.frappe .hljs-selector-id {
color: #8caaee;
}
.frappe .hljs-selector-class {
color: #81c8be;
}
.frappe .hljs-selector-attr {
color: #ca9ee6;
}
.frappe .hljs-selector-pseudo {
color: #81c8be;
}
.frappe .hljs-template-tag {
color: #eebebe;
}
.frappe .hljs-template-variable {
color: #eebebe;
}
.frappe .hljs-addition {
color: #a6d189;
background: rgba(166, 209, 137, 0.15);
}
.frappe .hljs-deletion {
color: #e78284;
background: rgba(231, 130, 132, 0.15);
}
.frappe code {
color: #c6d0f5;
background: #292c3c;
}
.frappe blockquote blockquote {
border-top: 0.1em solid #626880;
border-bottom: 0.1em solid #626880;
}
.frappe hr {
color: #626880;
}
.frappe del {
color: #949cbb;
}
.frappe .ace_gutter {
color: #838ba7;
background: #292c3c;
}
.frappe .ace_gutter-active-line.ace_gutter-cell {
color: #f4b8e4;
background: #292c3c;
}
.latte.hljs {
color: #4c4f69;
background: #eff1f5;
}
.latte .hljs-keyword {
color: #8839ef;
}
.latte .hljs-built_in {
color: #d20f39;
}
.latte .hljs-type {
color: #df8e1d;
}
.latte .hljs-literal {
color: #fe640b;
}
.latte .hljs-number {
color: #fe640b;
}
.latte .hljs-operator {
color: #179299;
}
.latte .hljs-punctuation {
color: #5c5f77;
}
.latte .hljs-property {
color: #179299;
}
.latte .hljs-regexp {
color: #ea76cb;
}
.latte .hljs-string {
color: #40a02b;
}
.latte .hljs-char.escape_ {
color: #40a02b;
}
.latte .hljs-subst {
color: #6c6f85;
}
.latte .hljs-symbol {
color: #dd7878;
}
.latte .hljs-variable {
color: #8839ef;
}
.latte .hljs-variable.language_ {
color: #8839ef;
}
.latte .hljs-variable.constant_ {
color: #fe640b;
}
.latte .hljs-title {
color: #1e66f5;
}
.latte .hljs-title.class_ {
color: #df8e1d;
}
.latte .hljs-title.function_ {
color: #1e66f5;
}
.latte .hljs-params {
color: #4c4f69;
}
.latte .hljs-comment {
color: #acb0be;
}
.latte .hljs-doctag {
color: #d20f39;
}
.latte .hljs-meta {
color: #fe640b;
}
.latte .hljs-section {
color: #1e66f5;
}
.latte .hljs-tag {
color: #6c6f85;
}
.latte .hljs-name {
color: #8839ef;
}
.latte .hljs-attr {
color: #1e66f5;
}
.latte .hljs-attribute {
color: #40a02b;
}
.latte .hljs-bullet {
color: #179299;
}
.latte .hljs-code {
color: #40a02b;
}
.latte .hljs-emphasis {
color: #d20f39;
font-style: italic;
}
.latte .hljs-strong {
color: #d20f39;
font-weight: bold;
}
.latte .hljs-formula {
color: #179299;
}
.latte .hljs-link {
color: #209fb5;
font-style: italic;
}
.latte .hljs-quote {
color: #40a02b;
font-style: italic;
}
.latte .hljs-selector-tag {
color: #df8e1d;
}
.latte .hljs-selector-id {
color: #1e66f5;
}
.latte .hljs-selector-class {
color: #179299;
}
.latte .hljs-selector-attr {
color: #8839ef;
}
.latte .hljs-selector-pseudo {
color: #179299;
}
.latte .hljs-template-tag {
color: #dd7878;
}
.latte .hljs-template-variable {
color: #dd7878;
}
.latte .hljs-addition {
color: #40a02b;
background: rgba(64, 160, 43, 0.15);
}
.latte .hljs-deletion {
color: #d20f39;
background: rgba(210, 15, 57, 0.15);
}
.latte code {
color: #4c4f69;
background: #e6e9ef;
}
.latte blockquote blockquote {
border-top: 0.1em solid #acb0be;
border-bottom: 0.1em solid #acb0be;
}
.latte hr {
color: #acb0be;
}
.latte del {
color: #7c7f93;
}
.latte .ace_gutter {
color: #8c8fa1;
background: #e6e9ef;
}
.latte .ace_gutter-active-line.ace_gutter-cell {
color: #ea76cb;
background: #e6e9ef;
}
.mocha {
--bg: #1e1e2e;
--fg: #cdd6f4;
--sidebar-bg: #181825;
--sidebar-fg: #cdd6f4;
--sidebar-non-existant: #6c7086;
--sidebar-active: #89b4fa;
--sidebar-spacer: #6c7086;
--scrollbar: #6c7086;
--icons: #6c7086;
--icons-hover: #7f849c;
--links: #89b4fa;
--inline-code-color: #fab387;
--theme-popup-bg: #181825;
--theme-popup-border: #6c7086;
--theme-hover: #6c7086;
--quote-bg: #181825;
--quote-border: #11111b;
--table-border-color: #11111b;
--table-header-bg: #181825;
--table-alternate-bg: #181825;
--searchbar-border-color: #11111b;
--searchbar-bg: #181825;
--searchbar-fg: #cdd6f4;
--searchbar-shadow-color: #11111b;
--searchresults-header-fg: #cdd6f4;
--searchresults-border-color: #11111b;
--searchresults-li-bg: #1e1e2e;
--search-mark-bg: #fab387;
--warning-border: #fab387;
}
.macchiato {
--bg: #24273a;
--fg: #cad3f5;
--sidebar-bg: #1e2030;
--sidebar-fg: #cad3f5;
--sidebar-non-existant: #6e738d;
--sidebar-active: #8aadf4;
--sidebar-spacer: #6e738d;
--scrollbar: #6e738d;
--icons: #6e738d;
--icons-hover: #8087a2;
--links: #8aadf4;
--inline-code-color: #f5a97f;
--theme-popup-bg: #1e2030;
--theme-popup-border: #6e738d;
--theme-hover: #6e738d;
--quote-bg: #1e2030;
--quote-border: #181926;
--table-border-color: #181926;
--table-header-bg: #1e2030;
--table-alternate-bg: #1e2030;
--searchbar-border-color: #181926;
--searchbar-bg: #1e2030;
--searchbar-fg: #cad3f5;
--searchbar-shadow-color: #181926;
--searchresults-header-fg: #cad3f5;
--searchresults-border-color: #181926;
--searchresults-li-bg: #24273a;
--search-mark-bg: #f5a97f;
--warning-border: #f5a97f;
}
.frappe {
--bg: #303446;
--fg: #c6d0f5;
--sidebar-bg: #292c3c;
--sidebar-fg: #c6d0f5;
--sidebar-non-existant: #737994;
--sidebar-active: #8caaee;
--sidebar-spacer: #737994;
--scrollbar: #737994;
--icons: #737994;
--icons-hover: #838ba7;
--links: #8caaee;
--inline-code-color: #ef9f76;
--theme-popup-bg: #292c3c;
--theme-popup-border: #737994;
--theme-hover: #737994;
--quote-bg: #292c3c;
--quote-border: #232634;
--table-border-color: #232634;
--table-header-bg: #292c3c;
--table-alternate-bg: #292c3c;
--searchbar-border-color: #232634;
--searchbar-bg: #292c3c;
--searchbar-fg: #c6d0f5;
--searchbar-shadow-color: #232634;
--searchresults-header-fg: #c6d0f5;
--searchresults-border-color: #232634;
--searchresults-li-bg: #303446;
--search-mark-bg: #ef9f76;
--warning-border: #ef9f76;
}
.latte {
--bg: #eff1f5;
--fg: #4c4f69;
--sidebar-bg: #e6e9ef;
--sidebar-fg: #4c4f69;
--sidebar-non-existant: #9ca0b0;
--sidebar-active: #1e66f5;
--sidebar-spacer: #9ca0b0;
--scrollbar: #9ca0b0;
--icons: #9ca0b0;
--icons-hover: #8c8fa1;
--links: #1e66f5;
--inline-code-color: #fe640b;
--theme-popup-bg: #e6e9ef;
--theme-popup-border: #9ca0b0;
--theme-hover: #9ca0b0;
--quote-bg: #e6e9ef;
--quote-border: #dce0e8;
--table-border-color: #dce0e8;
--table-header-bg: #e6e9ef;
--table-alternate-bg: #e6e9ef;
--searchbar-border-color: #dce0e8;
--searchbar-bg: #e6e9ef;
--searchbar-fg: #4c4f69;
--searchbar-shadow-color: #dce0e8;
--searchresults-header-fg: #4c4f69;
--searchresults-border-color: #dce0e8;
--searchresults-li-bg: #eff1f5;
--search-mark-bg: #fe640b;
--warning-border: #fe640b;
}

349
docs/theme/index.hbs vendored Normal file
View File

@ -0,0 +1,349 @@
<!DOCTYPE HTML>
<html lang="{{ language }}" class="{{ default_theme }}" dir="{{ text_direction }}">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>{{ title }}</title>
{{#if is_print }}
<meta name="robots" content="noindex">
{{/if}}
{{#if base_url}}
<base href="{{ base_url }}">
{{/if}}
<!-- Custom HTML head -->
{{> head}}
<meta name="description" content="{{ description }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
{{#if favicon_svg}}
<link rel="icon" href="{{ path_to_root }}favicon.svg">
{{/if}}
{{#if favicon_png}}
<link rel="shortcut icon" href="{{ path_to_root }}favicon.png">
{{/if}}
<link rel="stylesheet" href="{{ path_to_root }}css/variables.css">
<link rel="stylesheet" href="{{ path_to_root }}css/general.css">
<link rel="stylesheet" href="{{ path_to_root }}css/chrome.css">
{{#if print_enable}}
<link rel="stylesheet" href="{{ path_to_root }}css/print.css" media="print">
{{/if}}
<!-- Fonts -->
<link rel="stylesheet" href="{{ path_to_root }}FontAwesome/css/font-awesome.css">
{{#if copy_fonts}}
<link rel="stylesheet" href="{{ path_to_root }}fonts/fonts.css">
{{/if}}
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="{{ path_to_root }}highlight.css">
<link rel="stylesheet" href="{{ path_to_root }}tomorrow-night.css">
<link rel="stylesheet" href="{{ path_to_root }}ayu-highlight.css">
<!-- Custom theme stylesheets -->
{{#each additional_css}}
<link rel="stylesheet" href="{{ ../path_to_root }}{{ this }}">
{{/each}}
{{#if mathjax_support}}
<!-- MathJax -->
<script async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
{{/if}}
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "{{ path_to_root }}";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "{{ preferred_dark_theme }}" : "{{ default_theme }}";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('{{ default_theme }}')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
{{#toc}}{{/toc}}
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
{{> header}}
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="mocha">Mocha</button></li>
<li role="none"><button role="menuitem" class="theme" id="macchiato">Macchiato</button></li>
<li role="none"><button role="menuitem" class="theme" id="frappe">Frappé</button></li>
<li role="none"><button role="menuitem" class="theme" id="latte">Latte</button></li>
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
{{#if search_enabled}}
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
{{/if}}
</div>
<h1 class="menu-title">{{ book_title }}</h1>
<div class="right-buttons">
{{#if print_enable}}
<a href="{{ path_to_root }}print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
{{/if}}
{{#if git_repository_url}}
<a href="{{git_repository_url}}" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa {{git_repository_icon}}"></i>
</a>
{{/if}}
{{#if git_repository_edit_url}}
<a href="{{git_repository_edit_url}}" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
{{/if}}
</div>
</div>
{{#if search_enabled}}
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
{{/if}}
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
{{{ content }}}
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
{{#previous}}
<a rel="prev" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
{{/previous}}
{{#next}}
<a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
{{/next}}
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
{{#previous}}
<a rel="prev" href="{{ path_to_root }}{{link}}" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
{{/previous}}
{{#next}}
<a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
{{/next}}
</nav>
</div>
{{#if live_reload_endpoint}}
<!-- Livereload script (if served using the cli tool) -->
<script>
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsAddress = wsProtocol + "//" + location.host + "/" + "{{{live_reload_endpoint}}}";
const socket = new WebSocket(wsAddress);
socket.onmessage = function (event) {
if (event.data === "reload") {
socket.close();
location.reload();
}
};
window.onbeforeunload = function() {
socket.close();
}
</script>
{{/if}}
{{#if google_analytics}}
<!-- Google Analytics Tag -->
<script>
var localAddrs = ["localhost", "127.0.0.1", ""];
// make sure we don't activate google analytics if the developer is
// inspecting the book locally...
if (localAddrs.indexOf(document.location.hostname) === -1) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '{{google_analytics}}', 'auto');
ga('send', 'pageview');
}
</script>
{{/if}}
{{#if playground_line_numbers}}
<script>
window.playground_line_numbers = true;
</script>
{{/if}}
{{#if playground_copyable}}
<script>
window.playground_copyable = true;
</script>
{{/if}}
{{#if playground_js}}
<script src="{{ path_to_root }}ace.js"></script>
<script src="{{ path_to_root }}editor.js"></script>
<script src="{{ path_to_root }}mode-rust.js"></script>
<script src="{{ path_to_root }}theme-dawn.js"></script>
<script src="{{ path_to_root }}theme-tomorrow_night.js"></script>
{{/if}}
{{#if search_js}}
<script src="{{ path_to_root }}elasticlunr.min.js"></script>
<script src="{{ path_to_root }}mark.min.js"></script>
<script src="{{ path_to_root }}searcher.js"></script>
{{/if}}
<script src="{{ path_to_root }}clipboard.min.js"></script>
<script src="{{ path_to_root }}highlight.js"></script>
<script src="{{ path_to_root }}book.js"></script>
<!-- Custom JS scripts -->
{{#each additional_js}}
<script src="{{ ../path_to_root }}{{this}}"></script>
{{/each}}
{{#if is_print}}
{{#if mathjax_support}}
<script>
window.addEventListener('load', function() {
MathJax.Hub.Register.StartupHook('End', function() {
window.setTimeout(window.print, 100);
});
});
</script>
{{else}}
<script>
window.addEventListener('load', function() {
window.setTimeout(window.print, 100);
});
</script>
{{/if}}
{{/if}}
</div>
</body>
</html>

View File

@ -39,7 +39,7 @@ This example uses a template-style footer, which lets you place some text on the
A few template variables, such as `current_slide` and `total_slides` can be used to reference properties of the
presentation.
![](../docs/src/assets/example-footer.png)
[![asciicast](https://asciinema.org/a/DLpBDpCbEp5pSrNZ2Vh4mmIY1.svg)](https://asciinema.org/a/DLpBDpCbEp5pSrNZ2Vh4mmIY1)
# Columns
@ -49,11 +49,3 @@ This example shows how column layouts and pauses interact with each other. Note
because asciinema doesn't support these and it will otherwise look like a normal image if your terminal supports images.
[![asciicast](https://asciinema.org/a/x2tTDt0BIesvOXeal3UpdzMHp.svg)](https://asciinema.org/a/x2tTDt0BIesvOXeal3UpdzMHp)
# Speaker notes
[Source](/examples/speaker-notes.md)
This example shows how to use speaker notes.
[![asciicast](https://asciinema.org/a/ETusvlmHuHrcLKzwa0CMQRX2J.svg)](https://asciinema.org/a/ETusvlmHuHrcLKzwa0CMQRX2J)

View File

@ -1,34 +1,38 @@
---
title: Introducing _presenterm_
title: Introducing presenterm
author: Matias
---
Customizability
Introduction slide
---
_presenterm_ allows configuring almost anything about your presentation:
* The colors used.
* Layouts.
* Footers, including images in the footer.
<!-- pause -->
This is an example on how to configure a footer:
An introduction slide can be defined by using a front matter at the beginning of the markdown file:
```yaml
footer:
style: template
left:
image: doge.png
center: '<span class="noice">Colored</span> _footer_'
right: "{current_slide} / {total_slides}"
height: 5
---
title: My presentation title
sub_title: An optional subtitle
author: Your name which will appear somewhere in the bottom
---
```
palette:
classes:
noice:
foreground: red
The slide's theme can also be configured in the front matter:
```yaml
---
theme:
# Specify it by name for built-in themes
name: my-favorite-theme
# Otherwise specify the path for it
path: /home/myself/themes/epic.yaml
# Or override parts of the theme right here
override:
default:
colors:
foreground: white
---
```
<!-- end_slide -->
@ -36,27 +40,58 @@ palette:
Headers
---
Markdown headers can be used to set slide titles like:
Using commonmark setext headers allows you to set titles for your slides (like seen above!):
```markdown
```
Headers
-------
---
```
# Headers
# Other headers
Each header type can be styled differently.
All other header types are simply treated as headers within your slide.
## Subheaders
### And more
<!-- end_slide -->
Slide commands
---
Certain commands in the form of HTML comments can be used:
# Ending slides
In order to end a single slide, use:
```html
<!-- end_slide -->
```
# Creating pauses
Slides can be paused by using the `pause` command:
```html
<!-- pause -->
```
This allows you to:
<!-- pause -->
* Create suspense.
<!-- pause -->
* Have more interactive presentations.
<!-- pause -->
* Possibly more!
<!-- end_slide -->
Code highlighting
---
Highlight code in 50+ programming languages:
Code highlighting is enabled for code blocks that include the most commonly used programming languages:
```rust
// Rust
@ -71,25 +106,22 @@ def greet() -> str:
return "hi mom"
```
<!-- pause -->
-------
Code snippets can have different styles including no background:
```cpp +no_background +line_numbers
```cpp
// C++
string greet() {
return "hi mom";
}
```
And many more!
<!-- end_slide -->
Dynamic code highlighting
---
Dynamically highlight different subsets of lines:
Select specific subsets of lines to be highlighted dynamically as you move to the next slide. Optionally enable line
numbers to make it easier to specify which lines you're referring to!
```rust {1-4|6-10|all} +line_numbers
#[derive(Clone, Debug)]
@ -109,11 +141,12 @@ impl Person {
Snippet execution
---
Code snippets can be executed on demand:
Code snippets can be executed:
* For 20+ languages, including compiled ones.
* Display their output in real time.
* Comment out unimportant lines to hide them.
* For various languages, including compiled ones.
* Their output is shown in real time.
* Unimportant lines can be hidden so they don't clutter what you're trying to convey.
* By default by pressing `<ctrl-e>`.
```rust +exec
# use std::thread::sleep;
@ -132,17 +165,12 @@ fn main() {
Images
---
Images and animated gifs are supported in terminals such as:
Image rendering is supported as long as you're using iterm2, your terminal supports
the kitty graphics protocol (such as the kitty terminal itself!), or the sixel format.
* kitty
* iterm2
* wezterm
* ghostty
* Any sixel enabled terminal
<!-- column_layout: [1, 3, 1] -->
<!-- column: 1 -->
* Include images in your slides by using `![](path-to-image.extension)`.
* Images will be rendered in **their original size**.
* If they're too big they will be scaled down to fit the screen.
![](doge.png)
@ -153,15 +181,13 @@ _Picture by Alexis Bailey / CC BY-NC 4.0_
Column layouts
---
<!-- column_layout: [7, 3] -->
<!-- column_layout: [2, 1] -->
<!-- column: 0 -->
Use column layouts to structure your presentation:
Column layouts let you organize content into columns.
* Define the number of columns.
* Adjust column widths as needed.
* Write content into every column.
Here you can place code:
```rust
fn potato() -> u32 {
@ -169,15 +195,21 @@ fn potato() -> u32 {
}
```
Plus pretty much anything else:
* Bullet points.
* Images.
* _more_!
<!-- column: 1 -->
![](doge.png)
_Picture by Alexis Bailey / CC BY-NC 4.0_
<!-- reset_layout -->
---
Layouts can be reset at any time.
Because we just reset the layout, this text is now below both of the columns. Code and any other element will now look
like it usually does:
```python
print("Hello world!")
@ -188,23 +220,28 @@ print("Hello world!")
Text formatting
---
Text formatting works including:
Text formatting works as expected:
* **Bold text**.
* _Italics_.
* **_Bold and italic_**.
* ~Strikethrough~.
* `Inline code`.
* Links [](https://example.com/)
* <span style="color: red">Colored</span> text.
* <span style="color: blue; background-color: black">Background color</span> can be changed too.
* **This is bold text**.
* _This is italics_.
* **This is bold _and this is bold and italic_**.
* ~This is strikethrough text.~
* Inline code `is also supported`.
* Links look like this [](https://example.com/)
<!-- end_slide -->
More markdown
Other elements
---
Other markdown elements supported are:
Other elements supported are:
# Tables
| Name | Taste |
| ------ | ------ |
| Potato | Great |
| Carrot | Yuck |
# Block quotes
@ -212,21 +249,8 @@ Other markdown elements supported are:
> et exercitationem deleniti et quia maiores a cumque enim et
> aspernatur nesciunt sed adipisci quis.
# Alerts
# Thematic breaks
> [!caution]
> Github style alerts
A horizontal line by using `---`.
# Tables
| Name | Taste |
| ------ | ------ |
| Potato | Great |
| Carrot | Yuck |
<!-- end_slide -->
<!-- jump_to_middle -->
The end
---

View File

@ -3,15 +3,9 @@ theme:
override:
footer:
style: template
left:
image: doge.png
center: '**Introduction** to <span class="noice">footer</span> _styling_'
left: "@myhandle"
center: "Introduction to footer styling"
right: "{current_slide} / {total_slides}"
height: 5
palette:
classes:
noice:
foreground: red
---
First slide

View File

@ -1,43 +0,0 @@
Speaker Notes
===
`presenterm` supports speaker notes.
You can use the following HTML comment throughout your presentation markdown file:
```markdown
<!-- speaker_note: Your speaker note goes here. -->
```
<!-- speaker_note: This is a speaker note from slide 1. -->
And you can run a separate instance of `presenterm` to view them.
<!-- speaker_note: You can use multiple speaker notes within each slide and interleave them with other markdown. -->
<!-- end_slide -->
Usage
===
Run the following two commands in separate terminals.
<!-- speaker_note: This is a speaker note from slide 2. -->
The `--publish-speaker-notes` argument will render your actual presentation as normal, without speaker notes:
```
presenterm --publish-speaker-notes examples/speaker-notes.md
```
The `--listen-speaker-notes` argument will render only the speaker notes for the current slide being shown in the actual
presentation:
```
presenterm --listen-speaker-notes examples/speaker-notes.md
```
<!-- speaker_note: Demonstrate changing slides in the actual presentation. -->
As you change slides in your actual presentation, the speaker notes presentation slide will automatically navigate to the correct slide.
<!-- speaker_note: Isn't that cool? -->

View File

@ -7,13 +7,13 @@ bash:
c++:
filename: snippet.cpp
commands:
- ["g++", "-std=c++20", "-fdiagnostics-color=always", "$pwd/snippet.cpp", "-o", "$pwd/snippet"]
- ["g++", "-std=c++20", "$pwd/snippet.cpp", "-o", "$pwd/snippet"]
- ["$pwd/snippet"]
hidden_line_prefix: "/// "
c:
filename: snippet.c
commands:
- ["gcc", "$pwd/snippet.c", "-fdiagnostics-color=always", "-o", "$pwd/snippet"]
- ["gcc", "$pwd/snippet.c", "-o", "$pwd/snippet"]
- ["$pwd/snippet"]
hidden_line_prefix: "/// "
fish:
@ -28,10 +28,6 @@ go:
commands:
- ["go", "run", "$pwd/snippet.go"]
hidden_line_prefix: "/// "
haskell:
filename: snippet.hs
commands:
- ["runhaskell", "-w", "$pwd/snippet.hs"]
java:
filename: Snippet.java
commands:
@ -42,15 +38,10 @@ js:
commands:
- ["node", "$pwd/snippet.js"]
hidden_line_prefix: "/// "
julia:
filename: snippet.jl
commands:
- ["julia", "$pwd/snippet.jl"]
hidden_line_prefix: "/// "
kotlin:
filename: snippet.kts
commands:
- ["kotlinc", "-script", "$pwd/snippet.kts"]
- ["kotlinc", "-script", "$pwd/script.kts"]
hidden_line_prefix: "/// "
lua:
filename: snippet.lua
@ -74,10 +65,6 @@ python:
commands:
- ["python", "-u", "$pwd/snippet.py"]
hidden_line_prefix: "/// "
r:
filename: snippet.R
commands:
- ["Rscript", "$pwd/snippet.R"]
ruby:
filename: snippet.rb
commands:
@ -90,7 +77,7 @@ rust-script:
rust:
filename: snippet.rs
commands:
- ["rustc", "--crate-name", "presenterm_snippet", "$pwd/snippet.rs", "-o", "$pwd/snippet", "--color", "always"]
- ["rustc", "--crate-name", "presenterm_snippet", "$pwd/snippet.rs", "-o", "$pwd/snippet"]
- ["$pwd/snippet"]
hidden_line_prefix: "# "
sh:
@ -103,8 +90,3 @@ zsh:
commands:
- ["zsh", "$pwd/script.sh"]
hidden_line_prefix: "/// "
csharp:
filename: snippet.cs
commands:
- ["dotnet-script", "$pwd/snippet.cs"]
hidden_line_prefix: "/// "

View File

@ -1,12 +1,10 @@
#!/bin/bash
set -euo pipefail
script_dir=$(dirname "$0")
root_dir="${script_dir}/../"
current_schema=$(mktemp)
cargo run --features json-schema -q -- --generate-config-file-schema >"$current_schema"
cargo run -q -- --generate-config-file-schema >"$current_schema"
diff=$(diff --color=always -u "${root_dir}/config-file-schema.json" "$current_schema")
if [ $? -ne 0 ]; then

99
src/ansi.rs Normal file
View File

@ -0,0 +1,99 @@
use crate::{
markdown::{
elements::{Text, TextBlock},
text::WeightedTextBlock,
},
style::{Color, TextStyle},
};
use ansi_parser::{AnsiParser, AnsiSequence, Output};
pub(crate) struct AnsiSplitter {
lines: Vec<WeightedTextBlock>,
current_line: TextBlock,
current_style: TextStyle,
}
impl AnsiSplitter {
pub(crate) fn new(current_style: TextStyle) -> Self {
Self { lines: Default::default(), current_line: Default::default(), current_style }
}
pub(crate) fn split_lines(mut self, lines: &[String]) -> (Vec<WeightedTextBlock>, TextStyle) {
for line in lines {
for p in line.ansi_parse() {
match p {
Output::TextBlock(text) => {
self.current_line.0.push(Text::new(text, self.current_style));
}
Output::Escape(s) => self.handle_escape(&s),
}
}
let current_line = std::mem::take(&mut self.current_line);
self.lines.push(current_line.into());
}
(self.lines, self.current_style)
}
fn handle_escape(&mut self, s: &AnsiSequence) {
match s {
AnsiSequence::SetGraphicsMode(code) => {
let code = GraphicsCode(code);
code.update(&mut self.current_style);
}
AnsiSequence::EraseDisplay => {
self.lines.clear();
self.current_line.0.clear();
}
_ => (),
}
}
}
struct GraphicsCode<'a>(&'a [u8]);
impl GraphicsCode<'_> {
fn update(&self, style: &mut TextStyle) {
// RGB mode
let codes = self.0;
if codes.starts_with(&[38, 2]) || codes.starts_with(&[48, 2]) {
if codes.len() == 5 {
let color = Color::new(codes[2], codes[3], codes[4]);
if codes[0] == 38 {
style.colors.foreground = Some(color);
} else {
style.colors.background = Some(color);
}
}
return;
}
for value in codes {
match value {
0 => *style = TextStyle::default(),
1 => *style = (*style).bold(),
3 => *style = (*style).italics(),
4 => *style = (*style).underlined(),
9 => *style = (*style).strikethrough(),
30 => style.colors.foreground = Some(Color::Black),
40 => style.colors.background = Some(Color::Black),
31 => style.colors.foreground = Some(Color::Red),
41 => style.colors.background = Some(Color::Red),
32 => style.colors.foreground = Some(Color::Green),
42 => style.colors.background = Some(Color::Green),
33 => style.colors.foreground = Some(Color::Yellow),
43 => style.colors.background = Some(Color::Yellow),
34 => style.colors.foreground = Some(Color::Blue),
44 => style.colors.background = Some(Color::Blue),
35 => style.colors.foreground = Some(Color::Magenta),
45 => style.colors.background = Some(Color::Magenta),
36 => style.colors.foreground = Some(Color::Cyan),
46 => style.colors.background = Some(Color::Cyan),
37 => style.colors.foreground = Some(Color::White),
47 => style.colors.background = Some(Color::White),
39 => style.colors.foreground = None,
49 => style.colors.background = None,
_ => (),
}
}
}
}

View File

@ -1,4 +0,0 @@
pub(crate) mod execute;
pub(crate) mod highlighting;
pub(crate) mod padding;
pub(crate) mod snippet;

View File

@ -1,3 +0,0 @@
pub(crate) mod keyboard;
pub(crate) mod listener;
pub(crate) mod speaker_notes;

View File

@ -1,115 +0,0 @@
use serde::{Deserialize, Serialize};
use socket2::{Domain, Protocol, Socket, Type};
use std::{
io,
net::{SocketAddr, UdpSocket},
path::PathBuf,
};
pub struct SpeakerNotesEventPublisher {
socket: UdpSocket,
presentation_path: PathBuf,
}
impl SpeakerNotesEventPublisher {
pub fn new(address: SocketAddr, presentation_path: PathBuf) -> io::Result<Self> {
let socket = UdpSocket::bind("127.0.0.1:0")?;
socket.set_broadcast(true)?;
socket.connect(address)?;
Ok(Self { socket, presentation_path })
}
pub(crate) fn send(&self, event: SpeakerNotesEvent) -> io::Result<()> {
// Wrap this event in an envelope that contains the presentation path so listeners can
// ignore unrelated events.
let envelope = SpeakerNotesEventEnvelope { event, presentation_path: self.presentation_path.clone() };
let data = serde_json::to_string(&envelope).expect("serialization failed");
match self.socket.send(data.as_bytes()) {
Ok(_) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::ConnectionRefused => Ok(()),
Err(e) => Err(e),
}
}
}
pub struct SpeakerNotesEventListener {
socket: UdpSocket,
presentation_path: PathBuf,
}
impl SpeakerNotesEventListener {
pub fn new(address: SocketAddr, presentation_path: PathBuf) -> io::Result<Self> {
let s = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
// Use SO_REUSEADDR so we can have multiple listeners on the same port.
#[cfg(not(target_os = "macos"))]
s.set_reuse_address(true)?;
// Don't block so we can listen to the keyboard and this socket at the same time.
s.set_nonblocking(true)?;
s.bind(&address.into())?;
Ok(Self { socket: s.into(), presentation_path })
}
pub(crate) fn try_recv(&self) -> io::Result<Option<SpeakerNotesEvent>> {
let mut buffer = [0; 1024];
let bytes_read = match self.socket.recv(&mut buffer) {
Ok(bytes_read) => bytes_read,
Err(e) if e.kind() == io::ErrorKind::WouldBlock => return Ok(None),
Err(e) => return Err(e),
};
// Ignore garbage. Odds are this is someone else sending garbage rather than presenterm
// itself.
let Ok(envelope) = serde_json::from_slice::<SpeakerNotesEventEnvelope>(&buffer[0..bytes_read]) else {
return Ok(None);
};
if envelope.presentation_path == self.presentation_path { Ok(Some(envelope.event)) } else { Ok(None) }
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "command")]
pub(crate) enum SpeakerNotesEvent {
GoToSlide { slide: u32 },
Exit,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SpeakerNotesEventEnvelope {
presentation_path: PathBuf,
event: SpeakerNotesEvent,
}
#[cfg(not(target_os = "macos"))]
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{default_speaker_notes_listen_address, default_speaker_notes_publish_address};
use std::{thread::sleep, time::Duration};
fn make_listener(path: PathBuf) -> SpeakerNotesEventListener {
SpeakerNotesEventListener::new(default_speaker_notes_listen_address(), path).expect("building listener")
}
fn make_publisher(path: PathBuf) -> SpeakerNotesEventPublisher {
SpeakerNotesEventPublisher::new(default_speaker_notes_publish_address(), path).expect("building publisher")
}
#[test]
fn bind_multiple() {
let _l1 = make_listener("".into());
let _l2 = make_listener("".into());
}
#[test]
fn multicast() {
let path = PathBuf::from("/tmp/test.md");
let l1 = make_listener(path.clone());
let l2 = make_listener(path.clone());
let publisher = make_publisher(path);
let event = SpeakerNotesEvent::Exit;
publisher.send(event.clone()).expect("send failed");
sleep(Duration::from_millis(100));
assert_eq!(l1.try_recv().expect("recv first failed"), Some(event.clone()));
assert_eq!(l2.try_recv().expect("recv second failed"), Some(event));
}
}

View File

@ -1,26 +1,23 @@
use crate::{
code::snippet::SnippetLanguage,
commands::keyboard::KeyBinding,
terminal::{
GraphicsMode, capabilities::TerminalCapabilities, emulator::TerminalEmulator,
image::protocols::kitty::KittyMode,
},
GraphicsMode,
input::user::KeyBinding,
media::{emulator::TerminalEmulator, kitty::KittyMode},
processing::code::SnippetLanguage,
};
use clap::ValueEnum;
use schemars::JsonSchema;
use serde::Deserialize;
use std::{
collections::{BTreeMap, HashMap},
fs, io,
net::{IpAddr, Ipv4Addr, SocketAddr},
path::Path,
};
#[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Config {
/// The default configuration for the presentation.
#[serde(default)]
#[doc = "The default configuration for the presentation."]
pub defaults: DefaultsConfig,
#[serde(default)]
@ -37,15 +34,6 @@ pub struct Config {
#[serde(default)]
pub snippet: SnippetConfig,
#[serde(default)]
pub speaker_notes: SpeakerNotesConfig,
#[serde(default)]
pub export: ExportConfig,
#[serde(default)]
pub transition: Option<SlideTransitionConfig>,
}
impl Config {
@ -53,7 +41,7 @@ impl Config {
pub fn load(path: &Path) -> Result<Self, ConfigLoadError> {
let contents = match fs::read_to_string(path) {
Ok(contents) => contents,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(ConfigLoadError::NotFound),
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
Err(e) => return Err(e.into()),
};
let config = serde_yaml::from_str(&contents)?;
@ -66,23 +54,19 @@ pub enum ConfigLoadError {
#[error("io: {0}")]
Io(#[from] io::Error),
#[error("config file not found")]
NotFound,
#[error("invalid configuration: {0}")]
Invalid(#[from] serde_yaml::Error),
}
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DefaultsConfig {
/// The theme to use by default in every presentation unless overridden.
pub theme: Option<String>,
/// Override the terminal font size when in windows or when using sixel.
#[serde(default = "default_terminal_font_size")]
#[cfg_attr(feature = "json-schema", validate(range(min = 1)))]
#[serde(default = "default_font_size")]
#[validate(range(min = 1))]
pub terminal_font_size: u8,
/// The image protocol to use.
@ -92,98 +76,24 @@ pub struct DefaultsConfig {
/// Validate that the presentation does not overflow the terminal screen.
#[serde(default)]
pub validate_overflows: ValidateOverflows,
/// A max width in columns that the presentation must always be capped to.
#[serde(default = "default_u16_max")]
pub max_columns: u16,
/// The alignment the presentation should have if `max_columns` is set and the terminal is
/// larger than that.
#[serde(default)]
pub max_columns_alignment: MaxColumnsAlignment,
/// A max height in rows that the presentation must always be capped to.
#[serde(default = "default_u16_max")]
pub max_rows: u16,
/// The alignment the presentation should have if `max_rows` is set and the terminal is
/// larger than that.
#[serde(default)]
pub max_rows_alignment: MaxRowsAlignment,
/// The configuration for lists when incremental lists are enabled.
#[serde(default)]
pub incremental_lists: IncrementalListsConfig,
}
impl Default for DefaultsConfig {
fn default() -> Self {
Self {
theme: Default::default(),
terminal_font_size: default_terminal_font_size(),
terminal_font_size: default_font_size(),
image_protocol: Default::default(),
validate_overflows: Default::default(),
max_columns: default_u16_max(),
max_columns_alignment: Default::default(),
max_rows: default_u16_max(),
max_rows_alignment: Default::default(),
incremental_lists: Default::default(),
}
}
}
/// The configuration for lists when incremental lists are enabled.
#[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct IncrementalListsConfig {
/// Whether to pause before a list begins.
#[serde(default)]
pub pause_before: Option<bool>,
/// Whether to pause after a list ends.
#[serde(default)]
pub pause_after: Option<bool>,
}
fn default_terminal_font_size() -> u8 {
fn default_font_size() -> u8 {
16
}
/// The alignment to use when `defaults.max_columns` is set.
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MaxColumnsAlignment {
/// Align the presentation to the left.
Left,
/// Align the presentation on the center.
#[default]
Center,
/// Align the presentation to the right.
Right,
}
/// The alignment to use when `defaults.max_rows` is set.
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MaxRowsAlignment {
/// Align the presentation to the top.
Top,
/// Align the presentation on the center.
#[default]
Center,
/// Align the presentation to the bottom.
Bottom,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ValidateOverflows {
#[default]
@ -193,8 +103,7 @@ pub enum ValidateOverflows {
WhenDeveloping,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct OptionsConfig {
/// Whether slides are automatically terminated when a slide title is found.
@ -214,14 +123,9 @@ pub struct OptionsConfig {
/// Whether to be strict about parsing the presentation's front matter.
pub strict_front_matter_parsing: Option<bool>,
/// Assume snippets for these languages contain `+render` and render them automatically.
#[serde(default)]
pub auto_render_languages: Vec<SnippetLanguage>,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SnippetConfig {
/// The properties for snippet execution.
@ -237,8 +141,7 @@ pub struct SnippetConfig {
pub render: SnippetRenderConfig,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SnippetExecConfig {
/// Whether to enable snippet execution.
@ -249,8 +152,7 @@ pub struct SnippetExecConfig {
pub custom: BTreeMap<SnippetLanguage, LanguageSnippetExecutionConfig>,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SnippetExecReplaceConfig {
/// Whether to enable snippet replace-executions, which automatically run code snippets without
@ -258,8 +160,7 @@ pub struct SnippetExecReplaceConfig {
pub enable: bool,
}
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SnippetRenderConfig {
/// The number of threads to use when rendering.
@ -277,8 +178,7 @@ pub(crate) fn default_snippet_render_threads() -> usize {
2
}
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TypstConfig {
/// The pixels per inch when rendering latex/typst formulas.
@ -296,8 +196,7 @@ pub(crate) fn default_typst_ppi() -> u32 {
300
}
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MermaidConfig {
/// The scaling parameter to be used in the mermaid CLI.
@ -315,13 +214,8 @@ pub(crate) fn default_mermaid_scale() -> u32 {
2
}
pub(crate) fn default_u16_max() -> u16 {
u16::MAX
}
/// The snippet execution configuration for a specific programming language.
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Deserialize, JsonSchema)]
pub struct LanguageSnippetExecutionConfig {
/// The filename to use for the snippet input file.
pub filename: String,
@ -337,8 +231,7 @@ pub struct LanguageSnippetExecutionConfig {
pub hidden_line_prefix: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize, ValueEnum)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Deserialize, ValueEnum, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum ImageProtocol {
/// Automatically detect the best image protocol to use.
@ -377,10 +270,10 @@ impl TryFrom<&ImageProtocol> for GraphicsMode {
}
ImageProtocol::Iterm2 => GraphicsMode::Iterm2,
ImageProtocol::KittyLocal => {
GraphicsMode::Kitty { mode: KittyMode::Local, inside_tmux: TerminalCapabilities::is_inside_tmux() }
GraphicsMode::Kitty { mode: KittyMode::Local, inside_tmux: TerminalEmulator::is_inside_tmux() }
}
ImageProtocol::KittyRemote => {
GraphicsMode::Kitty { mode: KittyMode::Remote, inside_tmux: TerminalCapabilities::is_inside_tmux() }
GraphicsMode::Kitty { mode: KittyMode::Remote, inside_tmux: TerminalEmulator::is_inside_tmux() }
}
ImageProtocol::AsciiBlocks => GraphicsMode::AsciiBlocks,
#[cfg(feature = "sixel")]
@ -392,8 +285,7 @@ impl TryFrom<&ImageProtocol> for GraphicsMode {
}
}
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyBindingsConfig {
/// The keys that cause the presentation to move forwards.
@ -480,103 +372,6 @@ impl Default for KeyBindingsConfig {
}
}
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SpeakerNotesConfig {
/// The address in which to listen for speaker note events.
#[serde(default = "default_speaker_notes_listen_address")]
pub listen_address: SocketAddr,
/// The address in which to publish speaker notes events.
#[serde(default = "default_speaker_notes_publish_address")]
pub publish_address: SocketAddr,
/// Whether to always publish speaker notes.
#[serde(default)]
pub always_publish: bool,
}
impl Default for SpeakerNotesConfig {
fn default() -> Self {
Self {
listen_address: default_speaker_notes_listen_address(),
publish_address: default_speaker_notes_publish_address(),
always_publish: false,
}
}
}
/// The export configuration.
#[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ExportConfig {
/// The dimensions to use for presentation exports.
pub dimensions: Option<ExportDimensionsConfig>,
/// Whether pauses should create new slides.
#[serde(default)]
pub pauses: PauseExportPolicy,
}
/// The policy for pauses when exporting.
#[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum PauseExportPolicy {
/// Whether to ignore pauses.
#[default]
Ignore,
/// Create a new slide when a pause is found.
NewSlide,
}
/// The dimensions to use for presentation exports.
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ExportDimensionsConfig {
/// The number of rows.
pub rows: u16,
/// The number of columns.
pub columns: u16,
}
// The slide transition configuration.
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(tag = "style", deny_unknown_fields)]
pub struct SlideTransitionConfig {
/// The amount of time to take to perform the transition.
#[serde(default = "default_transition_duration_millis")]
pub duration_millis: u16,
/// The number of frames in a transition.
#[serde(default = "default_transition_frames")]
pub frames: usize,
/// The slide transition style.
pub animation: SlideTransitionStyleConfig,
}
// The slide transition style configuration.
#[derive(Clone, Debug, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(tag = "style", rename_all = "snake_case", deny_unknown_fields)]
pub enum SlideTransitionStyleConfig {
/// Slide horizontally.
SlideHorizontal,
/// Fade the new slide into the previous one.
Fade,
/// Collapse the current slide into the center of the screen.
CollapseHorizontal,
}
fn make_keybindings<const N: usize>(raw_bindings: [&str; N]) -> Vec<KeyBinding> {
let mut bindings = Vec::new();
for binding in raw_bindings {
@ -641,47 +436,14 @@ fn default_suspend_bindings() -> Vec<KeyBinding> {
make_keybindings(["<c-z>"])
}
fn default_transition_duration_millis() -> u16 {
1000
}
fn default_transition_frames() -> usize {
30
}
#[cfg(target_os = "linux")]
pub(crate) fn default_speaker_notes_listen_address() -> SocketAddr {
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 255, 255, 255)), 59418)
}
#[cfg(not(target_os = "linux"))]
pub(crate) fn default_speaker_notes_listen_address() -> SocketAddr {
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 59418)
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn default_speaker_notes_publish_address() -> SocketAddr {
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 255, 255, 255)), 59418)
}
#[cfg(target_os = "macos")]
pub(crate) fn default_speaker_notes_publish_address() -> SocketAddr {
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 59418)
}
#[cfg(test)]
mod test {
use super::*;
use crate::commands::keyboard::CommandKeyBindings;
use crate::input::user::CommandKeyBindings;
#[test]
fn default_bindings() {
let config = KeyBindingsConfig::default();
CommandKeyBindings::try_from(config).expect("construction failed");
}
#[test]
fn default_options_serde() {
serde_yaml::from_str::<'_, OptionsConfig>("implicit_slide_ends: true").expect("failed to parse");
}
}

View File

@ -1,20 +1,16 @@
use crate::{
ImageRegistry, MarkdownParser, PresentationBuilderOptions, Resources, ThemeOptions, Themes, ThirdPartyRender,
code::execute::SnippetExecutor,
commands::{
keyboard::{CommandKeyBindings, KeyboardListener},
listener::Command,
ImageRegistry, MarkdownParser, PresentationBuilderOptions, PresentationTheme, Resources, Themes, ThirdPartyRender,
execute::SnippetExecutor,
input::{
source::Command,
user::{CommandKeyBindings, UserInput},
},
markdown::elements::MarkdownElement,
presentation::{
Presentation,
builder::{BuildError, PresentationBuilder},
},
render::TerminalDrawer,
terminal::emulator::TerminalEmulator,
theme::raw::PresentationTheme,
presentation::Presentation,
processing::builder::{BuildError, PresentationBuilder},
render::{draw::TerminalDrawer, terminal::TerminalWrite},
};
use std::{io, sync::Arc};
use std::{io, rc::Rc};
const PRESENTATION: &str = r#"
# Header 1
@ -41,16 +37,16 @@ fn greet(name: &str) -> String {
<!-- end_slide -->
"#;
pub struct ThemesDemo {
pub struct ThemesDemo<W: TerminalWrite> {
themes: Themes,
input: KeyboardListener,
drawer: TerminalDrawer,
input: UserInput,
drawer: TerminalDrawer<W>,
}
impl ThemesDemo {
pub fn new(themes: Themes, bindings: CommandKeyBindings) -> io::Result<Self> {
let input = KeyboardListener::new(bindings);
let drawer = TerminalDrawer::new(Default::default(), Default::default())?;
impl<W: TerminalWrite> ThemesDemo<W> {
pub fn new(themes: Themes, bindings: CommandKeyBindings, writer: W) -> io::Result<Self> {
let input = UserInput::new(bindings);
let drawer = TerminalDrawer::new(writer, Default::default(), 1)?;
Ok(Self { themes, input, drawer })
}
@ -66,7 +62,7 @@ impl ThemesDemo {
}
let mut current = 0;
loop {
self.drawer.render_operations(presentations[current].current_slide().iter_visible_operations())?;
self.drawer.render_slide(&presentations[current])?;
let command = self.next_command()?;
match command {
@ -103,24 +99,21 @@ impl ThemesDemo {
theme: &PresentationTheme,
) -> Result<Presentation, BuildError> {
let image_registry = ImageRegistry::default();
let resources = Resources::new("non_existent", "non_existent", image_registry.clone());
let mut resources = Resources::new("non_existent", image_registry.clone());
let mut third_party = ThirdPartyRender::default();
let options = PresentationBuilderOptions {
theme_options: ThemeOptions { font_size_supported: TerminalEmulator::capabilities().font_size },
..Default::default()
};
let executer = Arc::new(SnippetExecutor::default());
let options = PresentationBuilderOptions::default();
let executer = Rc::new(SnippetExecutor::default());
let bindings_config = Default::default();
let builder = PresentationBuilder::new(
theme,
resources,
&mut resources,
&mut third_party,
executer,
&self.themes,
image_registry,
bindings_config,
options,
)?;
);
let mut elements = vec![MarkdownElement::SetexHeading { text: format!("theme: {theme_name}").into() }];
elements.extend(base_elements.iter().cloned());
builder.build(elements)

View File

@ -114,15 +114,10 @@ where
mod test {
use super::*;
use crate::{
markdown::{
text::WeightedLine,
text_style::{Color, Colors},
},
presentation::{Slide, SlideBuilder},
render::{
operation::{AsRenderOperations, BlockLine, Pollable, RenderAsync, ToggleState},
properties::WindowSize,
},
markdown::text::WeightedTextBlock,
presentation::{AsRenderOperations, BlockLine, RenderAsync, RenderAsyncState, Slide, SlideBuilder},
render::properties::WindowSize,
style::{Color, Colors},
theme::{Alignment, Margin},
};
use rstest::rstest;
@ -138,9 +133,12 @@ mod test {
}
impl RenderAsync for Dynamic {
fn pollable(&self) -> Box<dyn Pollable> {
// Use some random one, we don't care
Box::new(ToggleState::new(Default::default()))
fn start_render(&self) -> bool {
false
}
fn poll_state(&self) -> RenderAsyncState {
RenderAsyncState::Rendered
}
}
@ -156,7 +154,7 @@ mod test {
prefix: "".into(),
right_padding_length: 0,
repeat_prefix_on_wrap: false,
text: WeightedLine::from("".to_string()),
text: WeightedTextBlock::from("".to_string()),
alignment: Default::default(),
block_length: 42,
block_color: None,

View File

@ -1,17 +1,15 @@
//! Code execution.
use super::snippet::{SnippetExec, SnippetRepr};
use crate::{
code::snippet::{Snippet, SnippetLanguage},
config::LanguageSnippetExecutionConfig,
custom::LanguageSnippetExecutionConfig,
processing::code::{Snippet, SnippetLanguage},
};
use once_cell::sync::Lazy;
use os_pipe::PipeReader;
use std::{
collections::{BTreeMap, HashMap},
fmt::{self, Debug},
fs::File,
io::{self, BufRead, BufReader, Read, Write},
io::{self, BufRead, BufReader, Write},
path::{Path, PathBuf},
process::{self, Child, Stdio},
sync::{Arc, Mutex},
@ -20,9 +18,10 @@ use std::{
use tempfile::TempDir;
static EXECUTORS: Lazy<BTreeMap<SnippetLanguage, LanguageSnippetExecutionConfig>> =
Lazy::new(|| serde_yaml::from_slice(include_bytes!("../../executors.yaml")).expect("executors.yaml is broken"));
Lazy::new(|| serde_yaml::from_slice(include_bytes!("../executors.yaml")).expect("executors.yaml is broken"));
/// Allows executing code.
#[derive(Debug)]
pub struct SnippetExecutor {
executors: BTreeMap<SnippetLanguage, LanguageSnippetExecutionConfig>,
cwd: PathBuf,
@ -60,17 +59,12 @@ impl SnippetExecutor {
let config = self.language_config(snippet)?;
let script_dir = Self::write_snippet(snippet, config)?;
let state: Arc<Mutex<ExecutionState>> = Default::default();
let output_type = match snippet.attributes.representation {
SnippetRepr::Image => OutputType::Binary,
_ => OutputType::Lines,
};
let reader_handle = CommandsRunner::spawn(
state.clone(),
script_dir,
config.commands.clone(),
config.environment.clone(),
self.cwd.to_path_buf(),
output_type,
);
let handle = ExecutionHandle { state, reader_handle };
Ok(handle)
@ -108,9 +102,7 @@ impl SnippetExecutor {
}
fn language_config(&self, snippet: &Snippet) -> Result<&LanguageSnippetExecutionConfig, CodeExecuteError> {
let is_executable = !matches!(snippet.attributes.execution, SnippetExec::None);
let is_exec_replace = matches!(snippet.attributes.representation, SnippetRepr::ExecReplace);
if !is_executable && !is_exec_replace {
if !snippet.attributes.execute && !snippet.attributes.execute_replace {
return Err(CodeExecuteError::NotExecutableCode);
}
self.executors.get(&snippet.language).ok_or(CodeExecuteError::UnsupportedExecution)
@ -134,12 +126,6 @@ impl Default for SnippetExecutor {
}
}
impl Debug for SnippetExecutor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SnippetExecutor {{ .. }}")
}
}
/// An invalid executor was found.
#[derive(thiserror::Error, Debug)]
#[error("invalid snippet execution for '{0:?}': {1}")]
@ -191,16 +177,15 @@ impl CommandsRunner {
commands: Vec<Vec<String>>,
env: HashMap<String, String>,
cwd: PathBuf,
output_type: OutputType,
) -> thread::JoinHandle<()> {
let reader = Self { state, script_directory };
thread::spawn(move || reader.run(commands, env, cwd, output_type))
thread::spawn(|| reader.run(commands, env, cwd))
}
fn run(self, commands: Vec<Vec<String>>, env: HashMap<String, String>, cwd: PathBuf, output_type: OutputType) {
fn run(self, commands: Vec<Vec<String>>, env: HashMap<String, String>, cwd: PathBuf) {
let mut last_result = true;
for command in commands {
last_result = self.run_command(command, &env, &cwd, output_type);
last_result = self.run_command(command, &env, &cwd);
if !last_result {
break;
}
@ -212,23 +197,17 @@ impl CommandsRunner {
self.state.lock().unwrap().status = status;
}
fn run_command(
&self,
command: Vec<String>,
env: &HashMap<String, String>,
cwd: &Path,
output_type: OutputType,
) -> bool {
fn run_command(&self, command: Vec<String>, env: &HashMap<String, String>, cwd: &Path) -> bool {
let (mut child, reader) = match self.launch_process(command, env, cwd) {
Ok(inner) => inner,
Err(e) => {
let mut state = self.state.lock().unwrap();
state.status = ProcessStatus::Failure;
state.output.extend(e.to_string().into_bytes());
state.output.push(e.to_string());
return false;
}
};
let _ = Self::process_output(self.state.clone(), reader, output_type);
let _ = Self::process_output(self.state.clone(), reader);
match child.wait() {
Ok(code) => code.success(),
@ -261,41 +240,24 @@ impl CommandsRunner {
Ok((child, reader))
}
fn process_output(
state: Arc<Mutex<ExecutionState>>,
mut reader: os_pipe::PipeReader,
output_type: OutputType,
) -> io::Result<()> {
match output_type {
OutputType::Lines => {
let reader = BufReader::new(reader);
for line in reader.lines() {
let mut state = state.lock().unwrap();
state.output.extend(line?.into_bytes());
state.output.push(b'\n');
}
Ok(())
}
OutputType::Binary => {
let mut buffer = Vec::new();
reader.read_to_end(&mut buffer)?;
state.lock().unwrap().output.extend(buffer);
Ok(())
fn process_output(state: Arc<Mutex<ExecutionState>>, reader: os_pipe::PipeReader) -> io::Result<()> {
let reader = BufReader::new(reader);
for line in reader.lines() {
let mut line = line?;
if line.contains('\t') {
line = line.replace('\t', " ");
}
// TODO: consider not locking per line...
state.lock().unwrap().output.push(line);
}
Ok(())
}
}
#[derive(Clone, Copy)]
enum OutputType {
Lines,
Binary,
}
/// The state of the execution of a process.
#[derive(Clone, Default, Debug)]
pub(crate) struct ExecutionState {
pub(crate) output: Vec<u8>,
pub(crate) output: Vec<String>,
pub(crate) status: ProcessStatus,
}
@ -318,7 +280,7 @@ impl ProcessStatus {
#[cfg(test)]
mod test {
use super::*;
use crate::code::snippet::SnippetAttributes;
use crate::processing::code::SnippetAttributes;
#[test]
fn shell_code_execution() {
@ -329,7 +291,7 @@ echo 'bye'"
let code = Snippet {
contents,
language: SnippetLanguage::Shell,
attributes: SnippetAttributes { execution: SnippetExec::Exec, ..Default::default() },
attributes: SnippetAttributes { execute: true, ..Default::default() },
};
let handle = SnippetExecutor::default().execute_async(&code).expect("execution failed");
let state = loop {
@ -339,8 +301,8 @@ echo 'bye'"
}
};
let expected = b"hello world\nbye\n";
assert_eq!(state.output, expected);
let expected_lines = vec!["hello world", "bye"];
assert_eq!(state.output, expected_lines);
}
#[test]
@ -349,7 +311,7 @@ echo 'bye'"
let code = Snippet {
contents,
language: SnippetLanguage::Shell,
attributes: SnippetAttributes { execution: SnippetExec::None, ..Default::default() },
attributes: SnippetAttributes { execute: false, ..Default::default() },
};
let result = SnippetExecutor::default().execute_async(&code);
assert!(result.is_err());
@ -365,7 +327,7 @@ echo 'hello world'
let code = Snippet {
contents,
language: SnippetLanguage::Shell,
attributes: SnippetAttributes { execution: SnippetExec::Exec, ..Default::default() },
attributes: SnippetAttributes { execute: true, ..Default::default() },
};
let handle = SnippetExecutor::default().execute_async(&code).expect("execution failed");
let state = loop {
@ -375,8 +337,8 @@ echo 'hello world'
}
};
let expected = b"This message redirects to stderr\nhello world\n";
assert_eq!(state.output, expected);
let expected_lines = vec!["This message redirects to stderr", "hello world"];
assert_eq!(state.output, expected_lines);
}
#[test]
@ -390,7 +352,7 @@ echo 'hello world'
let code = Snippet {
contents,
language: SnippetLanguage::Shell,
attributes: SnippetAttributes { execution: SnippetExec::Exec, ..Default::default() },
attributes: SnippetAttributes { execute: true, ..Default::default() },
};
let handle = SnippetExecutor::default().execute_async(&code).expect("execution failed");
let state = loop {
@ -400,8 +362,9 @@ echo 'hello world'
}
};
let expected = b"this line was hidden\nthis line was hidden and contains another prefix /// \nhello world\n";
assert_eq!(state.output, expected);
let expected_lines =
vec!["this line was hidden", "this line was hidden and contains another prefix /// ", "hello world"];
assert_eq!(state.output, expected_lines);
}
#[test]

416
src/export.rs Normal file
View File

@ -0,0 +1,416 @@
use crate::{
MarkdownParser, PresentationTheme, Resources,
custom::KeyBindingsConfig,
execute::SnippetExecutor,
markdown::parse::ParseError,
media::{
image::{Image, ImageSource},
printer::{ImageResource, ResourceProperties},
},
presentation::{AsRenderOperations, Presentation, RenderAsyncState, RenderOperation},
processing::builder::{BuildError, PresentationBuilder, PresentationBuilderOptions, Themes},
render::properties::WindowSize,
third_party::ThirdPartyRender,
tools::{ExecutionError, ThirdPartyTools},
};
use base64::{Engine, engine::general_purpose::STANDARD};
use image::{DynamicImage, ImageEncoder, ImageError, codecs::png::PngEncoder};
use semver::Version;
use serde::Serialize;
use std::{
env, fs, io, iter,
path::{Path, PathBuf},
rc::Rc,
thread::sleep,
time::Duration,
};
const MINIMUM_EXPORTER_VERSION: Version = Version::new(0, 2, 0);
const ASYNC_RENDER_WAIT_COUNT: usize = 8;
/// Allows exporting presentations into PDF.
pub struct Exporter<'a> {
parser: MarkdownParser<'a>,
default_theme: &'a PresentationTheme,
resources: Resources,
third_party: ThirdPartyRender,
code_executor: Rc<SnippetExecutor>,
themes: Themes,
options: PresentationBuilderOptions,
}
impl<'a> Exporter<'a> {
/// Construct a new exporter.
pub fn new(
parser: MarkdownParser<'a>,
default_theme: &'a PresentationTheme,
resources: Resources,
third_party: ThirdPartyRender,
code_executor: Rc<SnippetExecutor>,
themes: Themes,
options: PresentationBuilderOptions,
) -> Self {
Self { parser, default_theme, resources, third_party, code_executor, themes, options }
}
/// Export the given presentation into PDF.
///
/// This uses a separate `presenterm-export` tool.
pub fn export_pdf(&mut self, presentation_path: &Path, extra_args: &[&str]) -> Result<(), ExportError> {
Self::validate_exporter_version()?;
println!("Analyzing presentation...");
let metadata = self.generate_metadata(presentation_path)?;
println!("Invoking presenterm-export...");
Self::execute_exporter(metadata, extra_args)?;
Ok(())
}
/// Generate the metadata for the given presentation.
pub fn generate_metadata(&mut self, presentation_path: &Path) -> Result<ExportMetadata, ExportError> {
let content = fs::read_to_string(presentation_path).map_err(ExportError::ReadPresentation)?;
let metadata = self.extract_metadata(&content, presentation_path)?;
Ok(metadata)
}
fn validate_exporter_version() -> Result<(), ExportError> {
let result = ThirdPartyTools::presenterm_export(&["--version"]).run_and_capture_stdout();
let version = match result {
Ok(version) => String::from_utf8(version).expect("not utf8"),
Err(ExecutionError::Execution { .. }) => return Err(ExportError::MinimumVersion),
Err(e) => return Err(e.into()),
};
let version = Version::parse(version.trim()).map_err(|_| ExportError::MinimumVersion)?;
if version >= MINIMUM_EXPORTER_VERSION { Ok(()) } else { Err(ExportError::MinimumVersion) }
}
/// Extract the metadata necessary to make an export.
fn extract_metadata(&mut self, content: &str, path: &Path) -> Result<ExportMetadata, ExportError> {
let elements = self.parser.parse(content)?;
let path = path.canonicalize().expect("canonicalize");
let mut presentation = PresentationBuilder::new(
self.default_theme,
&mut self.resources,
&mut self.third_party,
self.code_executor.clone(),
&self.themes,
Default::default(),
KeyBindingsConfig::default(),
self.options.clone(),
)
.build(elements)?;
let async_renders = Self::count_async_render_operations(&presentation);
let images = Self::build_image_metadata(&mut presentation)?;
Self::validate_theme_colors(&presentation)?;
let commands = Self::build_capture_commands(presentation, async_renders);
let metadata = ExportMetadata { commands, presentation_path: path, images };
Ok(metadata)
}
fn execute_exporter(metadata: ExportMetadata, extra_args: &[&str]) -> Result<(), ExportError> {
let presenterm_path = env::current_exe().map_err(ExportError::Io)?;
let presenterm_path = presenterm_path.display().to_string();
let presentation_path = metadata.presentation_path.display().to_string();
let metadata = serde_json::to_vec(&metadata).expect("serialization failed");
let mut args = vec![&presenterm_path, "--enable-export-mode"];
args.extend(extra_args);
args.push(&presentation_path);
ThirdPartyTools::presenterm_export(&args).stdin(metadata).run()?;
Ok(())
}
fn build_capture_commands(mut presentation: Presentation, async_renders: usize) -> Vec<CaptureCommand> {
let mut commands = Vec::new();
let slide_chunks: Vec<_> = presentation.iter_slides().map(|slide| slide.iter_chunks().count()).collect();
let mut next_slide = |commands: &mut Vec<CaptureCommand>| {
commands.push(CaptureCommand::SendKeys { keys: "l" });
commands.push(CaptureCommand::WaitForChange);
presentation.jump_next();
};
commands.extend(iter::repeat(CaptureCommand::WaitForChange).take(ASYNC_RENDER_WAIT_COUNT * async_renders));
for chunks in slide_chunks {
for _ in 0..chunks - 1 {
next_slide(&mut commands);
}
commands.push(CaptureCommand::Capture);
next_slide(&mut commands);
}
commands
}
fn count_async_render_operations(presentation: &Presentation) -> usize {
presentation
.iter_slides()
.map(|slide| {
slide.iter_visible_operations().filter(|op| matches!(op, RenderOperation::RenderAsync(_))).count()
})
.sum()
}
fn build_image_metadata(presentation: &mut Presentation) -> Result<Vec<ImageMetadata>, ExportError> {
let mut replacer = ImageReplacer::default();
replacer.replace_presentation_images(presentation);
let mut positions = Vec::new();
for image in replacer.images {
let meta = match image.original.source {
ImageSource::Filesystem(path) => {
let path = Some(path.canonicalize().map_err(ExportError::Io)?);
ImageMetadata { path, color: image.color, contents: None }
}
ImageSource::Generated => {
let mut buffer = Vec::new();
let dimensions = image.original.dimensions();
let ImageResource::Ascii(resource) = image.original.resource.as_ref() else {
panic!("not in ascii mode")
};
PngEncoder::new(&mut buffer).write_image(
resource.as_bytes(),
dimensions.0,
dimensions.1,
resource.color().into(),
)?;
let contents = Some(STANDARD.encode(buffer));
ImageMetadata { path: None, color: image.color, contents }
}
};
positions.push(meta);
}
Ok(positions)
}
fn validate_theme_colors(presentation: &Presentation) -> Result<(), ExportError> {
for slide in presentation.iter_slides() {
for operation in slide.iter_visible_operations() {
let RenderOperation::SetColors(colors) = operation else {
continue;
};
// The PDF requires a specific theme to be set, as "no background" means "what the
// browser uses" which is likely white and it will probably look terrible. It's
// better to err early and let you choose a theme that contains _some_ color.
if colors.background.is_none() {
return Err(ExportError::UnsupportedColor("background"));
}
if colors.foreground.is_none() {
return Err(ExportError::UnsupportedColor("foreground"));
}
}
}
Ok(())
}
}
#[derive(thiserror::Error, Debug)]
pub enum ExportError {
#[error("failed to read presentation: {0}")]
ReadPresentation(io::Error),
#[error("failed to parse presentation: {0}")]
ParsePresentation(#[from] ParseError),
#[error("failed to build presentation: {0}")]
BuildPresentation(#[from] BuildError),
#[error("unsupported {0} color in theme")]
UnsupportedColor(&'static str),
#[error("generating images: {0}")]
GeneratingImages(#[from] ImageError),
#[error(transparent)]
Execution(#[from] ExecutionError),
#[error("minimum presenterm-export version ({MINIMUM_EXPORTER_VERSION}) not met")]
MinimumVersion,
#[error("io: {0}")]
Io(io::Error),
}
/// The metadata necessary to export a presentation.
#[derive(Clone, Debug, Serialize)]
pub struct ExportMetadata {
presentation_path: PathBuf,
images: Vec<ImageMetadata>,
commands: Vec<CaptureCommand>,
}
/// Metadata about an image.
#[derive(Clone, Debug, Serialize)]
struct ImageMetadata {
path: Option<PathBuf>,
contents: Option<String>,
color: u32,
}
/// A command to whoever is capturing us indicating what to do.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "type")]
enum CaptureCommand {
Capture,
SendKeys { keys: &'static str },
WaitForChange,
}
struct ReplacedImage {
original: Image,
color: u32,
}
pub(crate) struct ImageReplacer {
next_color: u32,
images: Vec<ReplacedImage>,
}
impl ImageReplacer {
pub(crate) fn replace_presentation_images(&mut self, presentation: &mut Presentation) {
let callback = |operation: &mut RenderOperation| {
match operation {
RenderOperation::RenderImage(image, properties) => {
let replacement = self.replace_image(image.clone());
*operation = RenderOperation::RenderImage(replacement, properties.clone());
}
RenderOperation::RenderAsync(inner) => {
loop {
match inner.poll_state() {
RenderAsyncState::NotStarted => return,
RenderAsyncState::Rendering { .. } => {
sleep(Duration::from_millis(200));
continue;
}
RenderAsyncState::Rendered | RenderAsyncState::JustFinishedRendering => break,
};
}
let window_size = WindowSize { rows: 0, columns: 0, width: 0, height: 0 };
let mut new_operations = Vec::new();
for operation in inner.as_render_operations(&window_size) {
if let RenderOperation::RenderImage(image, properties) = operation {
let image = self.replace_image(image);
new_operations.push(RenderOperation::RenderImage(image, properties));
} else {
new_operations.push(operation);
}
}
// Replace this operation with a new operation that contains the replaced image
// and any other unmodified operations.
*operation = RenderOperation::RenderDynamic(Rc::new(RenderMany(new_operations)));
}
_ => (),
};
};
presentation.mutate_operations(callback);
}
fn replace_image(&mut self, image: Image) -> Image {
let dimensions = image.dimensions();
let color = self.allocate_color();
let rgb_color = Self::as_rgb(color);
let mut replacement = DynamicImage::new_rgb8(dimensions.0, dimensions.1);
let buffer = replacement.as_mut_rgb8().expect("not rgb8");
for pixel in buffer.pixels_mut() {
pixel.0 = rgb_color;
}
self.images.push(ReplacedImage { original: image, color });
Image::new(ImageResource::Ascii(replacement.into()), ImageSource::Generated)
}
fn allocate_color(&mut self) -> u32 {
let color = self.next_color;
self.next_color += 1;
color
}
fn as_rgb(color: u32) -> [u8; 3] {
[(color >> 16) as u8, (color >> 8) as u8, (color & 0xff) as u8]
}
}
impl Default for ImageReplacer {
fn default() -> Self {
Self { next_color: 0xffbad3, images: Vec::new() }
}
}
#[derive(Debug)]
struct RenderMany(Vec<RenderOperation>);
impl AsRenderOperations for RenderMany {
fn as_render_operations(&self, _: &WindowSize) -> Vec<RenderOperation> {
self.0.clone()
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::theme::PresentationThemeSet;
use comrak::Arena;
fn extract_metadata(content: &str, path: &str) -> ExportMetadata {
let arena = Arena::new();
let parser = MarkdownParser::new(&arena);
let theme = PresentationThemeSet::default().load_by_name("dark").unwrap();
let resources = Resources::new("examples", Default::default());
let third_party = ThirdPartyRender::default();
let code_executor = Default::default();
let themes = Themes::default();
let options = PresentationBuilderOptions { allow_mutations: false, ..Default::default() };
let mut exporter = Exporter::new(parser, &theme, resources, third_party, code_executor, themes, options);
exporter.extract_metadata(content, Path::new(path)).expect("metadata extraction failed")
}
#[test]
fn metadata() {
let presentation = r"
First
<!-- end_slide -->
hi
<!-- pause -->
mom
<!-- end_slide -->
![](doge.png)
<!-- end_slide -->
bye
<!-- pause -->
mom
";
let meta = extract_metadata(presentation, "examples/demo.md");
use CaptureCommand::*;
let expected_commands = vec![
// First slide
Capture,
SendKeys { keys: "l" },
WaitForChange,
// Second slide...
SendKeys { keys: "l" },
WaitForChange,
Capture,
SendKeys { keys: "l" },
WaitForChange,
// Third slide...
Capture,
SendKeys { keys: "l" },
WaitForChange,
// Fourth slide...
SendKeys { keys: "l" },
WaitForChange,
Capture,
SendKeys { keys: "l" },
WaitForChange,
];
assert_eq!(meta.commands, expected_commands);
}
}

View File

@ -1,313 +0,0 @@
use crate::{
MarkdownParser, Resources,
code::execute::SnippetExecutor,
config::{KeyBindingsConfig, PauseExportPolicy},
export::output::{ExportRenderer, OutputFormat},
markdown::{parse::ParseError, text_style::Color},
presentation::{
Presentation,
builder::{BuildError, PresentationBuilder, PresentationBuilderOptions, Themes},
poller::{Poller, PollerCommand},
},
render::{
RenderError,
operation::{AsRenderOperations, PollableState, RenderOperation},
properties::WindowSize,
},
theme::{ProcessingThemeError, raw::PresentationTheme},
third_party::ThirdPartyRender,
tools::{ExecutionError, ThirdPartyTools},
};
use crossterm::{
cursor::{MoveToColumn, MoveToNextLine, MoveUp},
execute,
style::{Print, PrintStyledContent, Stylize},
terminal::{Clear, ClearType},
};
use image::ImageError;
use std::{
fs, io,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
};
use tempfile::TempDir;
pub enum OutputDirectory {
Temporary(TempDir),
External(PathBuf),
}
impl OutputDirectory {
pub fn temporary() -> io::Result<Self> {
let dir = TempDir::with_suffix("presenterm")?;
Ok(Self::Temporary(dir))
}
pub fn external(path: PathBuf) -> io::Result<Self> {
fs::create_dir_all(&path)?;
Ok(Self::External(path))
}
pub(crate) fn path(&self) -> &Path {
match self {
Self::Temporary(temp) => temp.path(),
Self::External(path) => path,
}
}
}
/// Allows exporting presentations into PDF.
pub struct Exporter<'a> {
parser: MarkdownParser<'a>,
default_theme: &'a PresentationTheme,
resources: Resources,
third_party: ThirdPartyRender,
code_executor: Arc<SnippetExecutor>,
themes: Themes,
dimensions: WindowSize,
options: PresentationBuilderOptions,
}
impl<'a> Exporter<'a> {
/// Construct a new exporter.
#[allow(clippy::too_many_arguments)]
pub fn new(
parser: MarkdownParser<'a>,
default_theme: &'a PresentationTheme,
resources: Resources,
third_party: ThirdPartyRender,
code_executor: Arc<SnippetExecutor>,
themes: Themes,
mut options: PresentationBuilderOptions,
mut dimensions: WindowSize,
pause_policy: PauseExportPolicy,
) -> Self {
// We don't want dynamically highlighted code blocks.
options.allow_mutations = false;
options.theme_options.font_size_supported = true;
options.pause_create_new_slide = match pause_policy {
PauseExportPolicy::Ignore => false,
PauseExportPolicy::NewSlide => true,
};
// Make sure we have a 1:2 aspect ratio.
let width = (0.5 * dimensions.columns as f64) / (dimensions.rows as f64 / dimensions.height as f64);
dimensions.width = width as u16;
Self { parser, default_theme, resources, third_party, code_executor, themes, options, dimensions }
}
fn build_renderer(
&mut self,
presentation_path: &Path,
output_directory: OutputDirectory,
renderer: OutputFormat,
) -> Result<ExportRenderer, ExportError> {
let content = fs::read_to_string(presentation_path).map_err(ExportError::ReadPresentation)?;
let elements = self.parser.parse(&content)?;
let mut presentation = PresentationBuilder::new(
self.default_theme,
self.resources.clone(),
&mut self.third_party,
self.code_executor.clone(),
&self.themes,
Default::default(),
KeyBindingsConfig::default(),
self.options.clone(),
)?
.build(elements)?;
Self::validate_theme_colors(&presentation)?;
let mut render = ExportRenderer::new(self.dimensions.clone(), output_directory, renderer);
Self::log("waiting for images to be generated and code to be executed, if any...")?;
Self::render_async_images(&mut presentation);
for (index, slide) in presentation.into_slides().into_iter().enumerate() {
let index = index + 1;
Self::log(&format!("processing slide {index}..."))?;
render.process_slide(slide)?;
}
Self::log("invoking weasyprint...")?;
Ok(render)
}
/// Export the given presentation into PDF.
pub fn export_pdf(
mut self,
presentation_path: &Path,
output_directory: OutputDirectory,
output_path: Option<&Path>,
) -> Result<(), ExportError> {
println!(
"exporting using rows={}, columns={}, width={}, height={}",
self.dimensions.rows, self.dimensions.columns, self.dimensions.width, self.dimensions.height
);
println!("checking for weasyprint...");
Self::validate_weasyprint_exists()?;
Self::log("weasyprint installation found")?;
let render = self.build_renderer(presentation_path, output_directory, OutputFormat::Pdf)?;
let pdf_path = match output_path {
Some(path) => path.to_path_buf(),
None => presentation_path.with_extension("pdf"),
};
render.generate(&pdf_path)?;
execute!(
io::stdout(),
PrintStyledContent(
format!("output file is at {}\n", pdf_path.display()).stylize().with(Color::Green.into())
)
)?;
Ok(())
}
/// Export the given presentation into HTML.
pub fn export_html(
mut self,
presentation_path: &Path,
output_directory: OutputDirectory,
output_path: Option<&Path>,
) -> Result<(), ExportError> {
println!(
"exporting using rows={}, columns={}, width={}, height={}",
self.dimensions.rows, self.dimensions.columns, self.dimensions.width, self.dimensions.height
);
let render = self.build_renderer(presentation_path, output_directory, OutputFormat::Html)?;
let output_path = match output_path {
Some(path) => path.to_path_buf(),
None => presentation_path.with_extension("html"),
};
render.generate(&output_path)?;
execute!(
io::stdout(),
PrintStyledContent(
format!("output file is at {}\n", output_path.display()).stylize().with(Color::Green.into())
)
)?;
Ok(())
}
fn render_async_images(presentation: &mut Presentation) {
let poller = Poller::launch();
let mut pollables = Vec::new();
for (index, slide) in presentation.iter_slides().enumerate() {
for op in slide.iter_operations() {
if let RenderOperation::RenderAsync(inner) = op {
// Send a pollable to the poller and keep one for ourselves.
poller.send(PollerCommand::Poll { pollable: inner.pollable(), slide: index });
pollables.push(inner.pollable())
}
}
}
// Poll until they're all done
for mut pollable in pollables {
while let PollableState::Unmodified | PollableState::Modified = pollable.poll() {}
}
// Replace render asyncs with new operations that contains the replaced image
// and any other unmodified operations.
for slide in presentation.iter_slides_mut() {
for op in slide.iter_operations_mut() {
if let RenderOperation::RenderAsync(inner) = op {
let window_size = WindowSize { rows: 0, columns: 0, width: 0, height: 0 };
let new_operations = inner.as_render_operations(&window_size);
*op = RenderOperation::RenderDynamic(Rc::new(RenderMany(new_operations)));
}
}
}
}
fn validate_weasyprint_exists() -> Result<(), ExportError> {
let result = ThirdPartyTools::weasyprint(&["--version"]).run_and_capture_stdout();
match result {
Ok(_) => Ok(()),
Err(ExecutionError::Execution { .. }) => Err(ExportError::WeasyprintMissing),
Err(e) => Err(e.into()),
}
}
fn validate_theme_colors(presentation: &Presentation) -> Result<(), ExportError> {
for slide in presentation.iter_slides() {
for operation in slide.iter_visible_operations() {
let RenderOperation::SetColors(colors) = operation else {
continue;
};
// The PDF requires a specific theme to be set, as "no background" means "what the
// browser uses" which is likely white and it will probably look terrible. It's
// better to err early and let you choose a theme that contains _some_ color.
if colors.background.is_none() {
return Err(ExportError::UnsupportedColor("background"));
}
if colors.foreground.is_none() {
return Err(ExportError::UnsupportedColor("foreground"));
}
}
}
Ok(())
}
fn log(text: &str) -> io::Result<()> {
execute!(
io::stdout(),
MoveUp(1),
Clear(ClearType::CurrentLine),
MoveToColumn(0),
Print(text),
MoveToNextLine(1)
)
}
}
#[derive(thiserror::Error, Debug)]
pub enum ExportError {
#[error("failed to read presentation: {0}")]
ReadPresentation(io::Error),
#[error("failed to parse presentation: {0}")]
ParsePresentation(#[from] ParseError),
#[error("failed to build presentation: {0}")]
BuildPresentation(#[from] BuildError),
#[error("unsupported {0} color in theme")]
UnsupportedColor(&'static str),
#[error("generating images: {0}")]
GeneratingImages(#[from] ImageError),
#[error(transparent)]
Execution(#[from] ExecutionError),
#[error("weasyprint not found")]
WeasyprintMissing,
#[error("processing theme: {0}")]
ProcessingTheme(#[from] ProcessingThemeError),
#[error("io: {0}")]
Io(#[from] io::Error),
#[error("render: {0}")]
Render(#[from] RenderError),
}
#[derive(Debug)]
struct RenderMany(Vec<RenderOperation>);
impl AsRenderOperations for RenderMany {
fn as_render_operations(&self, _: &WindowSize) -> Vec<RenderOperation> {
self.0.clone()
}
}

View File

@ -1,122 +0,0 @@
use crate::markdown::text_style::{Color, TextAttribute, TextStyle};
use std::{borrow::Cow, fmt};
pub(crate) enum HtmlText {
Plain(String),
Styled { text: String, style: String },
}
impl HtmlText {
pub(crate) fn new(text: &str, style: &TextStyle, font_size: FontSize) -> Self {
if style == &TextStyle::default() {
return Self::Plain(text.to_string());
}
let mut css_styles = Vec::new();
let mut text_decorations = Vec::new();
for attr in style.iter_attributes() {
match attr {
TextAttribute::Bold => css_styles.push(Cow::Borrowed("font-weight: bold")),
TextAttribute::Italics => css_styles.push(Cow::Borrowed("font-style: italic")),
TextAttribute::Strikethrough => text_decorations.push(Cow::Borrowed("line-through")),
TextAttribute::Underlined => text_decorations.push(Cow::Borrowed("underline")),
TextAttribute::ForegroundColor(color) => {
let color = color_to_html(&color);
css_styles.push(format!("color: {color}").into());
}
TextAttribute::BackgroundColor(color) => {
let color = color_to_html(&color);
css_styles.push(format!("background-color: {color}").into());
}
};
}
if !text_decorations.is_empty() {
let text_decoration = text_decorations.join(" ");
css_styles.push(format!("text-decoration: {text_decoration}").into());
}
if style.size > 1 {
let font_size = font_size.scale(style.size);
css_styles.push(format!("font-size: {font_size}").into());
}
let css_style = css_styles.join("; ");
Self::Styled { text: text.to_string(), style: css_style }
}
}
impl fmt::Display for HtmlText {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Plain(text) => write!(f, "{text}"),
Self::Styled { text, style } => write!(f, "<span style=\"{style}\">{text}</span>"),
}
}
}
pub(crate) enum FontSize {
Pixels(u16),
}
impl FontSize {
fn scale(&self, size: u8) -> String {
match self {
Self::Pixels(scale) => format!("{}px", scale * size as u16),
}
}
}
pub(crate) fn color_to_html(color: &Color) -> String {
match color {
Color::Black => "#000000".into(),
Color::DarkGrey => "#5a5a5a".into(),
Color::Red => "#ff0000".into(),
Color::DarkRed => "#8b0000".into(),
Color::Green => "#00ff00".into(),
Color::DarkGreen => "#006400".into(),
Color::Yellow => "#ffff00".into(),
Color::DarkYellow => "#8b8000".into(),
Color::Blue => "#0000ff".into(),
Color::DarkBlue => "#00008b".into(),
Color::Magenta => "#ff00ff".into(),
Color::DarkMagenta => "#8b008b".into(),
Color::Cyan => "#00ffff".into(),
Color::DarkCyan => "#008b8b".into(),
Color::White => "#ffffff".into(),
Color::Grey => "#808080".into(),
Color::Rgb { r, g, b } => format!("#{r:02x}{g:02x}{b:02x}"),
}
}
#[cfg(test)]
mod test {
use super::*;
use rstest::rstest;
#[rstest]
#[case::none(TextStyle::default(), "")]
#[case::bold(TextStyle::default().bold(), "font-weight: bold")]
#[case::italics(TextStyle::default().italics(), "font-style: italic")]
#[case::bold_italics(TextStyle::default().bold().italics(), "font-weight: bold; font-style: italic")]
#[case::strikethrough(TextStyle::default().strikethrough(), "text-decoration: line-through")]
#[case::underlined(TextStyle::default().underlined(), "text-decoration: underline")]
#[case::strikethrough_underlined(
TextStyle::default().strikethrough().underlined(),
"text-decoration: line-through underline"
)]
#[case::foreground_color(TextStyle::default().fg_color(Color::new(1,2,3)), "color: #010203")]
#[case::background_color(TextStyle::default().bg_color(Color::new(1,2,3)), "background-color: #010203")]
#[case::font_size(TextStyle::default().size(3), "font-size: 6px")]
fn html_text(#[case] style: TextStyle, #[case] expected_style: &str) {
let html_text = HtmlText::new("", &style, FontSize::Pixels(2));
let style = match &html_text {
HtmlText::Plain(_) => "",
HtmlText::Styled { style, .. } => &style,
};
assert_eq!(style, expected_style);
}
#[test]
fn render_span() {
let html_text = HtmlText::new("hi", &TextStyle::default().bold(), FontSize::Pixels(1));
let rendered = html_text.to_string();
assert_eq!(rendered, "<span style=\"font-weight: bold\">hi</span>");
}
}

View File

@ -1,3 +0,0 @@
pub mod exporter;
pub(crate) mod html;
pub(crate) mod output;

View File

@ -1,260 +0,0 @@
use super::{
exporter::{ExportError, OutputDirectory},
html::{FontSize, color_to_html},
};
use crate::{
export::html::HtmlText,
markdown::text_style::TextStyle,
presentation::Slide,
render::{engine::RenderEngine, properties::WindowSize},
terminal::{
image::printer::TerminalImage,
virt::{TerminalGrid, VirtualTerminal},
},
tools::ThirdPartyTools,
};
use std::{
fs, io,
path::{Path, PathBuf},
};
// A magical multiplier that converts a font size in pixels to a font width.
//
// There's probably something somewhere that specifies what the relationship
// really is but I found this by trial and error an I'm okay with that.
const FONT_SIZE_WIDTH: f64 = 0.605;
const FONT_SIZE: u16 = 10;
const LINE_HEIGHT: u16 = 12;
struct HtmlSlide {
rows: Vec<String>,
background_color: Option<String>,
}
impl HtmlSlide {
fn new(grid: TerminalGrid) -> Result<Self, ExportError> {
let mut rows = Vec::new();
rows.push(String::from("<div class=\"container\">"));
for (y, row) in grid.rows.into_iter().enumerate() {
let mut finalized_row = "<div class=\"content-line\"><pre>".to_string();
let mut current_style = row.first().map(|c| c.style).unwrap_or_default();
let mut current_string = String::new();
let mut x = 0;
while x < row.len() {
let c = row[x];
if c.style != current_style {
finalized_row.push_str(&Self::finalize_string(&current_string, &current_style));
current_string = String::new();
current_style = c.style;
}
match c.character {
'<' => current_string.push_str("&lt;"),
'>' => current_string.push_str("&gt;"),
other => current_string.push(other),
}
if let Some(image) = grid.images.get(&(y as u16, x as u16)) {
let TerminalImage::Raw(raw_image) = image.image.image() else { panic!("not in raw image mode") };
let image_contents = raw_image.to_inline_html();
let width_pixels = (image.width_columns as f64 * FONT_SIZE as f64 * FONT_SIZE_WIDTH).ceil();
let image_tag = format!(
"<img width=\"{width_pixels}\" src=\"{image_contents}\" style=\"position: absolute\" />"
);
current_string.push_str(&image_tag);
}
x += c.style.size as usize;
}
if !current_string.is_empty() {
finalized_row.push_str(&Self::finalize_string(&current_string, &current_style));
}
finalized_row.push_str("</pre></div>");
rows.push(finalized_row);
}
rows.push(String::from("</div>"));
Ok(HtmlSlide { rows, background_color: grid.background_color.as_ref().map(color_to_html) })
}
fn finalize_string(s: &str, style: &TextStyle) -> String {
HtmlText::new(s, style, FontSize::Pixels(FONT_SIZE)).to_string()
}
}
pub(crate) struct ContentManager {
output_directory: OutputDirectory,
}
impl ContentManager {
pub(crate) fn new(output_directory: OutputDirectory) -> Self {
Self { output_directory }
}
fn persist_file(&self, name: &str, data: &[u8]) -> io::Result<PathBuf> {
let path = self.output_directory.path().join(name);
fs::write(&path, data)?;
Ok(path)
}
}
pub(crate) enum OutputFormat {
Pdf,
Html,
}
pub(crate) struct ExportRenderer {
content_manager: ContentManager,
output_format: OutputFormat,
dimensions: WindowSize,
html_body: String,
background_color: Option<String>,
}
impl ExportRenderer {
pub(crate) fn new(dimensions: WindowSize, output_directory: OutputDirectory, output_type: OutputFormat) -> Self {
let image_manager = ContentManager::new(output_directory);
Self {
content_manager: image_manager,
dimensions,
html_body: "".to_string(),
background_color: None,
output_format: output_type,
}
}
pub(crate) fn process_slide(&mut self, slide: Slide) -> Result<(), ExportError> {
let mut terminal = VirtualTerminal::new(self.dimensions.clone(), Default::default());
let engine = RenderEngine::new(&mut terminal, self.dimensions.clone(), Default::default());
engine.render(slide.iter_operations())?;
let grid = terminal.into_contents();
let slide = HtmlSlide::new(grid)?;
if self.background_color.is_none() {
self.background_color.clone_from(&slide.background_color);
}
for row in slide.rows {
self.html_body.push_str(&row);
self.html_body.push('\n');
}
Ok(())
}
pub(crate) fn generate(self, output_path: &Path) -> Result<(), ExportError> {
let html_body = &self.html_body;
let script = include_str!("script.js");
let width = (self.dimensions.columns as f64 * FONT_SIZE as f64 * FONT_SIZE_WIDTH).ceil();
let height = self.dimensions.rows * LINE_HEIGHT;
let background_color = self.background_color.unwrap_or_else(|| "black".into());
let container = match self.output_format {
OutputFormat::Pdf => String::from("display: contents;"),
OutputFormat::Html => String::from(
"
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
",
),
};
let css = format!(
r"
pre {{
margin: 0;
padding: 0;
}}
span {{
display: inline-block;
}}
body {{
margin: 0;
font-size: {FONT_SIZE}px;
line-height: {LINE_HEIGHT}px;
width: {width}px;
height: {height}px;
transform-origin: top left;
background-color: {background_color};
}}
.container {{
{container}
}}
.content-line {{
line-height: {LINE_HEIGHT}px;
height: {LINE_HEIGHT}px;
margin: 0px;
width: {width}px;
}}
.hidden {{
display: none;
}}
@page {{
margin: 0;
height: {height}px;
width: {width}px;
}}"
);
let html_script = match self.output_format {
OutputFormat::Pdf => String::new(),
OutputFormat::Html => {
format!(
"
<script>
let originalWidth = {width};
let originalHeight = {height};
{script}
</script>"
)
}
};
let style = match self.output_format {
OutputFormat::Pdf => String::new(),
OutputFormat::Html => format!(
"
<head>
<style>
{css}
</style>
</head>
"
),
};
let html = format!(
r"
<html>
{style}
<body>
{html_body}
{html_script}
</body>
</html>"
);
let html_path = self.content_manager.persist_file("index.html", html.as_bytes())?;
let css_path = self.content_manager.persist_file("styles.css", css.as_bytes())?;
match self.output_format {
OutputFormat::Pdf => {
ThirdPartyTools::weasyprint(&[
"-s",
css_path.to_string_lossy().as_ref(),
"--presentational-hints",
"-e",
"utf8",
html_path.to_string_lossy().as_ref(),
output_path.to_string_lossy().as_ref(),
])
.run()?;
}
OutputFormat::Html => {
fs::write(output_path, html.as_bytes())?;
}
}
Ok(())
}
}

View File

@ -1,45 +0,0 @@
document.addEventListener('DOMContentLoaded', function() {
const allLines = document.querySelectorAll('body > div');
const pageBreakMarkers = document.querySelectorAll('.container');
let currentPageIndex = 0;
function showCurrentPage() {
allLines.forEach((line) => {
line.classList.add('hidden');
});
allLines[currentPageIndex].classList.remove('hidden');
}
function scaler() {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
let widthScaledAmount= w/originalWidth;
let heightScaledAmount= h/originalHeight;
let scaledAmount = Math.min(widthScaledAmount, heightScaledAmount);
document.querySelector("body").style.transform = `scale(${scaledAmount})`;
}
function handleKeyPress(event) {
if (event.key === 'ArrowLeft') {
if (currentPageIndex > 0) {
currentPageIndex--;
showCurrentPage();
}
} else if (event.key === 'ArrowRight') {
if (currentPageIndex < pageBreakMarkers.length - 1) {
currentPageIndex++;
showCurrentPage();
}
}
}
document.addEventListener('keydown', handleKeyPress);
window.addEventListener("resize", scaler);
scaler();
showCurrentPage();
});

2
src/input/mod.rs Normal file
View File

@ -0,0 +1,2 @@
pub(crate) mod source;
pub(crate) mod user;

View File

@ -1,42 +1,29 @@
use super::{
keyboard::{CommandKeyBindings, KeyBindingsValidationError, KeyboardListener},
speaker_notes::{SpeakerNotesEvent, SpeakerNotesEventListener},
};
use crate::{config::KeyBindingsConfig, presenter::PresentationError};
use super::user::{CommandKeyBindings, KeyBindingsValidationError, UserInput};
use crate::custom::KeyBindingsConfig;
use serde::Deserialize;
use std::time::Duration;
use std::{io, time::Duration};
use strum::EnumDiscriminants;
/// A command listener that allows polling all command sources in a single place.
pub struct CommandListener {
keyboard: KeyboardListener,
speaker_notes_event_listener: Option<SpeakerNotesEventListener>,
/// The source of commands.
///
/// This expects user commands as well as watches over the presentation file to reload if it that
/// happens.
pub struct CommandSource {
user_input: UserInput,
}
impl CommandListener {
impl CommandSource {
/// Create a new command source over the given presentation path.
pub fn new(
config: KeyBindingsConfig,
speaker_notes_event_listener: Option<SpeakerNotesEventListener>,
) -> Result<Self, KeyBindingsValidationError> {
pub fn new(config: KeyBindingsConfig) -> Result<Self, KeyBindingsValidationError> {
let bindings = CommandKeyBindings::try_from(config)?;
Ok(Self { keyboard: KeyboardListener::new(bindings), speaker_notes_event_listener })
Ok(Self { user_input: UserInput::new(bindings) })
}
/// Try to get the next command.
///
/// This attempts to get a command and returns `Ok(None)` on timeout.
pub(crate) fn try_next_command(&mut self) -> Result<Option<Command>, PresentationError> {
if let Some(receiver) = &self.speaker_notes_event_listener {
if let Some(msg) = receiver.try_recv()? {
let command = match msg {
SpeakerNotesEvent::GoToSlide { slide } => Command::GoToSlide(slide),
SpeakerNotesEvent::Exit => Command::Exit,
};
return Ok(Some(command));
}
}
match self.keyboard.poll_next_command(Duration::from_millis(100))? {
pub(crate) fn try_next_command(&mut self) -> io::Result<Option<Command>> {
match self.user_input.poll_next_command(Duration::from_millis(250))? {
Some(command) => Ok(Some(command)),
None => Ok(None),
}

View File

@ -1,15 +1,17 @@
use super::listener::{Command, CommandDiscriminants};
use crate::config::KeyBindingsConfig;
use super::source::{Command, CommandDiscriminants};
use crate::custom::KeyBindingsConfig;
use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, poll, read};
use schemars::JsonSchema;
use serde_with::DeserializeFromStr;
use std::{fmt, io, iter, mem, str::FromStr, time::Duration};
/// A keyboard command listener.
pub struct KeyboardListener {
/// A user input handler.
pub struct UserInput {
bindings: CommandKeyBindings,
events: Vec<KeyEvent>,
}
impl KeyboardListener {
impl UserInput {
pub fn new(bindings: CommandKeyBindings) -> Self {
Self { bindings, events: Vec::new() }
}
@ -160,11 +162,8 @@ enum BindingMatch {
None,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct KeyBinding(#[cfg_attr(feature = "json-schema", schemars(with = "String"))] Vec<KeyMatcher>);
crate::utils::impl_deserialize_from_str!(KeyBinding);
#[derive(Clone, Debug, PartialEq, Eq, DeserializeFromStr, JsonSchema)]
pub struct KeyBinding(#[schemars(with = "String")] Vec<KeyMatcher>);
impl KeyBinding {
fn match_events(&self, mut events: &[KeyEvent]) -> BindingMatch {

38
src/lib.rs Normal file
View File

@ -0,0 +1,38 @@
//! Presenterm: a terminal slideshow presentation tool.
//!
//! This is not meant to be used as a crate!
pub(crate) mod ansi;
pub(crate) mod custom;
pub(crate) mod demo;
pub(crate) mod diff;
pub(crate) mod execute;
pub(crate) mod export;
pub(crate) mod input;
pub(crate) mod markdown;
pub(crate) mod media;
pub(crate) mod presentation;
pub(crate) mod presenter;
pub(crate) mod processing;
pub(crate) mod render;
pub(crate) mod resource;
pub(crate) mod style;
pub(crate) mod theme;
pub(crate) mod third_party;
pub(crate) mod tools;
pub use crate::{
custom::{Config, ImageProtocol, ValidateOverflows},
demo::ThemesDemo,
execute::SnippetExecutor,
export::{ExportError, Exporter},
input::source::CommandSource,
markdown::parse::MarkdownParser,
media::{graphics::GraphicsMode, printer::ImagePrinter, register::ImageRegistry},
presenter::{PresentMode, Presenter, PresenterOptions},
processing::builder::{PresentationBuilderOptions, Themes},
render::highlighting::{CodeHighlighter, HighlightThemeSet},
resource::Resources,
theme::{LoadThemeError, PresentationTheme, PresentationThemeSet},
third_party::{ThirdPartyConfigs, ThirdPartyRender},
};

View File

@ -1,62 +1,21 @@
use crate::{
code::{execute::SnippetExecutor, highlighting::HighlightThemeSet},
commands::listener::CommandListener,
config::{Config, ImageProtocol, ValidateOverflows},
demo::ThemesDemo,
export::exporter::Exporter,
markdown::parse::MarkdownParser,
presentation::builder::{PresentationBuilderOptions, Themes},
presenter::{PresentMode, Presenter, PresenterOptions},
resource::Resources,
terminal::{
GraphicsMode,
image::printer::{ImagePrinter, ImageRegistry},
},
theme::{raw::PresentationTheme, registry::PresentationThemeRegistry},
third_party::{ThirdPartyConfigs, ThirdPartyRender},
};
use anyhow::anyhow;
use clap::{CommandFactory, Parser, error::ErrorKind};
use commands::speaker_notes::{SpeakerNotesEventListener, SpeakerNotesEventPublisher};
use comrak::Arena;
use config::ConfigLoadError;
use crossterm::{
execute,
style::{PrintStyledContent, Stylize},
};
use directories::ProjectDirs;
use export::exporter::OutputDirectory;
use render::{engine::MaxSize, properties::WindowSize};
use presenterm::{
CommandSource, Config, Exporter, GraphicsMode, HighlightThemeSet, ImagePrinter, ImageProtocol, ImageRegistry,
MarkdownParser, PresentMode, PresentationBuilderOptions, PresentationTheme, PresentationThemeSet, Presenter,
PresenterOptions, Resources, SnippetExecutor, Themes, ThemesDemo, ThirdPartyConfigs, ThirdPartyRender,
ValidateOverflows,
};
use std::{
env::{self, current_dir},
io,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
};
use terminal::emulator::TerminalEmulator;
use theme::ThemeOptions;
mod code;
mod commands;
mod config;
mod demo;
mod export;
mod markdown;
mod presentation;
mod presenter;
mod render;
mod resource;
mod terminal;
mod theme;
mod third_party;
mod tools;
mod transitions;
mod ui;
mod utils;
const DEFAULT_THEME: &str = "dark";
const DEFAULT_EXPORT_PIXELS_PER_COLUMN: u16 = 20;
const DEFAULT_EXPORT_PIXELS_PER_ROW: u16 = DEFAULT_EXPORT_PIXELS_PER_COLUMN * 2;
/// Run slideshows from your terminal.
#[derive(Parser)]
@ -68,26 +27,21 @@ struct Cli {
path: Option<PathBuf>,
/// Export the presentation as a PDF rather than displaying it.
#[clap(short, long, group = "export")]
#[clap(short, long)]
export_pdf: bool,
/// Export the presentation as a HTML rather than displaying it.
#[clap(long, group = "export")]
export_html: bool,
/// The path in which to store temporary files used when exporting.
#[clap(long, requires = "export")]
export_temporary_path: Option<PathBuf>,
/// The output path for the exported PDF.
#[clap(short = 'o', long = "output", requires = "export")]
export_output: Option<PathBuf>,
/// Generate the PDF metadata without generating the PDF itself.
#[clap(long, hide = true)]
generate_pdf_metadata: bool,
/// Generate a JSON schema for the configuration file.
#[clap(long)]
#[cfg(feature = "json-schema")]
generate_config_file_schema: bool,
/// Run in export mode.
#[clap(long, hide = true)]
enable_export_mode: bool,
/// Use presentation mode.
#[clap(short, long, default_value_t = false)]
present: bool,
@ -97,13 +51,9 @@ struct Cli {
theme: Option<String>,
/// List all supported themes.
#[clap(long, group = "target")]
#[clap(long)]
list_themes: bool,
/// Print the theme in use.
#[clap(long, group = "target")]
current_theme: bool,
/// Display acknowledgements.
#[clap(long, group = "target")]
acknowledgements: bool,
@ -127,14 +77,6 @@ struct Cli {
/// The path to the configuration file.
#[clap(short, long)]
config_file: Option<String>,
/// Whether to publish speaker notes to local listeners.
#[clap(short = 'P', long, group = "speaker-notes")]
publish_speaker_notes: bool,
/// Whether to listen for speaker notes.
#[clap(short, long, group = "speaker-notes")]
listen_speaker_notes: bool,
}
fn create_splash() -> String {
@ -155,195 +97,89 @@ fn create_splash() -> String {
struct Customizations {
config: Config,
themes: Themes,
themes_path: Option<PathBuf>,
code_executor: SnippetExecutor,
}
impl Customizations {
fn load(config_file_path: Option<PathBuf>, cwd: &Path) -> Result<Self, Box<dyn std::error::Error>> {
let configs_path: PathBuf = match env::var("XDG_CONFIG_HOME") {
Ok(path) => Path::new(&path).join("presenterm"),
fn load_customizations(
config_file_path: Option<PathBuf>,
cwd: &Path,
) -> Result<Customizations, Box<dyn std::error::Error>> {
let configs_path: PathBuf = match env::var("XDG_CONFIG_HOME") {
Ok(path) => Path::new(&path).join("presenterm"),
Err(_) => {
let Some(project_dirs) = ProjectDirs::from("", "", "presenterm") else {
return Ok(Default::default());
};
project_dirs.config_dir().into()
}
};
let themes = load_themes(&configs_path)?;
let config_file_path = config_file_path.unwrap_or_else(|| configs_path.join("config.yaml"));
let config = Config::load(&config_file_path)?;
let code_executor = SnippetExecutor::new(config.snippet.exec.custom.clone(), cwd.to_path_buf())?;
Ok(Customizations { config, themes, code_executor })
}
fn load_themes(config_path: &Path) -> Result<Themes, Box<dyn std::error::Error>> {
let themes_path = config_path.join("themes");
let mut highlight_themes = HighlightThemeSet::default();
highlight_themes.register_from_directory(themes_path.join("highlighting"))?;
let mut presentation_themes = PresentationThemeSet::default();
presentation_themes.register_from_directory(&themes_path)?;
let themes = Themes { presentation: presentation_themes, highlight: highlight_themes };
Ok(themes)
}
fn display_acknowledgements() {
let acknowledgements = include_bytes!("../bat/acknowledgements.txt");
println!("{}", String::from_utf8_lossy(acknowledgements));
}
fn make_builder_options(config: &Config, mode: &PresentMode, force_default_theme: bool) -> PresentationBuilderOptions {
PresentationBuilderOptions {
allow_mutations: !matches!(mode, PresentMode::Export),
implicit_slide_ends: config.options.implicit_slide_ends.unwrap_or_default(),
command_prefix: config.options.command_prefix.clone().unwrap_or_default(),
image_attribute_prefix: config.options.image_attributes_prefix.clone().unwrap_or_else(|| "image:".to_string()),
incremental_lists: config.options.incremental_lists.unwrap_or_default(),
force_default_theme,
end_slide_shorthand: config.options.end_slide_shorthand.unwrap_or_default(),
print_modal_background: false,
strict_front_matter_parsing: config.options.strict_front_matter_parsing.unwrap_or(true),
enable_snippet_execution: config.snippet.exec.enable,
enable_snippet_execution_replace: config.snippet.exec_replace.enable,
}
}
fn load_default_theme(config: &Config, themes: &Themes, cli: &Cli) -> PresentationTheme {
let default_theme_name =
cli.theme.as_ref().or(config.defaults.theme.as_ref()).map(|s| s.as_str()).unwrap_or(DEFAULT_THEME);
let Some(default_theme) = themes.presentation.load_by_name(default_theme_name) else {
let valid_themes = themes.presentation.theme_names().join(", ");
let error_message = format!("invalid theme name, valid themes are: {valid_themes}");
Cli::command().error(ErrorKind::InvalidValue, error_message).exit();
};
default_theme
}
fn select_graphics_mode(cli: &Cli, config: &Config) -> GraphicsMode {
if cli.enable_export_mode || cli.export_pdf || cli.generate_pdf_metadata {
GraphicsMode::AsciiBlocks
} else {
let protocol = cli.image_protocol.as_ref().unwrap_or(&config.defaults.image_protocol);
match GraphicsMode::try_from(protocol) {
Ok(mode) => mode,
Err(_) => {
let Some(project_dirs) = ProjectDirs::from("", "", "presenterm") else {
return Ok(Default::default());
};
project_dirs.config_dir().into()
}
};
let themes_path = configs_path.join("themes");
let themes = Self::load_themes(&themes_path)?;
let require_config_file = config_file_path.is_some();
let config_file_path = config_file_path.unwrap_or_else(|| configs_path.join("config.yaml"));
let config = match Config::load(&config_file_path) {
Ok(config) => config,
Err(ConfigLoadError::NotFound) if !require_config_file => Default::default(),
Err(e) => return Err(e.into()),
};
let code_executor = SnippetExecutor::new(config.snippet.exec.custom.clone(), cwd.to_path_buf())?;
Ok(Customizations { config, themes, themes_path: Some(themes_path), code_executor })
}
fn load_themes(themes_path: &Path) -> Result<Themes, Box<dyn std::error::Error>> {
let mut highlight_themes = HighlightThemeSet::default();
highlight_themes.register_from_directory(themes_path.join("highlighting"))?;
let mut presentation_themes = PresentationThemeRegistry::default();
presentation_themes.register_from_directory(themes_path)?;
let themes = Themes { presentation: presentation_themes, highlight: highlight_themes };
Ok(themes)
}
}
struct CoreComponents {
third_party: ThirdPartyRender,
code_executor: Arc<SnippetExecutor>,
resources: Resources,
printer: Arc<ImagePrinter>,
builder_options: PresentationBuilderOptions,
themes: Themes,
default_theme: PresentationTheme,
config: Config,
present_mode: PresentMode,
graphics_mode: GraphicsMode,
}
impl CoreComponents {
fn new(cli: &Cli, path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
let mut resources_path = path.parent().unwrap_or(Path::new("./")).to_path_buf();
if resources_path == Path::new("") {
resources_path = "./".into();
}
let resources_path = resources_path.canonicalize().unwrap_or(resources_path);
let Customizations { config, themes, code_executor, themes_path } =
Customizations::load(cli.config_file.clone().map(PathBuf::from), &resources_path)?;
let default_theme = Self::load_default_theme(&config, &themes, cli);
let force_default_theme = cli.theme.is_some();
let present_mode = match (cli.present, cli.export_pdf) {
(true, _) | (_, true) => PresentMode::Presentation,
(false, false) => PresentMode::Development,
};
let mut builder_options = Self::make_builder_options(&config, force_default_theme, cli.listen_speaker_notes);
if cli.enable_snippet_execution {
builder_options.enable_snippet_execution = true;
}
if cli.enable_snippet_execution_replace {
builder_options.enable_snippet_execution_replace = true;
}
let graphics_mode = Self::select_graphics_mode(cli, &config);
let printer = Arc::new(ImagePrinter::new(graphics_mode.clone())?);
let registry = ImageRegistry::new(printer.clone());
let resources = Resources::new(
resources_path.clone(),
themes_path.unwrap_or_else(|| resources_path.clone()),
registry.clone(),
);
let third_party_config = ThirdPartyConfigs {
typst_ppi: config.typst.ppi.to_string(),
mermaid_scale: config.mermaid.scale.to_string(),
threads: config.snippet.render.threads,
};
let third_party = ThirdPartyRender::new(third_party_config, registry, &resources_path);
let code_executor = Arc::new(code_executor);
Ok(Self {
third_party,
code_executor,
resources,
printer,
builder_options,
themes,
default_theme,
config,
present_mode,
graphics_mode,
})
}
fn make_builder_options(
config: &Config,
force_default_theme: bool,
render_speaker_notes_only: bool,
) -> PresentationBuilderOptions {
PresentationBuilderOptions {
allow_mutations: true,
implicit_slide_ends: config.options.implicit_slide_ends.unwrap_or_default(),
command_prefix: config.options.command_prefix.clone().unwrap_or_default(),
image_attribute_prefix: config
.options
.image_attributes_prefix
.clone()
.unwrap_or_else(|| "image:".to_string()),
incremental_lists: config.options.incremental_lists.unwrap_or_default(),
force_default_theme,
end_slide_shorthand: config.options.end_slide_shorthand.unwrap_or_default(),
print_modal_background: false,
strict_front_matter_parsing: config.options.strict_front_matter_parsing.unwrap_or(true),
enable_snippet_execution: config.snippet.exec.enable,
enable_snippet_execution_replace: config.snippet.exec_replace.enable,
render_speaker_notes_only,
auto_render_languages: config.options.auto_render_languages.clone(),
theme_options: ThemeOptions { font_size_supported: TerminalEmulator::capabilities().font_size },
pause_before_incremental_lists: config.defaults.incremental_lists.pause_before.unwrap_or(true),
pause_after_incremental_lists: config.defaults.incremental_lists.pause_after.unwrap_or(true),
pause_create_new_slide: false,
}
}
fn select_graphics_mode(cli: &Cli, config: &Config) -> GraphicsMode {
if cli.export_pdf | cli.export_html {
GraphicsMode::Raw
} else {
let protocol = cli.image_protocol.as_ref().unwrap_or(&config.defaults.image_protocol);
match GraphicsMode::try_from(protocol) {
Ok(mode) => mode,
Err(_) => Cli::command()
.error(ErrorKind::InvalidValue, "sixel support was not enabled during compilation")
.exit(),
Cli::command().error(ErrorKind::InvalidValue, "sixel support was not enabled during compilation").exit()
}
}
}
fn load_default_theme(config: &Config, themes: &Themes, cli: &Cli) -> PresentationTheme {
let default_theme_name =
cli.theme.as_ref().or(config.defaults.theme.as_ref()).map(|s| s.as_str()).unwrap_or(DEFAULT_THEME);
let Some(default_theme) = themes.presentation.load_by_name(default_theme_name) else {
let valid_themes = themes.presentation.theme_names().join(", ");
let error_message = format!("invalid theme name, valid themes are: {valid_themes}");
Cli::command().error(ErrorKind::InvalidValue, error_message).exit();
};
default_theme
}
}
struct SpeakerNotesComponents {
events_listener: Option<SpeakerNotesEventListener>,
events_publisher: Option<SpeakerNotesEventPublisher>,
}
impl SpeakerNotesComponents {
fn new(cli: &Cli, config: &Config, path: &Path) -> anyhow::Result<Self> {
let full_presentation_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let publish_speaker_notes =
cli.publish_speaker_notes || (config.speaker_notes.always_publish && !cli.listen_speaker_notes);
let events_publisher = publish_speaker_notes
.then(|| {
SpeakerNotesEventPublisher::new(config.speaker_notes.publish_address, full_presentation_path.clone())
})
.transpose()
.map_err(|e| anyhow!("failed to create speaker notes publisher: {e}"))?;
let events_listener = cli
.listen_speaker_notes
.then(|| SpeakerNotesEventListener::new(config.speaker_notes.listen_address, full_presentation_path))
.transpose()
.map_err(|e| anyhow!("failed to create speaker notes listener: {e}"))?;
Ok(Self { events_listener, events_publisher })
}
}
fn overflow_validation_enabled(mode: &PresentMode, config: &ValidateOverflows) -> bool {
fn overflow_validation(mode: &PresentMode, config: &ValidateOverflows) -> bool {
match (config, mode) {
(ValidateOverflows::Always, _) => true,
(ValidateOverflows::Never, _) => false,
@ -353,111 +189,100 @@ fn overflow_validation_enabled(mode: &PresentMode, config: &ValidateOverflows) -
}
}
fn run(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
#[cfg(feature = "json-schema")]
fn run(mut cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
if cli.generate_config_file_schema {
let schema = schemars::schema_for!(Config);
serde_json::to_writer_pretty(io::stdout(), &schema).map_err(|e| format!("failed to write schema: {e}"))?;
return Ok(());
}
if cli.acknowledgements {
let acknowledgements = include_bytes!("../bat/acknowledgements.txt");
println!("{}", String::from_utf8_lossy(acknowledgements));
} else if cli.acknowledgements {
display_acknowledgements();
return Ok(());
} else if cli.list_themes {
// Load this ahead of time so we don't do it when we're already in raw mode.
TerminalEmulator::capabilities();
let Customizations { config, themes, .. } =
Customizations::load(cli.config_file.clone().map(PathBuf::from), &current_dir()?)?;
load_customizations(cli.config_file.clone().map(PathBuf::from), &current_dir()?)?;
let bindings = config.bindings.try_into()?;
let demo = ThemesDemo::new(themes, bindings)?;
let demo = ThemesDemo::new(themes, bindings, io::stdout())?;
demo.run()?;
return Ok(());
} else if cli.current_theme {
let Customizations { config, .. } =
Customizations::load(cli.config_file.clone().map(PathBuf::from), &current_dir()?)?;
let theme_name =
cli.theme.as_ref().or(config.defaults.theme.as_ref()).map(|s| s.as_str()).unwrap_or(DEFAULT_THEME);
println!("{theme_name}");
return Ok(());
}
// Disable this so we don't mess things up when generating PDFs
if cli.export_pdf {
TerminalEmulator::disable_capability_detection();
}
let Some(path) = cli.path.clone() else {
let Some(path) = cli.path.take() else {
Cli::command().error(ErrorKind::MissingRequiredArgument, "no path specified").exit();
};
let CoreComponents {
third_party,
code_executor,
resources,
printer,
mut builder_options,
themes,
default_theme,
config,
present_mode,
graphics_mode,
} = CoreComponents::new(&cli, &path)?;
let mut resources_path = path.parent().unwrap_or(Path::new("./")).to_path_buf();
if resources_path == Path::new("") {
resources_path = "./".into();
}
let resources_path = resources_path.canonicalize().unwrap_or(resources_path);
let Customizations { config, themes, code_executor } =
load_customizations(cli.config_file.clone().map(PathBuf::from), &resources_path)?;
let default_theme = load_default_theme(&config, &themes, &cli);
let force_default_theme = cli.theme.is_some();
let mode = match (cli.present, cli.enable_export_mode) {
(true, _) => PresentMode::Presentation,
(false, true) => PresentMode::Export,
(false, false) => PresentMode::Development,
};
let arena = Arena::new();
let parser = MarkdownParser::new(&arena);
let validate_overflows =
overflow_validation_enabled(&present_mode, &config.defaults.validate_overflows) || cli.validate_overflows;
if cli.export_pdf || cli.export_html {
let dimensions = match config.export.dimensions {
Some(dimensions) => WindowSize {
rows: dimensions.rows,
columns: dimensions.columns,
height: dimensions.rows * DEFAULT_EXPORT_PIXELS_PER_ROW,
width: dimensions.columns * DEFAULT_EXPORT_PIXELS_PER_COLUMN,
},
None => WindowSize::current(config.defaults.terminal_font_size)?,
};
let exporter = Exporter::new(
parser,
&default_theme,
resources,
third_party,
code_executor,
themes,
builder_options,
dimensions,
config.export.pauses,
);
let output_directory = match cli.export_temporary_path {
Some(path) => OutputDirectory::external(path),
None => OutputDirectory::temporary(),
}?;
let validate_overflows = overflow_validation(&mode, &config.defaults.validate_overflows) || cli.validate_overflows;
let mut options = make_builder_options(&config, &mode, force_default_theme);
if cli.enable_snippet_execution {
options.enable_snippet_execution = true;
}
if cli.enable_snippet_execution_replace {
options.enable_snippet_execution_replace = true;
}
let graphics_mode = select_graphics_mode(&cli, &config);
let printer = Arc::new(ImagePrinter::new(graphics_mode.clone())?);
let registry = ImageRegistry(printer.clone());
let resources = Resources::new(resources_path.clone(), registry.clone());
let third_party_config = ThirdPartyConfigs {
typst_ppi: config.typst.ppi.to_string(),
mermaid_scale: config.mermaid.scale.to_string(),
threads: config.snippet.render.threads,
};
let third_party = ThirdPartyRender::new(third_party_config, registry, &resources_path);
let code_executor = Rc::new(code_executor);
if cli.export_pdf || cli.generate_pdf_metadata {
let mut exporter =
Exporter::new(parser, &default_theme, resources, third_party, code_executor, themes, options);
let mut args = Vec::new();
if let Some(theme) = cli.theme.as_ref() {
args.extend(["--theme", theme]);
}
if let Some(path) = cli.config_file.as_ref() {
args.extend(["--config-file", path]);
}
if cli.enable_snippet_execution {
args.push("-x");
}
if cli.enable_snippet_execution_replace {
args.push("-X");
}
if cli.export_pdf {
exporter.export_pdf(&path, output_directory, cli.export_output.as_deref())?;
exporter.export_pdf(&path, &args)?;
} else {
exporter.export_html(&path, output_directory, cli.export_output.as_deref())?;
let meta = exporter.generate_metadata(&path)?;
println!("{}", serde_json::to_string_pretty(&meta)?);
}
} else {
let SpeakerNotesComponents { events_listener, events_publisher } =
SpeakerNotesComponents::new(&cli, &config, &path)?;
let command_listener = CommandListener::new(config.bindings.clone(), events_listener)?;
let commands = CommandSource::new(config.bindings.clone())?;
options.print_modal_background = matches!(graphics_mode, GraphicsMode::Kitty { .. });
builder_options.print_modal_background = matches!(graphics_mode, GraphicsMode::Kitty { .. });
let options = PresenterOptions {
builder_options,
mode: present_mode,
builder_options: options,
mode,
font_size_fallback: config.defaults.terminal_font_size,
bindings: config.bindings,
validate_overflows,
max_size: MaxSize {
max_columns: config.defaults.max_columns,
max_columns_alignment: config.defaults.max_columns_alignment,
max_rows: config.defaults.max_rows,
max_rows_alignment: config.defaults.max_rows_alignment,
},
transition: config.transition,
};
let presenter = Presenter::new(
&default_theme,
command_listener,
commands,
parser,
resources,
third_party,
@ -465,7 +290,6 @@ fn run(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
themes,
printer,
options,
events_publisher,
);
presenter.present(&path)?;
}
@ -475,8 +299,7 @@ fn run(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
fn main() {
let cli = Cli::parse();
if let Err(e) = run(cli) {
let _ =
execute!(io::stdout(), PrintStyledContent(format!("{e}\n").stylize().with(crossterm::style::Color::Red)));
eprintln!("{e}");
std::process::exit(1);
}
}

View File

@ -1,7 +1,5 @@
use super::text_style::{Color, TextStyle, UndefinedPaletteColorError};
use crate::theme::{ColorPalette, raw::RawColor};
use comrak::nodes::AlertType;
use std::{fmt, iter, path::PathBuf, str::FromStr};
use crate::style::TextStyle;
use std::{iter, path::PathBuf, str::FromStr};
use unicode_width::UnicodeWidthStr;
/// A markdown element.
@ -14,13 +12,13 @@ pub(crate) enum MarkdownElement {
FrontMatter(String),
/// A setex heading.
SetexHeading { text: Line<RawColor> },
SetexHeading { text: TextBlock },
/// A normal heading.
Heading { level: u8, text: Line<RawColor> },
Heading { level: u8, text: TextBlock },
/// A paragraph composed by a list of lines.
Paragraph(Vec<Line<RawColor>>),
Paragraph(Vec<TextBlock>),
/// An image.
Image { path: PathBuf, title: String, source_position: SourcePosition },
@ -52,29 +50,19 @@ pub(crate) enum MarkdownElement {
Comment { comment: String, source_position: SourcePosition },
/// A block quote containing a list of lines.
BlockQuote(Vec<Line<RawColor>>),
/// An alert.
Alert {
/// The alert's type.
alert_type: AlertType,
/// The optional title.
title: Option<String>,
/// The content lines in this alert.
lines: Vec<Line<RawColor>>,
},
BlockQuote(Vec<TextBlock>),
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SourcePosition {
#[derive(Clone, Debug, Default)]
pub(crate) struct SourcePosition {
pub(crate) start: LineColumn,
}
impl fmt::Display for SourcePosition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.start.line, self.start.column)
impl SourcePosition {
pub(crate) fn offset_lines(&self, offset: usize) -> SourcePosition {
let mut output = self.clone();
output.start.line += offset;
output
}
}
@ -84,7 +72,7 @@ impl From<comrak::nodes::Sourcepos> for SourcePosition {
}
}
#[derive(Clone, Copy, Debug, Default)]
#[derive(Clone, Debug, Default)]
pub(crate) struct LineColumn {
pub(crate) line: usize,
pub(crate) column: usize,
@ -96,26 +84,18 @@ impl From<comrak::nodes::LineColumn> for LineColumn {
}
}
/// A text line.
/// A block of text.
///
/// Text is represented as a series of chunks, each with their own formatting.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Line<C = Color>(pub(crate) Vec<Text<C>>);
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub(crate) struct TextBlock(pub(crate) Vec<Text>);
impl<C> Default for Line<C> {
fn default() -> Self {
Self(vec![])
}
}
impl<C> Line<C> {
impl TextBlock {
/// Get the total width for this text.
pub(crate) fn width(&self) -> usize {
self.0.iter().map(|text| text.content.width()).sum()
}
}
impl Line<Color> {
/// Applies the given style to this text.
pub(crate) fn apply_style(&mut self, style: &TextStyle) {
for text in &mut self.0 {
@ -124,19 +104,7 @@ impl Line<Color> {
}
}
impl Line<RawColor> {
/// Resolve the colors in this line.
pub(crate) fn resolve(self, palette: &ColorPalette) -> Result<Line<Color>, UndefinedPaletteColorError> {
let mut output = Vec::with_capacity(self.0.len());
for text in self.0 {
let style = text.style.resolve(palette)?;
output.push(Text::new(text.content, style));
}
Ok(Line(output))
}
}
impl<C, T: Into<Text<C>>> From<T> for Line<C> {
impl<T: Into<Text>> From<T> for TextBlock {
fn from(text: T) -> Self {
Self(vec![text.into()])
}
@ -146,36 +114,25 @@ impl<C, T: Into<Text<C>>> From<T> for Line<C> {
///
/// This is the most granular text representation: a `String` and a style.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Text<C = Color> {
pub(crate) struct Text {
pub(crate) content: String,
pub(crate) style: TextStyle<C>,
pub(crate) style: TextStyle,
}
impl<C> Default for Text<C> {
fn default() -> Self {
Self { content: Default::default(), style: TextStyle::default() }
}
}
impl<C> Text<C> {
impl Text {
/// Construct a new styled text.
pub(crate) fn new<S: Into<String>>(content: S, style: TextStyle<C>) -> Self {
pub(crate) fn new<S: Into<String>>(content: S, style: TextStyle) -> Self {
Self { content: content.into(), style }
}
/// Get the width of this text.
pub(crate) fn width(&self) -> usize {
self.content.width()
}
}
impl<C> From<String> for Text<C> {
impl From<String> for Text {
fn from(text: String) -> Self {
Self { content: text, style: TextStyle::default() }
}
}
impl<C> From<&str> for Text<C> {
impl From<&str> for Text {
fn from(text: &str) -> Self {
Self { content: text.into(), style: TextStyle::default() }
}
@ -190,7 +147,7 @@ pub(crate) struct ListItem {
pub(crate) depth: u8,
/// The contents of this list item.
pub(crate) contents: Line<RawColor>,
pub(crate) contents: TextBlock,
/// The type of list item.
pub(crate) item_type: ListItemType,
@ -203,10 +160,10 @@ pub(crate) enum ListItemType {
Unordered,
/// A list item for an ordered list that uses parenthesis after the list item number.
OrderedParens(usize),
OrderedParens,
/// A list item for an ordered list that uses a period after the list item number.
OrderedPeriod(usize),
OrderedPeriod,
}
/// A table.
@ -228,7 +185,7 @@ impl Table {
/// Iterates all the text entries in a column.
///
/// This includes the header.
pub(crate) fn iter_column(&self, column: usize) -> impl Iterator<Item = &Line<RawColor>> {
pub(crate) fn iter_column(&self, column: usize) -> impl Iterator<Item = &TextBlock> {
let header_element = &self.header.0[column];
let row_elements = self.rows.iter().map(move |row| &row.0[column]);
iter::once(header_element).chain(row_elements)
@ -237,7 +194,7 @@ impl Table {
/// A table row.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TableRow(pub(crate) Vec<Line<RawColor>>);
pub(crate) struct TableRow(pub(crate) Vec<TextBlock>);
/// A percentage.
#[derive(Clone, Debug, PartialEq, Eq)]

View File

@ -1,195 +0,0 @@
use super::text_style::{Color, TextStyle};
use crate::theme::raw::{ParseColorError, RawColor};
use std::{borrow::Cow, str, str::Utf8Error};
use tl::Attributes;
pub(crate) struct HtmlParseOptions {
pub(crate) strict: bool,
}
impl Default for HtmlParseOptions {
fn default() -> Self {
Self { strict: true }
}
}
#[derive(Default)]
pub(crate) struct HtmlParser {
options: HtmlParseOptions,
}
impl HtmlParser {
pub(crate) fn parse(self, input: &str) -> Result<HtmlInline, ParseHtmlError> {
if input.starts_with("</") {
if input.starts_with("</span") {
return Ok(HtmlInline::CloseSpan);
} else {
return Err(ParseHtmlError::UnsupportedClosingTag(input.to_string()));
}
}
let dom = tl::parse(input, Default::default())?;
let top = dom.children().iter().next().ok_or(ParseHtmlError::NoTags)?;
let node = top.get(dom.parser()).expect("failed to get");
let tag = node.as_tag().ok_or(ParseHtmlError::NoTags)?;
if tag.name().as_bytes() != b"span" {
return Err(ParseHtmlError::UnsupportedHtml);
}
let style = self.parse_attributes(tag.attributes())?;
Ok(HtmlInline::OpenSpan { style })
}
fn parse_attributes(&self, attributes: &Attributes) -> Result<TextStyle<RawColor>, ParseHtmlError> {
let mut style = TextStyle::default();
for (name, value) in attributes.iter() {
let value = value.unwrap_or(Cow::Borrowed(""));
match name.as_ref() {
"style" => self.parse_css_attribute(&value, &mut style)?,
"class" => {
style = style.fg_color(RawColor::ForegroundClass(value.to_string()));
style = style.bg_color(RawColor::BackgroundClass(value.to_string()));
}
_ => {
if self.options.strict {
return Err(ParseHtmlError::UnsupportedTagAttribute(name.to_string()));
}
}
}
}
Ok(style)
}
fn parse_css_attribute(&self, attribute: &str, style: &mut TextStyle<RawColor>) -> Result<(), ParseHtmlError> {
for attribute in attribute.split(';') {
let attribute = attribute.trim();
if attribute.is_empty() {
continue;
}
let (key, value) = attribute.split_once(':').ok_or(ParseHtmlError::NoColonInAttribute)?;
let key = key.trim();
let value = value.trim();
match key {
"color" => style.colors.foreground = Some(Self::parse_color(value)?),
"background-color" => style.colors.background = Some(Self::parse_color(value)?),
_ => {
if self.options.strict {
return Err(ParseHtmlError::UnsupportedCssAttribute(key.into()));
}
}
}
}
Ok(())
}
fn parse_color(input: &str) -> Result<RawColor, ParseHtmlError> {
if input.starts_with('#') {
let color = input.strip_prefix('#').unwrap().parse()?;
if matches!(color, RawColor::Color(Color::Rgb { .. })) { Ok(color) } else { Ok(input.parse()?) }
} else {
let color = input.parse::<RawColor>()?;
if matches!(color, RawColor::Color(Color::Rgb { .. })) {
Err(ParseHtmlError::InvalidColor("missing '#' in rgb color".into()))
} else {
Ok(color)
}
}
}
}
#[derive(Debug)]
pub(crate) enum HtmlInline {
OpenSpan { style: TextStyle<RawColor> },
CloseSpan,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum ParseHtmlError {
#[error("parsing html failed: {0}")]
ParsingHtml(#[from] tl::ParseError),
#[error("no html tags found")]
NoTags,
#[error("non utf8 content: {0}")]
NotUtf8(#[from] Utf8Error),
#[error("attribute has no ':'")]
NoColonInAttribute,
#[error("invalid color: {0}")]
InvalidColor(String),
#[error("invalid css attribute: {0}")]
UnsupportedCssAttribute(String),
#[error("HTML can only contain span tags")]
UnsupportedHtml,
#[error("unsupported tag attribute: {0}")]
UnsupportedTagAttribute(String),
#[error("unsupported closing tag: {0}")]
UnsupportedClosingTag(String),
}
impl From<ParseColorError> for ParseHtmlError {
fn from(e: ParseColorError) -> Self {
Self::InvalidColor(e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[test]
fn parse_style() {
let tag =
HtmlParser::default().parse(r#"<span style="color: red; background-color: black">"#).expect("parse failed");
let HtmlInline::OpenSpan { style } = tag else { panic!("not an open tag") };
assert_eq!(style, TextStyle::default().bg_color(Color::Black).fg_color(Color::Red));
}
#[test]
fn parse_class() {
let tag = HtmlParser::default().parse(r#"<span class="foo">"#).expect("parse failed");
let HtmlInline::OpenSpan { style } = tag else { panic!("not an open tag") };
assert_eq!(
style,
TextStyle::default()
.bg_color(RawColor::BackgroundClass("foo".into()))
.fg_color(RawColor::ForegroundClass("foo".into()))
);
}
#[test]
fn parse_end_tag() {
let tag = HtmlParser::default().parse("</span>").expect("parse failed");
assert!(matches!(tag, HtmlInline::CloseSpan));
}
#[rstest]
#[case::invalid_start_tag("<div>")]
#[case::invalid_end_tag("</div>")]
#[case::invalid_attribute("<span foo=\"bar\">")]
#[case::invalid_attribute("<span style=\"bleh: 42\"")]
#[case::invalid_color("<span style=\"color: 42\"")]
fn parse_invalid_html(#[case] input: &str) {
HtmlParser::default().parse(input).expect_err("parse succeeded");
}
#[rstest]
#[case::rgb("#ff0000", Color::Rgb{r: 255, g: 0, b: 0})]
#[case::red("red", Color::Red)]
fn parse_color(#[case] input: &str, #[case] expected: Color) {
let color = HtmlParser::parse_color(input).expect("parse failed");
assert_eq!(color, expected.into());
}
#[rstest]
#[case::rgb("ff0000")]
#[case::red("#red")]
fn parse_invalid_color(#[case] input: &str) {
HtmlParser::parse_color(input).expect_err("parse succeeded");
}
}

View File

@ -1,5 +1,3 @@
pub(crate) mod elements;
pub(crate) mod html;
pub(crate) mod parse;
pub(crate) mod text;
pub(crate) mod text_style;

View File

@ -1,16 +1,15 @@
use super::{
elements::{Line, ListItem, ListItemType, MarkdownElement, SourcePosition, Table, TableRow, Text},
html::{HtmlInline, HtmlParser, ParseHtmlError},
text_style::TextStyle,
use super::elements::SourcePosition;
use crate::{
markdown::elements::{ListItem, ListItemType, MarkdownElement, Table, TableRow, Text, TextBlock},
style::TextStyle,
};
use crate::theme::raw::RawColor;
use comrak::{
Arena, ComrakOptions,
arena_tree::Node,
format_commonmark,
nodes::{
Ast, AstNode, ListDelimType, ListType, NodeAlert, NodeCodeBlock, NodeHeading, NodeHtmlBlock, NodeList,
NodeValue, Sourcepos,
Ast, AstNode, ListDelimType, ListType, NodeCodeBlock, NodeHeading, NodeHtmlBlock, NodeList, NodeValue,
Sourcepos,
},
parse_document,
};
@ -23,7 +22,7 @@ use std::{
/// The result of parsing a markdown file.
pub(crate) type ParseResult<T> = Result<T, ParseError>;
struct ParserOptions(comrak::Options<'static>);
struct ParserOptions(ComrakOptions<'static>);
impl Default for ParserOptions {
fn default() -> Self {
@ -32,8 +31,6 @@ impl Default for ParserOptions {
options.extension.table = true;
options.extension.strikethrough = true;
options.extension.multiline_block_quotes = true;
options.extension.alerts = true;
options.extension.wikilinks_title_before_pipe = true;
Self(options)
}
}
@ -43,7 +40,7 @@ impl Default for ParserOptions {
/// This takes the contents of a markdown file and parses it into a list of [MarkdownElement].
pub struct MarkdownParser<'a> {
arena: &'a Arena<AstNode<'a>>,
options: comrak::Options<'static>,
options: ComrakOptions<'static>,
}
impl<'a> MarkdownParser<'a> {
@ -56,40 +53,37 @@ impl<'a> MarkdownParser<'a> {
pub(crate) fn parse(&self, contents: &str) -> ParseResult<Vec<MarkdownElement>> {
let node = parse_document(self.arena, contents, &self.options);
let mut elements = Vec::new();
let mut lines_offset = 0;
for node in node.children() {
let parsed_elements = self.parse_node(node).map_err(|e| ParseError::new(e.kind, e.sourcepos))?;
let mut parsed_elements =
self.parse_node(node).map_err(|e| ParseError::new(e.kind, e.sourcepos.offset_lines(lines_offset)))?;
if let Some(MarkdownElement::FrontMatter(contents)) = parsed_elements.first() {
lines_offset += contents.lines().count() + 2;
}
// comrak ignores the lines in the front matter so we need to offset this ourselves.
Self::adjust_source_positions(parsed_elements.iter_mut(), lines_offset);
elements.extend(parsed_elements);
}
Ok(elements)
}
/// Parse inlines in a markdown input.
pub(crate) fn parse_inlines(&self, line: &str) -> Result<Line<RawColor>, ParseInlinesError> {
let node = parse_document(self.arena, line, &self.options);
if node.children().count() == 0 {
return Ok(Default::default());
}
if node.children().count() > 1 {
return Err(ParseInlinesError("inline must be simple text".into()));
}
let node = node.first_child().expect("must have one child");
let data = node.data.borrow();
let NodeValue::Paragraph = &data.value else {
return Err(ParseInlinesError("inline must be simple text".into()));
};
let parser = InlinesParser::new(self.arena, SoftBreak::Space, StringifyImages::No);
let inlines = parser.parse(node).map_err(|e| ParseInlinesError(e.to_string()))?;
let mut output = Line::default();
for inline in inlines {
match inline {
Inline::Text(line) => {
output.0.extend(line.0);
}
Inline::Image { .. } => return Err(ParseInlinesError("images not supported".into())),
Inline::LineBreak => return Err(ParseInlinesError("line breaks not supported".into())),
fn adjust_source_positions<'b>(elements: impl Iterator<Item = &'b mut MarkdownElement>, lines_offset: usize) {
for element in elements {
let position = match element {
MarkdownElement::FrontMatter(_)
| MarkdownElement::SetexHeading { .. }
| MarkdownElement::Heading { .. }
| MarkdownElement::Paragraph(_)
| MarkdownElement::List(_)
| MarkdownElement::Table(_)
| MarkdownElement::ThematicBreak
| MarkdownElement::BlockQuote(_) => continue,
MarkdownElement::Comment { source_position, .. }
| MarkdownElement::Snippet { source_position, .. }
| MarkdownElement::Image { source_position, .. } => source_position,
};
*position = position.offset_lines(lines_offset);
}
Ok(output)
}
fn parse_node(&self, node: &'a AstNode<'a>) -> ParseResult<Vec<MarkdownElement>> {
@ -106,16 +100,15 @@ impl<'a> MarkdownParser<'a> {
NodeValue::Table(_) => self.parse_table(node)?,
NodeValue::CodeBlock(block) => Self::parse_code_block(block, data.sourcepos)?,
NodeValue::ThematicBreak => MarkdownElement::ThematicBreak,
NodeValue::HtmlBlock(block) => self.parse_html_block(block, data.sourcepos)?,
NodeValue::HtmlBlock(block) => Self::parse_html_block(block, data.sourcepos)?,
NodeValue::BlockQuote | NodeValue::MultilineBlockQuote(_) => self.parse_block_quote(node)?,
NodeValue::Alert(alert) => self.parse_alert(alert, node)?,
other => return Err(ParseErrorKind::UnsupportedElement(other.identifier()).with_sourcepos(data.sourcepos)),
};
Ok(vec![element])
}
fn parse_front_matter(contents: &str) -> ParseResult<MarkdownElement> {
// Remove leading and trailing delimiters before parsing. This is quite poopy but hey, it
// Remote leading and trailing delimiters before parsing. This is quite poopy but hey, it
// works.
let contents = contents.strip_prefix("---\n").unwrap_or(contents);
let contents = contents.strip_prefix("---\r\n").unwrap_or(contents);
@ -126,7 +119,7 @@ impl<'a> MarkdownParser<'a> {
Ok(MarkdownElement::FrontMatter(contents.into()))
}
fn parse_html_block(&self, block: &NodeHtmlBlock, sourcepos: Sourcepos) -> ParseResult<MarkdownElement> {
fn parse_html_block(block: &NodeHtmlBlock, sourcepos: Sourcepos) -> ParseResult<MarkdownElement> {
let block = block.literal.trim();
let start_tag = "<!--";
let end_tag = "-->";
@ -139,19 +132,19 @@ impl<'a> MarkdownParser<'a> {
}
fn parse_block_quote(&self, node: &'a AstNode<'a>) -> ParseResult<MarkdownElement> {
let mut lines = Vec::new();
let mut elements = Vec::new();
let inlines = InlinesParser::new(self.arena, SoftBreak::Newline, StringifyImages::Yes).parse(node)?;
for inline in inlines {
match inline {
Inline::Text(text) => lines.push(text),
Inline::LineBreak => lines.push(Line::from("")),
Inline::Text(text) => elements.push(text),
Inline::LineBreak => elements.push(TextBlock::from("")),
Inline::Image { .. } => {}
}
}
if lines.last() == Some(&Line::<RawColor>::from("")) {
lines.pop();
if elements.last() == Some(&TextBlock::from("")) {
elements.pop();
}
Ok(MarkdownElement::BlockQuote(lines))
Ok(MarkdownElement::BlockQuote(elements))
}
fn parse_code_block(block: &NodeCodeBlock, sourcepos: Sourcepos) -> ParseResult<MarkdownElement> {
@ -165,11 +158,6 @@ impl<'a> MarkdownParser<'a> {
})
}
fn parse_alert(&self, alert: &NodeAlert, node: &'a AstNode<'a>) -> ParseResult<MarkdownElement> {
let MarkdownElement::BlockQuote(lines) = self.parse_block_quote(node)? else { panic!("not a block quote") };
Ok(MarkdownElement::Alert { alert_type: alert.alert_type, title: alert.title.clone(), lines })
}
fn parse_heading(&self, heading: &NodeHeading, node: &'a AstNode<'a>) -> ParseResult<MarkdownElement> {
let text = self.parse_text(node)?;
if heading.setext {
@ -205,7 +193,7 @@ impl<'a> MarkdownParser<'a> {
Ok(elements)
}
fn parse_text(&self, node: &'a AstNode<'a>) -> ParseResult<Line<RawColor>> {
fn parse_text(&self, node: &'a AstNode<'a>) -> ParseResult<TextBlock> {
let inlines = InlinesParser::new(self.arena, SoftBreak::Space, StringifyImages::No).parse(node)?;
let mut chunks = Vec::new();
for inline in inlines {
@ -217,7 +205,7 @@ impl<'a> MarkdownParser<'a> {
}
};
}
Ok(Line(chunks))
Ok(TextBlock(chunks))
}
fn parse_list(&self, root: &'a AstNode<'a>, depth: u8) -> ParseResult<Vec<ListItem>> {
@ -243,8 +231,8 @@ impl<'a> MarkdownParser<'a> {
fn parse_list_item(&self, item: &NodeList, root: &'a AstNode<'a>, depth: u8) -> ParseResult<Vec<ListItem>> {
let item_type = match (item.list_type, item.delimiter) {
(ListType::Bullet, _) => ListItemType::Unordered,
(ListType::Ordered, ListDelimType::Paren) => ListItemType::OrderedParens(item.start),
(ListType::Ordered, ListDelimType::Period) => ListItemType::OrderedPeriod(item.start),
(ListType::Ordered, ListDelimType::Paren) => ListItemType::OrderedParens,
(ListType::Ordered, ListDelimType::Period) => ListItemType::OrderedPeriod,
};
let mut elements = Vec::new();
for node in root.children() {
@ -321,7 +309,7 @@ enum StringifyImages {
struct InlinesParser<'a> {
inlines: Vec<Inline>,
pending_text: Vec<Text<RawColor>>,
pending_text: Vec<Text>,
arena: &'a Arena<AstNode<'a>>,
soft_break: SoftBreak,
stringify_images: StringifyImages,
@ -341,16 +329,11 @@ impl<'a> InlinesParser<'a> {
fn store_pending_text(&mut self) {
let chunks = mem::take(&mut self.pending_text);
if !chunks.is_empty() {
self.inlines.push(Inline::Text(Line(chunks)));
self.inlines.push(Inline::Text(TextBlock(chunks)));
}
}
fn process_node(
&mut self,
node: &'a AstNode<'a>,
parent: &'a AstNode<'a>,
style: TextStyle<RawColor>,
) -> ParseResult<Option<HtmlStyle>> {
fn process_node(&mut self, node: &'a AstNode<'a>, parent: &'a AstNode<'a>, style: TextStyle) -> ParseResult<()> {
let data = node.data.borrow();
match &data.value {
NodeValue::Text(text) => {
@ -367,7 +350,7 @@ impl<'a> InlinesParser<'a> {
SoftBreak::Newline => {
self.store_pending_text();
}
SoftBreak::Space => self.pending_text.push(Text::new(" ", style)),
SoftBreak::Space => self.pending_text.push(Text::from(" ")),
};
}
NodeValue::Link(link) => {
@ -386,9 +369,6 @@ impl<'a> InlinesParser<'a> {
self.pending_text.push(Text::from(")"));
}
}
NodeValue::WikiLink(link) => {
self.pending_text.push(Text::new(link.url.clone(), TextStyle::default().link_url()));
}
NodeValue::LineBreak => {
self.store_pending_text();
self.inlines.push(Inline::LineBreak);
@ -396,7 +376,7 @@ impl<'a> InlinesParser<'a> {
NodeValue::Image(link) => {
if matches!(self.stringify_images, StringifyImages::Yes) {
self.pending_text.push(Text::from(format!("![{}]({})", link.title, link.url)));
return Ok(None);
return Ok(());
}
self.store_pending_text();
@ -439,51 +419,24 @@ impl<'a> InlinesParser<'a> {
};
self.process_children(node, style)?;
}
NodeValue::HtmlInline(html) => {
let html_inline = HtmlParser::default()
.parse(html)
.map_err(|e| ParseErrorKind::InvalidHtml(e).with_sourcepos(data.sourcepos))?;
match html_inline {
HtmlInline::OpenSpan { style } => return Ok(Some(HtmlStyle::Add(style))),
HtmlInline::CloseSpan => return Ok(Some(HtmlStyle::Remove)),
};
}
other => {
return Err(ParseErrorKind::UnsupportedStructure { container: "text", element: other.identifier() }
.with_sourcepos(data.sourcepos));
}
};
Ok(None)
Ok(())
}
fn process_children(&mut self, root: &'a AstNode<'a>, base_style: TextStyle<RawColor>) -> ParseResult<()> {
let mut html_styles = Vec::new();
let mut style = base_style.clone();
fn process_children(&mut self, root: &'a AstNode<'a>, style: TextStyle) -> ParseResult<()> {
for node in root.children() {
if let Some(html_style) = self.process_node(node, root, style.clone())? {
match html_style {
HtmlStyle::Add(style) => html_styles.push(style),
HtmlStyle::Remove => {
html_styles.pop();
}
};
style = base_style.clone();
for html_style in html_styles.iter().rev() {
style.merge(html_style);
}
}
self.process_node(node, root, style)?;
}
Ok(())
}
}
enum HtmlStyle {
Add(TextStyle<RawColor>),
Remove,
}
enum Inline {
Text(Line<RawColor>),
Text(TextBlock),
Image { path: String, title: String },
LineBreak,
}
@ -510,7 +463,7 @@ pub struct ParseError {
impl Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "parse error at {}: {}", self.sourcepos, self.kind)
write!(f, "parse error at {}:{}: {}", self.sourcepos.start.line, self.sourcepos.start.column, self.kind)
}
}
@ -532,9 +485,6 @@ pub(crate) enum ParseErrorKind {
/// We don't support unfenced code blocks.
UnfencedCodeBlock,
/// Invalid HTML was found.
InvalidHtml(ParseHtmlError),
/// An internal parsing error.
Internal(String),
}
@ -547,7 +497,6 @@ impl Display for ParseErrorKind {
write!(f, "unsupported structure in {container}: {element}")
}
Self::UnfencedCodeBlock => write!(f, "only fenced code blocks are supported"),
Self::InvalidHtml(inner) => write!(f, "invalid HTML: {inner}"),
Self::Internal(message) => write!(f, "internal error: {message}"),
}
}
@ -604,21 +553,12 @@ impl Identifier for NodeValue {
NodeValue::Underline => "underline",
NodeValue::SpoileredText => "spoilered text",
NodeValue::EscapedTag(_) => "escaped tag",
NodeValue::Subscript => "subscript",
NodeValue::Raw(_) => "raw",
NodeValue::Alert(_) => "alert",
}
}
}
#[derive(Debug, thiserror::Error)]
#[error("invalid markdown line: {0}")]
pub(crate) struct ParseInlinesError(String);
#[cfg(test)]
mod test {
use crate::markdown::text_style::Color;
use super::*;
use rstest::rstest;
use std::path::Path;
@ -669,24 +609,7 @@ boop
Text::new("strikethrough", TextStyle::default().strikethrough()),
];
let expected_elements = &[Line(expected_chunks)];
assert_eq!(elements, expected_elements);
}
#[test]
fn html_inlines() {
let parsed = parse_single(
"hi<span style=\"color: red\">red<span style=\"background-color: blue\">blue<span style=\"color: yellow\">yellow</span></span></span>",
);
let MarkdownElement::Paragraph(elements) = parsed else { panic!("not a paragraph: {parsed:?}") };
let expected_chunks = vec![
Text::from("hi"),
Text::new("red", TextStyle::default().fg_color(Color::Red)),
Text::new("blue", TextStyle::default().fg_color(Color::Red).bg_color(Color::Blue)),
Text::new("yellow", TextStyle::default().fg_color(Color::Yellow).bg_color(Color::Blue)),
];
let expected_elements = &[Line(expected_chunks)];
let expected_elements = &[TextBlock(expected_chunks)];
assert_eq!(elements, expected_elements);
}
@ -697,7 +620,7 @@ boop
let expected_chunks =
vec![Text::from("my "), Text::new("https://example.com", TextStyle::default().link_url())];
let expected_elements = &[Line(expected_chunks)];
let expected_elements = &[TextBlock(expected_chunks)];
assert_eq!(elements, expected_elements);
}
@ -713,7 +636,7 @@ boop
Text::from(")"),
];
let expected_elements = &[Line(expected_chunks)];
let expected_elements = &[TextBlock(expected_chunks)];
assert_eq!(elements, expected_elements);
}
@ -729,7 +652,7 @@ boop
Text::from("\""),
];
let expected_elements = &[Line(expected_chunks)];
let expected_elements = &[TextBlock(expected_chunks)];
assert_eq!(elements, expected_elements);
}
@ -748,17 +671,7 @@ boop
Text::from(")"),
];
let expected_elements = &[Line(expected_chunks)];
assert_eq!(elements, expected_elements);
}
#[test]
fn wikilink_wo_title() {
let parsed = parse_single("[[https://example.com]]");
let MarkdownElement::Paragraph(elements) = parsed else { panic!("not a paragraph: {parsed:?}") };
let expected_chunks = vec![Text::new("https://example.com", TextStyle::default().link_url())];
let expected_elements = &[Line(expected_chunks)];
let expected_elements = &[TextBlock(expected_chunks)];
assert_eq!(elements, expected_elements);
}
@ -822,26 +735,6 @@ Title
assert_eq!(next().depth, 0);
}
#[test]
fn ordered_list_starting_non_one() {
let parsed = parse_single(
r"
4. One
1. Sub1
2. Sub2
5. Two
6. Three",
);
let MarkdownElement::List(items) = parsed else { panic!("not a list: {parsed:?}") };
let mut items = items.into_iter();
let mut next = || items.next().expect("list ended prematurely");
assert_eq!(next().item_type, ListItemType::OrderedPeriod(4));
assert_eq!(next().item_type, ListItemType::OrderedPeriod(1));
assert_eq!(next().item_type, ListItemType::OrderedPeriod(2));
assert_eq!(next().item_type, ListItemType::OrderedPeriod(5));
assert_eq!(next().item_type, ListItemType::OrderedPeriod(6));
}
#[test]
fn line_breaks() {
let parsed = parse_all(
@ -951,21 +844,21 @@ let q = 42;
assert_eq!(lines.len(), 11);
assert_eq!(
lines[0],
Line(vec![Text::from("foo "), Text::new("is not", TextStyle::default().bold()), Text::from(" bar")])
TextBlock(vec![Text::from("foo "), Text::new("is not", TextStyle::default().bold()), Text::from(" bar")])
);
assert_eq!(
lines[1],
Line(vec![Text::from("![](hehe.png)"), Text::from(" test "), Text::from("![](potato.png)")])
TextBlock(vec![Text::from("![](hehe.png)"), Text::from(" test "), Text::from("![](potato.png)")])
);
assert_eq!(lines[2], Line::from(""));
assert_eq!(lines[3], Line(vec![Text::from("* "), Text::from("a")]));
assert_eq!(lines[4], Line(vec![Text::from("* "), Text::from("b")]));
assert_eq!(lines[5], Line::from(""));
assert_eq!(lines[6], Line(vec![Text::from("1. "), Text::from("a")]));
assert_eq!(lines[7], Line(vec![Text::from("2. "), Text::from("b")]));
assert_eq!(lines[8], Line::from(""));
assert_eq!(lines[9], Line(vec![Text::from("1) "), Text::from("a")]));
assert_eq!(lines[10], Line(vec![Text::from("2) "), Text::from("b")]));
assert_eq!(lines[2], TextBlock::from(""));
assert_eq!(lines[3], TextBlock(vec![Text::from("* "), Text::from("a")]));
assert_eq!(lines[4], TextBlock(vec![Text::from("* "), Text::from("b")]));
assert_eq!(lines[5], TextBlock::from(""));
assert_eq!(lines[6], TextBlock(vec![Text::from("1. "), Text::from("a")]));
assert_eq!(lines[7], TextBlock(vec![Text::from("2. "), Text::from("b")]));
assert_eq!(lines[8], TextBlock::from(""));
assert_eq!(lines[9], TextBlock(vec![Text::from("1) "), Text::from("a")]));
assert_eq!(lines[10], TextBlock(vec![Text::from("2) "), Text::from("b")]));
}
#[test]
@ -982,11 +875,11 @@ foo
);
let MarkdownElement::BlockQuote(lines) = parsed else { panic!("not a block quote: {parsed:?}") };
assert_eq!(lines.len(), 5);
assert_eq!(lines[0], Line::from("bar"));
assert_eq!(lines[1], Line::from("foo"));
assert_eq!(lines[2], Line::from(""));
assert_eq!(lines[3], Line(vec![Text::from("* "), Text::from("a")]));
assert_eq!(lines[4], Line(vec![Text::from("* "), Text::from("b")]));
assert_eq!(lines[0], TextBlock::from("bar"));
assert_eq!(lines[1], TextBlock::from("foo"));
assert_eq!(lines[2], TextBlock::from(""));
assert_eq!(lines[3], TextBlock(vec![Text::from("* "), Text::from("a")]));
assert_eq!(lines[4], TextBlock(vec![Text::from("* "), Text::from("b")]));
}
#[test]
@ -1018,7 +911,7 @@ mom
let Err(e) = result else {
panic!("parsing didn't fail");
};
assert_eq!(e.sourcepos.start.line, 6);
assert_eq!(e.sourcepos.start.line, 5);
assert_eq!(e.sourcepos.start.column, 3);
}
@ -1034,7 +927,7 @@ mom
",
);
let MarkdownElement::Comment { source_position, .. } = &parsed[1] else { panic!("not a comment") };
assert_eq!(source_position.start.line, 6);
assert_eq!(source_position.start.line, 5);
assert_eq!(source_position.start.column, 1);
}
@ -1049,32 +942,4 @@ mom
let expected = format!("hi{nl}mom{nl}");
assert_eq!(contents, &expected);
}
#[test]
fn parse_alert() {
let input = r"
> [!note]
> hi mom
> bye **mom**
";
let MarkdownElement::Alert { lines, .. } = parse_single(&input) else {
panic!("not an alert");
};
assert_eq!(lines.len(), 2);
}
#[test]
fn parse_inlines() {
let arena = Arena::new();
let input = "hello **mom** how _are you_?";
let parsed = MarkdownParser::new(&arena).parse_inlines(input).expect("parse failed");
let expected = &[
"hello ".into(),
Text::new("mom", TextStyle::default().bold()),
" how ".into(),
Text::new("are you", TextStyle::default().italics()),
"?".into(),
];
assert_eq!(parsed.0, expected);
}
}

View File

@ -1,21 +1,18 @@
use super::{
elements::{Line, Text},
text_style::TextStyle,
};
use super::elements::{Text, TextBlock};
use crate::style::TextStyle;
use std::mem;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
/// A weighted line of text.
/// A weighted block of text.
///
/// The weight of a character is its given by its width in unicode.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct WeightedLine {
pub(crate) struct WeightedTextBlock {
text: Vec<WeightedText>,
width: usize,
font_size: u8,
}
impl WeightedLine {
impl WeightedTextBlock {
/// Split this line into chunks of at most `max_length` width.
pub(crate) fn split(&self, max_length: usize) -> SplitTextIter {
SplitTextIter::new(&self.text, max_length)
@ -26,11 +23,6 @@ impl WeightedLine {
self.width
}
/// The height of this line.
pub(crate) fn font_size(&self) -> u8 {
self.font_size
}
/// Get an iterator to the underlying text chunks.
#[cfg(test)]
pub(crate) fn iter_texts(&self) -> impl Iterator<Item = &WeightedText> {
@ -38,18 +30,17 @@ impl WeightedLine {
}
}
impl From<Line> for WeightedLine {
fn from(block: Line) -> Self {
impl From<TextBlock> for WeightedTextBlock {
fn from(block: TextBlock) -> Self {
block.0.into()
}
}
impl From<Vec<Text>> for WeightedLine {
impl From<Vec<Text>> for WeightedTextBlock {
fn from(mut texts: Vec<Text>) -> Self {
let mut output = Vec::new();
let mut index = 0;
let mut width = 0;
let mut font_size = 1;
// Compact chunks so any consecutive chunk with the same style is merged into the same block.
while index < texts.len() {
let mut target = mem::replace(&mut texts[index], Text::from(""));
@ -59,25 +50,23 @@ impl From<Vec<Text>> for WeightedLine {
target.content.push_str(&current_content);
current += 1;
}
let size = target.style.size.max(1);
width += target.content.width() * size as usize;
width += target.content.width();
output.push(target.into());
index = current;
font_size = font_size.max(size);
}
Self { text: output, width, font_size }
Self { text: output, width }
}
}
impl From<String> for WeightedLine {
impl From<String> for WeightedTextBlock {
fn from(text: String) -> Self {
let width = text.width();
let text = vec![WeightedText::from(text)];
Self { text, width, font_size: 1 }
Self { text, width }
}
}
impl From<&str> for WeightedLine {
impl From<&str> for WeightedTextBlock {
fn from(text: &str) -> Self {
Self::from(text.to_string())
}
@ -201,7 +190,6 @@ impl<'a> WeightedTextRef<'a> {
return (self.make_ref(0, self.text.len()), self.make_ref(0, 0));
}
let max_length = (max_length / self.style.size as usize).max(1);
let target_chunk = self.substr(max_length + 1);
let output_chunk = match target_chunk.rsplit_once(' ') {
Some((before, _)) => before,
@ -233,7 +221,7 @@ impl<'a> WeightedTextRef<'a> {
pub(crate) fn width(&self) -> usize {
let last_width = self.accumulators.last().map(|a| a.width).unwrap_or(0);
let first_width = self.accumulators.first().map(|a| a.width).unwrap_or(0);
(last_width - first_width) * self.style.size as usize
last_width - first_width
}
fn bytes_until(&self, index: usize) -> usize {
@ -304,15 +292,6 @@ mod test {
assert_eq!(rest.width(), 3);
}
#[test]
fn font_size_split() {
let text = WeightedText::from(Text::new("█████", TextStyle::default().size(2)));
let text_ref = text.to_ref();
let (head, rest) = text_ref.word_split_at_length(3);
assert_eq!(head.width(), 2);
assert_eq!(rest.width(), 8);
}
#[test]
fn make_ref() {
let text = WeightedText::from("hello world");
@ -336,7 +315,7 @@ mod test {
#[test]
fn split_at_full_length() {
let text = WeightedLine::from("hello world");
let text = WeightedTextBlock::from("hello world");
let lines = join_lines(text.split(11));
let expected = vec!["hello world"];
assert_eq!(lines, expected);
@ -344,11 +323,7 @@ mod test {
#[test]
fn no_split_necessary() {
let text = WeightedLine {
text: vec![WeightedText::from("short"), WeightedText::from("text")],
width: 0,
font_size: 1,
};
let text = WeightedTextBlock { text: vec![WeightedText::from("short"), WeightedText::from("text")], width: 0 };
let lines = join_lines(text.split(50));
let expected = vec!["short text"];
assert_eq!(lines, expected);
@ -356,8 +331,7 @@ mod test {
#[test]
fn split_lines_single() {
let text =
WeightedLine { text: vec![WeightedText::from("this is a slightly long line")], width: 0, font_size: 1 };
let text = WeightedTextBlock { text: vec![WeightedText::from("this is a slightly long line")], width: 0 };
let lines = join_lines(text.split(6));
let expected = vec!["this", "is a", "slight", "ly", "long", "line"];
assert_eq!(lines, expected);
@ -365,14 +339,13 @@ mod test {
#[test]
fn split_lines_multi() {
let text = WeightedLine {
let text = WeightedTextBlock {
text: vec![
WeightedText::from("this is a slightly long line"),
WeightedText::from("another chunk"),
WeightedText::from("yet some other piece"),
],
width: 0,
font_size: 1,
};
let lines = join_lines(text.split(10));
let expected = vec!["this is a", "slightly", "long line", "another", "chunk yet", "some other", "piece"];
@ -381,14 +354,13 @@ mod test {
#[test]
fn long_splits() {
let text = WeightedLine {
let text = WeightedTextBlock {
text: vec![
WeightedText::from("this is a slightly long line"),
WeightedText::from("another chunk"),
WeightedText::from("yet some other piece"),
],
width: 0,
font_size: 1,
};
let lines = join_lines(text.split(50));
let expected = vec!["this is a slightly long line another chunk yet some", "other piece"];
@ -397,7 +369,7 @@ mod test {
#[test]
fn prefixed_by_whitespace() {
let text = WeightedLine::from(" * bullet");
let text = WeightedTextBlock::from(" * bullet");
let lines = join_lines(text.split(50));
let expected = vec![" * bullet"];
assert_eq!(lines, expected);
@ -405,7 +377,7 @@ mod test {
#[test]
fn utf8_character() {
let text = WeightedLine::from("• A");
let text = WeightedTextBlock::from("• A");
let lines = join_lines(text.split(50));
let expected = vec!["• A"];
assert_eq!(lines, expected);
@ -414,7 +386,7 @@ mod test {
#[test]
fn many_utf8_characters() {
let content = "█████ ██";
let text = WeightedLine::from(content);
let text = WeightedTextBlock::from(content);
let lines = join_lines(text.split(3));
let expected = vec!["███", "██", "██"];
assert_eq!(lines, expected);
@ -423,7 +395,7 @@ mod test {
#[test]
fn no_whitespaces_ascii() {
let content = "X".repeat(10);
let text = WeightedLine::from(content);
let text = WeightedTextBlock::from(content);
let lines = join_lines(text.split(3));
let expected = vec!["XXX", "XXX", "XXX", "X"];
assert_eq!(lines, expected);
@ -432,7 +404,7 @@ mod test {
#[test]
fn no_whitespaces_utf8() {
let content = "".repeat(10);
let text = WeightedLine::from(content);
let text = WeightedTextBlock::from(content);
let lines = join_lines(text.split(3));
let expected = vec!["───", "───", "───", ""];
assert_eq!(lines, expected);
@ -441,7 +413,7 @@ mod test {
#[test]
fn wide_characters() {
let content = " ";
let text = WeightedLine::from(content);
let text = WeightedTextBlock::from(content);
let lines = join_lines(text.split(10));
// Each word is 10 characters long
let expected = vec!["", ""];
@ -455,7 +427,7 @@ mod test {
#[case::split(&["hello".into(), Text::new(" ", TextStyle::default().bold()), "world".into()], 3)]
#[case::split_merged(&["hello".into(), Text::new(" ", TextStyle::default().bold()), Text::new("w", TextStyle::default().bold()), "orld".into()], 3)]
fn compaction(#[case] texts: &[Text], #[case] expected: usize) {
let block = WeightedLine::from(texts.to_vec());
let block = WeightedTextBlock::from(texts.to_vec());
assert_eq!(block.text.len(), expected);
}
}

View File

@ -1,390 +0,0 @@
use crate::theme::{ColorPalette, raw::RawColor};
use crossterm::style::{StyledContent, Stylize};
use hex::FromHexError;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display};
/// The style of a piece of text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct TextStyle<C = Color> {
flags: u8,
pub(crate) colors: Colors<C>,
pub(crate) size: u8,
}
impl<C> Default for TextStyle<C> {
fn default() -> Self {
Self { flags: Default::default(), colors: Default::default(), size: 1 }
}
}
impl<C> TextStyle<C>
where
C: Clone,
{
pub(crate) fn colored(colors: Colors<C>) -> Self {
Self { colors, ..Default::default() }
}
pub(crate) fn size(mut self, size: u8) -> Self {
self.size = size.min(16);
self
}
/// Add bold to this style.
pub(crate) fn bold(self) -> Self {
self.add_flag(TextFormatFlags::Bold)
}
/// Add italics to this style.
pub(crate) fn italics(self) -> Self {
self.add_flag(TextFormatFlags::Italics)
}
/// Indicate this text is a piece of inline code.
pub(crate) fn code(self) -> Self {
self.add_flag(TextFormatFlags::Code)
}
/// Add strikethrough to this style.
pub(crate) fn strikethrough(self) -> Self {
self.add_flag(TextFormatFlags::Strikethrough)
}
/// Add underline to this style.
pub(crate) fn underlined(self) -> Self {
self.add_flag(TextFormatFlags::Underlined)
}
/// Indicate this is a link label.
pub(crate) fn link_label(self) -> Self {
self.bold()
}
/// Indicate this is a link title.
pub(crate) fn link_title(self) -> Self {
self.italics()
}
/// Indicate this is a link url.
pub(crate) fn link_url(self) -> Self {
self.italics().underlined()
}
/// Set the background color for this text style.
pub(crate) fn bg_color<U: Into<C>>(mut self, color: U) -> Self {
self.colors.background = Some(color.into());
self
}
/// Set the foreground color for this text style.
pub(crate) fn fg_color<U: Into<C>>(mut self, color: U) -> Self {
self.colors.foreground = Some(color.into());
self
}
/// Set the colors on this style.
pub(crate) fn colors(mut self, colors: Colors<C>) -> Self {
self.colors = colors;
self
}
/// Check whether this text is code.
pub(crate) fn is_code(&self) -> bool {
self.has_flag(TextFormatFlags::Code)
}
/// Merge this style with another one.
pub(crate) fn merge(&mut self, other: &TextStyle<C>) {
self.flags |= other.flags;
self.size = self.size.max(other.size);
self.colors.background = self.colors.background.clone().or(other.colors.background.clone());
self.colors.foreground = self.colors.foreground.clone().or(other.colors.foreground.clone());
}
/// Return a new style merged with the one passed in.
pub(crate) fn merged(mut self, other: &TextStyle<C>) -> Self {
self.merge(other);
self
}
fn add_flag(mut self, flag: TextFormatFlags) -> Self {
self.flags |= flag as u8;
self
}
fn has_flag(&self, flag: TextFormatFlags) -> bool {
self.flags & flag as u8 != 0
}
}
impl TextStyle<Color> {
/// Apply this style to a piece of text.
pub(crate) fn apply<'a>(&self, text: &'a str) -> StyledContent<impl Display + Clone + 'a> {
let text = FontSizedStr { contents: text, font_size: self.size };
let mut styled = StyledContent::new(Default::default(), text);
for attr in self.iter_attributes() {
styled = match attr {
TextAttribute::Bold => styled.bold(),
TextAttribute::Italics => styled.italic(),
TextAttribute::Strikethrough => styled.crossed_out(),
TextAttribute::Underlined => styled.underlined(),
TextAttribute::ForegroundColor(color) => styled.with(color.into()),
TextAttribute::BackgroundColor(color) => styled.on(color.into()),
}
}
styled
}
pub(crate) fn into_raw(self) -> TextStyle<RawColor> {
let colors = Colors {
background: self.colors.background.map(Into::into),
foreground: self.colors.foreground.map(Into::into),
};
TextStyle { flags: self.flags, colors, size: self.size }
}
/// Iterate all attributes in this style.
pub(crate) fn iter_attributes(&self) -> AttributeIterator {
AttributeIterator {
flags: self.flags,
next_mask: Some(TextFormatFlags::Bold),
background_color: self.colors.background,
foreground_color: self.colors.foreground,
}
}
}
impl TextStyle<RawColor> {
pub(crate) fn resolve(&self, palette: &ColorPalette) -> Result<TextStyle, UndefinedPaletteColorError> {
let colors = self.colors.resolve(palette)?;
Ok(TextStyle { flags: self.flags, colors, size: self.size })
}
}
pub(crate) struct AttributeIterator {
flags: u8,
next_mask: Option<TextFormatFlags>,
background_color: Option<Color>,
foreground_color: Option<Color>,
}
impl Iterator for AttributeIterator {
type Item = TextAttribute;
fn next(&mut self) -> Option<Self::Item> {
if let Some(c) = self.background_color.take() {
return Some(TextAttribute::BackgroundColor(c));
}
if let Some(c) = self.foreground_color.take() {
return Some(TextAttribute::ForegroundColor(c));
}
use TextFormatFlags::*;
loop {
let next_mask = self.next_mask?;
self.next_mask = match next_mask {
Bold => Some(Italics),
Italics => Some(Strikethrough),
Code => Some(Strikethrough),
Strikethrough => Some(Underlined),
Underlined => None,
};
if self.flags & next_mask as u8 != 0 {
let attr = match next_mask {
Bold => TextAttribute::Bold,
Italics => TextAttribute::Italics,
Code => panic!("code shouldn't reach here"),
Strikethrough => TextAttribute::Strikethrough,
Underlined => TextAttribute::Underlined,
};
return Some(attr);
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum TextAttribute {
Bold,
Italics,
Strikethrough,
Underlined,
ForegroundColor(Color),
BackgroundColor(Color),
}
#[derive(Clone)]
struct FontSizedStr<'a> {
contents: &'a str,
font_size: u8,
}
impl fmt::Display for FontSizedStr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let contents = &self.contents;
match self.font_size {
0 | 1 => write!(f, "{contents}"),
size => write!(f, "\x1b]66;s={size};{contents}\x1b\\"),
}
}
}
#[derive(Clone, Copy, Debug)]
enum TextFormatFlags {
Bold = 1,
Italics = 2,
Code = 4,
Strikethrough = 8,
Underlined = 16,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum Color {
Black,
DarkGrey,
Red,
DarkRed,
Green,
DarkGreen,
Yellow,
DarkYellow,
Blue,
DarkBlue,
Magenta,
DarkMagenta,
Cyan,
DarkCyan,
White,
Grey,
Rgb { r: u8, g: u8, b: u8 },
}
impl Color {
pub(crate) fn new(r: u8, g: u8, b: u8) -> Self {
Self::Rgb { r, g, b }
}
pub(crate) fn as_rgb(&self) -> Option<(u8, u8, u8)> {
match self {
Self::Rgb { r, g, b } => Some((*r, *g, *b)),
_ => None,
}
}
pub(crate) fn from_ansi(color: u8) -> Option<Self> {
let color = match color {
30 | 40 => Color::Black,
31 | 41 => Color::Red,
32 | 42 => Color::Green,
33 | 43 => Color::Yellow,
34 | 44 => Color::Blue,
35 | 45 => Color::Magenta,
36 | 46 => Color::Cyan,
37 | 47 => Color::White,
_ => return None,
};
Some(color)
}
}
impl From<Color> for crossterm::style::Color {
fn from(value: Color) -> Self {
use crossterm::style::Color as C;
match value {
Color::Black => C::Black,
Color::DarkGrey => C::DarkGrey,
Color::Red => C::Red,
Color::DarkRed => C::DarkRed,
Color::Green => C::Green,
Color::DarkGreen => C::DarkGreen,
Color::Yellow => C::Yellow,
Color::DarkYellow => C::DarkYellow,
Color::Blue => C::Blue,
Color::DarkBlue => C::DarkBlue,
Color::Magenta => C::Magenta,
Color::DarkMagenta => C::DarkMagenta,
Color::Cyan => C::Cyan,
Color::DarkCyan => C::DarkCyan,
Color::White => C::White,
Color::Grey => C::Grey,
Color::Rgb { r, g, b } => C::Rgb { r, g, b },
}
}
}
#[derive(Debug, thiserror::Error)]
#[error("unresolved palette color: {0}")]
pub(crate) struct PaletteColorError(String);
#[derive(Debug, thiserror::Error)]
#[error("undefined palette color: {0}")]
pub(crate) struct UndefinedPaletteColorError(pub(crate) String);
/// Text colors.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub(crate) struct Colors<C = Color> {
/// The background color.
pub(crate) background: Option<C>,
/// The foreground color.
pub(crate) foreground: Option<C>,
}
impl<C> Default for Colors<C> {
fn default() -> Self {
Self { background: None, foreground: None }
}
}
impl Colors<RawColor> {
pub(crate) fn resolve(&self, palette: &ColorPalette) -> Result<Colors<Color>, UndefinedPaletteColorError> {
let background = self.background.clone().map(|c| c.resolve(palette)).transpose()?.flatten();
let foreground = self.foreground.clone().map(|c| c.resolve(palette)).transpose()?.flatten();
Ok(Colors { foreground, background })
}
}
impl From<Colors> for crossterm::style::Colors {
fn from(value: Colors) -> Self {
let foreground = value.foreground.map(Color::into);
let background = value.background.map(Color::into);
Self { foreground, background }
}
}
#[derive(thiserror::Error, Debug)]
pub(crate) enum ParseColorError {
#[error("invalid hex color: {0}")]
Hex(#[from] FromHexError),
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[rstest]
#[case::default(TextStyle::default(), &[])]
#[case::code(TextStyle::default().code(), &[])]
#[case::bold(TextStyle::default().bold(), &[TextAttribute::Bold])]
#[case::italics(TextStyle::default().italics(), &[TextAttribute::Italics])]
#[case::strikethrough(TextStyle::default().strikethrough(), &[TextAttribute::Strikethrough])]
#[case::underlined(TextStyle::default().underlined(), &[TextAttribute::Underlined])]
#[case::bg_color(TextStyle::default().bg_color(Color::Red), &[TextAttribute::BackgroundColor(Color::Red)])]
#[case::bg_color(TextStyle::default().fg_color(Color::Red), &[TextAttribute::ForegroundColor(Color::Red)])]
#[case::all(
TextStyle::default().bold().code().italics().strikethrough().underlined().bg_color(Color::Black).fg_color(Color::Red),
&[
TextAttribute::BackgroundColor(Color::Black),
TextAttribute::ForegroundColor(Color::Red),
TextAttribute::Bold,
TextAttribute::Italics,
TextAttribute::Strikethrough,
TextAttribute::Underlined,
]
)]
fn iterate_attributes(#[case] style: TextStyle, #[case] expected: &[TextAttribute]) {
let attrs: Vec<_> = style.iter_attributes().collect();
assert_eq!(attrs, expected);
}
}

136
src/media/ascii.rs Normal file
View File

@ -0,0 +1,136 @@
use super::printer::{PrintImage, PrintImageError, PrintOptions, RegisterImageError, ResourceProperties};
use crossterm::{
QueueableCommand,
cursor::{MoveRight, MoveToColumn},
style::{Color, Stylize},
};
use image::{DynamicImage, GenericImageView, Pixel, Rgba, imageops::FilterType};
use itertools::Itertools;
use std::{fs, ops::Deref};
const TOP_CHAR: char = '▀';
const BOTTOM_CHAR: char = '▄';
pub(crate) struct AsciiResource(DynamicImage);
impl ResourceProperties for AsciiResource {
fn dimensions(&self) -> (u32, u32) {
self.0.dimensions()
}
}
impl From<DynamicImage> for AsciiResource {
fn from(image: DynamicImage) -> Self {
let image = image.into_rgba8();
Self(image.into())
}
}
impl Deref for AsciiResource {
type Target = DynamicImage;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Default)]
pub struct AsciiPrinter;
impl AsciiPrinter {
fn pixel_color(pixel: &Rgba<u8>, background: Option<Color>) -> Option<Color> {
let [r, g, b, alpha] = pixel.0;
if alpha == 0 {
None
} else if alpha < 255 {
// For alpha > 0 && < 255, we blend it with the background color (if any). This helps
// smooth the image's borders.
let mut pixel = *pixel;
match background {
Some(Color::Rgb { r, g, b }) => {
pixel.blend(&Rgba([r, g, b, 255 - alpha]));
Some(Color::Rgb { r: pixel[0], g: pixel[1], b: pixel[2] })
}
// For transparent backgrounds, we can't really know whether we should blend it
// towards light or dark.
None | Some(_) => Some(Color::Rgb { r, g, b }),
}
} else {
Some(Color::Rgb { r, g, b })
}
}
}
impl PrintImage for AsciiPrinter {
type Resource = AsciiResource;
fn register_image(&self, image: image::DynamicImage) -> Result<Self::Resource, RegisterImageError> {
Ok(AsciiResource(image))
}
fn register_resource<P: AsRef<std::path::Path>>(&self, path: P) -> Result<Self::Resource, RegisterImageError> {
let contents = fs::read(path)?;
let image = image::load_from_memory(&contents)?;
Ok(AsciiResource(image))
}
fn print<W>(&self, image: &Self::Resource, options: &PrintOptions, writer: &mut W) -> Result<(), PrintImageError>
where
W: std::io::Write,
{
// The strategy here is taken from viuer: use half vertical ascii blocks in combination
// with foreground/background colors to fit 2 vertical pixels per cell. That is, cell (x, y)
// will contain the pixels at (x, y) and (x, y + 1) combined.
let image = image.0.resize_exact(options.columns as u32, 2 * options.rows as u32, FilterType::Triangle);
let image = image.into_rgba8();
let default_background = options.background_color.map(Color::from);
// Iterate pixel rows in pairs to be able to merge both pixels in a single iteration.
// Note that may not have a second row if there's an odd number of them.
for mut rows in &image.rows().chunks(2) {
writer.queue(MoveToColumn(options.cursor_position.column))?;
let top_row = rows.next().unwrap();
let mut bottom_row = rows.next();
for top_pixel in top_row {
let bottom_pixel = bottom_row.as_mut().and_then(|pixels| pixels.next());
// Get pixel colors for both of these. At this point the special case for the odd
// number of rows disappears as we treat a transparent pixel and a non-existent
// one the same: they're simply transparent.
let background = options.background_color.map(Color::from);
let top = Self::pixel_color(top_pixel, background);
let bottom = bottom_pixel.and_then(|c| Self::pixel_color(c, background));
match (top, bottom) {
(Some(top), Some(bottom)) => {
write!(writer, "{}", TOP_CHAR.with(top).on(bottom))?;
}
(Some(top), None) => {
write!(writer, "{}", TOP_CHAR.with(top).maybe_on(default_background))?;
}
(None, Some(bottom)) => {
write!(writer, "{}", BOTTOM_CHAR.with(bottom).maybe_on(default_background))?;
}
(None, None) => {
writer.queue(MoveRight(1))?;
}
};
}
writeln!(writer)?;
}
Ok(())
}
}
trait StylizeExt: Stylize {
fn maybe_on(self, color: Option<Color>) -> Self::Styled;
}
impl<T: Stylize> StylizeExt for T {
fn maybe_on(self, color: Option<Color>) -> Self::Styled {
match color {
Some(background) => self.on(background),
None => self.stylize(),
}
}
}

View File

@ -1,16 +1,14 @@
use super::{GraphicsMode, capabilities::TerminalCapabilities, image::protocols::kitty::KittyMode};
use std::{env, sync::OnceLock};
use super::kitty::local_mode_supported;
use crate::{GraphicsMode, media::kitty::KittyMode};
use std::env;
use strum::IntoEnumIterator;
static CAPABILITIES: OnceLock<TerminalCapabilities> = OnceLock::new();
#[derive(Debug, strum::EnumIter)]
pub enum TerminalEmulator {
Kitty,
Iterm2,
WezTerm,
Ghostty,
Mintty,
Kitty,
Konsole,
Foot,
Yaft,
@ -21,6 +19,10 @@ pub enum TerminalEmulator {
}
impl TerminalEmulator {
pub fn is_inside_tmux() -> bool {
env::var("TERM_PROGRAM").ok().as_deref() == Some("tmux")
}
pub fn detect() -> Self {
let term = env::var("TERM").unwrap_or_default();
let term_program = env::var("TERM_PROGRAM").unwrap_or_default();
@ -32,26 +34,18 @@ impl TerminalEmulator {
TerminalEmulator::Unknown
}
pub(crate) fn capabilities() -> TerminalCapabilities {
CAPABILITIES.get_or_init(|| TerminalCapabilities::query().unwrap_or_default()).clone()
}
pub(crate) fn disable_capability_detection() {
CAPABILITIES.get_or_init(TerminalCapabilities::default);
}
pub fn preferred_protocol(&self) -> GraphicsMode {
let capabilities = Self::capabilities();
let inside_tmux = Self::is_inside_tmux();
let modes = [
GraphicsMode::Iterm2,
GraphicsMode::Kitty { mode: KittyMode::Local, inside_tmux: capabilities.tmux },
GraphicsMode::Kitty { mode: KittyMode::Remote, inside_tmux: capabilities.tmux },
GraphicsMode::Kitty { mode: KittyMode::Local, inside_tmux },
GraphicsMode::Kitty { mode: KittyMode::Remote, inside_tmux },
#[cfg(feature = "sixel")]
GraphicsMode::Sixel,
GraphicsMode::AsciiBlocks,
];
for mode in modes {
if self.supports_graphics_mode(&mode, &capabilities) {
if self.supports_graphics_mode(&mode) {
return mode;
}
}
@ -60,11 +54,10 @@ impl TerminalEmulator {
fn is_detected(&self, term: &str, term_program: &str) -> bool {
match self {
TerminalEmulator::Kitty => term.contains("kitty"),
TerminalEmulator::Iterm2 => term_program.contains("iTerm"),
TerminalEmulator::WezTerm => term_program.contains("WezTerm"),
TerminalEmulator::Mintty => term_program.contains("mintty"),
TerminalEmulator::Ghostty => term_program.contains("ghostty"),
TerminalEmulator::Kitty => term.contains("kitty"),
TerminalEmulator::Konsole => env::var("KONSOLE_VERSION").is_ok(),
TerminalEmulator::Foot => ["foot", "foot-extra"].contains(&term),
TerminalEmulator::Yaft => term == "yaft-256color",
@ -75,39 +68,41 @@ impl TerminalEmulator {
}
}
fn supports_graphics_mode(&self, mode: &GraphicsMode, capabilities: &TerminalCapabilities) -> bool {
fn supports_graphics_mode(&self, mode: &GraphicsMode) -> bool {
match (mode, self) {
(GraphicsMode::Kitty { mode, .. }, Self::Kitty | Self::WezTerm | Self::Ghostty) => match mode {
KittyMode::Local => capabilities.kitty_local,
(GraphicsMode::Kitty { mode, inside_tmux }, Self::Kitty | Self::WezTerm) => match mode {
KittyMode::Local => local_mode_supported(*inside_tmux).unwrap_or_default(),
KittyMode::Remote => true,
},
(GraphicsMode::Kitty { mode: KittyMode::Local, .. }, Self::Unknown) => {
// If we don't know the emulator but we detected that we support kitty use it,
// **unless** we are inside tmux and we "guess" that we're using wezterm. This is
// because wezterm's support for unicode placeholders (needed to display images in
// kitty when inside tmux) is not implemented (see
// https://github.com/wez/wezterm/issues/986).
//
// We can only really guess it's wezterm by checking environment variables and will
// not work if you started tmux on a different emulator and are running presenterm
// in wezterm.
capabilities.kitty_local && (!capabilities.tmux || !Self::guess_wezterm())
}
(GraphicsMode::Kitty { mode: KittyMode::Remote, .. }, Self::Unknown) => {
// Same as the above
capabilities.kitty_remote && (!capabilities.tmux || !Self::guess_wezterm())
}
(GraphicsMode::Iterm2, Self::Iterm2 | Self::WezTerm | Self::Mintty | Self::Konsole) => true,
(GraphicsMode::AsciiBlocks, _) => true,
#[cfg(feature = "sixel")]
(GraphicsMode::Sixel, Self::Foot | Self::Yaft | Self::Mlterm) => true,
#[cfg(feature = "sixel")]
(GraphicsMode::Sixel, Self::St | Self::Xterm | Self::Unknown) => capabilities.sixel,
(GraphicsMode::Sixel, Self::St | Self::Xterm) => supports_sixel().unwrap_or_default(),
_ => false,
}
}
fn guess_wezterm() -> bool {
env::var("WEZTERM_EXECUTABLE").is_ok()
}
}
#[cfg(feature = "sixel")]
fn supports_sixel() -> std::io::Result<bool> {
use console::{Key, Term};
use std::io::Write;
let mut term = Term::stdout();
write!(&mut term, "\x1b[c")?;
term.flush()?;
let mut response = String::new();
while let Ok(key) = term.read_key() {
if let Key::Char(c) = key {
response.push(c);
if c == 'c' {
break;
}
}
}
Ok(response.contains(";4;") || response.contains(";4c"))
}

13
src/media/graphics.rs Normal file
View File

@ -0,0 +1,13 @@
use super::kitty::KittyMode;
#[derive(Clone, Debug)]
pub enum GraphicsMode {
Iterm2,
Kitty {
mode: KittyMode,
inside_tmux: bool,
},
AsciiBlocks,
#[cfg(feature = "sixel")]
Sixel,
}

45
src/media/image.rs Normal file
View File

@ -0,0 +1,45 @@
use crate::media::printer::{ImageResource, ResourceProperties};
use std::{fmt::Debug, ops::Deref, path::PathBuf, sync::Arc};
/// An image.
///
/// This stores the image in an [std::sync::Arc] so it's cheap to clone.
#[derive(Clone)]
pub(crate) struct Image {
pub(crate) resource: Arc<ImageResource>,
pub(crate) source: ImageSource,
}
impl PartialEq for Image {
fn eq(&self, other: &Self) -> bool {
self.source == other.source
}
}
impl Debug for Image {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (width, height) = self.resource.dimensions();
write!(f, "Image<{width}x{height}>")
}
}
impl Image {
/// Constructs a new image.
pub(crate) fn new(resource: ImageResource, source: ImageSource) -> Self {
Self { resource: Arc::new(resource), source }
}
}
impl Deref for Image {
type Target = ImageResource;
fn deref(&self) -> &Self::Target {
&self.resource
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum ImageSource {
Filesystem(PathBuf),
Generated,
}

80
src/media/iterm.rs Normal file
View File

@ -0,0 +1,80 @@
use super::printer::{PrintImage, PrintImageError, PrintOptions, RegisterImageError, ResourceProperties};
use base64::{Engine, engine::general_purpose::STANDARD};
use image::{GenericImageView, ImageEncoder, codecs::png::PngEncoder};
use std::{env, fs, path::Path};
pub(crate) struct ItermResource {
dimensions: (u32, u32),
raw_length: usize,
base64_contents: String,
}
impl ItermResource {
fn new(contents: Vec<u8>, dimensions: (u32, u32)) -> Self {
let raw_length = contents.len();
let base64_contents = STANDARD.encode(&contents);
Self { dimensions, raw_length, base64_contents }
}
}
impl ResourceProperties for ItermResource {
fn dimensions(&self) -> (u32, u32) {
self.dimensions
}
}
pub struct ItermPrinter {
// Whether this is iterm2. Otherwise it can be a terminal that _supports_ the iterm2 protocol.
is_iterm: bool,
}
impl Default for ItermPrinter {
fn default() -> Self {
for key in ["TERM_PROGRAM", "LC_TERMINAL"] {
if let Ok(value) = env::var(key) {
if value.contains("iTerm") {
return Self { is_iterm: true };
}
}
}
Self { is_iterm: false }
}
}
impl PrintImage for ItermPrinter {
type Resource = ItermResource;
fn register_image(&self, image: image::DynamicImage) -> Result<Self::Resource, RegisterImageError> {
let dimensions = image.dimensions();
let mut contents = Vec::new();
let encoder = PngEncoder::new(&mut contents);
encoder.write_image(image.as_bytes(), dimensions.0, dimensions.1, image.color().into())?;
Ok(ItermResource::new(contents, dimensions))
}
fn register_resource<P: AsRef<Path>>(&self, path: P) -> Result<Self::Resource, RegisterImageError> {
let contents = fs::read(path)?;
let image = image::load_from_memory(&contents)?;
Ok(ItermResource::new(contents, image.dimensions()))
}
fn print<W>(&self, image: &Self::Resource, options: &PrintOptions, writer: &mut W) -> Result<(), PrintImageError>
where
W: std::io::Write,
{
let size = image.raw_length;
let columns = options.columns;
let rows = options.rows;
let contents = &image.base64_contents;
write!(
writer,
"\x1b]1337;File=size={size};width={columns};height={rows};inline=1;preserveAspectRatio=0:{contents}\x07"
)?;
// iterm2 really respects what we say and leaves no space, whereas wezterm does leave an
// extra line here.
if self.is_iterm {
writeln!(writer)?;
}
Ok(())
}
}

View File

@ -1,20 +1,18 @@
use crate::{
markdown::text_style::{Color, TextStyle},
terminal::{
image::printer::{ImageProperties, ImageSpec, PrintImage, PrintImageError, PrintOptions, RegisterImageError},
printer::{TerminalCommand, TerminalIo},
},
};
use super::printer::{PrintImage, PrintImageError, PrintOptions, RegisterImageError, ResourceProperties};
use crate::style::Color;
use base64::{Engine, engine::general_purpose::STANDARD};
use image::{AnimationDecoder, Delay, EncodableLayout, ImageReader, RgbaImage, codecs::gif::GifDecoder};
use console::{Key, Term};
use crossterm::{QueueableCommand, cursor::MoveToColumn, style::SetForegroundColor};
use image::{AnimationDecoder, Delay, DynamicImage, EncodableLayout, ImageReader, RgbaImage, codecs::gif::GifDecoder};
use rand::Rng;
use std::{
fmt,
fs::{self, File},
io::{self, BufReader},
io::{self, BufReader, Write},
path::{Path, PathBuf},
sync::atomic::{AtomicU32, Ordering},
};
use tempfile::{TempDir, tempdir};
use tempfile::{NamedTempFile, TempDir, tempdir};
const IMAGE_PLACEHOLDER: &str = "\u{10EEEE}";
const DIACRITICS: &[u32] = &[
@ -49,9 +47,9 @@ enum GenericResource<B> {
type RawResource = GenericResource<RgbaImage>;
impl RawResource {
fn into_memory_resource(self) -> KittyImage {
fn into_memory_resource(self) -> KittyResource {
match self {
Self::Image(image) => KittyImage {
Self::Image(image) => KittyResource {
dimensions: image.dimensions(),
resource: GenericResource::Image(KittyBuffer::Memory(image.into_raw())),
},
@ -62,37 +60,18 @@ impl RawResource {
.map(|frame| GifFrame { delay: frame.delay, buffer: KittyBuffer::Memory(frame.buffer.into_raw()) })
.collect();
let resource = GenericResource::Gif(frames);
KittyImage { dimensions, resource }
KittyResource { dimensions, resource }
}
}
}
}
pub(crate) struct KittyImage {
pub(crate) struct KittyResource {
dimensions: (u32, u32),
resource: GenericResource<KittyBuffer>,
}
impl KittyImage {
pub(crate) fn as_rgba8(&self) -> RgbaImage {
let first_frame = match &self.resource {
GenericResource::Image(buffer) => buffer,
GenericResource::Gif(gif_frames) => &gif_frames[0].buffer,
};
let buffer = match first_frame {
KittyBuffer::Filesystem(path) => {
let Ok(contents) = fs::read(path) else {
return RgbaImage::default();
};
contents
}
KittyBuffer::Memory(buffer) => buffer.clone(),
};
RgbaImage::from_raw(self.dimensions.0, self.dimensions.1, buffer).unwrap_or_default()
}
}
impl ImageProperties for KittyImage {
impl ResourceProperties for KittyResource {
fn dimensions(&self) -> (u32, u32) {
self.dimensions
}
@ -134,16 +113,16 @@ impl KittyPrinter {
self.base_directory.path().join(file_number.to_string())
}
fn persist_image(&self, image: RgbaImage) -> io::Result<KittyImage> {
fn persist_image(&self, image: RgbaImage) -> io::Result<KittyResource> {
let path = self.allocate_tempfile();
fs::write(&path, image.as_bytes())?;
let buffer = KittyBuffer::Filesystem(path);
let resource = KittyImage { dimensions: image.dimensions(), resource: GenericResource::Image(buffer) };
let resource = KittyResource { dimensions: image.dimensions(), resource: GenericResource::Image(buffer) };
Ok(resource)
}
fn persist_gif(&self, frames: Vec<GifFrame<RgbaImage>>) -> io::Result<KittyImage> {
fn persist_gif(&self, frames: Vec<GifFrame<RgbaImage>>) -> io::Result<KittyResource> {
let mut persisted_frames = Vec::new();
let mut dimensions = (0, 0);
for frame in frames {
@ -154,10 +133,10 @@ impl KittyPrinter {
let frame = GifFrame { delay: frame.delay, buffer: KittyBuffer::Filesystem(path) };
persisted_frames.push(frame);
}
Ok(KittyImage { dimensions, resource: GenericResource::Gif(persisted_frames) })
Ok(KittyResource { dimensions, resource: GenericResource::Gif(persisted_frames) })
}
fn persist_resource(&self, resource: RawResource) -> io::Result<KittyImage> {
fn persist_resource(&self, resource: RawResource) -> io::Result<KittyResource> {
match resource {
RawResource::Image(image) => self.persist_image(image),
RawResource::Gif(frames) => self.persist_gif(frames),
@ -165,18 +144,18 @@ impl KittyPrinter {
}
fn generate_image_id() -> u32 {
fastrand::u32(1..u32::MAX)
rand::thread_rng().gen_range(1..u32::MAX)
}
fn print_image<T>(
fn print_image<W>(
&self,
dimensions: (u32, u32),
buffer: &KittyBuffer,
terminal: &mut T,
writer: &mut W,
print_options: &PrintOptions,
) -> Result<(), PrintImageError>
where
T: TerminalIo,
W: io::Write,
{
let mut options = vec![
ControlOption::Format(ImageFormat::Rgba),
@ -195,25 +174,25 @@ impl KittyPrinter {
}
match &buffer {
KittyBuffer::Filesystem(path) => self.print_local(options, path, terminal)?,
KittyBuffer::Memory(buffer) => self.print_remote(options, buffer, terminal, false)?,
KittyBuffer::Filesystem(path) => self.print_local(options, path, writer)?,
KittyBuffer::Memory(buffer) => self.print_remote(options, buffer, writer, false)?,
};
if self.tmux {
self.print_unicode_placeholders(terminal, print_options, image_id)?;
self.print_unicode_placeholders(writer, print_options, image_id)?;
}
Ok(())
}
fn print_gif<T>(
fn print_gif<W>(
&self,
dimensions: (u32, u32),
frames: &[GifFrame<KittyBuffer>],
terminal: &mut T,
writer: &mut W,
print_options: &PrintOptions,
) -> Result<(), PrintImageError>
where
T: TerminalIo,
W: io::Write,
{
let image_id = Self::generate_image_id();
for (frame_id, frame) in frames.iter().enumerate() {
@ -243,8 +222,8 @@ impl KittyPrinter {
let is_frame = frame_id > 0;
match &frame.buffer {
KittyBuffer::Filesystem(path) => self.print_local(options, path, terminal)?,
KittyBuffer::Memory(buffer) => self.print_remote(options, buffer, terminal, is_frame)?,
KittyBuffer::Filesystem(path) => self.print_local(options, path, writer)?,
KittyBuffer::Memory(buffer) => self.print_remote(options, buffer, writer, is_frame)?,
};
if frame_id == 0 {
@ -254,8 +233,8 @@ impl KittyPrinter {
ControlOption::FrameId(1),
ControlOption::Loops(1),
];
let command = self.make_command(options, "").to_string();
terminal.execute(&TerminalCommand::PrintText { content: &command, style: Default::default() })?;
let command = self.make_command(options, "");
write!(writer, "{command}")?;
} else if frame_id == 1 {
let options = &[
ControlOption::Action(Action::Animate),
@ -263,12 +242,12 @@ impl KittyPrinter {
ControlOption::FrameId(1),
ControlOption::AnimationState(2),
];
let command = self.make_command(options, "").to_string();
terminal.execute(&TerminalCommand::PrintText { content: &command, style: Default::default() })?;
let command = self.make_command(options, "");
write!(writer, "{command}")?;
}
}
if self.tmux {
self.print_unicode_placeholders(terminal, print_options, image_id)?;
self.print_unicode_placeholders(writer, print_options, image_id)?;
}
let options = &[
ControlOption::Action(Action::Animate),
@ -278,8 +257,8 @@ impl KittyPrinter {
ControlOption::Loops(1),
ControlOption::Quiet(2),
];
let command = self.make_command(options, "").to_string();
terminal.execute(&TerminalCommand::PrintText { content: &command, style: Default::default() })?;
let command = self.make_command(options, "");
write!(writer, "{command}")?;
Ok(())
}
@ -287,14 +266,14 @@ impl KittyPrinter {
ControlCommand { options, payload, tmux: self.tmux }
}
fn print_local<T>(
fn print_local<W>(
&self,
mut options: Vec<ControlOption>,
path: &Path,
terminal: &mut T,
writer: &mut W,
) -> Result<(), PrintImageError>
where
T: TerminalIo,
W: io::Write,
{
let Some(path) = path.to_str() else {
return Err(PrintImageError::other("path is not valid utf8"));
@ -302,20 +281,20 @@ impl KittyPrinter {
let encoded_path = STANDARD.encode(path);
options.push(ControlOption::Medium(TransmissionMedium::LocalFile));
let command = self.make_command(&options, &encoded_path).to_string();
terminal.execute(&TerminalCommand::PrintText { content: &command, style: Default::default() })?;
let command = self.make_command(&options, &encoded_path);
write!(writer, "{command}")?;
Ok(())
}
fn print_remote<T>(
fn print_remote<W>(
&self,
mut options: Vec<ControlOption>,
frame: &[u8],
terminal: &mut T,
writer: &mut W,
is_frame: bool,
) -> Result<(), PrintImageError>
where
T: TerminalIo,
W: io::Write,
{
options.push(ControlOption::Medium(TransmissionMedium::Direct));
@ -331,8 +310,8 @@ impl KittyPrinter {
options.push(ControlOption::MoreData(more));
let payload = &payload[start..end];
let command = self.make_command(&options, payload).to_string();
terminal.execute(&TerminalCommand::PrintText { content: &command, style: Default::default() })?;
let command = self.make_command(&options, payload);
write!(writer, "{command}")?;
options.clear();
if is_frame {
@ -342,17 +321,14 @@ impl KittyPrinter {
Ok(())
}
fn print_unicode_placeholders<T>(
fn print_unicode_placeholders<W: Write>(
&self,
terminal: &mut T,
writer: &mut W,
options: &PrintOptions,
image_id: u32,
) -> Result<(), PrintImageError>
where
T: TerminalIo,
{
) -> Result<(), PrintImageError> {
let color = Color::new((image_id >> 16) as u8, (image_id >> 8) as u8, image_id as u8);
let style = TextStyle::default().fg_color(color);
writer.queue(SetForegroundColor(color.into()))?;
if options.rows.max(options.columns) >= DIACRITICS.len() as u16 {
return Err(PrintImageError::other("image is too large to fit in tmux"));
}
@ -362,13 +338,12 @@ impl KittyPrinter {
let row_diacritic = char::from_u32(DIACRITICS[row as usize]).unwrap();
for column in 0..options.columns {
let column_diacritic = char::from_u32(DIACRITICS[column as usize]).unwrap();
let content = format!("{IMAGE_PLACEHOLDER}{row_diacritic}{column_diacritic}{last_byte}");
terminal.execute(&TerminalCommand::PrintText { content: &content, style })?;
write!(writer, "{IMAGE_PLACEHOLDER}{row_diacritic}{column_diacritic}{last_byte}")?;
}
if row != options.rows - 1 {
terminal.execute(&TerminalCommand::MoveDown(1))?;
writeln!(writer)?;
}
terminal.execute(&TerminalCommand::MoveLeft(options.columns))?;
writer.queue(MoveToColumn(options.cursor_position.column))?;
}
Ok(())
}
@ -393,28 +368,37 @@ impl KittyPrinter {
}
impl PrintImage for KittyPrinter {
type Image = KittyImage;
type Resource = KittyResource;
fn register(&self, spec: ImageSpec) -> Result<Self::Image, RegisterImageError> {
let image = match spec {
ImageSpec::Generated(image) => RawResource::Image(image.into_rgba8()),
ImageSpec::Filesystem(path) => Self::load_raw_resource(&path)?,
};
fn register_image(&self, image: DynamicImage) -> Result<Self::Resource, RegisterImageError> {
let resource = RawResource::Image(image.into_rgba8());
let resource = match &self.mode {
KittyMode::Local => self.persist_resource(image)?,
KittyMode::Remote => image.into_memory_resource(),
KittyMode::Local => self.persist_resource(resource)?,
KittyMode::Remote => resource.into_memory_resource(),
};
Ok(resource)
}
fn print<T>(&self, image: &Self::Image, options: &PrintOptions, terminal: &mut T) -> Result<(), PrintImageError>
where
T: TerminalIo,
{
match &image.resource {
GenericResource::Image(resource) => self.print_image(image.dimensions, resource, terminal, options)?,
GenericResource::Gif(frames) => self.print_gif(image.dimensions, frames, terminal, options)?,
fn register_resource<P: AsRef<Path>>(&self, path: P) -> Result<Self::Resource, RegisterImageError> {
let resource = Self::load_raw_resource(path.as_ref())?;
let resource = match &self.mode {
KittyMode::Local => self.persist_resource(resource)?,
KittyMode::Remote => resource.into_memory_resource(),
};
Ok(resource)
}
fn print<W: std::io::Write>(
&self,
image: &Self::Resource,
options: &PrintOptions,
writer: &mut W,
) -> Result<(), PrintImageError> {
match &image.resource {
GenericResource::Image(resource) => self.print_image(image.dimensions, resource, writer, options)?,
GenericResource::Gif(frames) => self.print_gif(image.dimensions, frames, writer, options)?,
};
writeln!(writer)?;
Ok(())
}
}
@ -425,10 +409,10 @@ pub enum KittyMode {
Remote,
}
pub(crate) struct ControlCommand<'a, D> {
pub(crate) options: &'a [ControlOption],
pub(crate) payload: D,
pub(crate) tmux: bool,
struct ControlCommand<'a, D> {
options: &'a [ControlOption],
payload: D,
tmux: bool,
}
impl<D: fmt::Display> fmt::Display for ControlCommand<'_, D> {
@ -454,7 +438,7 @@ impl<D: fmt::Display> fmt::Display for ControlCommand<'_, D> {
}
#[derive(Debug, Clone)]
pub(crate) enum ControlOption {
enum ControlOption {
Action(Action),
Format(ImageFormat),
Medium(TransmissionMedium),
@ -499,7 +483,7 @@ impl fmt::Display for ControlOption {
}
#[derive(Debug, Clone)]
pub(crate) enum ImageFormat {
enum ImageFormat {
Rgba,
}
@ -514,7 +498,7 @@ impl fmt::Display for ImageFormat {
}
#[derive(Debug, Clone)]
pub(crate) enum TransmissionMedium {
enum TransmissionMedium {
Direct,
LocalFile,
}
@ -531,7 +515,7 @@ impl fmt::Display for TransmissionMedium {
}
#[derive(Debug, Clone)]
pub(crate) enum Action {
enum Action {
Animate,
TransmitAndDisplay,
TransmitFrame,
@ -550,3 +534,40 @@ impl fmt::Display for Action {
write!(f, "{value}")
}
}
pub(crate) fn local_mode_supported(inside_tmux: bool) -> io::Result<bool> {
let mut file = NamedTempFile::new()?;
let image = DynamicImage::new_rgba8(1, 1);
file.write_all(image.into_rgba8().as_raw().as_bytes())?;
file.flush()?;
let Some(path) = file.path().as_os_str().to_str() else {
return Ok(false);
};
let encoded_path = STANDARD.encode(path);
let options = &[
ControlOption::Format(ImageFormat::Rgba),
ControlOption::Action(Action::Query),
ControlOption::Medium(TransmissionMedium::LocalFile),
ControlOption::ImageId(rand::random()),
ControlOption::Width(1),
ControlOption::Height(1),
];
let mut writer = io::stdout();
let command = ControlCommand { options, payload: encoded_path, tmux: inside_tmux };
write!(writer, "{command}")?;
writer.flush()?;
let term = Term::stdout();
let mut response = String::new();
while let Ok(key) = term.read_key() {
match key {
Key::Unknown => break,
Key::UnknownEscSeq(seq) if seq == ['\\'] => break,
Key::Char(c) => response.push(c),
_ => continue,
}
}
Ok(response.ends_with(";OK"))
}

11
src/media/mod.rs Normal file
View File

@ -0,0 +1,11 @@
mod ascii;
pub(crate) mod emulator;
pub(crate) mod graphics;
pub(crate) mod image;
mod iterm;
pub(crate) mod kitty;
pub(crate) mod printer;
pub(crate) mod register;
pub(crate) mod scale;
#[cfg(feature = "sixel")]
pub(crate) mod sixel;

194
src/media/printer.rs Normal file
View File

@ -0,0 +1,194 @@
use super::{
ascii::{AsciiPrinter, AsciiResource},
graphics::GraphicsMode,
iterm::{ItermPrinter, ItermResource},
kitty::{KittyMode, KittyPrinter, KittyResource},
};
use crate::{render::properties::CursorPosition, style::Color};
use image::{DynamicImage, ImageError};
use std::{borrow::Cow, io, path::Path};
pub(crate) trait PrintImage {
type Resource: ResourceProperties;
/// Register an image.
fn register_image(&self, image: DynamicImage) -> Result<Self::Resource, RegisterImageError>;
/// Load and register a resource from the given path.
fn register_resource<P: AsRef<Path>>(&self, path: P) -> Result<Self::Resource, RegisterImageError>;
fn print<W>(&self, image: &Self::Resource, options: &PrintOptions, writer: &mut W) -> Result<(), PrintImageError>
where
W: io::Write;
}
pub(crate) trait ResourceProperties {
fn dimensions(&self) -> (u32, u32);
}
#[derive(Debug)]
pub(crate) struct PrintOptions {
pub(crate) columns: u16,
pub(crate) rows: u16,
pub(crate) cursor_position: CursorPosition,
pub(crate) z_index: i32,
pub(crate) background_color: Option<Color>,
// Width/height in pixels.
#[allow(dead_code)]
pub(crate) column_width: u16,
#[allow(dead_code)]
pub(crate) row_height: u16,
}
pub(crate) enum ImageResource {
Kitty(KittyResource),
Iterm(ItermResource),
Ascii(AsciiResource),
#[cfg(feature = "sixel")]
Sixel(super::sixel::SixelResource),
}
impl ResourceProperties for ImageResource {
fn dimensions(&self) -> (u32, u32) {
match self {
Self::Kitty(resource) => resource.dimensions(),
Self::Iterm(resource) => resource.dimensions(),
Self::Ascii(resource) => resource.dimensions(),
#[cfg(feature = "sixel")]
Self::Sixel(resource) => resource.dimensions(),
}
}
}
pub enum ImagePrinter {
Kitty(KittyPrinter),
Iterm(ItermPrinter),
Ascii(AsciiPrinter),
Null,
#[cfg(feature = "sixel")]
Sixel(super::sixel::SixelPrinter),
}
impl Default for ImagePrinter {
fn default() -> Self {
Self::new_ascii()
}
}
impl ImagePrinter {
pub fn new(mode: GraphicsMode) -> Result<Self, CreatePrinterError> {
let printer = match mode {
GraphicsMode::Kitty { mode, inside_tmux } => Self::new_kitty(mode, inside_tmux)?,
GraphicsMode::Iterm2 => Self::new_iterm(),
GraphicsMode::AsciiBlocks => Self::new_ascii(),
#[cfg(feature = "sixel")]
GraphicsMode::Sixel => Self::new_sixel()?,
};
Ok(printer)
}
fn new_kitty(mode: KittyMode, inside_tmux: bool) -> io::Result<Self> {
Ok(Self::Kitty(KittyPrinter::new(mode, inside_tmux)?))
}
fn new_iterm() -> Self {
Self::Iterm(ItermPrinter::default())
}
fn new_ascii() -> Self {
Self::Ascii(AsciiPrinter)
}
#[cfg(feature = "sixel")]
fn new_sixel() -> Result<Self, CreatePrinterError> {
Ok(Self::Sixel(super::sixel::SixelPrinter::new()?))
}
}
impl PrintImage for ImagePrinter {
type Resource = ImageResource;
fn register_image(&self, image: DynamicImage) -> Result<Self::Resource, RegisterImageError> {
let resource = match self {
Self::Kitty(printer) => ImageResource::Kitty(printer.register_image(image)?),
Self::Iterm(printer) => ImageResource::Iterm(printer.register_image(image)?),
Self::Ascii(printer) => ImageResource::Ascii(printer.register_image(image)?),
Self::Null => return Err(RegisterImageError::Unsupported),
#[cfg(feature = "sixel")]
Self::Sixel(printer) => ImageResource::Sixel(printer.register_image(image)?),
};
Ok(resource)
}
fn register_resource<P: AsRef<Path>>(&self, path: P) -> Result<Self::Resource, RegisterImageError> {
let resource = match self {
Self::Kitty(printer) => ImageResource::Kitty(printer.register_resource(path)?),
Self::Iterm(printer) => ImageResource::Iterm(printer.register_resource(path)?),
Self::Ascii(printer) => ImageResource::Ascii(printer.register_resource(path)?),
Self::Null => return Err(RegisterImageError::Unsupported),
#[cfg(feature = "sixel")]
Self::Sixel(printer) => ImageResource::Sixel(printer.register_resource(path)?),
};
Ok(resource)
}
fn print<W>(&self, image: &Self::Resource, options: &PrintOptions, writer: &mut W) -> Result<(), PrintImageError>
where
W: io::Write,
{
match (self, image) {
(Self::Kitty(printer), ImageResource::Kitty(image)) => printer.print(image, options, writer),
(Self::Iterm(printer), ImageResource::Iterm(image)) => printer.print(image, options, writer),
(Self::Ascii(printer), ImageResource::Ascii(image)) => printer.print(image, options, writer),
(Self::Null, _) => Ok(()),
#[cfg(feature = "sixel")]
(Self::Sixel(printer), ImageResource::Sixel(image)) => printer.print(image, options, writer),
_ => Err(PrintImageError::Unsupported),
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum CreatePrinterError {
#[error("io: {0}")]
Io(#[from] io::Error),
#[error("unexpected: {0}")]
Other(String),
}
#[derive(Debug, thiserror::Error)]
pub enum PrintImageError {
#[error(transparent)]
Io(#[from] io::Error),
#[error("unsupported image type")]
Unsupported,
#[error("image decoding: {0}")]
Image(#[from] ImageError),
#[error("other: {0}")]
Other(Cow<'static, str>),
}
#[derive(Debug, thiserror::Error)]
pub enum RegisterImageError {
#[error(transparent)]
Io(#[from] io::Error),
#[error("image decoding: {0}")]
Image(#[from] ImageError),
#[error("printer can't register resources")]
Unsupported,
}
impl PrintImageError {
pub(crate) fn other<S>(message: S) -> Self
where
S: Into<Cow<'static, str>>,
{
Self::Other(message.into())
}
}

24
src/media/register.rs Normal file
View File

@ -0,0 +1,24 @@
use super::{
image::{Image, ImageSource},
printer::{PrintImage, RegisterImageError},
};
use crate::ImagePrinter;
use image::DynamicImage;
use std::{path::PathBuf, sync::Arc};
#[derive(Clone, Default)]
pub struct ImageRegistry(pub Arc<ImagePrinter>);
impl ImageRegistry {
pub(crate) fn register_image(&self, image: DynamicImage) -> Result<Image, RegisterImageError> {
let resource = self.0.register_image(image)?;
let image = Image::new(resource, ImageSource::Generated);
Ok(image)
}
pub(crate) fn register_resource(&self, path: PathBuf) -> Result<Image, RegisterImageError> {
let resource = self.0.register_resource(&path)?;
let image = Image::new(resource, ImageSource::Filesystem(path));
Ok(image)
}
}

64
src/media/scale.rs Normal file
View File

@ -0,0 +1,64 @@
use crate::render::properties::{CursorPosition, WindowSize};
/// Scale an image to a specific size.
pub(crate) fn scale_image(
scale_size: &WindowSize,
window_dimensions: &WindowSize,
image_width: u32,
image_height: u32,
position: &CursorPosition,
) -> TerminalRect {
let aspect_ratio = image_height as f64 / image_width as f64;
let column_in_pixels = scale_size.pixels_per_column();
let width_in_columns = scale_size.columns;
let image_width = width_in_columns as f64 * column_in_pixels;
let image_height = image_width * aspect_ratio;
fit_image_to_window(window_dimensions, image_width as u32, image_height as u32, position)
}
/// Shrink an image so it fits the dimensions of the layout it's being displayed in.
pub(crate) fn fit_image_to_window(
dimensions: &WindowSize,
image_width: u32,
image_height: u32,
position: &CursorPosition,
) -> TerminalRect {
let aspect_ratio = image_height as f64 / image_width as f64;
// Compute the image's width in columns by translating pixels -> columns.
let column_in_pixels = dimensions.pixels_per_column();
let column_margin = (dimensions.columns as f64 * 0.95) as u32;
let mut width_in_columns = (image_width as f64 / column_in_pixels) as u32;
// Do the same for its height.
let row_in_pixels = dimensions.pixels_per_row();
let height_in_rows = (image_height as f64 / row_in_pixels) as u32;
// If the image doesn't fit vertically, shrink it.
let available_height = dimensions.rows.saturating_sub(position.row) as u32;
if height_in_rows > available_height {
// Because we only use the width to draw, here we scale the width based on how much we
// need to shrink the height.
let shrink_ratio = available_height as f64 / height_in_rows as f64;
width_in_columns = (width_in_columns as f64 * shrink_ratio).ceil() as u32;
}
// Don't go too far wide.
let width_in_columns = width_in_columns.min(column_margin);
let height_in_rows = (width_in_columns as f64 * aspect_ratio / 2.0) as u16;
let width_in_columns = width_in_columns.max(1);
let height_in_rows = height_in_rows.max(1);
// Draw it in the middle
let start_column = dimensions.columns / 2 - (width_in_columns / 2) as u16;
let start_column = start_column + position.column;
TerminalRect { start_column, columns: width_in_columns as u16, rows: height_in_rows }
}
#[derive(Debug)]
pub(crate) struct TerminalRect {
pub(crate) start_column: u16,
pub(crate) columns: u16,
pub(crate) rows: u16,
}

View File

@ -1,26 +1,17 @@
use crate::terminal::{
image::printer::{
CreatePrinterError, ImageProperties, ImageSpec, PrintImage, PrintImageError, PrintOptions, RegisterImageError,
},
printer::{TerminalCommand, TerminalIo},
use super::printer::{
CreatePrinterError, PrintImage, PrintImageError, PrintOptions, RegisterImageError, ResourceProperties,
};
use image::{DynamicImage, GenericImageView, RgbaImage, imageops::FilterType};
use image::{DynamicImage, GenericImageView, imageops::FilterType};
use sixel_rs::{
encoder::{Encoder, QuickFrameBuilder},
optflags::EncodePolicy,
sys::PixelFormat,
};
use std::fs;
use std::{fs, io};
pub(crate) struct SixelImage(DynamicImage);
pub(crate) struct SixelResource(DynamicImage);
impl SixelImage {
pub(crate) fn as_rgba8(&self) -> RgbaImage {
self.0.to_rgba8()
}
}
impl ImageProperties for SixelImage {
impl ResourceProperties for SixelResource {
fn dimensions(&self) -> (u32, u32) {
self.0.dimensions()
}
@ -36,25 +27,24 @@ impl SixelPrinter {
}
impl PrintImage for SixelPrinter {
type Image = SixelImage;
type Resource = SixelResource;
fn register(&self, spec: ImageSpec) -> Result<Self::Image, RegisterImageError> {
match spec {
ImageSpec::Generated(image) => Ok(SixelImage(image)),
ImageSpec::Filesystem(path) => {
let contents = fs::read(path)?;
let image = image::load_from_memory(&contents)?;
Ok(SixelImage(image))
}
}
fn register_image(&self, image: image::DynamicImage) -> Result<Self::Resource, RegisterImageError> {
Ok(SixelResource(image))
}
fn print<T>(&self, image: &Self::Image, options: &PrintOptions, terminal: &mut T) -> Result<(), PrintImageError>
fn register_resource<P: AsRef<std::path::Path>>(&self, path: P) -> Result<Self::Resource, RegisterImageError> {
let contents = fs::read(path)?;
let image = image::load_from_memory(&contents)?;
Ok(SixelResource(image))
}
fn print<W>(&self, image: &Self::Resource, options: &PrintOptions, writer: &mut W) -> Result<(), PrintImageError>
where
T: TerminalIo,
W: io::Write,
{
// We're already positioned in the right place but we may not have flushed that yet.
terminal.execute(&TerminalCommand::Flush)?;
writer.flush()?;
let encoder = Encoder::new().map_err(|e| PrintImageError::other(format!("creating sixel encoder: {e:?}")))?;
encoder

View File

@ -1,17 +1,21 @@
use crate::{config::OptionsConfig, render::operation::RenderOperation};
use crate::{
custom::OptionsConfig,
markdown::text::{WeightedText, WeightedTextBlock},
media::image::Image,
render::properties::WindowSize,
style::{Color, Colors},
theme::{Alignment, Margin, PresentationTheme},
};
use serde::Deserialize;
use std::{
cell::RefCell,
collections::HashSet,
fmt::Debug,
ops::Deref,
rc::Rc,
sync::{Arc, Mutex},
};
pub(crate) mod builder;
pub(crate) mod diff;
pub(crate) mod poller;
#[derive(Debug)]
pub(crate) struct Modals {
pub(crate) slide_index: Vec<RenderOperation>,
@ -37,11 +41,6 @@ impl Presentation {
self.slides.iter()
}
/// Iterate the slides in this presentation.
pub(crate) fn iter_slides_mut(&mut self) -> impl Iterator<Item = &mut Slide> {
self.slides.iter_mut()
}
/// Iterate the operations that render the slide index.
pub(crate) fn iter_slide_index_operations(&self) -> impl Iterator<Item = &RenderOperation> {
self.modals.slide_index.iter()
@ -53,6 +52,7 @@ impl Presentation {
}
/// Consume this presentation and return its slides.
#[cfg(test)]
pub(crate) fn into_slides(self) -> Vec<Slide> {
self.slides
}
@ -140,7 +140,92 @@ impl Presentation {
self.current_slide().current_chunk_index()
}
pub(crate) fn current_slide_mut(&mut self) -> &mut Slide {
/// Trigger async render operations in all slides.
pub(crate) fn trigger_all_async_renders(&mut self) -> HashSet<usize> {
let mut triggered_slides = HashSet::new();
for (index, slide) in self.slides.iter_mut().enumerate() {
for operation in slide.iter_operations_mut() {
if let RenderOperation::RenderAsync(operation) = operation {
if operation.start_render() {
triggered_slides.insert(index);
}
}
}
}
triggered_slides
}
/// Trigger async render operations in this slide.
pub(crate) fn trigger_slide_async_renders(&mut self) -> bool {
let slide = self.current_slide_mut();
let mut any_rendered = false;
for operation in slide.iter_visible_operations_mut() {
if let RenderOperation::RenderAsync(operation) = operation {
let is_rendered = operation.start_render();
any_rendered = any_rendered || is_rendered;
}
}
any_rendered
}
// Get all slides that contain async render operations.
pub(crate) fn slides_with_async_renders(&self) -> HashSet<usize> {
let mut indexes = HashSet::new();
for (index, slide) in self.slides.iter().enumerate() {
for operation in slide.iter_operations() {
if let RenderOperation::RenderAsync(operation) = operation {
if matches!(operation.poll_state(), RenderAsyncState::Rendering { .. }) {
indexes.insert(index);
break;
}
}
}
}
indexes
}
/// Poll every async render operation in the current slide and check whether they're completed.
pub(crate) fn poll_slide_async_renders(&mut self) -> RenderAsyncState {
let slide = self.current_slide_mut();
let mut slide_state = RenderAsyncState::Rendered;
for operation in slide.iter_operations_mut() {
if let RenderOperation::RenderAsync(operation) = operation {
let state = operation.poll_state();
slide_state = match (&slide_state, &state) {
// If one finished rendering and another one still is rendering, claim that we
// are still rendering and there's modifications.
(RenderAsyncState::JustFinishedRendering, RenderAsyncState::Rendering { .. })
| (RenderAsyncState::Rendering { .. }, RenderAsyncState::JustFinishedRendering) => {
RenderAsyncState::Rendering { modified: true }
}
// Render + modified overrides anything, rendering overrides only "rendered".
(_, RenderAsyncState::Rendering { modified: true })
| (RenderAsyncState::Rendered, RenderAsyncState::Rendering { .. })
| (_, RenderAsyncState::JustFinishedRendering) => state,
_ => slide_state,
};
}
}
slide_state
}
/// Run a callback through every operation and let it mutate it in place.
///
/// This should be used with care!
pub(crate) fn mutate_operations<F>(&mut self, mut callback: F)
where
F: FnMut(&mut RenderOperation),
{
for slide in &mut self.slides {
for chunk in &mut slide.chunks {
for operation in &mut chunk.operations {
callback(operation);
}
}
}
}
fn current_slide_mut(&mut self) -> &mut Slide {
let index = self.current_slide_index();
&mut self.slides[index]
}
@ -298,7 +383,7 @@ impl Slide {
self.current_chunk().reset_mutations();
}
pub(crate) fn show_all_chunks(&mut self) {
fn show_all_chunks(&mut self) {
self.visible_chunks = self.chunks.len();
for chunk in &self.chunks {
chunk.apply_all_mutations();
@ -463,7 +548,152 @@ pub(crate) struct PresentationThemeMetadata {
/// Any specific overrides for the presentation's theme.
#[serde(default, rename = "override")]
pub(crate) overrides: Option<crate::theme::raw::PresentationTheme>,
pub(crate) overrides: Option<PresentationTheme>,
}
/// A line of preformatted text to be rendered.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BlockLine {
pub(crate) prefix: WeightedText,
pub(crate) right_padding_length: u16,
pub(crate) repeat_prefix_on_wrap: bool,
pub(crate) text: WeightedTextBlock,
pub(crate) block_length: u16,
pub(crate) block_color: Option<Color>,
pub(crate) alignment: Alignment,
}
/// A render operation.
///
/// Render operations are primitives that allow the input markdown file to be decoupled with what
/// we draw on the screen.
#[derive(Clone, Debug)]
pub(crate) enum RenderOperation {
/// Clear the entire screen.
ClearScreen,
/// Set the colors to be used for any subsequent operations.
SetColors(Colors),
/// Jump the draw cursor into the vertical center, that is, at `screen_height / 2`.
JumpToVerticalCenter,
/// Jumps to the N-th row in the current layout.
///
/// The index is zero based where 0 represents the top row.
JumpToRow { index: u16 },
/// Jumps to the N-th to last row in the current layout.
///
/// The index is zero based where 0 represents the bottom row.
JumpToBottomRow { index: u16 },
/// Render text.
RenderText { line: WeightedTextBlock, alignment: Alignment },
/// Render a line break.
RenderLineBreak,
/// Render an image.
RenderImage(Image, ImageProperties),
/// Render a line.
RenderBlockLine(BlockLine),
/// Render a dynamically generated sequence of render operations.
///
/// This allows drawing something on the screen that requires knowing dynamic properties of the
/// screen, like window size, without coupling the transformation of markdown into
/// [RenderOperation] with the screen itself.
RenderDynamic(Rc<dyn AsRenderOperations>),
/// An operation that is rendered asynchronously.
RenderAsync(Rc<dyn RenderAsync>),
/// Initialize a column layout.
///
/// The value for each column is the width of the column in column-unit units, where the entire
/// screen contains `columns.sum()` column-units.
InitColumnLayout { columns: Vec<u8> },
/// Enter a column in a column layout.
///
/// The index is 0-index based and will be tied to a previous `InitColumnLayout` operation.
EnterColumn { column: usize },
/// Exit the current layout and go back to the default one.
ExitLayout,
/// Apply a margin to every following operation.
ApplyMargin(MarginProperties),
/// Pop an `ApplyMargin` operation.
PopMargin,
}
/// The properties of an image being rendered.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ImageProperties {
pub(crate) z_index: i32,
pub(crate) size: ImageSize,
pub(crate) restore_cursor: bool,
pub(crate) background_color: Option<Color>,
}
/// The size used when printing an image.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) enum ImageSize {
#[default]
ShrinkIfNeeded,
Specific(u16, u16),
WidthScaled {
ratio: f64,
},
}
/// Slide properties, set on initialization.
#[derive(Clone, Debug, Default)]
pub(crate) struct MarginProperties {
/// The horizontal margin.
pub(crate) horizontal_margin: Margin,
/// The margin at the bottom of the slide.
pub(crate) bottom_slide_margin: u16,
}
/// A type that can generate render operations.
pub(crate) trait AsRenderOperations: Debug + 'static {
/// Generate render operations.
fn as_render_operations(&self, dimensions: &WindowSize) -> Vec<RenderOperation>;
/// Get the content in this type to diff it against another `AsRenderOperations`.
fn diffable_content(&self) -> Option<&str> {
None
}
}
/// An operation that can be rendered asynchronously.
pub(crate) trait RenderAsync: AsRenderOperations {
/// Start the render for this operation.
///
/// Should return true if the invocation triggered the rendering (aka if rendering wasn't
/// already started before).
fn start_render(&self) -> bool;
/// Update the internal state and return the updated state.
fn poll_state(&self) -> RenderAsyncState;
}
/// The state of a [RenderAsync].
#[derive(Clone, Debug, Default)]
pub(crate) enum RenderAsyncState {
#[default]
NotStarted,
Rendering {
modified: bool,
},
Rendered,
JustFinishedRendering,
}
#[cfg(test)]

View File

@ -1,390 +0,0 @@
use super::{BuildError, BuildResult, ExecutionMode, PresentationBuilderOptions};
use crate::{
ImageRegistry,
code::{
execute::SnippetExecutor,
highlighting::SnippetHighlighter,
snippet::{
ExternalFile, Highlight, HighlightContext, HighlightGroup, HighlightMutator, HighlightedLine, Snippet,
SnippetExec, SnippetLanguage, SnippetLine, SnippetParser, SnippetRepr, SnippetSplitter,
},
},
markdown::elements::SourcePosition,
presentation::ChunkMutator,
render::{
operation::{AsRenderOperations, RenderAsyncStartPolicy, RenderOperation},
properties::WindowSize,
},
resource::Resources,
theme::{Alignment, CodeBlockStyle, PresentationTheme},
third_party::{ThirdPartyRender, ThirdPartyRenderRequest},
ui::execution::{
RunAcquireTerminalSnippet, RunImageSnippet, RunSnippetOperation, SnippetExecutionDisabledOperation,
disabled::ExecutionType, snippet::DisplaySeparator,
},
};
use itertools::Itertools;
use std::{cell::RefCell, rc::Rc, sync::Arc};
pub(crate) struct SnippetProcessorState<'a> {
pub(crate) resources: &'a Resources,
pub(crate) image_registry: &'a ImageRegistry,
pub(crate) snippet_executor: Arc<SnippetExecutor>,
pub(crate) theme: &'a PresentationTheme,
pub(crate) third_party: &'a ThirdPartyRender,
pub(crate) highlighter: &'a SnippetHighlighter,
pub(crate) options: &'a PresentationBuilderOptions,
pub(crate) font_size: u8,
}
pub(crate) struct SnippetProcessor<'a> {
operations: Vec<RenderOperation>,
mutators: Vec<Box<dyn ChunkMutator>>,
resources: &'a Resources,
image_registry: &'a ImageRegistry,
snippet_executor: Arc<SnippetExecutor>,
theme: &'a PresentationTheme,
third_party: &'a ThirdPartyRender,
highlighter: &'a SnippetHighlighter,
options: &'a PresentationBuilderOptions,
font_size: u8,
}
impl<'a> SnippetProcessor<'a> {
pub(crate) fn new(state: SnippetProcessorState<'a>) -> Self {
let SnippetProcessorState {
resources,
image_registry,
snippet_executor,
theme,
third_party,
highlighter,
options,
font_size,
} = state;
Self {
operations: Vec::new(),
mutators: Vec::new(),
resources,
image_registry,
snippet_executor,
theme,
third_party,
highlighter,
options,
font_size,
}
}
pub(crate) fn process_code(
mut self,
info: String,
code: String,
source_position: SourcePosition,
) -> Result<SnippetOperations, BuildError> {
self.do_process_code(info, code, source_position)?;
let Self { operations, mutators, .. } = self;
Ok(SnippetOperations { operations, mutators })
}
fn do_process_code(&mut self, info: String, code: String, source_position: SourcePosition) -> BuildResult {
let mut snippet = SnippetParser::parse(info, code)
.map_err(|e| BuildError::InvalidSnippet { source_position, error: e.to_string() })?;
if matches!(snippet.language, SnippetLanguage::File) {
snippet = self.load_external_snippet(snippet, source_position)?;
}
if self.options.auto_render_languages.contains(&snippet.language) {
snippet.attributes.representation = SnippetRepr::Render;
}
self.push_differ(snippet.contents.clone());
// Redraw slide if attributes change
self.push_differ(format!("{:?}", snippet.attributes));
let execution_allowed = self.is_execution_allowed(&snippet);
match snippet.attributes.representation {
SnippetRepr::Render => return self.push_rendered_code(snippet, source_position),
SnippetRepr::Image => {
if execution_allowed {
return self.push_code_as_image(snippet);
}
}
SnippetRepr::ExecReplace => {
if execution_allowed {
return self.push_code_execution(snippet, 0, ExecutionMode::ReplaceSnippet);
}
}
SnippetRepr::Snippet => (),
};
let block_length = self.push_code_lines(&snippet);
match snippet.attributes.execution {
SnippetExec::None => Ok(()),
SnippetExec::Exec | SnippetExec::AcquireTerminal if !execution_allowed => {
let exec_type = match snippet.attributes.representation {
SnippetRepr::Image => ExecutionType::Image,
SnippetRepr::ExecReplace => ExecutionType::ExecReplace,
SnippetRepr::Render | SnippetRepr::Snippet => ExecutionType::Execute,
};
self.push_execution_disabled_operation(exec_type);
Ok(())
}
SnippetExec::Exec => self.push_code_execution(snippet, block_length, ExecutionMode::AlongSnippet),
SnippetExec::AcquireTerminal => self.push_acquire_terminal_execution(snippet, block_length),
}
}
fn is_execution_allowed(&self, snippet: &Snippet) -> bool {
match snippet.attributes.representation {
SnippetRepr::Snippet => self.options.enable_snippet_execution,
SnippetRepr::Image | SnippetRepr::ExecReplace => self.options.enable_snippet_execution_replace,
SnippetRepr::Render => true,
}
}
fn push_code_lines(&mut self, snippet: &Snippet) -> u16 {
let lines = SnippetSplitter::new(&self.theme.code, self.snippet_executor.hidden_line_prefix(&snippet.language))
.split(snippet);
let block_length = lines.iter().map(|line| line.width()).max().unwrap_or(0) * self.font_size as usize;
let block_length = block_length as u16;
let (lines, context) = self.highlight_lines(snippet, lines, block_length);
for line in lines {
self.operations.push(RenderOperation::RenderDynamic(Rc::new(line)));
}
self.operations.push(RenderOperation::SetColors(self.theme.default_style.style.colors));
if self.options.allow_mutations && context.borrow().groups.len() > 1 {
self.mutators.push(Box::new(HighlightMutator::new(context)));
}
block_length
}
fn load_external_snippet(
&mut self,
mut code: Snippet,
source_position: SourcePosition,
) -> Result<Snippet, BuildError> {
let file: ExternalFile = serde_yaml::from_str(&code.contents)
.map_err(|e| BuildError::InvalidSnippet { source_position, error: e.to_string() })?;
let path = file.path;
let path_display = path.display();
let contents = self.resources.external_snippet(&path).map_err(|e| BuildError::InvalidSnippet {
source_position,
error: format!("failed to load {path_display}: {e}"),
})?;
code.language = file.language;
code.contents = Self::filter_lines(contents, file.start_line, file.end_line);
Ok(code)
}
fn filter_lines(code: String, start: Option<usize>, end: Option<usize>) -> String {
let start = start.map(|s| s.saturating_sub(1));
match (start, end) {
(None, None) => code,
(None, Some(end)) => code.lines().take(end).join("\n"),
(Some(start), None) => code.lines().skip(start).join("\n"),
(Some(start), Some(end)) => code.lines().skip(start).take(end.saturating_sub(start)).join("\n"),
}
}
fn push_rendered_code(&mut self, code: Snippet, source_position: SourcePosition) -> BuildResult {
let Snippet { contents, language, attributes } = code;
let request = match language {
SnippetLanguage::Typst => ThirdPartyRenderRequest::Typst(contents, self.theme.typst.clone()),
SnippetLanguage::Latex => ThirdPartyRenderRequest::Latex(contents, self.theme.typst.clone()),
SnippetLanguage::Mermaid => ThirdPartyRenderRequest::Mermaid(contents, self.theme.mermaid.clone()),
_ => {
return Err(BuildError::InvalidSnippet {
source_position,
error: format!("language {language:?} doesn't support rendering"),
})?;
}
};
let operation = self.third_party.render(request, self.theme, attributes.width)?;
self.operations.push(operation);
Ok(())
}
fn highlight_lines(
&self,
code: &Snippet,
lines: Vec<SnippetLine>,
block_length: u16,
) -> (Vec<HighlightedLine>, Rc<RefCell<HighlightContext>>) {
let mut code_highlighter = self.highlighter.language_highlighter(&code.language);
let style = self.code_style(code);
let block_length = self.theme.code.alignment.adjust_size(block_length);
let font_size = self.font_size;
let dim_style = {
let mut highlighter = self.highlighter.language_highlighter(&SnippetLanguage::Rust);
highlighter.style_line("//", &style).0.first().expect("no styles").style.size(font_size)
};
let groups = match self.options.allow_mutations {
true => code.attributes.highlight_groups.clone(),
false => vec![HighlightGroup::new(vec![Highlight::All])],
};
let context =
Rc::new(RefCell::new(HighlightContext { groups, current: 0, block_length, alignment: style.alignment }));
let mut output = Vec::new();
for line in lines.into_iter() {
let prefix = line.dim_prefix(&dim_style);
let highlighted = line.highlight(&mut code_highlighter, &style, font_size);
let not_highlighted = line.dim(&dim_style);
let line_number = line.line_number;
let context = context.clone();
output.push(HighlightedLine {
prefix,
right_padding_length: line.right_padding_length * self.font_size as u16,
highlighted,
not_highlighted,
line_number,
context,
block_color: dim_style.colors.background,
});
}
(output, context)
}
fn code_style(&self, snippet: &Snippet) -> CodeBlockStyle {
let mut style = self.theme.code.clone();
if snippet.attributes.no_background {
style.background = false;
}
style
}
fn push_execution_disabled_operation(&mut self, exec_type: ExecutionType) {
let policy = match exec_type {
ExecutionType::ExecReplace | ExecutionType::Image => RenderAsyncStartPolicy::Automatic,
ExecutionType::Execute => RenderAsyncStartPolicy::OnDemand,
};
let operation = SnippetExecutionDisabledOperation::new(
self.theme.execution_output.status.failure_style,
self.theme.code.alignment,
policy,
exec_type,
);
self.operations.push(RenderOperation::RenderAsync(Rc::new(operation)));
}
fn push_code_as_image(&mut self, snippet: Snippet) -> BuildResult {
if !self.snippet_executor.is_execution_supported(&snippet.language) {
return Err(BuildError::UnsupportedExecution(snippet.language));
}
let operation = RunImageSnippet::new(
snippet,
self.snippet_executor.clone(),
self.image_registry.clone(),
self.theme.execution_output.status.clone(),
);
let operation = RenderOperation::RenderAsync(Rc::new(operation));
self.operations.push(operation);
Ok(())
}
fn push_acquire_terminal_execution(&mut self, snippet: Snippet, block_length: u16) -> BuildResult {
if !self.snippet_executor.is_execution_supported(&snippet.language) {
return Err(BuildError::UnsupportedExecution(snippet.language));
}
let block_length = self.theme.code.alignment.adjust_size(block_length);
let operation = RunAcquireTerminalSnippet::new(
snippet,
self.snippet_executor.clone(),
self.theme.execution_output.status.clone(),
block_length,
self.font_size,
);
let operation = RenderOperation::RenderAsync(Rc::new(operation));
self.operations.push(operation);
Ok(())
}
fn push_code_execution(&mut self, snippet: Snippet, block_length: u16, mode: ExecutionMode) -> BuildResult {
if !self.snippet_executor.is_execution_supported(&snippet.language) {
return Err(BuildError::UnsupportedExecution(snippet.language));
}
let separator = match mode {
ExecutionMode::AlongSnippet => DisplaySeparator::On,
ExecutionMode::ReplaceSnippet => DisplaySeparator::Off,
};
let default_alignment = self.code_style(&snippet).alignment;
// If we're replacing the snippet output and we have center alignment, use center alignment but
// without any margins and minimum sizes so we truly center the output.
let alignment = match (&mode, default_alignment) {
(ExecutionMode::ReplaceSnippet, Alignment::Center { .. }) => {
Alignment::Center { minimum_margin: Default::default(), minimum_size: 0 }
}
(_, alignment) => alignment,
};
let default_colors = self.theme.default_style.style.colors;
let mut execution_output_style = self.theme.execution_output.clone();
if snippet.attributes.no_background {
execution_output_style.style.colors.background = None;
}
let policy = match mode {
ExecutionMode::AlongSnippet => RenderAsyncStartPolicy::OnDemand,
ExecutionMode::ReplaceSnippet => RenderAsyncStartPolicy::Automatic,
};
let operation = RunSnippetOperation::new(
snippet,
self.snippet_executor.clone(),
default_colors,
execution_output_style,
block_length,
separator,
alignment,
self.font_size,
policy,
);
let operation = RenderOperation::RenderAsync(Rc::new(operation));
self.operations.push(operation);
Ok(())
}
fn push_differ(&mut self, text: String) {
self.operations.push(RenderOperation::RenderDynamic(Rc::new(Differ(text))));
}
}
pub(crate) struct SnippetOperations {
pub(crate) operations: Vec<RenderOperation>,
pub(crate) mutators: Vec<Box<dyn ChunkMutator>>,
}
#[derive(Debug)]
struct Differ(String);
impl AsRenderOperations for Differ {
fn as_render_operations(&self, _: &WindowSize) -> Vec<RenderOperation> {
Vec::new()
}
fn diffable_content(&self) -> Option<&str> {
Some(&self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[rstest]
#[case::no_filters(None, None, &["a", "b", "c", "d", "e"])]
#[case::start_from_first(Some(1), None, &["a", "b", "c", "d", "e"])]
#[case::start_from_second(Some(2), None, &["b", "c", "d", "e"])]
#[case::start_from_end(Some(5), None, &["e"])]
#[case::start_from_past_end(Some(6), None, &[])]
#[case::end_last(None, Some(5), &["a", "b", "c", "d", "e"])]
#[case::end_one_before_last(None, Some(4), &["a", "b", "c", "d"])]
#[case::end_at_first(None, Some(1), &["a"])]
#[case::end_at_zero(None, Some(0), &[])]
#[case::start_and_end(Some(2), Some(3), &["b", "c"])]
#[case::crossed(Some(2), Some(1), &[])]
fn filter_lines(#[case] start: Option<usize>, #[case] end: Option<usize>, #[case] expected: &[&str]) {
let code = ["a", "b", "c", "d", "e"].join("\n");
let output = SnippetProcessor::filter_lines(code, start, end);
let expected = expected.join("\n");
assert_eq!(output, expected);
}
}

View File

@ -1,118 +0,0 @@
use crate::render::operation::{Pollable, PollableState};
use std::{
sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel},
thread,
time::Duration,
};
const POLL_INTERVAL: Duration = Duration::from_millis(25);
pub(crate) struct Poller {
sender: Sender<PollerCommand>,
receiver: Receiver<PollableEffect>,
}
impl Poller {
pub(crate) fn launch() -> Self {
let (command_sender, command_receiver) = channel();
let (effect_sender, effect_receiver) = channel();
let worker = PollerWorker::new(command_receiver, effect_sender);
thread::spawn(move || {
worker.run();
});
Self { sender: command_sender, receiver: effect_receiver }
}
pub(crate) fn send(&self, command: PollerCommand) {
let _ = self.sender.send(command);
}
pub(crate) fn next_effect(&mut self) -> Option<PollableEffect> {
self.receiver.try_recv().ok()
}
}
/// An effect caused by a pollable.
#[derive(Clone)]
pub(crate) enum PollableEffect {
/// Refresh the given slide.
RefreshSlide(usize),
/// Display an error for the given slide.
DisplayError { slide: usize, error: String },
}
/// A poller command.
pub(crate) enum PollerCommand {
/// Start polling a pollable that's positioned in the given slide.
Poll { pollable: Box<dyn Pollable>, slide: usize },
/// Reset all pollables.
Reset,
}
struct PollerWorker {
receiver: Receiver<PollerCommand>,
sender: Sender<PollableEffect>,
pollables: Vec<(Box<dyn Pollable>, usize)>,
}
impl PollerWorker {
fn new(receiver: Receiver<PollerCommand>, sender: Sender<PollableEffect>) -> Self {
Self { receiver, sender, pollables: Default::default() }
}
fn run(mut self) {
loop {
match self.receiver.recv_timeout(POLL_INTERVAL) {
Ok(command) => self.process_command(command),
// TODO don't loop forever.
Err(RecvTimeoutError::Timeout) => self.poll(),
Err(RecvTimeoutError::Disconnected) => break,
};
}
}
fn process_command(&mut self, command: PollerCommand) {
match command {
PollerCommand::Poll { mut pollable, slide } => {
// Poll and only insert if it's still running.
match pollable.poll() {
PollableState::Unmodified | PollableState::Modified => {
self.pollables.push((pollable, slide));
}
PollableState::Done => {
let _ = self.sender.send(PollableEffect::RefreshSlide(slide));
}
PollableState::Failed { error } => {
let _ = self.sender.send(PollableEffect::DisplayError { slide, error });
}
};
}
PollerCommand::Reset => self.pollables.clear(),
}
}
fn poll(&mut self) {
let mut removables = Vec::new();
for (index, (pollable, slide)) in self.pollables.iter_mut().enumerate() {
let slide = *slide;
let (effect, remove) = match pollable.poll() {
PollableState::Unmodified => (None, false),
PollableState::Modified => (Some(PollableEffect::RefreshSlide(slide)), false),
PollableState::Done => (Some(PollableEffect::RefreshSlide(slide)), true),
PollableState::Failed { error } => (Some(PollableEffect::DisplayError { slide, error }), true),
};
if let Some(effect) = effect {
let _ = self.sender.send(effect);
}
if remove {
removables.push(index);
}
}
// Walk back and swap remove to avoid invalidating indexes.
for index in removables.iter().rev() {
self.pollables.swap_remove(*index);
}
}
}

View File

@ -1,48 +1,32 @@
use crate::{
code::execute::SnippetExecutor,
commands::{
listener::{Command, CommandListener},
speaker_notes::{SpeakerNotesEvent, SpeakerNotesEventPublisher},
},
config::{KeyBindingsConfig, SlideTransitionConfig, SlideTransitionStyleConfig},
custom::KeyBindingsConfig,
diff::PresentationDiffer,
execute::SnippetExecutor,
export::ImageReplacer,
input::source::{Command, CommandSource},
markdown::parse::{MarkdownParser, ParseError},
presentation::{
Presentation, Slide,
builder::{BuildError, PresentationBuilder, PresentationBuilderOptions, Themes},
diff::PresentationDiffer,
poller::{PollableEffect, Poller, PollerCommand},
},
media::{printer::ImagePrinter, register::ImageRegistry},
presentation::{Presentation, RenderAsyncState},
processing::builder::{BuildError, PresentationBuilder, PresentationBuilderOptions, Themes},
render::{
ErrorSource, RenderError, RenderResult, TerminalDrawer, TerminalDrawerOptions,
ascii_scaler::AsciiScaler,
engine::{MaxSize, RenderEngine, RenderEngineOptions},
operation::{Pollable, RenderAsyncStartPolicy, RenderOperation},
draw::{ErrorSource, RenderError, RenderResult, TerminalDrawer},
properties::WindowSize,
validate::OverflowValidator,
},
resource::Resources,
terminal::{
image::printer::{ImagePrinter, ImageRegistry},
printer::{TerminalCommand, TerminalIo},
virt::{ImageBehavior, TerminalGrid, VirtualTerminal},
},
theme::{ProcessingThemeError, raw::PresentationTheme},
theme::PresentationTheme,
third_party::ThirdPartyRender,
transitions::{
AnimateTransition, AnimationFrame, LinesFrame, TransitionDirection,
collapse_horizontal::CollapseHorizontalAnimation, fade::FadeAnimation,
slide_horizontal::SlideHorizontalAnimation,
},
};
use std::{
collections::HashSet,
fmt::Display,
fs,
io::{self},
io::{self, Stdout},
mem,
ops::Deref,
path::Path,
rc::Rc,
sync::Arc,
time::{Duration, Instant},
};
pub struct PresenterOptions {
@ -51,8 +35,6 @@ pub struct PresenterOptions {
pub font_size_fallback: u8,
pub bindings: KeyBindingsConfig,
pub validate_overflows: bool,
pub max_size: MaxSize,
pub transition: Option<SlideTransitionConfig>,
}
/// A slideshow presenter.
@ -60,17 +42,16 @@ pub struct PresenterOptions {
/// This type puts everything else together.
pub struct Presenter<'a> {
default_theme: &'a PresentationTheme,
listener: CommandListener,
commands: CommandSource,
parser: MarkdownParser<'a>,
resources: Resources,
third_party: ThirdPartyRender,
code_executor: Arc<SnippetExecutor>,
code_executor: Rc<SnippetExecutor>,
state: PresenterState,
slides_with_pending_async_renders: HashSet<usize>,
image_printer: Arc<ImagePrinter>,
themes: Themes,
options: PresenterOptions,
speaker_notes_event_publisher: Option<SpeakerNotesEventPublisher>,
poller: Poller,
}
impl<'a> Presenter<'a> {
@ -78,29 +59,27 @@ impl<'a> Presenter<'a> {
#[allow(clippy::too_many_arguments)]
pub fn new(
default_theme: &'a PresentationTheme,
listener: CommandListener,
commands: CommandSource,
parser: MarkdownParser<'a>,
resources: Resources,
third_party: ThirdPartyRender,
code_executor: Arc<SnippetExecutor>,
code_executor: Rc<SnippetExecutor>,
themes: Themes,
image_printer: Arc<ImagePrinter>,
options: PresenterOptions,
speaker_notes_event_publisher: Option<SpeakerNotesEventPublisher>,
) -> Self {
Self {
default_theme,
listener,
commands,
parser,
resources,
third_party,
code_executor,
state: PresenterState::Empty,
slides_with_pending_async_renders: HashSet::new(),
image_printer,
themes,
options,
speaker_notes_event_publisher,
poller: Poller::launch(),
}
}
@ -110,23 +89,26 @@ impl<'a> Presenter<'a> {
self.resources.watch_presentation_file(path.to_path_buf());
}
self.state = PresenterState::Presenting(Presentation::from(vec![]));
self.try_reload(path, true)?;
self.try_reload(path, true);
let drawer_options = TerminalDrawerOptions {
font_size_fallback: self.options.font_size_fallback,
max_size: self.options.max_size.clone(),
};
let mut drawer = TerminalDrawer::new(self.image_printer.clone(), drawer_options)?;
let mut drawer =
TerminalDrawer::new(io::stdout(), self.image_printer.clone(), self.options.font_size_fallback)?;
loop {
if matches!(self.options.mode, PresentMode::Export) {
if let PresenterState::Failure { error, .. } = &self.state {
return Err(PresentationError::Fatal(format!("failed to run presentation: {error}")));
}
}
// Poll async renders once before we draw just in case.
self.poll_async_renders()?;
self.render(&mut drawer)?;
loop {
if self.process_poller_effects()? {
if self.poll_async_renders()? {
self.render(&mut drawer)?;
}
let command = match self.listener.try_next_command()? {
let command = match self.commands.try_next_command()? {
Some(command) => command,
_ => match self.resources.resources_modified() {
true => Command::Reload,
@ -139,76 +121,24 @@ impl<'a> Presenter<'a> {
},
};
match self.apply_command(command) {
CommandSideEffect::Exit => {
self.publish_event(SpeakerNotesEvent::Exit)?;
return Ok(());
}
CommandSideEffect::Exit => return Ok(()),
CommandSideEffect::Suspend => {
self.suspend(&mut drawer);
break;
}
CommandSideEffect::Reload => {
self.try_reload(path, false)?;
self.try_reload(path, false);
break;
}
CommandSideEffect::Redraw => {
self.try_scale_transition_images()?;
break;
}
CommandSideEffect::AnimateNextSlide => {
self.animate_next_slide(&mut drawer)?;
break;
}
CommandSideEffect::AnimatePreviousSlide => {
self.animate_previous_slide(&mut drawer)?;
break;
}
CommandSideEffect::None => (),
};
}
self.publish_event(SpeakerNotesEvent::GoToSlide {
slide: self.state.presentation().current_slide_index() as u32 + 1,
})?;
}
}
fn process_poller_effects(&mut self) -> Result<bool, PresentationError> {
let current_slide = match &self.state {
PresenterState::Presenting(presentation)
| PresenterState::SlideIndex(presentation)
| PresenterState::KeyBindings(presentation)
| PresenterState::Failure { presentation, .. } => presentation.current_slide_index(),
PresenterState::Empty => usize::MAX,
};
let mut refreshed = false;
let mut needs_render = false;
while let Some(effect) = self.poller.next_effect() {
match effect {
PollableEffect::RefreshSlide(index) => {
needs_render = needs_render || index == current_slide;
refreshed = true;
}
PollableEffect::DisplayError { slide, error } => {
let presentation = mem::take(&mut self.state).into_presentation();
self.state =
PresenterState::failure(error, presentation, ErrorSource::Slide(slide + 1), FailureMode::Other);
needs_render = true;
}
}
}
if refreshed {
self.try_scale_transition_images()?;
}
Ok(needs_render)
}
fn publish_event(&self, event: SpeakerNotesEvent) -> io::Result<()> {
if let Some(publisher) = &self.speaker_notes_event_publisher {
publisher.send(event)?;
}
Ok(())
}
fn check_async_error(&mut self) -> bool {
let error_holder = self.state.presentation().state.async_error_holder();
let error_holder = error_holder.lock().unwrap();
@ -227,18 +157,37 @@ impl<'a> Presenter<'a> {
}
}
fn render(&mut self, drawer: &mut TerminalDrawer) -> RenderResult {
fn poll_async_renders(&mut self) -> Result<bool, RenderError> {
if matches!(self.state, PresenterState::Failure { .. }) {
return Ok(false);
}
let current_index = self.state.presentation().current_slide_index();
if self.slides_with_pending_async_renders.contains(&current_index) {
let state = self.state.presentation_mut().poll_slide_async_renders();
match state {
RenderAsyncState::NotStarted | RenderAsyncState::Rendering { modified: false } => (),
RenderAsyncState::Rendering { modified: true } => {
return Ok(true);
}
RenderAsyncState::Rendered | RenderAsyncState::JustFinishedRendering => {
self.slides_with_pending_async_renders.remove(&current_index);
return Ok(true);
}
};
}
Ok(false)
}
fn render(&mut self, drawer: &mut TerminalDrawer<Stdout>) -> RenderResult {
let result = match &self.state {
PresenterState::Presenting(presentation) => {
drawer.render_operations(presentation.current_slide().iter_visible_operations())
}
PresenterState::Presenting(presentation) => drawer.render_slide(presentation),
PresenterState::SlideIndex(presentation) => {
drawer.render_operations(presentation.current_slide().iter_visible_operations())?;
drawer.render_operations(presentation.iter_slide_index_operations())
drawer.render_slide(presentation)?;
drawer.render_slide_index(presentation)
}
PresenterState::KeyBindings(presentation) => {
drawer.render_operations(presentation.current_slide().iter_visible_operations())?;
drawer.render_operations(presentation.iter_bindings_operations())
drawer.render_slide(presentation)?;
drawer.render_key_bindings(presentation)
}
PresenterState::Failure { error, source, .. } => drawer.render_error(error, source),
PresenterState::Empty => panic!("cannot render without state"),
@ -282,37 +231,16 @@ impl<'a> Presenter<'a> {
}
};
let needs_redraw = match command {
Command::Next => {
let current_slide = presentation.current_slide_index();
if !presentation.jump_next() {
false
} else if presentation.current_slide_index() != current_slide {
return CommandSideEffect::AnimateNextSlide;
} else {
true
}
}
Command::Next => presentation.jump_next(),
Command::NextFast => presentation.jump_next_fast(),
Command::Previous => {
let current_slide = presentation.current_slide_index();
if !presentation.jump_previous() {
false
} else if presentation.current_slide_index() != current_slide {
return CommandSideEffect::AnimatePreviousSlide;
} else {
true
}
}
Command::Previous => presentation.jump_previous(),
Command::PreviousFast => presentation.jump_previous_fast(),
Command::FirstSlide => presentation.jump_first_slide(),
Command::LastSlide => presentation.jump_last_slide(),
Command::GoToSlide(number) => presentation.go_to_slide(number.saturating_sub(1) as usize),
Command::RenderAsyncOperations => {
let pollables = Self::trigger_slide_async_renders(presentation);
if !pollables.is_empty() {
for pollable in pollables {
self.poller.send(PollerCommand::Poll { pollable, slide: presentation.current_slide_index() });
}
if presentation.trigger_slide_async_renders() {
self.slides_with_pending_async_renders.insert(self.state.presentation().current_slide_index());
return CommandSideEffect::Redraw;
} else {
return CommandSideEffect::None;
@ -339,11 +267,11 @@ impl<'a> Presenter<'a> {
if needs_redraw { CommandSideEffect::Redraw } else { CommandSideEffect::None }
}
fn try_reload(&mut self, path: &Path, force: bool) -> RenderResult {
fn try_reload(&mut self, path: &Path, force: bool) {
if matches!(self.options.mode, PresentMode::Presentation) && !force {
return Ok(());
return;
}
self.poller.send(PollerCommand::Reset);
self.slides_with_pending_async_renders.clear();
self.resources.clear_watches();
match self.load_presentation(path) {
Ok(mut presentation) => {
@ -355,40 +283,22 @@ impl<'a> Presenter<'a> {
presentation.go_to_slide(current.current_slide_index());
presentation.jump_chunk(current.current_chunk());
}
self.start_automatic_async_renders(&mut presentation);
self.slides_with_pending_async_renders = match self.options.mode {
PresentMode::Development | PresentMode::Presentation => {
presentation.slides_with_async_renders().into_iter().collect()
}
// Trigger all async renders so we get snippet execution output in the PDF
// file.
PresentMode::Export => presentation.trigger_all_async_renders(),
};
self.state = self.validate_overflows(presentation);
self.try_scale_transition_images()?;
}
Err(e) => {
let presentation = mem::take(&mut self.state).into_presentation();
self.state = PresenterState::failure(e, presentation, ErrorSource::Presentation, FailureMode::Other);
}
};
Ok(())
}
fn try_scale_transition_images(&self) -> RenderResult {
if self.options.transition.is_none() {
return Ok(());
}
let options = RenderEngineOptions { max_size: self.options.max_size.clone(), ..Default::default() };
let scaler = AsciiScaler::new(options);
let dimensions = WindowSize::current(self.options.font_size_fallback)?;
scaler.process(self.state.presentation(), &dimensions)?;
Ok(())
}
fn trigger_slide_async_renders(presentation: &mut Presentation) -> Vec<Box<dyn Pollable>> {
let slide = presentation.current_slide_mut();
let mut pollables = Vec::new();
for operation in slide.iter_visible_operations_mut() {
if let RenderOperation::RenderAsync(operation) = operation {
if let RenderAsyncStartPolicy::OnDemand = operation.start_policy() {
pollables.push(operation.pollable());
}
}
}
pollables
}
fn is_displaying_other_error(&self) -> bool {
@ -415,17 +325,22 @@ impl<'a> Presenter<'a> {
fn load_presentation(&mut self, path: &Path) -> Result<Presentation, LoadPresentationError> {
let content = fs::read_to_string(path).map_err(LoadPresentationError::Reading)?;
let elements = self.parser.parse(&content)?;
let presentation = PresentationBuilder::new(
let export_mode = matches!(self.options.mode, PresentMode::Export);
let mut presentation = PresentationBuilder::new(
self.default_theme,
self.resources.clone(),
&mut self.resources,
&mut self.third_party,
self.code_executor.clone(),
&self.themes,
ImageRegistry::new(self.image_printer.clone()),
ImageRegistry(self.image_printer.clone()),
self.options.bindings.clone(),
self.options.builder_options.clone(),
)?
)
.build(elements)?;
if export_mode {
ImageReplacer::default().replace_presentation_images(&mut presentation);
}
Ok(presentation)
}
@ -451,7 +366,7 @@ impl<'a> Presenter<'a> {
}
}
fn suspend(&self, drawer: &mut TerminalDrawer) {
fn suspend(&self, drawer: &mut TerminalDrawer<Stdout>) {
#[cfg(unix)]
unsafe {
drawer.terminal.suspend();
@ -459,140 +374,6 @@ impl<'a> Presenter<'a> {
drawer.terminal.resume();
}
}
fn animate_next_slide(&mut self, drawer: &mut TerminalDrawer) -> RenderResult {
let Some(config) = self.options.transition.clone() else {
return Ok(());
};
let options = drawer.render_engine_options();
let presentation = self.state.presentation_mut();
let dimensions = WindowSize::current(self.options.font_size_fallback)?;
presentation.jump_previous();
let left = Self::virtual_render(presentation.current_slide(), dimensions.clone(), &options)?;
presentation.jump_next();
let right = Self::virtual_render(presentation.current_slide(), dimensions.clone(), &options)?;
let direction = TransitionDirection::Next;
self.animate_transition(drawer, left, right, direction, dimensions, config)
}
fn animate_previous_slide(&mut self, drawer: &mut TerminalDrawer) -> RenderResult {
let Some(config) = self.options.transition.clone() else {
return Ok(());
};
let options = drawer.render_engine_options();
let presentation = self.state.presentation_mut();
let dimensions = WindowSize::current(self.options.font_size_fallback)?;
presentation.jump_next();
// Re-borrow to avoid calling fns above while mutably borrowing
let presentation = self.state.presentation_mut();
let right = Self::virtual_render(presentation.current_slide(), dimensions.clone(), &options)?;
presentation.jump_previous();
let left = Self::virtual_render(presentation.current_slide(), dimensions.clone(), &options)?;
let direction = TransitionDirection::Previous;
self.animate_transition(drawer, left, right, direction, dimensions, config)
}
fn animate_transition(
&mut self,
drawer: &mut TerminalDrawer,
left: TerminalGrid,
right: TerminalGrid,
direction: TransitionDirection,
dimensions: WindowSize,
config: SlideTransitionConfig,
) -> RenderResult {
let first = match &direction {
TransitionDirection::Next => left.clone(),
TransitionDirection::Previous => right.clone(),
};
match &config.animation {
SlideTransitionStyleConfig::SlideHorizontal => self.run_animation(
drawer,
first,
SlideHorizontalAnimation::new(left, right, dimensions, direction),
config,
),
SlideTransitionStyleConfig::Fade => {
self.run_animation(drawer, first, FadeAnimation::new(left, right, direction), config)
}
SlideTransitionStyleConfig::CollapseHorizontal => {
self.run_animation(drawer, first, CollapseHorizontalAnimation::new(left, right, direction), config)
}
}
}
fn run_animation<T>(
&mut self,
drawer: &mut TerminalDrawer,
first: TerminalGrid,
animation: T,
config: SlideTransitionConfig,
) -> RenderResult
where
T: AnimateTransition,
{
let total_time = Duration::from_millis(config.duration_millis as u64);
let frames: usize = config.frames;
let total_frames = animation.total_frames();
let step = total_time / (frames as u32 * 2);
let mut last_frame_index = 0;
let mut frame_index = 1;
// Render the first frame as text to have images as ascii
Self::render_frame(&LinesFrame::from(&first).build_commands(), drawer)?;
while frame_index < total_frames {
let start = Instant::now();
let frame = animation.build_frame(frame_index, last_frame_index);
let commands = frame.build_commands();
Self::render_frame(&commands, drawer)?;
let elapsed = start.elapsed();
let sleep_needed = step.saturating_sub(elapsed);
if sleep_needed.as_millis() > 0 {
std::thread::sleep(step);
}
last_frame_index = frame_index;
frame_index += total_frames.div_ceil(frames);
}
Ok(())
}
fn render_frame(commands: &[TerminalCommand<'_>], drawer: &mut TerminalDrawer) -> RenderResult {
drawer.terminal.execute(&TerminalCommand::BeginUpdate)?;
for command in commands {
drawer.terminal.execute(command)?;
}
drawer.terminal.execute(&TerminalCommand::EndUpdate)?;
drawer.terminal.execute(&TerminalCommand::Flush)?;
Ok(())
}
fn virtual_render(
slide: &Slide,
dimensions: WindowSize,
options: &RenderEngineOptions,
) -> Result<TerminalGrid, RenderError> {
let mut term = VirtualTerminal::new(dimensions.clone(), ImageBehavior::PrintAscii);
let engine = RenderEngine::new(&mut term, dimensions.clone(), options.clone());
engine.render(slide.iter_visible_operations())?;
Ok(term.into_contents())
}
fn start_automatic_async_renders(&self, presentation: &mut Presentation) {
for (index, slide) in presentation.iter_slides_mut().enumerate() {
for operation in slide.iter_operations_mut() {
if let RenderOperation::RenderAsync(operation) = operation {
if let RenderAsyncStartPolicy::Automatic = operation.start_policy() {
let pollable = operation.pollable();
self.poller.send(PollerCommand::Poll { pollable, slide: index });
}
}
}
}
}
}
enum CommandSideEffect {
@ -600,8 +381,6 @@ enum CommandSideEffect {
Suspend,
Redraw,
Reload,
AnimateNextSlide,
AnimatePreviousSlide,
None,
}
@ -673,6 +452,9 @@ pub enum PresentMode {
/// This is a live presentation so we don't want hot reloading.
Presentation,
/// We are running a presentation that's being consumed by `presenterm-export`.
Export,
}
/// An error when loading a presentation.
@ -686,9 +468,6 @@ pub enum LoadPresentationError {
#[error(transparent)]
Processing(#[from] BuildError),
#[error("processing theme: {0}")]
ProcessingTheme(#[from] ProcessingThemeError),
}
/// An error during the presentation.
@ -699,4 +478,7 @@ pub enum PresentationError {
#[error("io: {0}")]
Io(#[from] io::Error),
#[error("fatal error: {0}")]
Fatal(String),
}

File diff suppressed because it is too large Load Diff

View File

@ -1,50 +1,49 @@
use super::{
highlighting::{LanguageHighlighter, StyledTokens},
padding::NumberPadder,
};
use super::padding::NumberPadder;
use crate::{
PresentationTheme,
markdown::{
elements::{Percent, PercentParseError},
text::{WeightedLine, WeightedText},
text_style::{Color, TextStyle},
text::{WeightedText, WeightedTextBlock},
},
presentation::ChunkMutator,
presentation::{AsRenderOperations, BlockLine, ChunkMutator, RenderOperation},
render::{
operation::{AsRenderOperations, BlockLine, RenderOperation},
highlighting::{LanguageHighlighter, StyledTokens},
properties::WindowSize,
},
style::{Color, TextStyle},
theme::{Alignment, CodeBlockStyle},
};
use serde::Deserialize;
use serde_with::DeserializeFromStr;
use std::{cell::RefCell, convert::Infallible, fmt::Write, ops::Range, path::PathBuf, rc::Rc, str::FromStr};
use strum::{EnumDiscriminants, EnumIter};
use unicode_width::UnicodeWidthStr;
pub(crate) struct SnippetSplitter<'a> {
style: &'a CodeBlockStyle,
pub(crate) struct CodePreparer<'a> {
theme: &'a PresentationTheme,
hidden_line_prefix: Option<&'a str>,
}
impl<'a> SnippetSplitter<'a> {
pub(crate) fn new(style: &'a CodeBlockStyle, hidden_line_prefix: Option<&'a str>) -> Self {
Self { style, hidden_line_prefix }
impl<'a> CodePreparer<'a> {
pub(crate) fn new(theme: &'a PresentationTheme, hidden_line_prefix: Option<&'a str>) -> Self {
Self { theme, hidden_line_prefix }
}
pub(crate) fn split(&self, code: &Snippet) -> Vec<SnippetLine> {
pub(crate) fn prepare(&self, code: &Snippet) -> Vec<CodeLine> {
let mut lines = Vec::new();
let horizontal_padding = self.style.padding.horizontal;
let vertical_padding = self.style.padding.vertical;
let horizontal_padding = self.theme.code.padding.horizontal.unwrap_or(0);
let vertical_padding = self.theme.code.padding.vertical.unwrap_or(0);
if vertical_padding > 0 {
lines.push(SnippetLine::empty());
lines.push(CodeLine::empty());
}
self.push_lines(code, horizontal_padding, &mut lines);
if vertical_padding > 0 {
lines.push(SnippetLine::empty());
lines.push(CodeLine::empty());
}
lines
}
fn push_lines(&self, code: &Snippet, horizontal_padding: u8, lines: &mut Vec<SnippetLine>) {
fn push_lines(&self, code: &Snippet, horizontal_padding: u8, lines: &mut Vec<CodeLine>) {
if code.contents.is_empty() {
return;
}
@ -61,19 +60,19 @@ impl<'a> SnippetSplitter<'a> {
}
line.push('\n');
let line_number = Some(index as u16 + 1);
lines.push(SnippetLine { prefix, code: line, right_padding_length: padding.len() as u16, line_number });
lines.push(CodeLine { prefix, code: line, right_padding_length: padding.len() as u16, line_number });
}
}
}
pub(crate) struct SnippetLine {
pub(crate) struct CodeLine {
pub(crate) prefix: String,
pub(crate) code: String,
pub(crate) right_padding_length: u16,
pub(crate) line_number: Option<u16>,
}
impl SnippetLine {
impl CodeLine {
pub(crate) fn empty() -> Self {
Self { prefix: String::new(), code: "\n".into(), right_padding_length: 0, line_number: None }
}
@ -86,14 +85,11 @@ impl SnippetLine {
&self,
code_highlighter: &mut LanguageHighlighter,
block_style: &CodeBlockStyle,
font_size: u8,
) -> WeightedLine {
let mut line = code_highlighter.highlight_line(&self.code, block_style);
line.apply_style(&TextStyle::default().size(font_size));
line.into()
) -> WeightedTextBlock {
code_highlighter.highlight_line(&self.code, block_style).0.into()
}
pub(crate) fn dim(&self, dim_style: &TextStyle) -> WeightedLine {
pub(crate) fn dim(&self, dim_style: &TextStyle) -> WeightedTextBlock {
let output = vec![StyledTokens { style: *dim_style, tokens: &self.code }.apply_style()];
output.into()
}
@ -108,7 +104,7 @@ impl SnippetLine {
pub(crate) struct HighlightContext {
pub(crate) groups: Vec<HighlightGroup>,
pub(crate) current: usize,
pub(crate) block_length: u16,
pub(crate) block_length: usize,
pub(crate) alignment: Alignment,
}
@ -116,8 +112,8 @@ pub(crate) struct HighlightContext {
pub(crate) struct HighlightedLine {
pub(crate) prefix: WeightedText,
pub(crate) right_padding_length: u16,
pub(crate) highlighted: WeightedLine,
pub(crate) not_highlighted: WeightedLine,
pub(crate) highlighted: WeightedTextBlock,
pub(crate) not_highlighted: WeightedTextBlock,
pub(crate) line_number: Option<u16>,
pub(crate) context: Rc<RefCell<HighlightContext>>,
pub(crate) block_color: Option<Color>,
@ -139,8 +135,8 @@ impl AsRenderOperations for HighlightedLine {
right_padding_length: self.right_padding_length,
repeat_prefix_on_wrap: false,
text,
block_length: context.block_length,
alignment: context.alignment,
block_length: context.block_length as u16,
alignment: context.alignment.clone(),
block_color: self.block_color,
}),
RenderOperation::RenderLineBreak,
@ -195,11 +191,11 @@ impl ChunkMutator for HighlightMutator {
}
}
pub(crate) type ParseResult<T> = Result<T, SnippetBlockParseError>;
pub(crate) type ParseResult<T> = Result<T, CodeBlockParseError>;
pub(crate) struct SnippetParser;
pub(crate) struct CodeBlockParser;
impl SnippetParser {
impl CodeBlockParser {
pub(crate) fn parse(info: String, code: String) -> ParseResult<Snippet> {
let (language, attributes) = Self::parse_block_info(&info)?;
let code = Snippet { contents: code, language, attributes };
@ -209,8 +205,8 @@ impl SnippetParser {
fn parse_block_info(input: &str) -> ParseResult<(SnippetLanguage, SnippetAttributes)> {
let (language, input) = Self::parse_language(input);
let attributes = Self::parse_attributes(input)?;
if attributes.width.is_some() && !matches!(attributes.representation, SnippetRepr::Render) {
return Err(SnippetBlockParseError::NotRenderSnippet("width"));
if attributes.width.is_some() && !attributes.auto_render {
return Err(CodeBlockParseError::NotRenderSnippet("width"));
}
Ok((language, attributes))
}
@ -227,34 +223,19 @@ impl SnippetParser {
let mut attributes = SnippetAttributes::default();
let mut processed_attributes = Vec::new();
while let (Some(attribute), rest) = Self::parse_attribute(input)? {
let discriminant = SnippetAttributeDiscriminants::from(&attribute);
let discriminant = AttributeDiscriminants::from(&attribute);
if processed_attributes.contains(&discriminant) {
return Err(SnippetBlockParseError::DuplicateAttribute("duplicate attribute"));
return Err(CodeBlockParseError::DuplicateAttribute("duplicate attribute"));
}
use SnippetAttribute::*;
match attribute {
ExecReplace | Image | Render if attributes.representation != SnippetRepr::Snippet => {
return Err(SnippetBlockParseError::MultipleRepresentation);
}
LineNumbers => attributes.line_numbers = true,
Exec => {
if attributes.execution != SnippetExec::AcquireTerminal {
attributes.execution = SnippetExec::Exec;
}
}
ExecReplace => {
attributes.representation = SnippetRepr::ExecReplace;
attributes.execution = SnippetExec::Exec;
}
Image => {
attributes.representation = SnippetRepr::Image;
attributes.execution = SnippetExec::Exec;
}
Render => attributes.representation = SnippetRepr::Render,
AcquireTerminal => attributes.execution = SnippetExec::AcquireTerminal,
NoBackground => attributes.no_background = true,
HighlightedLines(lines) => attributes.highlight_groups = lines,
Width(width) => attributes.width = Some(width),
Attribute::LineNumbers => attributes.line_numbers = true,
Attribute::Exec => attributes.execute = true,
Attribute::ExecReplace => attributes.execute_replace = true,
Attribute::AutoRender => attributes.auto_render = true,
Attribute::NoBackground => attributes.no_background = true,
Attribute::AcquireTerminal => attributes.acquire_terminal = true,
Attribute::HighlightedLines(lines) => attributes.highlight_groups = lines,
Attribute::Width(width) => attributes.width = Some(width),
};
processed_attributes.push(discriminant);
input = rest;
@ -265,40 +246,39 @@ impl SnippetParser {
Ok(attributes)
}
fn parse_attribute(input: &str) -> ParseResult<(Option<SnippetAttribute>, &str)> {
fn parse_attribute(input: &str) -> ParseResult<(Option<Attribute>, &str)> {
let input = Self::skip_whitespace(input);
let (attribute, input) = match input.chars().next() {
Some('+') => {
let token = Self::next_identifier(&input[1..]);
let attribute = match token {
"line_numbers" => SnippetAttribute::LineNumbers,
"exec" => SnippetAttribute::Exec,
"exec_replace" => SnippetAttribute::ExecReplace,
"image" => SnippetAttribute::Image,
"render" => SnippetAttribute::Render,
"no_background" => SnippetAttribute::NoBackground,
"acquire_terminal" => SnippetAttribute::AcquireTerminal,
"line_numbers" => Attribute::LineNumbers,
"exec" => Attribute::Exec,
"exec_replace" => Attribute::ExecReplace,
"render" => Attribute::AutoRender,
"no_background" => Attribute::NoBackground,
"acquire_terminal" => Attribute::AcquireTerminal,
token if token.starts_with("width:") => {
let value = input.split_once("+width:").unwrap().1;
let (width, input) = Self::parse_width(value)?;
return Ok((Some(SnippetAttribute::Width(width)), input));
return Ok((Some(Attribute::Width(width)), input));
}
_ => return Err(SnippetBlockParseError::InvalidToken(Self::next_identifier(input).into())),
_ => return Err(CodeBlockParseError::InvalidToken(Self::next_identifier(input).into())),
};
(Some(attribute), &input[token.len() + 1..])
}
Some('{') => {
let (lines, input) = Self::parse_highlight_groups(&input[1..])?;
(Some(SnippetAttribute::HighlightedLines(lines)), input)
(Some(Attribute::HighlightedLines(lines)), input)
}
Some(_) => return Err(SnippetBlockParseError::InvalidToken(Self::next_identifier(input).into())),
Some(_) => return Err(CodeBlockParseError::InvalidToken(Self::next_identifier(input).into())),
None => (None, input),
};
Ok((attribute, input))
}
fn parse_highlight_groups(input: &str) -> ParseResult<(Vec<HighlightGroup>, &str)> {
use SnippetBlockParseError::InvalidHighlightedLines;
use CodeBlockParseError::InvalidHighlightedLines;
let Some((head, tail)) = input.split_once('}') else {
return Err(InvalidHighlightedLines("no enclosing '}'".into()));
};
@ -327,9 +307,9 @@ impl SnippetParser {
Some((left, right)) => {
let left = Self::parse_number(left)?;
let right = Self::parse_number(right)?;
let right = right.checked_add(1).ok_or_else(|| {
SnippetBlockParseError::InvalidHighlightedLines(format!("{right} is too large"))
})?;
let right = right
.checked_add(1)
.ok_or_else(|| CodeBlockParseError::InvalidHighlightedLines(format!("{right} is too large")))?;
highlights.push(Highlight::Range(left..right));
}
None => {
@ -345,12 +325,12 @@ impl SnippetParser {
input
.trim()
.parse()
.map_err(|_| SnippetBlockParseError::InvalidHighlightedLines(format!("not a number: '{input}'")))
.map_err(|_| CodeBlockParseError::InvalidHighlightedLines(format!("not a number: '{input}'")))
}
fn parse_width(input: &str) -> ParseResult<(Percent, &str)> {
let end_index = input.find(' ').unwrap_or(input.len());
let value = input[0..end_index].parse().map_err(SnippetBlockParseError::InvalidWidth)?;
let value = input[0..end_index].parse().map_err(CodeBlockParseError::InvalidWidth)?;
Ok((value, &input[end_index..]))
}
@ -367,7 +347,7 @@ impl SnippetParser {
}
#[derive(thiserror::Error, Debug)]
pub enum SnippetBlockParseError {
pub enum CodeBlockParseError {
#[error("invalid code attribute: {0}")]
InvalidToken(String),
@ -380,20 +360,16 @@ pub enum SnippetBlockParseError {
#[error("duplicate attribute: {0}")]
DuplicateAttribute(&'static str),
#[error("+exec_replace +image and +render can't be used together ")]
MultipleRepresentation,
#[error("attribute {0} can only be set in +render blocks")]
NotRenderSnippet(&'static str),
}
#[derive(EnumDiscriminants)]
enum SnippetAttribute {
enum Attribute {
LineNumbers,
Exec,
ExecReplace,
Image,
Render,
AutoRender,
HighlightedLines(Vec<HighlightGroup>),
Width(Percent),
NoBackground,
@ -438,8 +414,7 @@ impl Snippet {
}
/// The language of a code snippet.
#[derive(Clone, Debug, PartialEq, Eq, EnumIter, PartialOrd, Ord)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, EnumIter, PartialOrd, Ord, DeserializeFromStr)]
pub enum SnippetLanguage {
Ada,
Asp,
@ -463,13 +438,11 @@ pub enum SnippetLanguage {
File,
Fish,
Go,
GraphQL,
Haskell,
Html,
Java,
JavaScript,
Json,
Julia,
Kotlin,
Latex,
Lua,
@ -494,7 +467,6 @@ pub enum SnippetLanguage {
Sql,
Swift,
Svelte,
Tcl,
Terraform,
Toml,
TypeScript,
@ -502,14 +474,11 @@ pub enum SnippetLanguage {
Unknown(String),
Xml,
Yaml,
Verilog,
Vue,
Zig,
Zsh,
}
crate::utils::impl_deserialize_from_str!(SnippetLanguage);
impl FromStr for SnippetLanguage {
type Err = Infallible;
@ -537,13 +506,11 @@ impl FromStr for SnippetLanguage {
"file" => File,
"fish" => Fish,
"go" => Go,
"graphql" => GraphQL,
"haskell" => Haskell,
"html" => Html,
"java" => Java,
"javascript" | "js" => JavaScript,
"json" => Json,
"julia" => Julia,
"kotlin" => Kotlin,
"latex" => Latex,
"lua" => Lua,
@ -568,14 +535,12 @@ impl FromStr for SnippetLanguage {
"sql" => Sql,
"svelte" => Svelte,
"swift" => Swift,
"tcl" => Tcl,
"terraform" => Terraform,
"toml" => Toml,
"typescript" | "ts" => TypeScript,
"typst" => Typst,
"xml" => Xml,
"yaml" => Yaml,
"verilog" => Verilog,
"vue" => Vue,
"zig" => Zig,
"zsh" => Zsh,
@ -588,11 +553,18 @@ impl FromStr for SnippetLanguage {
/// Attributes for code snippets.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct SnippetAttributes {
/// The way the snippet should be represented.
pub(crate) representation: SnippetRepr,
/// Whether the snippet is marked as executable.
pub(crate) execute: bool,
/// The way the snippet should be executed.
pub(crate) execution: SnippetExec,
/// Whether the snippet is marked as an executable block that will be replaced with the output
/// of its execution.
pub(crate) execute_replace: bool,
/// Whether a snippet is marked to be auto rendered.
///
/// An auto rendered snippet is transformed during parsing, leading to some visual
/// representation of it being shown rather than the original code.
pub(crate) auto_render: bool,
/// Whether the snippet should show line numbers.
pub(crate) line_numbers: bool,
@ -607,23 +579,9 @@ pub(crate) struct SnippetAttributes {
/// Whether to add no background to a snippet.
pub(crate) no_background: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) enum SnippetRepr {
#[default]
Snippet,
Image,
Render,
ExecReplace,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) enum SnippetExec {
#[default]
None,
Exec,
AcquireTerminal,
/// Whether this code snippet acquires the terminal when ran.
pub(crate) acquire_terminal: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@ -659,8 +617,6 @@ pub(crate) enum Highlight {
pub(crate) struct ExternalFile {
pub(crate) path: PathBuf,
pub(crate) language: SnippetLanguage,
pub(crate) start_line: Option<usize>,
pub(crate) end_line: Option<usize>,
}
#[cfg(test)]
@ -670,12 +626,12 @@ mod test {
use rstest::rstest;
fn parse_language(input: &str) -> SnippetLanguage {
let (language, _) = SnippetParser::parse_block_info(input).expect("parse failed");
let (language, _) = CodeBlockParser::parse_block_info(input).expect("parse failed");
language
}
fn try_parse_attributes(input: &str) -> Result<SnippetAttributes, SnippetBlockParseError> {
let (_, attributes) = SnippetParser::parse_block_info(input)?;
fn try_parse_attributes(input: &str) -> Result<SnippetAttributes, CodeBlockParseError> {
let (_, attributes) = CodeBlockParser::parse_block_info(input)?;
Ok(attributes)
}
@ -692,7 +648,7 @@ mod test {
language: SnippetLanguage::Unknown("".to_string()),
attributes: SnippetAttributes { line_numbers: true, ..Default::default() },
};
let lines = SnippetSplitter::new(&Default::default(), None).split(&code);
let lines = CodePreparer::new(&Default::default(), None).prepare(&code);
assert_eq!(lines.len(), total_lines);
let mut lines = lines.into_iter().enumerate();
@ -721,37 +677,21 @@ mod test {
#[test]
fn one_attribute() {
let attributes = parse_attributes("bash +exec");
assert_eq!(attributes.execution, SnippetExec::Exec);
assert!(attributes.execute);
assert!(!attributes.line_numbers);
}
#[test]
fn two_attributes() {
let attributes = parse_attributes("bash +exec +line_numbers");
assert_eq!(attributes.execution, SnippetExec::Exec);
assert!(attributes.execute);
assert!(attributes.line_numbers);
}
#[test]
fn acquire_terminal() {
let attributes = parse_attributes("bash +acquire_terminal +exec");
assert_eq!(attributes.execution, SnippetExec::AcquireTerminal);
assert_eq!(attributes.representation, SnippetRepr::Snippet);
assert!(!attributes.line_numbers);
}
#[test]
fn image() {
let attributes = parse_attributes("bash +image +exec");
assert_eq!(attributes.execution, SnippetExec::Exec);
assert_eq!(attributes.representation, SnippetRepr::Image);
assert!(!attributes.line_numbers);
}
#[test]
fn invalid_attributes() {
SnippetParser::parse_block_info("bash +potato").unwrap_err();
SnippetParser::parse_block_info("bash potato").unwrap_err();
CodeBlockParser::parse_block_info("bash +potato").unwrap_err();
CodeBlockParser::parse_block_info("bash potato").unwrap_err();
}
#[rstest]
@ -767,7 +707,7 @@ mod test {
#[case::too_large_end("{1-65536}")]
fn invalid_line_highlights(#[case] input: &str) {
let input = format!("bash {input}");
SnippetParser::parse_block_info(&input).expect_err("parsed successfully");
CodeBlockParser::parse_block_info(&input).expect_err("parsed successfully");
}
#[test]
@ -785,10 +725,13 @@ mod test {
#[test]
fn highlight_line_range() {
let attributes = parse_attributes("bash { 1, 2-4,6 , all , 10 - 12 }");
assert_eq!(
attributes.highlight_groups,
&[HighlightGroup::new(vec![Single(1), Range(2..5), Single(6), All, Range(10..13)])]
);
assert_eq!(attributes.highlight_groups, &[HighlightGroup::new(vec![
Single(1),
Range(2..5),
Single(6),
All,
Range(10..13)
])]);
}
#[test]
@ -802,7 +745,7 @@ mod test {
#[test]
fn parse_width() {
let attributes = parse_attributes("mermaid +width:50% +render");
assert_eq!(attributes.representation, SnippetRepr::Render);
assert!(attributes.auto_render);
assert_eq!(attributes.width, Some(Percent(50)));
}
@ -850,7 +793,7 @@ println!("Hello world");
#[test]
fn tabs_in_snippet() {
let snippet = Snippet { contents: "\thi".into(), language: SnippetLanguage::C, attributes: Default::default() };
let lines = SnippetSplitter::new(&Default::default(), None).split(&snippet);
let lines = CodePreparer::new(&Default::default(), None).prepare(&snippet);
assert_eq!(lines[0].code, " hi\n");
}
}

363
src/processing/execution.rs Normal file
View File

@ -0,0 +1,363 @@
use crossterm::{
ExecutableCommand, cursor,
terminal::{self, disable_raw_mode, enable_raw_mode},
};
use super::separator::{RenderSeparator, SeparatorWidth};
use crate::{
PresentationTheme,
ansi::AnsiSplitter,
execute::{ExecutionHandle, ExecutionState, ProcessStatus, SnippetExecutor},
markdown::{
elements::{Text, TextBlock},
text::WeightedTextBlock,
},
presentation::{AsRenderOperations, BlockLine, RenderAsync, RenderAsyncState, RenderOperation},
processing::code::Snippet,
render::{properties::WindowSize, terminal::should_hide_cursor},
style::{Colors, TextStyle},
theme::{Alignment, ExecutionStatusBlockStyle, Margin},
};
use std::{
cell::RefCell,
io::{self},
mem,
ops::Deref,
rc::Rc,
};
const MINIMUM_SEPARATOR_WIDTH: u16 = 32;
#[derive(Debug)]
struct RunSnippetOperationInner {
handle: Option<ExecutionHandle>,
output_lines: Vec<WeightedTextBlock>,
state: RenderAsyncState,
max_line_length: u16,
starting_style: TextStyle,
}
#[derive(Debug)]
pub(crate) struct RunSnippetOperation {
code: Snippet,
executor: Rc<SnippetExecutor>,
default_colors: Colors,
block_colors: Colors,
status_colors: ExecutionStatusBlockStyle,
block_length: u16,
alignment: Alignment,
inner: Rc<RefCell<RunSnippetOperationInner>>,
state_description: RefCell<Text>,
separator: DisplaySeparator,
}
impl RunSnippetOperation {
pub(crate) fn new(
code: Snippet,
executor: Rc<SnippetExecutor>,
theme: &PresentationTheme,
block_length: u16,
separator: DisplaySeparator,
alignment: Alignment,
) -> Self {
let default_colors = theme.default_style.colors;
let block_colors = theme.execution_output.colors;
let status_colors = theme.execution_output.status.clone();
let not_started_colors = status_colors.not_started;
let block_length = match &alignment {
Alignment::Left { .. } | Alignment::Right { .. } => block_length,
Alignment::Center { minimum_size, .. } => block_length.max(*minimum_size),
};
let inner = RunSnippetOperationInner {
handle: None,
output_lines: Vec::new(),
state: RenderAsyncState::default(),
max_line_length: 0,
starting_style: TextStyle::default(),
};
Self {
code,
executor,
default_colors,
block_colors,
status_colors,
block_length,
alignment,
inner: Rc::new(RefCell::new(inner)),
state_description: Text::new("not started", TextStyle::default().colors(not_started_colors)).into(),
separator,
}
}
}
#[derive(Debug)]
pub(crate) enum DisplaySeparator {
On,
Off,
}
impl AsRenderOperations for RunSnippetOperation {
fn as_render_operations(&self, _dimensions: &WindowSize) -> Vec<RenderOperation> {
let inner = self.inner.borrow();
let description = self.state_description.borrow();
let mut operations = match self.separator {
DisplaySeparator::On => {
let heading = TextBlock(vec![" [".into(), description.clone(), "] ".into()]);
let separator_width = match &self.alignment {
Alignment::Left { .. } | Alignment::Right { .. } => SeparatorWidth::FitToWindow,
// We need a minimum here otherwise if the code/block length is too narrow, the separator is
// word-wrapped and looks bad.
Alignment::Center { .. } => SeparatorWidth::Fixed(self.block_length.max(MINIMUM_SEPARATOR_WIDTH)),
};
let separator = RenderSeparator::new(heading, separator_width);
vec![
RenderOperation::RenderLineBreak,
RenderOperation::RenderDynamic(Rc::new(separator)),
RenderOperation::RenderLineBreak,
]
}
DisplaySeparator::Off => vec![],
};
if matches!(inner.state, RenderAsyncState::NotStarted) {
return operations;
}
operations.extend([RenderOperation::RenderLineBreak, RenderOperation::SetColors(self.block_colors)]);
let has_margin = match &self.alignment {
Alignment::Left { margin } => !margin.is_empty(),
Alignment::Right { margin } => !margin.is_empty(),
Alignment::Center { minimum_margin, minimum_size } => !minimum_margin.is_empty() || minimum_size != &0,
};
let block_length =
if has_margin { self.block_length.max(inner.max_line_length) } else { inner.max_line_length };
for line in &inner.output_lines {
operations.push(RenderOperation::RenderBlockLine(BlockLine {
prefix: "".into(),
right_padding_length: 0,
repeat_prefix_on_wrap: false,
text: line.clone(),
block_length,
alignment: self.alignment.clone(),
block_color: self.block_colors.background,
}));
operations.push(RenderOperation::RenderLineBreak);
}
operations.push(RenderOperation::SetColors(self.default_colors));
operations
}
}
impl RenderAsync for RunSnippetOperation {
fn poll_state(&self) -> RenderAsyncState {
let mut inner = self.inner.borrow_mut();
if let Some(handle) = inner.handle.as_mut() {
let mut state = handle.state.lock().unwrap();
let ExecutionState { output, status } = &mut *state;
*self.state_description.borrow_mut() = match status {
ProcessStatus::Running => Text::new("running", TextStyle::default().colors(self.status_colors.running)),
ProcessStatus::Success => {
Text::new("finished", TextStyle::default().colors(self.status_colors.success))
}
ProcessStatus::Failure => {
Text::new("finished with error", TextStyle::default().colors(self.status_colors.failure))
}
};
let new_lines = mem::take(output);
let modified = !new_lines.is_empty();
let is_finished = status.is_finished();
drop(state);
let mut max_line_length = 0;
let (new_lines, style) = AnsiSplitter::new(inner.starting_style).split_lines(&new_lines);
for line in &new_lines {
let width = u16::try_from(line.width()).unwrap_or(u16::MAX);
max_line_length = max_line_length.max(width);
}
inner.starting_style = style;
if is_finished {
inner.handle.take();
inner.state = RenderAsyncState::JustFinishedRendering;
} else {
inner.state = RenderAsyncState::Rendering { modified };
}
inner.output_lines.extend(new_lines);
inner.max_line_length = inner.max_line_length.max(max_line_length);
}
inner.state.clone()
}
fn start_render(&self) -> bool {
let mut inner = self.inner.borrow_mut();
if !matches!(inner.state, RenderAsyncState::NotStarted) {
return false;
}
match self.executor.execute_async(&self.code) {
Ok(handle) => {
inner.handle = Some(handle);
inner.state = RenderAsyncState::Rendering { modified: false };
true
}
Err(e) => {
inner.output_lines = vec![WeightedTextBlock::from(e.to_string())];
inner.state = RenderAsyncState::Rendered;
true
}
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct SnippetExecutionDisabledOperation {
colors: Colors,
alignment: Alignment,
started: RefCell<bool>,
}
impl SnippetExecutionDisabledOperation {
pub(crate) fn new(colors: Colors, alignment: Alignment) -> Self {
Self { colors, alignment, started: Default::default() }
}
}
impl AsRenderOperations for SnippetExecutionDisabledOperation {
fn as_render_operations(&self, _: &WindowSize) -> Vec<RenderOperation> {
if !*self.started.borrow() {
return Vec::new();
}
vec![
RenderOperation::RenderLineBreak,
RenderOperation::RenderText {
line: vec![Text::new("snippet execution is disabled", TextStyle::default().colors(self.colors))].into(),
alignment: self.alignment.clone(),
},
RenderOperation::RenderLineBreak,
]
}
}
impl RenderAsync for SnippetExecutionDisabledOperation {
fn start_render(&self) -> bool {
let was_started = mem::replace(&mut *self.started.borrow_mut(), true);
!was_started
}
fn poll_state(&self) -> RenderAsyncState {
RenderAsyncState::Rendered
}
}
#[derive(Default, Clone)]
enum AcquireTerminalSnippetState {
#[default]
NotStarted,
Success,
Failure(Vec<String>),
}
impl std::fmt::Debug for AcquireTerminalSnippetState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotStarted => write!(f, "NotStarted"),
Self::Success => write!(f, "Success"),
Self::Failure(_) => write!(f, "Failure"),
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct RunAcquireTerminalSnippet {
snippet: Snippet,
block_length: u16,
executor: Rc<SnippetExecutor>,
colors: ExecutionStatusBlockStyle,
state: RefCell<AcquireTerminalSnippetState>,
}
impl RunAcquireTerminalSnippet {
pub(crate) fn new(
snippet: Snippet,
executor: Rc<SnippetExecutor>,
colors: ExecutionStatusBlockStyle,
block_length: u16,
) -> Self {
Self { snippet, block_length, executor, colors, state: Default::default() }
}
}
impl RunAcquireTerminalSnippet {
fn invoke(&self) -> Result<(), String> {
let mut stdout = io::stdout();
stdout
.execute(terminal::LeaveAlternateScreen)
.and_then(|_| disable_raw_mode())
.map_err(|e| format!("failed to deinit terminal: {e}"))?;
// save result for later, but first reinit the terminal
let result = self.executor.execute_sync(&self.snippet).map_err(|e| format!("failed to run snippet: {e}"));
stdout
.execute(terminal::EnterAlternateScreen)
.and_then(|_| enable_raw_mode())
.map_err(|e| format!("failed to reinit terminal: {e}"))?;
if should_hide_cursor() {
stdout.execute(cursor::Hide).map_err(|e| e.to_string())?;
}
result
}
}
impl AsRenderOperations for RunAcquireTerminalSnippet {
fn as_render_operations(&self, _dimensions: &WindowSize) -> Vec<RenderOperation> {
let state = self.state.borrow();
let separator_text = match state.deref() {
AcquireTerminalSnippetState::NotStarted => {
Text::new("not started", TextStyle::colored(self.colors.not_started))
}
AcquireTerminalSnippetState::Success => Text::new("finished", TextStyle::colored(self.colors.success)),
AcquireTerminalSnippetState::Failure(_) => {
Text::new("finished with error", TextStyle::colored(self.colors.failure))
}
};
let heading = TextBlock(vec![" [".into(), separator_text, "] ".into()]);
let separator_width = SeparatorWidth::Fixed(self.block_length.max(MINIMUM_SEPARATOR_WIDTH));
let separator = RenderSeparator::new(heading, separator_width);
let mut ops = vec![
RenderOperation::RenderLineBreak,
RenderOperation::RenderDynamic(Rc::new(separator)),
RenderOperation::RenderLineBreak,
];
if let AcquireTerminalSnippetState::Failure(lines) = state.deref() {
ops.push(RenderOperation::RenderLineBreak);
for line in lines {
ops.extend([
RenderOperation::RenderText {
line: vec![Text::new(line, TextStyle::default().colors(self.colors.failure))].into(),
alignment: Alignment::Left { margin: Margin::Percent(25) },
},
RenderOperation::RenderLineBreak,
]);
}
}
ops
}
}
impl RenderAsync for RunAcquireTerminalSnippet {
fn start_render(&self) -> bool {
if !matches!(*self.state.borrow(), AcquireTerminalSnippetState::NotStarted) {
return false;
}
if let Err(e) = self.invoke() {
let lines = e.lines().map(ToString::to_string).collect();
*self.state.borrow_mut() = AcquireTerminalSnippetState::Failure(lines);
} else {
*self.state.borrow_mut() = AcquireTerminalSnippetState::Success;
}
true
}
fn poll_state(&self) -> RenderAsyncState {
RenderAsyncState::Rendered
}
}

87
src/processing/footer.rs Normal file
View File

@ -0,0 +1,87 @@
use crate::{
markdown::elements::Text,
presentation::{AsRenderOperations, RenderOperation},
render::properties::WindowSize,
style::{Colors, TextStyle},
theme::{Alignment, FooterStyle, Margin},
};
use std::{cell::RefCell, rc::Rc};
use unicode_width::UnicodeWidthStr;
#[derive(Debug, Default)]
pub(crate) struct FooterContext {
pub(crate) total_slides: usize,
pub(crate) author: String,
pub(crate) title: String,
pub(crate) sub_title: String,
pub(crate) event: String,
pub(crate) location: String,
pub(crate) date: String,
}
#[derive(Debug)]
pub(crate) struct FooterGenerator {
pub(crate) current_slide: usize,
pub(crate) context: Rc<RefCell<FooterContext>>,
pub(crate) style: FooterStyle,
}
impl FooterGenerator {
fn render_template(
template: &str,
current_slide: &str,
context: &FooterContext,
colors: Colors,
alignment: Alignment,
) -> RenderOperation {
let contents = template
.replace("{current_slide}", current_slide)
.replace("{total_slides}", &context.total_slides.to_string())
.replace("{title}", &context.title)
.replace("{sub_title}", &context.sub_title)
.replace("{event}", &context.event)
.replace("{location}", &context.location)
.replace("{date}", &context.date)
.replace("{author}", &context.author);
let text = Text::new(contents, TextStyle::default().colors(colors));
RenderOperation::RenderText { line: vec![text].into(), alignment }
}
}
impl AsRenderOperations for FooterGenerator {
fn as_render_operations(&self, dimensions: &WindowSize) -> Vec<RenderOperation> {
let context = self.context.borrow();
match &self.style {
FooterStyle::Template { left, center, right, colors } => {
let current_slide = (self.current_slide + 1).to_string();
// We print this one row below the bottom so there's one row of padding.
let mut operations = vec![RenderOperation::JumpToBottomRow { index: 1 }];
let margin = Margin::Fixed(1);
let alignments = [
Alignment::Left { margin: margin.clone() },
Alignment::Center { minimum_size: 0, minimum_margin: margin.clone() },
Alignment::Right { margin: margin.clone() },
];
for (text, alignment) in [left, center, right].iter().zip(alignments) {
if let Some(text) = text {
operations.push(Self::render_template(text, &current_slide, &context, *colors, alignment));
}
}
operations
}
FooterStyle::ProgressBar { character, colors } => {
let character = character.unwrap_or('█').to_string();
let total_columns = dimensions.columns as usize / character.width();
let progress_ratio = (self.current_slide + 1) as f64 / context.total_slides as f64;
let columns_ratio = (total_columns as f64 * progress_ratio).ceil();
let bar = character.repeat(columns_ratio as usize);
let bar = Text::new(bar, TextStyle::default().colors(*colors));
vec![RenderOperation::JumpToBottomRow { index: 0 }, RenderOperation::RenderText {
line: vec![bar].into(),
alignment: Alignment::Left { margin: Margin::Fixed(0) },
}]
}
FooterStyle::Empty => vec![],
}
}
}

View File

@ -1,4 +1,7 @@
pub(crate) mod builder;
pub(crate) mod code;
pub(crate) mod execution;
pub(crate) mod footer;
pub(crate) mod modals;
pub(crate) mod padding;
pub(crate) mod separator;

View File

@ -1,21 +1,19 @@
use crate::{
code::padding::NumberPadder,
commands::keyboard::KeyBinding,
config::KeyBindingsConfig,
PresentationTheme,
custom::KeyBindingsConfig,
input::user::KeyBinding,
markdown::{
elements::{Line, Text},
text::WeightedLine,
text_style::TextStyle,
elements::{Text, TextBlock},
text::WeightedTextBlock,
},
presentation::PresentationState,
render::{
operation::{
AsRenderOperations, ImagePosition, ImageRenderProperties, ImageSize, MarginProperties, RenderOperation,
},
properties::WindowSize,
media::image::Image,
presentation::{
AsRenderOperations, ImageProperties, ImageSize, MarginProperties, PresentationState, RenderOperation,
},
terminal::image::Image,
theme::{Margin, PresentationTheme},
processing::padding::NumberPadder,
render::properties::WindowSize,
style::{Colors, TextStyle},
theme::Margin,
};
use std::{iter, rc::Rc};
use unicode_width::UnicodeWidthStr;
@ -24,12 +22,12 @@ static MODAL_Z_INDEX: i32 = -1;
#[derive(Default)]
pub(crate) struct IndexBuilder {
titles: Vec<Line>,
titles: Vec<TextBlock>,
background: Option<Image>,
}
impl IndexBuilder {
pub(crate) fn add_title(&mut self, title: Line) {
pub(crate) fn add_title(&mut self, title: TextBlock) {
self.titles.push(title);
}
@ -45,9 +43,9 @@ impl IndexBuilder {
title.0.insert(0, format!("{index}: ").into());
builder.content.push(title);
}
let base_style = theme.modals.style;
let selection_style = theme.modals.selection_style;
let ModalContent { prefix, content, suffix, content_width } = builder.build(base_style);
let base_color = theme.modals.colors.merge(&theme.default_style.colors);
let selection_style = TextStyle::default().colors(theme.modals.selection_colors).bold();
let ModalContent { prefix, content, suffix, content_width } = builder.build(base_color);
let drawer = IndexDrawer {
prefix,
rows: content,
@ -127,15 +125,15 @@ impl KeyBindingsModalBuilder {
Self::build_line("Exit", &config.exit),
]);
let lines = builder.content.len();
let style = theme.modals.style;
let content = builder.build(style);
let colors = theme.default_style.colors.clone().merge(&theme.modals.colors);
let content = builder.build(colors);
let content_width = content.content_width;
let mut operations = content.into_operations();
operations.insert(0, CenterModalContent::new(content_width, lines, self.background).into());
operations
}
fn build_line(label: &str, bindings: &[KeyBinding]) -> Line {
fn build_line(label: &str, bindings: &[KeyBinding]) -> TextBlock {
let mut text = vec![Text::new(label, TextStyle::default().bold()), ": ".into()];
for (index, binding) in bindings.iter().enumerate() {
if index > 0 {
@ -143,13 +141,13 @@ impl KeyBindingsModalBuilder {
}
text.push(Text::new(binding.to_string(), TextStyle::default().italics()));
}
Line(text)
TextBlock(text)
}
}
struct ModalBuilder {
heading: String,
content: Vec<Line>,
content: Vec<TextBlock>,
}
impl ModalBuilder {
@ -157,14 +155,14 @@ impl ModalBuilder {
Self { heading: heading.into(), content: Vec::new() }
}
fn build(self, style: TextStyle) -> ModalContent {
let longest_line = self.content.iter().map(Line::width).max().unwrap_or(0) as u16;
fn build(self, colors: Colors) -> ModalContent {
let longest_line = self.content.iter().map(TextBlock::width).max().unwrap_or(0) as u16;
let longest_line = longest_line.max(self.heading.len() as u16);
// Ensure we have a minimum width so it doesn't look too narrow.
let longest_line = longest_line.max(12);
// The final text looks like "| <content> |"
let content_width = longest_line + 6;
let mut prefix = vec![RenderOperation::SetColors(style.colors)];
let mut prefix = vec![RenderOperation::SetColors(colors)];
let heading = Self::center_line(self.heading, longest_line as usize);
prefix.extend(Border::Top.render_line(content_width));
@ -242,11 +240,11 @@ impl ContentRow {
self
}
fn build(self) -> WeightedLine {
fn build(self) -> WeightedTextBlock {
let mut chunks = self.content;
chunks.insert(0, self.prefix);
chunks.push(self.suffix);
WeightedLine::from(chunks)
WeightedTextBlock::from(chunks)
}
}
@ -263,7 +261,7 @@ impl Border {
let mut line = String::from(opening);
line.push_str(&"".repeat(content_length.saturating_sub(2) as usize));
line.push(closing);
let horizontal_border = WeightedLine::from(vec![Text::from(line)]);
let horizontal_border = WeightedTextBlock::from(vec![Text::from(line)]);
[
RenderOperation::RenderText { line: horizontal_border.clone(), alignment: Default::default() },
RenderOperation::RenderLineBreak,
@ -296,7 +294,7 @@ impl CenterModalContent {
impl AsRenderOperations for CenterModalContent {
fn as_render_operations(&self, dimensions: &WindowSize) -> Vec<RenderOperation> {
let margin = dimensions.columns.saturating_sub(self.content_width) / 2;
let properties = MarginProperties { horizontal: Margin::Fixed(margin), top: 0, bottom: 0 };
let properties = MarginProperties { horizontal_margin: Margin::Fixed(margin), bottom_slide_margin: 0 };
// However many we see + 3 for the title and 1 at the bottom.
let content_height = (self.content_height + 4) as u16;
let target_row = dimensions.rows.saturating_sub(content_height) / 2;
@ -304,12 +302,11 @@ impl AsRenderOperations for CenterModalContent {
let mut operations =
vec![RenderOperation::ApplyMargin(properties), RenderOperation::JumpToRow { index: target_row }];
if let Some(image) = &self.background {
let properties = ImageRenderProperties {
let properties = ImageProperties {
z_index: MODAL_Z_INDEX,
size: ImageSize::Specific(self.content_width, content_height),
restore_cursor: true,
background_color: None,
position: ImagePosition::Center,
};
operations.push(RenderOperation::RenderImage(image.clone(), properties));
}

View File

@ -1,11 +1,8 @@
use crate::{
markdown::{
elements::{Line, Text},
text_style::TextStyle,
},
markdown::elements::TextBlock,
presentation::{AsRenderOperations, BlockLine, RenderOperation},
render::{
layout::{Layout, Positioning},
operation::{AsRenderOperations, BlockLine, RenderOperation},
properties::WindowSize,
},
theme::{Alignment, Margin},
@ -20,18 +17,15 @@ pub(crate) enum SeparatorWidth {
FitToWindow,
}
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub(crate) struct RenderSeparator {
heading: Line,
heading: TextBlock,
width: SeparatorWidth,
font_size: u8,
}
impl RenderSeparator {
pub(crate) fn new<S: Into<Line>>(heading: S, width: SeparatorWidth, font_size: u8) -> Self {
let mut heading: Line = heading.into();
heading.apply_style(&TextStyle::default().size(font_size));
Self { heading, width, font_size }
pub(crate) fn new<S: Into<TextBlock>>(heading: S, width: SeparatorWidth) -> Self {
Self { heading: heading.into(), width }
}
}
@ -48,26 +42,24 @@ impl AsRenderOperations for RenderSeparator {
SeparatorWidth::Fixed(width) => {
let Positioning { max_line_length, .. } =
Layout::new(Alignment::Center { minimum_margin: Margin::Fixed(0), minimum_size: 0 })
.with_font_size(self.font_size)
.compute(dimensions, width);
max_line_length.min(width) as usize
}
SeparatorWidth::FitToWindow => dimensions.columns as usize,
};
let style = TextStyle::default().size(self.font_size);
let separator = match self.heading.width() == 0 {
true => Line::from(Text::new(character.repeat(width / self.font_size as usize), style)),
true => TextBlock::from(character.repeat(width)),
false => {
let width = width.saturating_sub(self.heading.width());
let (dashes_len, remainder) = (width / 2, width % 2);
let mut dashes = character.repeat(dashes_len);
let mut line = Line::from(Text::new(dashes.clone(), style));
let mut line = TextBlock::from(dashes.clone());
line.0.extend(self.heading.0.iter().cloned());
if remainder > 0 {
dashes.push_str(character);
}
line.0.push(Text::new(dashes, style));
line.0.push(dashes.into());
line
}
};

View File

@ -1,102 +0,0 @@
use super::{
RenderError,
engine::{RenderEngine, RenderEngineOptions},
};
use crate::{
WindowSize,
presentation::Presentation,
terminal::{
image::Image,
printer::{TerminalCommand, TerminalError, TerminalIo},
},
};
use std::thread;
use unicode_width::UnicodeWidthStr;
pub(crate) struct AsciiScaler {
options: RenderEngineOptions,
}
impl AsciiScaler {
pub(crate) fn new(options: RenderEngineOptions) -> Self {
Self { options }
}
pub(crate) fn process(self, presentation: &Presentation, dimensions: &WindowSize) -> Result<(), RenderError> {
let mut collector = ImageCollector::default();
for slide in presentation.iter_slides() {
let engine = RenderEngine::new(&mut collector, dimensions.clone(), self.options.clone());
engine.render(slide.iter_operations())?;
}
thread::spawn(move || Self::scale(collector.images));
Ok(())
}
fn scale(images: Vec<ScalableImage>) {
for image in images {
let ascii_image = image.image.to_ascii();
ascii_image.cache_scaling(image.columns, image.rows);
}
}
}
struct ScalableImage {
image: Image,
rows: u16,
columns: u16,
}
struct ImageCollector {
current_column: u16,
current_row: u16,
current_row_height: u16,
images: Vec<ScalableImage>,
}
impl Default for ImageCollector {
fn default() -> Self {
Self { current_row: 0, current_column: 0, current_row_height: 1, images: Default::default() }
}
}
impl TerminalIo for ImageCollector {
fn execute(&mut self, command: &TerminalCommand<'_>) -> Result<(), TerminalError> {
use TerminalCommand::*;
match command {
MoveTo { column, row } => {
self.current_column = *column;
self.current_row = *row;
}
MoveToRow(row) => self.current_row = *row,
MoveToColumn(column) => self.current_column = *column,
MoveDown(amount) => self.current_row = self.current_row.saturating_add(*amount),
MoveRight(amount) => self.current_column = self.current_column.saturating_add(*amount),
MoveLeft(amount) => self.current_column = self.current_column.saturating_sub(*amount),
MoveToNextLine => {
self.current_row = self.current_row.saturating_add(1);
self.current_column = 0;
self.current_row_height = 1;
}
PrintText { content, style } => {
self.current_column = self.current_column.saturating_add(content.width() as u16);
self.current_row_height = self.current_row_height.max(style.size as u16);
}
PrintImage { image, options } => {
// we can only really cache filesystem images for now
let image = ScalableImage { image: image.clone(), rows: options.rows * 2, columns: options.columns };
self.images.push(image);
}
ClearScreen => {
self.current_column = 0;
self.current_row = 0;
self.current_row_height = 1;
}
BeginUpdate | EndUpdate | Flush | SetColors(_) | SetBackgroundColor(_) => (),
};
Ok(())
}
fn cursor_row(&self) -> u16 {
self.current_row
}
}

132
src/render/draw.rs Normal file
View File

@ -0,0 +1,132 @@
use super::{
engine::RenderEngine,
terminal::{Terminal, TerminalWrite},
};
use crate::{
markdown::{elements::Text, text::WeightedTextBlock},
media::printer::{ImagePrinter, PrintImageError},
presentation::{Presentation, RenderOperation},
render::properties::WindowSize,
style::{Color, Colors, TextStyle},
theme::{Alignment, Margin},
};
use std::{io, sync::Arc};
/// The result of a render operation.
pub(crate) type RenderResult = Result<(), RenderError>;
/// Allows drawing elements in the terminal.
pub(crate) struct TerminalDrawer<W: TerminalWrite> {
pub(crate) terminal: Terminal<W>,
font_size_fallback: u8,
}
impl<W> TerminalDrawer<W>
where
W: TerminalWrite,
{
/// Construct a drawer over a [std::io::Write].
pub(crate) fn new(handle: W, image_printer: Arc<ImagePrinter>, font_size_fallback: u8) -> io::Result<Self> {
let terminal = Terminal::new(handle, image_printer)?;
Ok(Self { terminal, font_size_fallback })
}
/// Render a slide.
pub(crate) fn render_slide(&mut self, presentation: &Presentation) -> RenderResult {
let dimensions = WindowSize::current(self.font_size_fallback)?;
let slide = presentation.current_slide();
let engine = self.create_engine(dimensions);
engine.render(slide.iter_visible_operations())?;
Ok(())
}
/// Render an error.
pub(crate) fn render_error(&mut self, message: &str, source: &ErrorSource) -> RenderResult {
let dimensions = WindowSize::current(self.font_size_fallback)?;
let heading_text = match source {
ErrorSource::Presentation => "Error loading presentation".to_string(),
ErrorSource::Slide(slide) => {
format!("Error in slide {slide}")
}
};
let heading = vec![Text::new(heading_text, TextStyle::default().bold()), Text::from(": ")];
let total_lines = message.lines().count();
let starting_row = (dimensions.rows / 2).saturating_sub(total_lines as u16 / 2 + 3);
let alignment = Alignment::Left { margin: Margin::Percent(25) };
let mut operations = vec![
RenderOperation::SetColors(Colors {
foreground: Some(Color::new(255, 0, 0)),
background: Some(Color::new(0, 0, 0)),
}),
RenderOperation::ClearScreen,
RenderOperation::JumpToRow { index: starting_row },
RenderOperation::RenderText { line: WeightedTextBlock::from(heading), alignment: alignment.clone() },
RenderOperation::RenderLineBreak,
RenderOperation::RenderLineBreak,
];
for line in message.lines() {
let error = vec![Text::from(line)];
let op = RenderOperation::RenderText { line: WeightedTextBlock::from(error), alignment: alignment.clone() };
operations.extend([op, RenderOperation::RenderLineBreak]);
}
let engine = self.create_engine(dimensions);
engine.render(operations.iter())?;
Ok(())
}
pub(crate) fn render_slide_index(&mut self, presentation: &Presentation) -> RenderResult {
let dimensions = WindowSize::current(self.font_size_fallback)?;
let engine = self.create_engine(dimensions);
engine.render(presentation.iter_slide_index_operations())?;
Ok(())
}
pub(crate) fn render_key_bindings(&mut self, presentation: &Presentation) -> RenderResult {
let dimensions = WindowSize::current(self.font_size_fallback)?;
let engine = self.create_engine(dimensions);
engine.render(presentation.iter_bindings_operations())?;
Ok(())
}
fn create_engine(&mut self, dimensions: WindowSize) -> RenderEngine<W> {
let options = Default::default();
RenderEngine::new(&mut self.terminal, dimensions, options)
}
}
/// A rendering error.
#[derive(thiserror::Error, Debug)]
pub enum RenderError {
#[error("io: {0}")]
Io(#[from] io::Error),
#[error("unsupported structure: {0}")]
UnsupportedStructure(&'static str),
#[error("screen is too small")]
TerminalTooSmall,
#[error("tried to move to non existent layout location")]
InvalidLayoutEnter,
#[error("tried to pop default screen")]
PopDefaultScreen,
#[error("printing image: {0}")]
PrintImage(#[from] PrintImageError),
#[error("horizontal overflow")]
HorizontalOverflow,
#[error("vertical overflow")]
VerticalOverflow,
#[error(transparent)]
Other(Box<dyn std::error::Error>),
}
pub(crate) enum ErrorSource {
Presentation,
Slide(usize),
}

View File

@ -1,83 +1,54 @@
use super::{
RenderError, RenderResult, layout::Layout, operation::ImagePosition, properties::CursorPosition, text::TextDrawer,
draw::{RenderError, RenderResult},
layout::Layout,
properties::CursorPosition,
terminal::{Terminal, TerminalWrite},
text::TextDrawer,
};
use crate::{
config::{MaxColumnsAlignment, MaxRowsAlignment},
markdown::{text::WeightedLine, text_style::Colors},
render::{
layout::Positioning,
operation::{
AsRenderOperations, BlockLine, ImageRenderProperties, ImageSize, MarginProperties, RenderAsync,
RenderOperation,
},
properties::WindowSize,
markdown::text::WeightedTextBlock,
media::{
image::Image,
printer::{PrintOptions, ResourceProperties},
scale::{fit_image_to_window, scale_image},
},
terminal::{
image::{
Image,
printer::{ImageProperties, PrintOptions},
scale::{ImageScaler, ScaleImage},
},
printer::{TerminalCommand, TerminalIo},
presentation::{
AsRenderOperations, BlockLine, ImageProperties, ImageSize, MarginProperties, RenderAsync, RenderOperation,
},
render::{layout::Positioning, properties::WindowSize},
style::Colors,
theme::Alignment,
};
use std::mem;
const MINIMUM_LINE_LENGTH: u16 = 10;
#[derive(Clone, Debug)]
pub(crate) struct MaxSize {
pub(crate) max_columns: u16,
pub(crate) max_columns_alignment: MaxColumnsAlignment,
pub(crate) max_rows: u16,
pub(crate) max_rows_alignment: MaxRowsAlignment,
}
impl Default for MaxSize {
fn default() -> Self {
Self {
max_columns: u16::MAX,
max_columns_alignment: Default::default(),
max_rows: u16::MAX,
max_rows_alignment: Default::default(),
}
}
}
#[derive(Clone, Debug)]
#[derive(Debug, Default)]
pub(crate) struct RenderEngineOptions {
pub(crate) validate_overflows: bool,
pub(crate) max_size: MaxSize,
pub(crate) column_layout_margin: u16,
}
impl Default for RenderEngineOptions {
fn default() -> Self {
Self { validate_overflows: false, max_size: Default::default(), column_layout_margin: 4 }
}
}
pub(crate) struct RenderEngine<'a, T>
pub(crate) struct RenderEngine<'a, W>
where
T: TerminalIo,
W: TerminalWrite,
{
terminal: &'a mut T,
terminal: &'a mut Terminal<W>,
window_rects: Vec<WindowRect>,
colors: Colors,
max_modified_row: u16,
layout: LayoutState,
options: RenderEngineOptions,
image_scaler: Box<dyn ScaleImage>,
}
impl<'a, T> RenderEngine<'a, T>
impl<'a, W> RenderEngine<'a, W>
where
T: TerminalIo,
W: TerminalWrite,
{
pub(crate) fn new(terminal: &'a mut T, window_dimensions: WindowSize, options: RenderEngineOptions) -> Self {
let max_modified_row = terminal.cursor_row();
let current_rect = Self::starting_rect(window_dimensions, &options);
pub(crate) fn new(
terminal: &'a mut Terminal<W>,
window_dimensions: WindowSize,
options: RenderEngineOptions,
) -> Self {
let max_modified_row = terminal.cursor_row;
let current_rect = WindowRect { dimensions: window_dimensions, start_column: 0 };
let window_rects = vec![current_rect.clone()];
Self {
terminal,
@ -86,46 +57,16 @@ where
max_modified_row,
layout: Default::default(),
options,
image_scaler: Box::<ImageScaler>::default(),
}
}
fn starting_rect(mut dimensions: WindowSize, options: &RenderEngineOptions) -> WindowRect {
let mut start_row = 0;
let mut start_column = 0;
if dimensions.columns > options.max_size.max_columns {
let extra_width = dimensions.columns - options.max_size.max_columns;
dimensions = dimensions.shrink_columns(extra_width);
start_column = match options.max_size.max_columns_alignment {
MaxColumnsAlignment::Left => 0,
MaxColumnsAlignment::Center => extra_width / 2,
MaxColumnsAlignment::Right => extra_width,
};
}
if dimensions.rows > options.max_size.max_rows {
let extra_height = dimensions.rows - options.max_size.max_rows;
dimensions = dimensions.shrink_rows(extra_height);
start_row = match options.max_size.max_rows_alignment {
MaxRowsAlignment::Top => 0,
MaxRowsAlignment::Center => extra_height / 2,
MaxRowsAlignment::Bottom => extra_height,
};
}
WindowRect { dimensions, start_column, start_row }
}
pub(crate) fn render<'b>(mut self, operations: impl Iterator<Item = &'b RenderOperation>) -> RenderResult {
let current_rect = self.current_rect().clone();
self.terminal.execute(&TerminalCommand::BeginUpdate)?;
if current_rect.start_row != 0 || current_rect.start_column != 0 {
self.terminal
.execute(&TerminalCommand::MoveTo { column: current_rect.start_column, row: current_rect.start_row })?;
}
self.terminal.begin_update()?;
for operation in operations {
self.render_one(operation)?;
}
self.terminal.execute(&TerminalCommand::EndUpdate)?;
self.terminal.execute(&TerminalCommand::Flush)?;
self.terminal.end_update()?;
self.terminal.flush()?;
if self.options.validate_overflows && self.max_modified_row > self.window_rects[0].dimensions.rows {
return Err(RenderError::VerticalOverflow);
}
@ -141,8 +82,7 @@ where
RenderOperation::JumpToVerticalCenter => self.jump_to_vertical_center(),
RenderOperation::JumpToRow { index } => self.jump_to_row(*index),
RenderOperation::JumpToBottomRow { index } => self.jump_to_bottom(*index),
RenderOperation::JumpToColumn { index } => self.jump_to_column(*index),
RenderOperation::RenderText { line, alignment } => self.render_text(line, *alignment),
RenderOperation::RenderText { line, alignment } => self.render_text(line, alignment),
RenderOperation::RenderLineBreak => self.render_line_break(),
RenderOperation::RenderImage(image, properties) => self.render_image(image, properties),
RenderOperation::RenderBlockLine(operation) => self.render_block_line(operation),
@ -152,10 +92,7 @@ where
RenderOperation::EnterColumn { column } => self.enter_column(*column),
RenderOperation::ExitLayout => self.exit_layout(),
}?;
if let LayoutState::EnteredColumn { column, columns } = &mut self.layout {
columns[*column].current_row = self.terminal.cursor_row();
};
self.max_modified_row = self.max_modified_row.max(self.terminal.cursor_row());
self.max_modified_row = self.max_modified_row.max(self.terminal.cursor_row);
Ok(())
}
@ -169,21 +106,17 @@ where
}
fn clear_screen(&mut self) -> RenderResult {
let current = self.current_rect().clone();
self.terminal.execute(&TerminalCommand::ClearScreen)?;
self.terminal.execute(&TerminalCommand::MoveTo { column: current.start_column, row: current.start_row })?;
self.terminal.clear_screen()?;
self.terminal.move_to(0, 0)?;
self.max_modified_row = 0;
Ok(())
}
fn apply_margin(&mut self, properties: &MarginProperties) -> RenderResult {
let MarginProperties { horizontal: horizontal_margin, top, bottom } = properties;
let MarginProperties { horizontal_margin, bottom_slide_margin } = properties;
let current = self.current_rect();
let margin = horizontal_margin.as_characters(current.dimensions.columns);
let new_rect = current.shrink_horizontal(margin).shrink_bottom(*bottom).shrink_top(*top);
if new_rect.start_row != self.terminal.cursor_row() {
self.terminal.execute(&TerminalCommand::MoveToRow(new_rect.start_row))?;
}
let new_rect = current.apply_margin(margin).shrink_rows(*bottom_slide_margin);
self.window_rects.push(new_rect);
Ok(())
}
@ -202,113 +135,76 @@ where
}
fn apply_colors(&mut self) -> RenderResult {
self.terminal.execute(&TerminalCommand::SetColors(self.colors))?;
self.terminal.set_colors(self.colors)?;
Ok(())
}
fn jump_to_vertical_center(&mut self) -> RenderResult {
let current = self.current_rect();
let center_row = current.dimensions.rows / 2;
let center_row = center_row.saturating_add(current.start_row);
self.terminal.execute(&TerminalCommand::MoveToRow(center_row))?;
let center_row = self.current_dimensions().rows / 2;
self.terminal.move_to_row(center_row)?;
Ok(())
}
fn jump_to_row(&mut self, row: u16) -> RenderResult {
// Make this relative to the beginning of the current rect.
let row = self.current_rect().start_row.saturating_add(row);
self.terminal.execute(&TerminalCommand::MoveToRow(row))?;
fn jump_to_row(&mut self, index: u16) -> RenderResult {
self.terminal.move_to_row(index)?;
Ok(())
}
fn jump_to_bottom(&mut self, index: u16) -> RenderResult {
let current = self.current_rect();
let target_row = current.dimensions.rows.saturating_sub(index).saturating_sub(1);
let target_row = target_row.saturating_add(current.start_row);
self.terminal.execute(&TerminalCommand::MoveToRow(target_row))?;
let target_row = self.current_dimensions().rows.saturating_sub(index).saturating_sub(1);
self.terminal.move_to_row(target_row)?;
Ok(())
}
fn jump_to_column(&mut self, column: u16) -> RenderResult {
// Make this relative to the beginning of the current rect.
let column = self.current_rect().start_column.saturating_add(column);
self.terminal.execute(&TerminalCommand::MoveToColumn(column))?;
Ok(())
}
fn render_text(&mut self, text: &WeightedLine, alignment: Alignment) -> RenderResult {
let layout = self.build_layout(alignment);
fn render_text(&mut self, text: &WeightedTextBlock, alignment: &Alignment) -> RenderResult {
let layout = self.build_layout(alignment.clone());
let dimensions = self.current_dimensions();
let positioning = layout.compute(dimensions, text.width() as u16);
let prefix = "".into();
let text_drawer = TextDrawer::new(&prefix, 0, text, positioning, &self.colors, MINIMUM_LINE_LENGTH)?;
let center_newlines = matches!(alignment, Alignment::Center { .. });
let text_drawer = text_drawer.center_newlines(center_newlines);
text_drawer.draw(self.terminal)?;
// Restore colors
self.apply_colors()
let text_drawer = TextDrawer::new(&prefix, 0, text, positioning, &self.colors)?;
text_drawer.draw(self.terminal)
}
fn render_line_break(&mut self) -> RenderResult {
self.terminal.execute(&TerminalCommand::MoveToNextLine)?;
self.terminal.move_to_next_line(1)?;
Ok(())
}
fn render_image(&mut self, image: &Image, properties: &ImageRenderProperties) -> RenderResult {
let rect = self.current_rect().clone();
let starting_row = self.terminal.cursor_row();
let starting_cursor =
CursorPosition { row: starting_row.saturating_sub(rect.start_row), column: rect.start_column };
fn render_image(&mut self, image: &Image, properties: &ImageProperties) -> RenderResult {
let rect = self.current_rect();
let starting_position = CursorPosition { row: self.terminal.cursor_row, column: rect.start_column };
let (width, height) = image.image().dimensions();
let (columns, rows) = match properties.size {
let (width, height) = image.dimensions();
let (cursor_position, columns, rows) = match properties.size {
ImageSize::ShrinkIfNeeded => {
let image_scale =
self.image_scaler.fit_image_to_rect(&rect.dimensions, width, height, &starting_cursor);
(image_scale.columns, image_scale.rows)
let scale = fit_image_to_window(&rect.dimensions, width, height, &starting_position);
(CursorPosition { row: starting_position.row, column: scale.start_column }, scale.columns, scale.rows)
}
ImageSize::Specific(columns, rows) => (columns, rows),
ImageSize::Specific(columns, rows) => (starting_position.clone(), columns, rows),
ImageSize::WidthScaled { ratio } => {
let extra_columns = (rect.dimensions.columns as f64 * (1.0 - ratio)).ceil() as u16;
let dimensions = rect.dimensions.shrink_columns(extra_columns);
let image_scale =
self.image_scaler.scale_image(&dimensions, &rect.dimensions, width, height, &starting_cursor);
(image_scale.columns, image_scale.rows)
let scale = scale_image(&dimensions, &rect.dimensions, width, height, &starting_position);
(CursorPosition { row: starting_position.row, column: scale.start_column }, scale.columns, scale.rows)
}
};
let cursor = match &properties.position {
ImagePosition::Cursor => starting_cursor.clone(),
ImagePosition::Center => Self::center_cursor(columns, &rect.dimensions, &starting_cursor),
ImagePosition::Right => Self::align_cursor_right(columns, &rect.dimensions, &starting_cursor),
};
self.terminal.execute(&TerminalCommand::MoveToColumn(cursor.column))?;
let options = PrintOptions {
columns,
rows,
cursor_position,
z_index: properties.z_index,
column_width: rect.dimensions.pixels_per_column() as u16,
row_height: rect.dimensions.pixels_per_row() as u16,
background_color: properties.background_color,
};
self.terminal.execute(&TerminalCommand::PrintImage { image: image.clone(), options })?;
self.terminal.print_image(image, &options)?;
if properties.restore_cursor {
self.terminal.execute(&TerminalCommand::MoveTo { column: starting_cursor.column, row: starting_row })?;
self.terminal.move_to(starting_position.column, starting_position.row)?;
} else {
self.terminal.execute(&TerminalCommand::MoveToRow(starting_row + rows))?;
self.terminal.move_to_row(starting_position.row + rows)?;
}
self.apply_colors()
}
fn center_cursor(columns: u16, window: &WindowSize, cursor: &CursorPosition) -> CursorPosition {
let start_column = window.columns / 2 - (columns / 2);
let start_column = start_column + cursor.column;
CursorPosition { row: cursor.row, column: start_column }
}
fn align_cursor_right(columns: u16, window: &WindowSize, cursor: &CursorPosition) -> CursorPosition {
let start_column = window.columns.saturating_sub(columns).saturating_add(cursor.column);
CursorPosition { row: cursor.row, column: start_column }
Ok(())
}
fn render_block_line(&mut self, operation: &BlockLine) -> RenderResult {
@ -321,7 +217,7 @@ where
right_padding_length,
repeat_prefix_on_wrap,
} = operation;
let layout = self.build_layout(*alignment).with_font_size(text.font_size());
let layout = self.build_layout(alignment.clone());
let dimensions = self.current_dimensions();
let Positioning { max_line_length, start_column } = layout.compute(dimensions, *block_length);
@ -329,13 +225,12 @@ where
return Err(RenderError::HorizontalOverflow);
}
self.terminal.execute(&TerminalCommand::MoveToColumn(start_column))?;
self.terminal.move_to_column(start_column)?;
let positioning = Positioning { max_line_length, start_column };
let text_drawer =
TextDrawer::new(prefix, *right_padding_length, text, positioning, &self.colors, MINIMUM_LINE_LENGTH)?
.with_surrounding_block(*block_color)
.repeat_prefix_on_wrap(*repeat_prefix_on_wrap);
let text_drawer = TextDrawer::new(prefix, *right_padding_length, text, positioning, &self.colors)?
.with_surrounding_block(*block_color)
.repeat_prefix_on_wrap(*repeat_prefix_on_wrap);
text_drawer.draw(self.terminal)?;
// Restore colors
@ -363,53 +258,47 @@ where
if !matches!(self.layout, LayoutState::Default) {
self.exit_layout()?;
}
let columns = columns
.iter()
.map(|width| Column { width: *width as u16, current_row: self.terminal.cursor_row() })
.collect();
self.layout = LayoutState::InitializedColumn { columns };
let columns = columns.iter().copied().map(u16::from).collect();
let current_position = self.terminal.cursor_row;
self.layout = LayoutState::InitializedColumn { columns, start_row: current_position };
Ok(())
}
fn enter_column(&mut self, column_index: usize) -> RenderResult {
let columns = match mem::take(&mut self.layout) {
let (columns, start_row) = match mem::take(&mut self.layout) {
LayoutState::Default => return Err(RenderError::InvalidLayoutEnter),
LayoutState::InitializedColumn { columns, .. } | LayoutState::EnteredColumn { columns, .. }
if column_index >= columns.len() =>
{
return Err(RenderError::InvalidLayoutEnter);
}
LayoutState::InitializedColumn { columns } => columns,
LayoutState::EnteredColumn { columns, .. } => {
LayoutState::InitializedColumn { columns, start_row } => (columns, start_row),
LayoutState::EnteredColumn { columns, start_row, .. } => {
// Pop this one and start clean
self.pop_margin()?;
columns
(columns, start_row)
}
};
let total_column_units: u16 = columns.iter().map(|c| c.width).sum();
let column_units_before: u16 = columns.iter().take(column_index).map(|c| c.width).sum();
let total_column_units: u16 = columns.iter().sum();
let column_units_before: u16 = columns.iter().take(column_index).sum();
let current_rect = self.current_rect();
let unit_width = current_rect.dimensions.columns as f64 / total_column_units as f64;
let start_column = current_rect.start_column + (unit_width * column_units_before as f64) as u16;
let start_row = columns[column_index].current_row;
let new_column_count = (total_column_units - columns[column_index].width) * unit_width as u16;
let new_size = current_rect
.dimensions
.shrink_columns(new_column_count)
.shrink_rows(start_row.saturating_sub(current_rect.start_row));
let mut dimensions = WindowRect { dimensions: new_size, start_column, start_row };
let new_column_count = (total_column_units - columns[column_index]) * unit_width as u16;
let new_size = current_rect.dimensions.shrink_columns(new_column_count);
let mut dimensions = WindowRect { dimensions: new_size, start_column };
// Shrink every column's right edge except for last
if column_index < columns.len() - 1 {
dimensions = dimensions.shrink_right(self.options.column_layout_margin);
dimensions = dimensions.shrink_right(4);
}
// Shrink every column's left edge except for first
if column_index > 0 {
dimensions = dimensions.shrink_left(self.options.column_layout_margin);
dimensions = dimensions.shrink_left(4);
}
self.window_rects.push(dimensions);
self.terminal.execute(&TerminalCommand::MoveToRow(start_row))?;
self.layout = LayoutState::EnteredColumn { column: column_index, columns };
self.layout = LayoutState::EnteredColumn { columns, start_row };
self.terminal.move_to_row(start_row)?;
Ok(())
}
@ -417,7 +306,7 @@ where
match &self.layout {
LayoutState::Default | LayoutState::InitializedColumn { .. } => Ok(()),
LayoutState::EnteredColumn { .. } => {
self.terminal.execute(&TerminalCommand::MoveTo { column: 0, row: self.max_modified_row })?;
self.terminal.move_to(0, self.max_modified_row)?;
self.layout = LayoutState::Default;
self.pop_margin()?;
Ok(())
@ -435,507 +324,41 @@ enum LayoutState {
#[default]
Default,
InitializedColumn {
columns: Vec<Column>,
columns: Vec<u16>,
start_row: u16,
},
EnteredColumn {
column: usize,
columns: Vec<Column>,
columns: Vec<u16>,
start_row: u16,
},
}
struct Column {
width: u16,
current_row: u16,
}
#[derive(Clone, Debug)]
struct WindowRect {
dimensions: WindowSize,
start_column: u16,
start_row: u16,
}
impl WindowRect {
fn shrink_horizontal(&self, margin: u16) -> Self {
fn apply_margin(&self, margin: u16) -> Self {
let dimensions = self.dimensions.shrink_columns(margin.saturating_mul(2));
let start_column = self.start_column + margin;
Self { dimensions, start_column, start_row: self.start_row }
Self { dimensions, start_column }
}
fn shrink_left(&self, size: u16) -> Self {
let dimensions = self.dimensions.shrink_columns(size);
let start_column = self.start_column.saturating_add(size);
Self { dimensions, start_column, start_row: self.start_row }
Self { dimensions, start_column }
}
fn shrink_right(&self, size: u16) -> Self {
let dimensions = self.dimensions.shrink_columns(size);
Self { dimensions, start_column: self.start_column, start_row: self.start_row }
Self { dimensions, start_column: self.start_column }
}
fn shrink_top(&self, rows: u16) -> Self {
fn shrink_rows(&self, rows: u16) -> Self {
let dimensions = self.dimensions.shrink_rows(rows);
let start_row = self.start_row.saturating_add(rows);
Self { dimensions, start_column: self.start_column, start_row }
}
fn shrink_bottom(&self, rows: u16) -> Self {
let dimensions = self.dimensions.shrink_rows(rows);
Self { dimensions, start_column: self.start_column, start_row: self.start_row }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
markdown::text_style::{Color, TextStyle},
terminal::{
image::{
ImageSource,
printer::{PrintImageError, TerminalImage},
scale::TerminalRect,
},
printer::TerminalError,
},
theme::Margin,
};
use ::image::{ColorType, DynamicImage};
use rstest::rstest;
use std::io;
use unicode_width::UnicodeWidthStr;
#[derive(Debug, PartialEq)]
enum Instruction {
MoveTo(u16, u16),
MoveToRow(u16),
MoveToColumn(u16),
MoveDown(u16),
MoveRight(u16),
MoveLeft(u16),
MoveToNextLine,
PrintText(String),
ClearScreen,
SetBackgroundColor(Color),
PrintImage(PrintOptions),
}
#[derive(Default)]
struct TerminalBuf {
instructions: Vec<Instruction>,
cursor_row: u16,
}
impl TerminalBuf {
fn push(&mut self, instruction: Instruction) -> io::Result<()> {
self.instructions.push(instruction);
Ok(())
}
fn move_to(&mut self, column: u16, row: u16) -> io::Result<()> {
self.cursor_row = row;
self.push(Instruction::MoveTo(column, row))
}
fn move_to_row(&mut self, row: u16) -> io::Result<()> {
self.cursor_row = row;
self.push(Instruction::MoveToRow(row))
}
fn move_to_column(&mut self, column: u16) -> io::Result<()> {
self.push(Instruction::MoveToColumn(column))
}
fn move_down(&mut self, amount: u16) -> io::Result<()> {
self.push(Instruction::MoveDown(amount))
}
fn move_right(&mut self, amount: u16) -> io::Result<()> {
self.push(Instruction::MoveRight(amount))
}
fn move_left(&mut self, amount: u16) -> io::Result<()> {
self.push(Instruction::MoveLeft(amount))
}
fn move_to_next_line(&mut self) -> io::Result<()> {
self.push(Instruction::MoveToNextLine)
}
fn print_text(&mut self, content: &str, _style: &TextStyle) -> io::Result<()> {
let content = content.to_string();
if content.is_empty() {
return Ok(());
}
self.cursor_row = content.width() as u16;
self.push(Instruction::PrintText(content))
}
fn clear_screen(&mut self) -> io::Result<()> {
self.cursor_row = 0;
self.push(Instruction::ClearScreen)
}
fn set_colors(&mut self, _colors: Colors) -> io::Result<()> {
Ok(())
}
fn set_background_color(&mut self, color: Color) -> io::Result<()> {
self.push(Instruction::SetBackgroundColor(color))
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
fn print_image(&mut self, _image: &Image, options: &PrintOptions) -> Result<(), PrintImageError> {
let _ = self.push(Instruction::PrintImage(options.clone()));
Ok(())
}
}
impl TerminalIo for TerminalBuf {
fn execute(&mut self, command: &TerminalCommand<'_>) -> Result<(), TerminalError> {
use TerminalCommand::*;
match command {
BeginUpdate => (),
EndUpdate => (),
MoveTo { column, row } => self.move_to(*column, *row)?,
MoveToRow(row) => self.move_to_row(*row)?,
MoveToColumn(column) => self.move_to_column(*column)?,
MoveDown(amount) => self.move_down(*amount)?,
MoveRight(amount) => self.move_right(*amount)?,
MoveLeft(amount) => self.move_left(*amount)?,
MoveToNextLine => self.move_to_next_line()?,
PrintText { content, style } => self.print_text(content, style)?,
ClearScreen => self.clear_screen()?,
SetColors(colors) => self.set_colors(*colors)?,
SetBackgroundColor(color) => self.set_background_color(*color)?,
Flush => self.flush()?,
PrintImage { image, options } => self.print_image(image, options)?,
};
Ok(())
}
fn cursor_row(&self) -> u16 {
self.cursor_row
}
}
struct DummyImageScaler;
impl ScaleImage for DummyImageScaler {
fn scale_image(
&self,
_scale_size: &WindowSize,
_window_dimensions: &WindowSize,
image_width: u32,
image_height: u32,
_position: &CursorPosition,
) -> TerminalRect {
TerminalRect { rows: image_width as u16, columns: image_height as u16 }
}
fn fit_image_to_rect(
&self,
_dimensions: &WindowSize,
image_width: u32,
image_height: u32,
_position: &CursorPosition,
) -> TerminalRect {
TerminalRect { rows: image_width as u16, columns: image_height as u16 }
}
}
fn do_render(max_size: MaxSize, operations: &[RenderOperation]) -> Vec<Instruction> {
let mut buf = TerminalBuf::default();
let dimensions = WindowSize { rows: 100, columns: 100, height: 200, width: 200 };
let options = RenderEngineOptions { validate_overflows: false, max_size, column_layout_margin: 0 };
let mut engine = RenderEngine::new(&mut buf, dimensions, options);
engine.image_scaler = Box::new(DummyImageScaler);
engine.render(operations.iter()).expect("render failed");
buf.instructions
}
fn render(operations: &[RenderOperation]) -> Vec<Instruction> {
do_render(Default::default(), operations)
}
fn render_with_max_size(operations: &[RenderOperation]) -> Vec<Instruction> {
let max_size = MaxSize {
max_rows: 10,
max_rows_alignment: MaxRowsAlignment::Center,
max_columns: 20,
max_columns_alignment: MaxColumnsAlignment::Center,
};
do_render(max_size, operations)
}
#[test]
fn columns() {
let ops = render(&[
RenderOperation::InitColumnLayout { columns: vec![1, 1] },
// print on column 0
RenderOperation::EnterColumn { column: 0 },
RenderOperation::RenderText { line: "A".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
// print on column 1
RenderOperation::EnterColumn { column: 1 },
RenderOperation::RenderText { line: "B".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
// go back to column 0 and print
RenderOperation::EnterColumn { column: 0 },
RenderOperation::RenderText { line: "1".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
]);
let expected = [
Instruction::MoveToRow(0),
Instruction::MoveToColumn(0),
Instruction::PrintText("A".into()),
Instruction::MoveToRow(0),
Instruction::MoveToColumn(50),
Instruction::PrintText("B".into()),
// when we go back we should proceed from where we left off (row == 1)
Instruction::MoveToRow(1),
Instruction::MoveToColumn(0),
Instruction::PrintText("1".into()),
];
assert_eq!(ops, expected);
}
#[test]
fn bottom_margin() {
let ops = render(&[
RenderOperation::ApplyMargin(MarginProperties { horizontal: Margin::Fixed(1), top: 0, bottom: 10 }),
RenderOperation::RenderText { line: "A".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
RenderOperation::JumpToBottomRow { index: 0 },
RenderOperation::RenderText { line: "B".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
]);
let expected = [
Instruction::MoveToColumn(1),
Instruction::PrintText("A".into()),
// 100 - 10 (bottom margin)
Instruction::MoveToRow(89),
Instruction::MoveToColumn(1),
Instruction::PrintText("B".into()),
];
assert_eq!(ops, expected);
}
#[test]
fn top_margin() {
let ops = render(&[
RenderOperation::ApplyMargin(MarginProperties { horizontal: Margin::Fixed(1), top: 3, bottom: 0 }),
RenderOperation::RenderText { line: "A".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
]);
let expected = [Instruction::MoveToRow(3), Instruction::MoveToColumn(1), Instruction::PrintText("A".into())];
assert_eq!(ops, expected);
}
#[test]
fn margins() {
let ops = render(&[
RenderOperation::ApplyMargin(MarginProperties { horizontal: Margin::Fixed(1), top: 3, bottom: 10 }),
RenderOperation::JumpToRow { index: 0 },
RenderOperation::RenderText { line: "A".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
RenderOperation::JumpToBottomRow { index: 0 },
RenderOperation::RenderText { line: "B".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
]);
let expected = [
Instruction::MoveToRow(3),
Instruction::MoveToRow(3),
Instruction::MoveToColumn(1),
Instruction::PrintText("A".into()),
// 100 - 10 (bottom margin)
Instruction::MoveToRow(89),
Instruction::MoveToColumn(1),
Instruction::PrintText("B".into()),
];
assert_eq!(ops, expected);
}
#[test]
fn nested_margins() {
let ops = render(&[
RenderOperation::ApplyMargin(MarginProperties { horizontal: Margin::Fixed(1), top: 0, bottom: 10 }),
RenderOperation::ApplyMargin(MarginProperties { horizontal: Margin::Fixed(1), top: 0, bottom: 10 }),
RenderOperation::RenderText { line: "A".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
RenderOperation::JumpToBottomRow { index: 0 },
RenderOperation::RenderText { line: "B".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
// pop and go to bottom, this should go back up to the end of the first margin
RenderOperation::PopMargin,
RenderOperation::JumpToBottomRow { index: 0 },
RenderOperation::RenderText { line: "C".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
]);
let expected = [
Instruction::MoveToColumn(2),
Instruction::PrintText("A".into()),
// 100 - 10 (margin) - 10 (second margin)
Instruction::MoveToRow(79),
Instruction::MoveToColumn(2),
Instruction::PrintText("B".into()),
// 100 - 10 (margin)
Instruction::MoveToRow(89),
Instruction::MoveToColumn(1),
Instruction::PrintText("C".into()),
];
assert_eq!(ops, expected);
}
#[test]
fn margin_with_max_size() {
let ops = render_with_max_size(&[
RenderOperation::RenderText { line: "A".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
RenderOperation::ApplyMargin(MarginProperties { horizontal: Margin::Fixed(1), top: 2, bottom: 1 }),
RenderOperation::RenderText { line: "B".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
RenderOperation::JumpToBottomRow { index: 0 },
RenderOperation::RenderText { line: "C".into(), alignment: Alignment::Left { margin: Margin::Fixed(0) } },
]);
let expected = [
// centered 20x10
Instruction::MoveTo(40, 45),
Instruction::MoveToColumn(40),
Instruction::PrintText("A".into()),
// jump 2 down because of top margin
Instruction::MoveToRow(47),
// jump 1 right because of horizontal margin
Instruction::MoveToColumn(41),
Instruction::PrintText("B".into()),
// rows go from 47 to 53 (7 total)
Instruction::MoveToRow(53),
Instruction::MoveToColumn(41),
Instruction::PrintText("C".into()),
];
assert_eq!(ops, expected);
}
// print the same 2x2 image with all size configs, they should all yield the same
#[rstest]
#[case::shrink(ImageSize::ShrinkIfNeeded)]
#[case::specific(ImageSize::Specific(2, 2))]
#[case::width_scaled(ImageSize::WidthScaled { ratio: 1.0 })]
fn image(#[case] size: ImageSize) {
let image = DynamicImage::new(2, 2, ColorType::Rgba8);
let image = Image::new(TerminalImage::Ascii(image.into()), ImageSource::Generated);
let properties = ImageRenderProperties {
z_index: 0,
size,
restore_cursor: false,
background_color: None,
position: ImagePosition::Cursor,
};
let ops = render_with_max_size(&[RenderOperation::RenderImage(image, properties)]);
let expected = [
// centered 20x10, the image is 2x2 so we stand one away from center
Instruction::MoveTo(40, 45),
Instruction::MoveToColumn(40),
Instruction::PrintImage(PrintOptions {
columns: 2,
rows: 2,
z_index: 0,
background_color: None,
column_width: 2,
row_height: 2,
}),
// place cursor after the image
Instruction::MoveToRow(47),
];
assert_eq!(ops, expected);
}
// same as the above but center it
#[rstest]
#[case::shrink(ImageSize::ShrinkIfNeeded)]
#[case::specific(ImageSize::Specific(2, 2))]
#[case::width_scaled(ImageSize::WidthScaled { ratio: 1.0 })]
fn centered_image(#[case] size: ImageSize) {
let image = DynamicImage::new(2, 2, ColorType::Rgba8);
let image = Image::new(TerminalImage::Ascii(image.into()), ImageSource::Generated);
let properties = ImageRenderProperties {
z_index: 0,
size,
restore_cursor: false,
background_color: None,
position: ImagePosition::Center,
};
let ops = render_with_max_size(&[RenderOperation::RenderImage(image, properties)]);
let expected = [
// centered 20x10, the image is 2x2 so we stand one away from center
Instruction::MoveTo(40, 45),
Instruction::MoveToColumn(49),
Instruction::PrintImage(PrintOptions {
columns: 2,
rows: 2,
z_index: 0,
background_color: None,
column_width: 2,
row_height: 2,
}),
// place cursor after the image
Instruction::MoveToRow(47),
];
assert_eq!(ops, expected);
}
// same as the above but use right alignment
#[rstest]
#[case::shrink(ImageSize::ShrinkIfNeeded)]
#[case::specific(ImageSize::Specific(2, 2))]
#[case::width_scaled(ImageSize::WidthScaled { ratio: 1.0 })]
fn right_aligned_image(#[case] size: ImageSize) {
let image = DynamicImage::new(2, 2, ColorType::Rgba8);
let image = Image::new(TerminalImage::Ascii(image.into()), ImageSource::Generated);
let properties = ImageRenderProperties {
z_index: 0,
size,
restore_cursor: false,
background_color: None,
position: ImagePosition::Right,
};
let ops = render_with_max_size(&[RenderOperation::RenderImage(image, properties)]);
let expected = [
// right aligned 20x10, the image is 2x2 so we stand one away from the right
Instruction::MoveTo(40, 45),
Instruction::MoveToColumn(58),
Instruction::PrintImage(PrintOptions {
columns: 2,
rows: 2,
z_index: 0,
background_color: None,
column_width: 2,
row_height: 2,
}),
// place cursor after the image
Instruction::MoveToRow(47),
];
assert_eq!(ops, expected);
}
// same as the above but center it
#[rstest]
fn restore_cursor_after_image() {
let image = DynamicImage::new(2, 2, ColorType::Rgba8);
let image = Image::new(TerminalImage::Ascii(image.into()), ImageSource::Generated);
let properties = ImageRenderProperties {
z_index: 0,
size: ImageSize::ShrinkIfNeeded,
restore_cursor: true,
background_color: None,
position: ImagePosition::Center,
};
let ops = render_with_max_size(&[RenderOperation::RenderImage(image, properties)]);
let expected = [
// centered 20x10, the image is 2x2 so we stand one away from center
Instruction::MoveTo(40, 45),
Instruction::MoveToColumn(49),
Instruction::PrintImage(PrintOptions {
columns: 2,
rows: 2,
z_index: 0,
background_color: None,
column_width: 2,
row_height: 2,
}),
// place cursor after the image
Instruction::MoveTo(40, 45),
];
assert_eq!(ops, expected);
Self { dimensions, start_column: self.start_column }
}
}

View File

@ -1,9 +1,7 @@
use crate::{
code::snippet::SnippetLanguage,
markdown::{
elements::{Line, Text},
text_style::{Color, TextStyle},
},
markdown::elements::{Text, TextBlock},
processing::code::SnippetLanguage,
style::{Color, TextStyle},
theme::CodeBlockStyle,
};
use flate2::read::ZlibDecoder;
@ -40,16 +38,16 @@ pub struct HighlightThemeSet {
impl HighlightThemeSet {
/// Construct a new highlighter using the given [syntect] theme name.
pub fn load_by_name(&self, name: &str) -> Option<SnippetHighlighter> {
pub fn load_by_name(&self, name: &str) -> Option<CodeHighlighter> {
let mut themes = self.themes.borrow_mut();
// Check if we already loaded this one.
if let Some(theme) = themes.get(name).cloned() {
Some(SnippetHighlighter { theme })
Some(CodeHighlighter { theme })
}
// Otherwise try to deserialize it from bat's themes
else if let Some(theme) = self.deserialize_bat_theme(name) {
themes.insert(name.into(), theme.clone());
Some(SnippetHighlighter { theme })
Some(CodeHighlighter { theme })
} else {
None
}
@ -85,13 +83,13 @@ impl Default for HighlightThemeSet {
}
}
/// A snippet highlighter.
/// A code highlighter.
#[derive(Clone)]
pub(crate) struct SnippetHighlighter {
pub struct CodeHighlighter {
theme: Rc<Theme>,
}
impl SnippetHighlighter {
impl CodeHighlighter {
/// Create a highlighter for a specific language.
pub(crate) fn language_highlighter(&self, language: &SnippetLanguage) -> LanguageHighlighter {
let extension = Self::language_extension(language);
@ -125,13 +123,11 @@ impl SnippetHighlighter {
File => "txt",
Fish => "fish",
Go => "go",
GraphQL => "graphql",
Haskell => "hs",
Html => "html",
Java => "java",
JavaScript => "js",
Json => "json",
Julia => "jl",
Kotlin => "kt",
Latex => "tex",
Lua => "lua",
@ -156,14 +152,12 @@ impl SnippetHighlighter {
Sql => "sql",
Swift => "swift",
Svelte => "svelte",
Tcl => "tcl",
Terraform => "tf",
Toml => "toml",
TypeScript => "ts",
Typst => "txt",
// default to plain text so we get the same look&feel
Unknown(_) => "txt",
Verilog => "v",
Vue => "vue",
Xml => "xml",
Yaml => "yaml",
@ -173,7 +167,7 @@ impl SnippetHighlighter {
}
}
impl Default for SnippetHighlighter {
impl Default for CodeHighlighter {
fn default() -> Self {
let themes = HighlightThemeSet::default();
themes.load_by_name("base16-eighties.dark").expect("default theme not found")
@ -185,11 +179,11 @@ pub(crate) struct LanguageHighlighter<'a> {
}
impl LanguageHighlighter<'_> {
pub(crate) fn highlight_line(&mut self, line: &str, block_style: &CodeBlockStyle) -> Line {
pub(crate) fn highlight_line(&mut self, line: &str, block_style: &CodeBlockStyle) -> TextBlock {
self.style_line(line, block_style)
}
pub(crate) fn style_line(&mut self, line: &str, block_style: &CodeBlockStyle) -> Line {
pub(crate) fn style_line(&mut self, line: &str, block_style: &CodeBlockStyle) -> TextBlock {
let texts: Vec<_> = self
.highlighter
.highlight_line(line, &SYNTAX_SET)
@ -197,7 +191,7 @@ impl LanguageHighlighter<'_> {
.into_iter()
.map(|(style, tokens)| StyledTokens::new(style, tokens, block_style).apply_style())
.collect();
Line(texts)
TextBlock(texts)
}
}
@ -208,7 +202,7 @@ pub(crate) struct StyledTokens<'a> {
impl<'a> StyledTokens<'a> {
pub(crate) fn new(style: Style, tokens: &'a str, block_style: &CodeBlockStyle) -> Self {
let has_background = block_style.background;
let has_background = block_style.background.unwrap_or(true);
let background = has_background.then_some(parse_color(style.background)).flatten();
let foreground = parse_color(style.foreground);
let mut style = TextStyle::default();
@ -258,7 +252,7 @@ mod test {
#[test]
fn language_extensions_exist() {
for language in SnippetLanguage::iter() {
let extension = SnippetHighlighter::language_extension(&language);
let extension = CodeHighlighter::language_extension(&language);
let syntax = SYNTAX_SET.find_syntax_by_extension(extension);
assert!(syntax.is_some(), "extension {extension} for {language:?} not found");
}
@ -266,7 +260,7 @@ mod test {
#[test]
fn default_highlighter() {
SnippetHighlighter::default();
CodeHighlighter::default();
}
#[test]

View File

@ -4,12 +4,11 @@ use crate::{render::properties::WindowSize, theme::Alignment};
pub(crate) struct Layout {
alignment: Alignment,
start_column_offset: u16,
font_size: u16,
}
impl Layout {
pub(crate) fn new(alignment: Alignment) -> Self {
Self { alignment, start_column_offset: 0, font_size: 1 }
Self { alignment, start_column_offset: 0 }
}
pub(crate) fn with_start_column(mut self, column: u16) -> Self {
@ -17,13 +16,7 @@ impl Layout {
self
}
pub(crate) fn with_font_size(mut self, font_size: u8) -> Self {
self.font_size = font_size as u16;
self
}
pub(crate) fn compute(&self, dimensions: &WindowSize, text_length: u16) -> Positioning {
let text_length = text_length * self.font_size;
let max_line_length;
let mut start_column;
match &self.alignment {

View File

@ -1,161 +1,8 @@
pub(crate) mod ascii_scaler;
pub(crate) mod draw;
pub(crate) mod engine;
pub(crate) mod highlighting;
pub(crate) mod layout;
pub(crate) mod operation;
pub(crate) mod properties;
pub(crate) mod terminal;
pub(crate) mod text;
pub(crate) mod validate;
use crate::{
markdown::{
elements::Text,
text::WeightedLine,
text_style::{Color, Colors, PaletteColorError, TextStyle},
},
render::{operation::RenderOperation, properties::WindowSize},
terminal::{
Terminal,
image::printer::{ImagePrinter, PrintImageError},
printer::TerminalError,
},
theme::{Alignment, Margin},
};
use engine::{MaxSize, RenderEngine, RenderEngineOptions};
use operation::AsRenderOperations;
use std::{
io::{self, Stdout},
iter,
rc::Rc,
sync::Arc,
};
/// The result of a render operation.
pub(crate) type RenderResult = Result<(), RenderError>;
pub(crate) struct TerminalDrawerOptions {
pub(crate) font_size_fallback: u8,
pub(crate) max_size: MaxSize,
}
impl Default for TerminalDrawerOptions {
fn default() -> Self {
Self { font_size_fallback: 1, max_size: Default::default() }
}
}
/// Allows drawing on the terminal.
pub(crate) struct TerminalDrawer {
pub(crate) terminal: Terminal<Stdout>,
options: TerminalDrawerOptions,
}
impl TerminalDrawer {
pub(crate) fn new(image_printer: Arc<ImagePrinter>, options: TerminalDrawerOptions) -> io::Result<Self> {
let terminal = Terminal::new(io::stdout(), image_printer)?;
Ok(Self { terminal, options })
}
pub(crate) fn render_operations<'a>(
&mut self,
operations: impl Iterator<Item = &'a RenderOperation>,
) -> RenderResult {
let dimensions = WindowSize::current(self.options.font_size_fallback)?;
let engine = self.create_engine(dimensions);
engine.render(operations)?;
Ok(())
}
pub(crate) fn render_error(&mut self, message: &str, source: &ErrorSource) -> RenderResult {
let operation = RenderErrorOperation { message: message.into(), source: source.clone() };
let operation = RenderOperation::RenderDynamic(Rc::new(operation));
let dimensions = WindowSize::current(self.options.font_size_fallback)?;
let engine = self.create_engine(dimensions);
engine.render(iter::once(&operation))?;
Ok(())
}
pub(crate) fn render_engine_options(&self) -> RenderEngineOptions {
RenderEngineOptions { max_size: self.options.max_size.clone(), ..Default::default() }
}
fn create_engine(&mut self, dimensions: WindowSize) -> RenderEngine<Terminal<Stdout>> {
let options = self.render_engine_options();
RenderEngine::new(&mut self.terminal, dimensions, options)
}
}
/// A rendering error.
#[derive(thiserror::Error, Debug)]
pub(crate) enum RenderError {
#[error("io: {0}")]
Io(#[from] io::Error),
#[error("terminal: {0}")]
Terminal(#[from] TerminalError),
#[error("screen is too small")]
TerminalTooSmall,
#[error("tried to move to non existent layout location")]
InvalidLayoutEnter,
#[error("tried to pop default screen")]
PopDefaultScreen,
#[error("printing image: {0}")]
PrintImage(#[from] PrintImageError),
#[error("horizontal overflow")]
HorizontalOverflow,
#[error("vertical overflow")]
VerticalOverflow,
#[error(transparent)]
PaletteColor(#[from] PaletteColorError),
}
#[derive(Clone, Debug)]
pub(crate) enum ErrorSource {
Presentation,
Slide(usize),
}
#[derive(Debug)]
struct RenderErrorOperation {
message: String,
source: ErrorSource,
}
impl AsRenderOperations for RenderErrorOperation {
fn as_render_operations(&self, dimensions: &WindowSize) -> Vec<RenderOperation> {
let heading_text = match self.source {
ErrorSource::Presentation => "Error loading presentation".to_string(),
ErrorSource::Slide(slide) => {
format!("Error in slide {slide}")
}
};
let heading = vec![Text::new(heading_text, TextStyle::default().bold()), Text::from(": ")];
let total_lines = self.message.lines().count();
let starting_row = (dimensions.rows / 2).saturating_sub(total_lines as u16 / 2 + 3);
let alignment = Alignment::Left { margin: Margin::Percent(25) };
let mut operations = vec![
RenderOperation::SetColors(Colors {
foreground: Some(Color::new(255, 0, 0)),
background: Some(Color::new(0, 0, 0)),
}),
RenderOperation::ClearScreen,
RenderOperation::JumpToRow { index: starting_row },
RenderOperation::RenderText { line: WeightedLine::from(heading), alignment },
RenderOperation::RenderLineBreak,
RenderOperation::RenderLineBreak,
];
for line in self.message.lines() {
let error = vec![Text::from(line)];
let op = RenderOperation::RenderText { line: WeightedLine::from(error), alignment };
operations.extend([op, RenderOperation::RenderLineBreak]);
}
operations
}
}

View File

@ -1,220 +0,0 @@
use super::properties::WindowSize;
use crate::{
markdown::{
text::{WeightedLine, WeightedText},
text_style::{Color, Colors},
},
terminal::image::Image,
theme::{Alignment, Margin},
};
use std::{
fmt::Debug,
rc::Rc,
sync::{Arc, Mutex},
};
const DEFAULT_IMAGE_Z_INDEX: i32 = -2;
/// A line of preformatted text to be rendered.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BlockLine {
pub(crate) prefix: WeightedText,
pub(crate) right_padding_length: u16,
pub(crate) repeat_prefix_on_wrap: bool,
pub(crate) text: WeightedLine,
pub(crate) block_length: u16,
pub(crate) block_color: Option<Color>,
pub(crate) alignment: Alignment,
}
/// A render operation.
///
/// Render operations are primitives that allow the input markdown file to be decoupled with what
/// we draw on the screen.
#[derive(Clone, Debug)]
pub(crate) enum RenderOperation {
/// Clear the entire screen.
ClearScreen,
/// Set the colors to be used for any subsequent operations.
SetColors(Colors),
/// Jump the draw cursor into the vertical center, that is, at `screen_height / 2`.
JumpToVerticalCenter,
/// Jumps to the N-th row in the current layout.
///
/// The index is zero based where 0 represents the top row.
JumpToRow { index: u16 },
/// Jumps to the N-th to last row in the current layout.
///
/// The index is zero based where 0 represents the bottom row.
JumpToBottomRow { index: u16 },
/// Jump to the N-th column in the current layout.
JumpToColumn { index: u16 },
/// Render text.
RenderText { line: WeightedLine, alignment: Alignment },
/// Render a line break.
RenderLineBreak,
/// Render an image.
RenderImage(Image, ImageRenderProperties),
/// Render a line.
RenderBlockLine(BlockLine),
/// Render a dynamically generated sequence of render operations.
///
/// This allows drawing something on the screen that requires knowing dynamic properties of the
/// screen, like window size, without coupling the transformation of markdown into
/// [RenderOperation] with the screen itself.
RenderDynamic(Rc<dyn AsRenderOperations>),
/// An operation that is rendered asynchronously.
RenderAsync(Rc<dyn RenderAsync>),
/// Initialize a column layout.
///
/// The value for each column is the width of the column in column-unit units, where the entire
/// screen contains `columns.sum()` column-units.
InitColumnLayout { columns: Vec<u8> },
/// Enter a column in a column layout.
///
/// The index is 0-index based and will be tied to a previous `InitColumnLayout` operation.
EnterColumn { column: usize },
/// Exit the current layout and go back to the default one.
ExitLayout,
/// Apply a margin to every following operation.
ApplyMargin(MarginProperties),
/// Pop an `ApplyMargin` operation.
PopMargin,
}
/// The properties of an image being rendered.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ImageRenderProperties {
pub(crate) z_index: i32,
pub(crate) size: ImageSize,
pub(crate) restore_cursor: bool,
pub(crate) background_color: Option<Color>,
pub(crate) position: ImagePosition,
}
impl Default for ImageRenderProperties {
fn default() -> Self {
Self {
z_index: DEFAULT_IMAGE_Z_INDEX,
size: Default::default(),
restore_cursor: false,
background_color: None,
position: ImagePosition::Center,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum ImagePosition {
Cursor,
Center,
Right,
}
/// The size used when printing an image.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) enum ImageSize {
#[default]
ShrinkIfNeeded,
Specific(u16, u16),
WidthScaled {
ratio: f64,
},
}
/// Slide properties, set on initialization.
#[derive(Clone, Debug, Default)]
pub(crate) struct MarginProperties {
/// The horizontal margin.
pub(crate) horizontal: Margin,
/// The margin at the top.
pub(crate) top: u16,
/// The margin at the bottom.
pub(crate) bottom: u16,
}
/// A type that can generate render operations.
pub(crate) trait AsRenderOperations: Debug + 'static {
/// Generate render operations.
fn as_render_operations(&self, dimensions: &WindowSize) -> Vec<RenderOperation>;
/// Get the content in this type to diff it against another `AsRenderOperations`.
fn diffable_content(&self) -> Option<&str> {
None
}
}
/// An operation that can be rendered asynchronously.
pub(crate) trait RenderAsync: AsRenderOperations {
/// Create a pollable for this render async.
///
/// The pollable will be used to poll this by a separate thread, so all state that will
/// be loaded asynchronously should be shared between this operation and any pollables
/// generated from it.
fn pollable(&self) -> Box<dyn Pollable>;
/// Get the start policy for this render.
fn start_policy(&self) -> RenderAsyncStartPolicy {
RenderAsyncStartPolicy::OnDemand
}
}
/// The start policy for an async render.
#[derive(Copy, Clone, Debug)]
pub(crate) enum RenderAsyncStartPolicy {
/// Start automatically.
Automatic,
/// Start on demand.
OnDemand,
}
/// A pollable that can be used to pull and update the state of an operation asynchronously.
pub(crate) trait Pollable: Send + 'static {
/// Update the internal state and return the updated state.
fn poll(&mut self) -> PollableState;
}
/// The state of a [Pollable].
#[derive(Clone, Debug)]
pub(crate) enum PollableState {
Unmodified,
Modified,
Done,
Failed { error: String },
}
pub(crate) struct ToggleState {
toggled: Arc<Mutex<bool>>,
}
impl ToggleState {
pub(crate) fn new(toggled: Arc<Mutex<bool>>) -> Self {
Self { toggled }
}
}
impl Pollable for ToggleState {
fn poll(&mut self) -> PollableState {
*self.toggled.lock().unwrap() = true;
PollableState::Done
}
}

Some files were not shown because too many files have changed in this diff Show More