Download the PHP package torchlight/engine without Composer
On this page you can find all versions of the php package torchlight/engine. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download torchlight/engine
More information about torchlight/engine
Files in torchlight/engine
Package engine
Short Description The PHP-based Torchlight code annotation and rendering engine.
License MIT
Informations about the package engine
Torchlight Engine brings Torchlight's code annotation syntax to PHP, built on top of the excellent Phiki syntax highlighting package. No node or API required.
Torchlight enables you to add annotations to your code, drawing your reader's attention to specific parts, highlighting lines, visualizing diffs, and much more. Combined with the syntax highlighting provided by Phiki, Torchlight is a perfect fit for technical blogs, documentation, and so much more.
Torchlight annotations are written as comments in the language of your code sample, eliminating red squigglies and errors within your editor or IDE.
As an example, here is how we could focus our reader's attention on lines 6 and 7:
When rendered, our readers would be presented with something like the following:
How simple is that? We're pretty proud of it and know you'll love it, too.
- Installation
- Getting Started
- Modifying the CommonMark Extension
- Specifying the Extension's Default Language
- Caching Highlighted Code
- Laravel
- Statamic
- Rendering Code Manually
- Notes on User Provided Content
- Frequently Asked Questions
- Is the Torchlight API going away now?
- How much does Torchlight Engine cost?
- Does Torchlight Engine require an API key or network access?
- What about the Laravel and CommonMark packages?
- Will this package replace the existing CommonMark package?
- Some themes are missing compared to the API version. How come?
- Can I add custom themes to Torchlight Engine?
- Are the custom grammars from the API version supported?
- Some of my highlighting looks different now. How come?
- Are there breaking changes?
- Differences Between Torchlight Engine and Torchlight API
- CSS and Theming
- Standard CSS
- Tailwind
- Dark Mode
- Available Themes
- Custom Themes
- Registering a Theme from a File
- Registering a Theme from an Array
- Overriding Theme Colors
-
Annotations
- Plain Text Annotations
- JSON Annotations
- Ranges
- Annotation Range Cheat Sheet
- Single Lines
- N-Many Lines
- Offset and Length
- Applying an Annotation to All Lines
- Start and End
- Supported Annotations
- Highlighting Lines
- Alternative Highlight Class
- Highlight Shorthand
- Focusing
- Focusing Shorthand
- Focusing CSS
- Collapsing
- Customizing the Summary Text
- Collapsing Required CSS
- Default to Open
- Removing Summary Carets
- Hiding Lines
- Diffs
- Diff Shorthand
- Removing Diff Indicators
- Standalone Diff Indicators
- Diff Indicators Without Line Numbers
- Diff Ranges
- Preserving Syntax Colors
- Word Diff
- Classes and IDs
- Using Range Modifiers
-
Character Ranges
- Linking
- Auto-linking URLs
- Link Requirements
- Link Ranges
- Reindexing Line Numbers
- Manually Setting a New Number
- No Line Number at All
- Relative Line Number Changes
- Reindexing with Range Modifiers
- Reindex Differences Between Torchlight API
- Vim-style Relative Line Numbers
- Highlighting Files and Directory Structures
- Options
- Setting Default Options Globally
- Setting Default Themes Globally
- Setting Options Per Block
- Line Numbers
- Changing the Starting Line Number
- Changing Line Number Styles
- Adding Line Number Right Padding
- Summary Indicator
- Adding Extra Classes to the Torchlight Code Element
- The Copyable Option
- Indent Guides
- Column Guides
- Disabling Torchlight Annotations
- Extensibility
- Custom Annotations
- Annotation Macros
- Replacers
- Token Transformers
- Block Decorators
- Reporting Issues
- Contributing
- Credits
- License
Installation
You may install Torchlight Engine via Composer:
Torchlight Engine requires at least PHP 8.2, but PHP 8.4+ is recommended.
Getting Started
Torchlight Engine provides a league/commonmark extension, making it simple to start using Torchlight in your markdown content.
You may register the extension with any CommonMark Environment object like so:
`php
`
Modifying the CommonMark Extension
The CommonMark extension provides a few different ways to modify its behavior.
Specifying the Extension's Default Language
To change the extension's default language that should be used when authors omit the language on a code block, we can call the setDefaultGrammar on the underlying renderer:
This code block would now use PHP by default. `
Caching Highlighted Code
A custom cache may be used to cache highlighted code blocks. Integrators may implement the Torchlight\Engine\CommonMark\BlockCache interface:
The cache implementation may be set on the extension by calling the setBlockCache on the underlying renderer:
Laravel
[!NOTE] This section highlights using the provided CommonMark extension with Laravel. Updated versions of the Laravel client are planned for the future.
You may use the provided CommonMark extension with Laravel's Str::markdown() or str()->markdown() methods by adding the extension to your method call:
Statamic
To integrate Torchlight Engine with Statamic, you may add the CommonMark extension like so:
Rendering Code Manually
You may also use the engine "manually". The following code example provides the minimum amount of code to use the Engine to render code:
Notes on User Provided Content
Phiki and Torchlight Engine, while incredibly powerful, are still early projects, and it is possible to encounter infinite loops with some grammars and input. As always, you should exercise caution when rendering any user-provided content.
If you encounter one of these scenarios please create an issue so it can be looked into.
Frequently Asked Questions
Is the Torchlight API going away now?
The Torchlight API will remain as-is for now. Any changes to the hosted service will be communicated ahead of time.
How much does Torchlight Engine cost?
Torchlight Engine is free.
Does Torchlight Engine require an API key or network access?
No. Torchlight Engine is a PHP-based, offline renderer built on top of Phiki.
What about the Laravel and CommonMark packages?
There are plans to upgrade both of these packages to support Torchlight Engine. More information on this topic will come in the future.
Will this package replace the existing CommonMark package?
No, there are no immediate plans to deprecate the existing CommonMark package as it provides additional features not currently available in the extension shipped with this package (notably integration with the torchlight.php configuration file). However, if you need a CommonMark extension that has no Laravel dependency, the extension provided by this package is what you are looking for.
Some themes are missing compared to the API version. How come?
Some themes available via. Torchlight API are not available with Torchlight Engine; this is largely due to them not being distributed any longer, or licensing information was not readily available. You can add your own themes using the methods described in Custom Themes.
Can I add custom themes to Torchlight Engine?
Yes! You can register custom themes from a file or an array, and override colors on existing themes. See Custom Themes for details.
Are the custom grammars from the API version supported?
Yes, even the files grammar!
Some of my highlighting looks different now. How come?
There may be differences in highlighting due to the underlying tokenizer and theme system. Please report any egregious issues and we will work to help get them resolved.
Are there breaking changes?
Great care has been taken to avoid breaking changes, and adhere to the existing HTML structure as closely as possible. However, there are some scenarios where behavior has been changed.
Please refer to the Differences Between Torchlight Engine and Torchlight API section for more information.
Differences Between Torchlight Engine and Torchlight API
There are a small number of differences when comparing Torchlight Engine and the Torchlight API versions:
- Invalid JSON input for block options will throw an instance of
Torchlight\Engine\Exceptions\InvalidJsonException. The API version may attempt to parse the invalid JSON or silently discard the error. - The been adjusted to be more predictable and consistent with other modifiers.
- Dark mode support no longer requires duplicate code blocks.
- The
lineNumberAndDiffIndicatorRightPaddingblock option applies padding more predictably.- When using
lineNumberAndDiffIndicatorRightPaddinganddiffIndicatorsInPlaceOfLineNumbers: falsetogether, the padding will be added to the right of the diff indicators, instead of in-between them.
- When using
CSS and Theming
Torchlight handles the highlighting of all of your code for you, but there are a few styles that you will likely need to add to your CSS to make it just right.
This is the CSS we prefer, which sets up some line padding, margin off of the line numbers, and overflow scrolling. Your CSS is totally up to you though!
Standard CSS
This is the vanilla CSS version, see below for the TailwindCSS version.
Tailwind
Here is the Tailwind version:
Dark Mode
Torchlight Engine utilizes Phiki for syntax highlighting, and recommends using its multi-theme support for dark mode.
When instantiating an instance of the CommonMark extension, you may supply multiple themes like so:
The first entry, light in this case, will be used as the default theme. Other themes in the array may be conditionally rendered with CSS.
Query-based dark mode:
Class-based dark mode:
You can learn more about rendering multiple themes with Phiki here. The only change when rendering multiple themes with Torchlight Engine is the placement of the background-color property, to prevent conflicts with some annotations, such as diff add and remove.
Available Themes
The following themes are available:
- one-dark-pro
- solarized-light
- vitesse-black
- github-light-default
- slack-dark
- everforest-dark
- rose-pine-moon
- everforest-light
- laserwave
- github-light-high-contrast
- catppuccin-mocha
- red
- material-theme-lighter
- one-light
- aurora-x
- tokyo-night
- catppuccin-macchiato
- github-dark
- rose-pine-dawn
- poimandres
- github-dark-high-contrast
- material-theme
- dracula
- github-dark-default
- github-dark-dimmed
- rose-pine
- kanagawa-lotus
- kanagawa-dragon
- dark-plus
- ayu-dark
- min-dark
- monokai
- nord
- catppuccin-frappe
- github-light
- dracula-soft
- synthwave-84
- vitesse-dark
- andromeeda
- light-plus
- slack-ochin
- solarized-dark
- material-theme-ocean
- vitesse-light
- vesper
- kanagawa-wave
- plastic
- material-theme-darker
- night-owl
- catppuccin-latte
- min-light
- snazzy-light
- houston
- material-theme-palenight
- atom-one-dark
- cobalt2
- dark-404
- fortnite
- material-theme-default
- moonlight-ii
- moonlight
- olaolu-palenight-contrast
- olaolu-palenight
- serendipity-dark
- serendipity-light
- shades-of-purple
- slack-theme-dark-mode
- slack-theme-ochin
- winter-is-coming-blue
- winter-is-coming-dark
- winter-is-coming-light
Custom Themes
You can register custom themes from a VS Code theme file, an array, or override colors on existing themes.
Registering a Theme from a File
The theme file should be a standard VS Code theme JSON file with colors and tokenColors keys.
Registering a Theme from an Array
Overriding Theme Colors
You can override specific colors on any theme using Theme::override():
This works with multi-theme dark mode as well:
Torchlight-specific color keys are also available, such as torchlight.markupInsertedBackground, torchlight.markupDeletedBackground, torchlight.activeLineNumberColor, and torchlight.lineNumberColor.
Annotations
One of the things that makes Torchlight such a joy to author with is that you can control how your code is rendered via comments in the code you're writing.
If you want to highlight a specific line, you can add a code comment with the magic syntax [tl! highlight] and that line will be highlighted.
Gone are the days of inscrutable line number definitions at the top of your file, only to have them become outdated the moment you add or remove a line.
Most other tools use a series of line numbers up front to denote highlight or focus lines:
`
If you don't have the syntax memorized, it's hard to tell what those numbers mean. And of course when you add a line or remove a line, everything changes and you have to recalculate!
With Torchlight, you control your display with inline annotations in comments.
All inline annotations are wrapped within square brackets and start with tl!, leaving you with the following format: [tl! ... ... ...].
For example, if you are using Torchlight to render the following block of PHP:
and you wanted to draw attention to lines 6 & 7, you could focus those lines by using the focus annotation:
Resulting in the following:
Notice that Torchlight is smart enough to not only strip the annotation from line 6, but the annotation and comment syntax from line 7, leaving your code pristine.
If the entirety of the comment is Torchlight annotations, the comment will be removed from the rendered code. If there is additional content in the comment, that content will remain and the annotation will be stripped out.
Because annotations are actual code comments, it doesn't mess up your authoring experience by throwing invalid characters in your code.
Inline annotations support different keywords, modifiers, and range definitions
- Annotating a Range of Lines
- Highlighting Lines
- Focusing Lines
- Expanding and Collapsing Sections
- Diffing Lines
- Adding Custom IDs and Classes
- Auto-linking URLs
- Changing Line Numbers
Remember that the comment syntax varies based on what language you are highlighting, so be sure to use actual comments.
For example if you're highlighting HTML, you would use HTML comment tags <!-- -->. See the example on line 5.
Annotations can be used with plain text and JSON, despite them having no "official" comment support as a language.
Plain Text Annotations
For plain text, everything is treated "as if" it's a comment, so you can just put the annotation on any line.
JSON Annotations
JSON uses the double slash // comment style, even though it's not official spec. Forgive us.
Ranges
Sometimes you want to apply an annotation to a whole set of lines, without having to add dozens of comments.
We have provided several different methods to achieve this, so you may pick the one that best fits your use case.
Annotation Range Cheat Sheet
Single Lines
By default, every annotation applies only to the line that it lives on.
For example, this will only highlight the line it is on, line number 2.
N-Many Lines
To highlight the current line, and the next N lines, you may use the :N modifier.
In this example, we will highlight the current line (2) and the next two lines (3 & 4).
This also works with negative numbers :-N
Offset and Length
If you have a bit of code that is hard to reach with a comment, perhaps a heredoc, you can use the focus:M,N syntax where M is the number of lines above or below the current line, and N is the number of lines to highlight.
Here we're going to start 6 lines down, and highlight 3 lines total.
You can also start from the bottom by using a negative offset. We'll start 7 lines up and highlight 3 lines again.
Applying an Annotation to All Lines
You may use the all modifier to apply an annotation to all lines. For example, the following would apply the autolink annotation to every line:
Start and End
Sometimes you want to define a start and end line, and annotate everything in the middle.
You may do this with the :start and :end modifiers.
Supported Annotations
All of them! Ranges are supported for all of the Torchlight annotation keywords:
highlight(alias~~)focus(alias**)add(alias++)remove(alias--)collapseautolinkreindexword-diff(aliaswd)monohidemarklinklensgutterregion
Custom classes and IDs are supported as well.
.my-custom-class:start.my-custom-class:end.my-custom-class:1,10.my-custom-class:3.my-custom-class:-1,5
Torchlight also plays nicely with prefixed Tailwind classes:
.sm:py-4:start.sm:py-4:end.sm:py-4:1,10.sm:py-4:3.sm:py-4:-1,5
Remember that an HTML ID must be unique on the page, so while it's unlikely that you'd want to apply an ID to a range of lines, you may want to apply it to a line you cannot reach.
For example, to reach four lines down and add an ID of popover-trigger, you could do the following:
Highlighting Lines
The highlight annotation will pull the line highlight background color from your chosen theme, and apply it to the background of the line, drawing focus to that specific line:
It also applies a line-highlight class to the line.
If you have any lines highlighted, Torchlight will add a has-highlight-lines class to your code tag.
Every theme is different in the way that it chooses to represent highlighted lines, so be sure to try a few out.
Alternative Highlight Class
If you don't like the highlight color that your theme uses, you can apply a custom class instead, e.g. .highlight or .foobar:
Highlight Shorthand
If you find typing highlight prohibitively slow (who has the time?), you can use ~~ as a shorthand.
Focusing
The focus annotation adds a line-focus class to the line, and a has-focus-lines class to your code tag.
Used in conjunction with the CSS below, every line that you've applied [tl! focus] to will be sharp and clear, and the rest will be blurry and dim. If a user hovers over the code block, everything will come into focus.
Focusing Shorthand
As an alternative to focus, you can use **.
Focusing CSS
Here is the CSS required to achieve the focus effect:
Collapsing
Sometimes in your documentation or a blog post, you want to focus the reader on a specific block of code, but allow them to see the rest of the code if they need to.
One way you can achieve that is by using the focus annotation to blur the irrelevant code, but you can also use Torchlight to collapse blocks of code using native HTML, no JavaScript required.
In this example, we're going to collapse the heading_permalink options, as they might distract from the point of the example.
We can do this by using the collapse annotation:
Collapsed section closed:
Collapsed section open:
These lines will now be wrapped in a summary / detail pair of tags, that allows the user to natively toggle the open and closed state of the block. Torchlight will also add a has-summaries class to your code tag anytime you define a summary range.
You can use the start end method of defining a range, or any of the other range modifiers.
Here's an example using the N-many modifier to collapse the 5 lines following the annotation:
Customizing the Summary Text
By default, Torchlight will add a subtle ... in place of the collapsed text, but you can customize that by passing in the summaryCollapsedIndicator options:
Collapsing Required CSS
You will need to add the following CSS to your page to accomplish the hiding:
Default to Open
By default, when you define a collapse range it will be collapsed. If you want to define the range but default it to open, you can add the open keyword:
Removing Summary Carets
You can disable summary carets by setting the showSummaryCarets block option:
Setting this to false will disable the collapse gutter entirely:
Hiding Lines
The hide annotation removes lines from the rendered output entirely. Contiguous hidden ranges are replaced with an elision indicator:
The hidden lines will be replaced with a <span class="tl-elision">...</span> marker. You can customize the placeholder text by passing it as an argument: [tl! hide("--- snip ---")].
The first line of a hidden range receives the line-elided class, and remaining hidden lines receive the line-hidden class. The code block gets a has-hidden-lines class.
Unlike collapse, hidden lines cannot be expanded by the user -- they are fully removed from the output.
Diffs
To demonstrate the addition and removal of lines, you can use the add and remove keywords.
Torchlight will look through your theme to find the appropriate foreground and background colors to apply to the specific lines.
It will also apply line-add and line-remove classes to the individual lines. To the code element it will apply the has-diff-lines class, and potentially has-add-lines and has-remove-lines.
Diff Shorthand
You can use ++ and -- as shorthand for add and remove.
Removing Diff Indicators
Here is an example of a diff, with no indicators.
Notice that the colors of the lines just change to the standard colors you expect to see.
If you'd like to show the +/- indicators, you can do so by turning them on at the block level, or globally in your client's configuration.
For these examples we'll do it at the block level so we can see how it works.
Let's change the behavior by passing diffIndicators: true.
Take a look where the line numbers are and notice the indicators:
[!NOTE] If you'd like to reindex the line numbers after a diff, you can do that.
Standalone Diff Indicators
By default, we swap them in place of the line numbers, but you can also disable that behavior by using the extremely descriptive, verbose option diffIndicatorsInPlaceOfLineNumbers.
Now the line numbers remain, and the indicators get their own column.
Each standalone indicator has the diff-indicator class applied, along with one of the following:
diff-indicator-add- For lines that were addeddiff-indicator-remove- For lines that were removeddiff-indicator-empty- For lines that were unchanged
Diff Indicators Without Line Numbers
In the scenario where you:
- turn on diff indicators
- turn off line numbers
- turn on diff indicators in place of line numbers (this is the default)
Your indicators will still show up in the line-number classes, not the standalone classes mentioned above.
The reason we have chosen this approach is so that you don't have to add the diff-indicator styles ever when you choose to put your indicators in the line number column.
Diff Ranges
The diff annotations support the entire set of range modifiers to help you quickly annotate a whole set of lines.
Check out the range docs for more details, but here is a quick cheat sheet.
Preserving Syntax Colors
By default, the diff add and remove annotations will apply the corresponding text color, replacing the original token colors:
Notice how the text color has changed to red and green? We can disable this by setting the diffPreserveSyntaxColors block option:
Word Diff
For more granular diffs, you can use the word-diff annotation (shorthand wd) to show word-level differences between two consecutive lines. Place the annotation on the second line, and Torchlight will compute the differences against the line above it:
The annotated line is removed from the output, and the differences are rendered inline on the previous line using <span class="word-diff-del"> and <span class="word-diff-ins"> elements. A has-word-diff class is added to the code block, and the modified line receives a line-word-diff class.
You can use multiple wd annotations in a single block, each comparing against its preceding line.
Classes and IDs
You can add your own custom classes by preceding them with a ., or add an ID with a #.
You can space out your classes like we did above, or just run them all together: .font-bold.italic.animate-pulse#pulse
Torchlight also supports Tailwind + the Tailwind JIT syntax, so you can do pretty much anything you can think of:
Using Range Modifiers
You can also apply any range modifiers to custom classes.
Check out the range docs for more details, but here is a quick cheat sheet.
Remember that an HTML ID must be unique on the page, so while it's unlikely that you'd want to apply an ID to a range of lines, you may want to apply it to a line you cannot reach.
For example, to reach four lines down and add an ID of popover-trigger, you could do the following:
Character Ranges
You may also apply classes and IDs to character ranges on the current line by prefixing your range with the c character. Instead of supplying a range of line numbers, we supply the character range.
For example, the range .inner-highlight:c26,34 instructs Torchlight to wrap the tokens from characters 26 through 34 with the inner-highlight class:
[!NOTE] You will need to add the desired CSS to style your character range classes.
Linking
The link annotation makes lines or character ranges clickable. Pass the URL as an argument:
This wraps the line content in an <a href="..." class="tl-link"> tag and adds a has-links class to the code block.
For inline links on specific text, use a character range:
This adds a tl-link class and data-href attribute to the character range, which you can style with CSS.
[!NOTE] For automatically linking URLs that appear in your code, see Auto-linking URLs instead.
Auto-linking URLs
Sometimes your code contains URLs to other supporting documentation. It's a nice experience for the reader if those URLs were actually links instead of having to copy-paste them.
It's a little thing, but Torchlight sweats the little things so you don't have to.
Using the autolink annotation, Torchlight will look for URLs and turn them into links for you.
The resulting link will look like this (color will change depending on your theme):
Torchlight adds a torchlight-link class, and rel + target attributes.
The rel=noopener attribute ensures that a malicious website doesn't have access to the window.opener property. Although this is less of a concern now with modern browsers, we still want you to be covered.
Read more about rel=noopener at mathiasbynens.github.io/rel-noopener.
Link Requirements
Your URL must start with one of the following in order to match:
http:https:www.
Link Ranges
The auto-link annotation supports the entire set of range modifiers to help you quickly annotate a whole set of lines.
Check out the range docs for more details, but here is a quick cheat sheet.
Reindexing Line Numbers
Now we're really getting into the weeds, but that's exactly what Torchlight is here for.
Sometimes it really matters what the line number is that goes along with your code sample. In the case where you can't get it right, you might be tempted to turn them off altogether.
Torchlight offers a few ways to reindex the lines, using the reindex annotation.
To reindex a line, you will add the reindex annotation. This annotation is a little bit different than the others, because it accepts an argument in parenthesis.
Here are a few examples:
reindex(-1): whatever this line number would have been, reduce it by onereindex(+1): whatever this line number would have been, increment it by onereindex(5): regardless of what number this should be, make it5reindex(null): don't show a line number here.
Manually Setting a New Number
To just outright set a new number, use the reindex(N) style:
Torchlight will continue with the next number after the one you set.
No Line Number at All
If you want a line to have no line number, use the reindex(null) annotation:
If you don't immediately reindex, Torchlight just treats that line as if it doesn't exist for numbering purposes.
Relative Line Number Changes
Often times it's easiest to think in terms of "increment" or "decrement" instead of thinking in absolutes. Especially as time goes on and your samples may change, it's nice to have the relative numbers always work.
This can be a really nice touch when showing diffs, to keep the numbering legit.
To change the numbers relatively, use the reindex(+N) and reindex(-N) styles.
Of course, it doesn't have to just be 1, it could be any number.
Reindexing with Range Modifiers
The reindex annotation does work with the annotation range modifiers, so you can do some pretty wacky stuff.
If you wanted to reach down several lines and apply a reindex, you totally could!
Here we are going to reach down 6 lines, and apply a +5 reindex to 1 line only.
Or if you wanted to null out the second stanza, you could do that also.
Why you would ever want to do this, I have no idea. But if you want to, you can!
Vim-style Relative Line Numbers
[!IMPORTANT]
Thevim.relativeandvim.preserveannotations were not designed to work in conjunction with other reindex annotations. Because of this, their use in combination with other reindex annotations is considered undefined behavior.
You may reindex your line numbers similar to Vim's relative line numbers. When you do this, the line numbers will count how far away they are from the annotation:
The annotation's line will be reindex to 0, since that is the distance away from the annotation. If you'd like to preserve the current line number, you may use the vim.preserve annotation instead:
Reindex Differences Between Torchlight API
Torchlight Engine makes some breaking changes when compared to the behavior of the Torchlight API. This was done to make the behavior of reindexing with annotation ranges more predictable and consistent with the other annotations; there should be little to no impact on your code examples unless you are doing some crazy things.
Be sure to double check any reindex examples if you are migrating from the Torchlight API!
Highlighting Files and Directory Structures
Torchlight provides a custom files language that can be used to highlight files and directory structures:
files // torchlight! { "lineNumbers": false, "fileStyle": "ascii" } resources/ name with space/
Full line comment
blueprints/ # Partial comment
collections/
blog/
post.yaml # Old name [tl! --]
basic_post.yaml # New name [tl! ++]
art_directed_post.yaml
taxonomies/
tags/
tag.yaml
globals/
global.yaml
company.yaml
assets/
main.yaml
forms/
contact.yaml
user.yaml
`
The files language supports two modes or styles:
ascii: Renders connecting lines using ASCII charactershtml: Adds a number of HTML elements with class names that can be styled using CSS. If you'd like to use this option, you are encouraged to experiment with the generated output
Options
Each of these is covered in detail on its own page, but here is an overview of each option and what it does.
- lineNumbers - turn line numbers on or off
- lineNumbersStart - the number of the first line
- lineNumbersStyle - the CSS style to apply to line numbers
- lineNumberAndDiffIndicatorRightPadding - padding to the right of line numbers/indicators
- diffIndicators - turn on diff indicators (
+/-) - diffIndicatorsInPlaceOfLineNumbers - use the line number location for diff indicators
- diffPreserveSyntaxColors - keep syntax colors on diff lines
- summaryCollapsedIndicator - the text to show when a range is collapsed
- classes - extra CSS classes on the code element
- copyable - add a hidden element for copy-to-clipboard
- indentGuides - show indent guide lines (
"html","ascii", orfalse) - indentGuidesTabWidth - control the tab width used for indent guide calculation
- columnGuides - show vertical column guides at specific positions
- withGutter - show or hide the gutter area
- torchlightAnnotations - disable Torchlight annotation processing altogether.
Setting Default Options Globally
When using Torchlight Engine without any clients, or helper packages, we need to tell it how to resolve any default global options. This is done by specifying a callback function that returns the default options:
If you have an array of options, you may also use the static fromArray helper method:
As an example, if you are working in a Laravel project that already has a torchlight.php configuration file, you can continue using those options like so (this will become unnecessary once the Laravel client has been updated):
Setting Default Themes Globally
Like with global options, we need to specify a callback letting Torchlight Engine's CommonMark extension know which theme to use. This only applies if you do not specify a theme when instantiating the extension instance.
For example, we can specify default themes that will be used if the extension is not configured when instantiated:
As another example, we could use the torchlight.theme configuration value within an existing Laravel application like so:
Setting Options Per Block
Some blocks you'll want to set options individually. Any options you set on the block level will override that same option on the global level.
To set block level options, the first line of your block must be a comment, in the language of the block.
The comment must begin with torchlight! and be followed by valid JSON.
Line-based annotations may also be configured directly through block or global options. The following option keys map to their matching annotations: highlightLines, addLines, removeLines, focusLines, autolinkLines, monoLines, and hideLines.
Here is an example turning line numbers off for a single block:
Any option that you can set at the global level, you can set at the block level.
Line Numbers
Torchlight adds line numbers by default, but you can disable them globally or on the block level by changing the lineNumbers option to false.
Here's an example of the block level change:
Changing the Starting Line Number
To change the starting number of a block, you may use the lineNumbersStart option:
Note: we also have a reindex annotation to control the line number line by line.
Changing Line Number Styles
By default, Torchlight applies a reasonable set of CSS style to your line numbers:
If you want to control that, you can pass in a lineNumbersStyle option.
There are a couple of things to note when using this option.
The first is that you will likely want to include the -webkit-user-select: none; user-select: none; styles, so that when your visitors copy your code they don't get the line numbers. Because that's the worst.
Copy the code above and notice that the line numbers will be selected, versus the block right above it (Torchlight default).
The other thing to note is that you'll need to be thoughtful when adding color declarations.
Torchlight uses the theme's color scheme to handle insert and remove lines, so it's probably best to leave the color declaration off altogether.
Adding Line Number Right Padding
You may add right padding to your line numbers using the lineNumberAndDiffIndicatorRightPadding block option:
If you are using standalone diff indicators, right padding will be applied to the right of those:
Right padding being applied to the right of diff indicators is a small change in behavior compared to Torchlight API.
Summary Indicator
When using the collapse annotation, Torchlight will add an ellipses ... to indicate where the collapsed code is.
This is the default behavior:
If you'd like to change the ... to something else, you can do so by changing the summaryCollapsedIndicator option:
Adding Extra Classes to the Torchlight Code Element
You may add extra classes to the code element by using the classes block option:
When Torchlight renders the code block it will add those classes to the generated code block:
The Copyable Option
You can use the copyable block option to instruct Torchlight to add a hidden HTML element with the torchlight-copy-target class to the generated output. This hidden element will contain the raw text that may be used to implement a copy & paste feature:
Indent Guides
Torchlight can render vertical indent guide lines to help visualize code structure. Enable them with the indentGuides option:
The indentGuides option accepts:
"html"- render stylable guide spans inside the highlighted output"ascii"- render ASCII guide characters directly in the code outputfalse- disable indent guides (default)
You can also set the tab width used for guide calculation with indentGuidesTabWidth. If not set, Torchlight will auto-detect it from the code.
When using indentGuides: "html", indent guides require CSS for styling. The following snippet provides an example of how you might style indent guides:
Column Guides
Column guides render vertical guide markers at specific column positions, useful for showing line length limits:
You can specify multiple column positions:
For each column guide, Torchlight injects a <span class="torchlight-colguide torchlight-colguide-{col}"> element into each line and adds torchlight-colguide-{col} classes to line elements. The block receives a has-column-guides class and a --tl-colguide-max CSS variable set to the largest column value.
You may style these column guides with CSS:
Gutter Visibility
Set withGutter to false to remove the entire gutter area, including line numbers, diff markers, collapse indicators, and any custom gutter content:
Disabling Torchlight Annotations
If for whatever reason you want to disable all of the Torchlight annotations, you may do so with the torchlightAnnotations option.
This option was added specifically for these docs. We don't expect you'll need it unless you're trying to show how Torchlight works!
Extensibility
Torchlight Engine provides several extension points for customizing behavior without modifying the core.
Custom Annotations
You can register custom annotations using closures:
The AnnotationContext provides helpers for modifying lines and character ranges:
addBlockClass(string $class)- add a class to the code blockaddLineClass(array|string $class)- add a class to the annotated line(s)addLineAttribute(string $name, string $value)- add an HTML attribute to the lineaddAttributesToCharacterRange(array $attributes)- add attributes to a character rangeaddClassToCharacterRange(string $class)- add a class to a character rangegetMethodArgs()- get the annotation's method arguments (e.g., the value in[tl! name("value")])getOptions()- get the annotation's optionsisCharacterRange()- check if this is a character range annotationgetLineText(int $line)- get the text content of a linegetStartLine()/getEndLine()- get the annotation's line range
To support character ranges, pass true as the third argument:
Annotation Macros
Macros compose existing annotations under a single name:
Now [tl! important] will apply both highlight and the .important-line class.
Replacers
Replacers post-process the final HTML output. Use them to redact secrets or transform content:
Token Transformers
Token transformers modify the token output for specific grammars before rendering. Implement the TokenTransformer interface:
Block Decorators
Block decorators add content after the main code block. Implement the BlockDecorator interface:
Upgrading Custom Preprocessors
If you implement Torchlight\Engine\Contracts\Preprocessor, add a supports() method when upgrading:
If your preprocessor should only run for specific languages, return true only for those grammar names. Closure-based preprocessors are unchanged.
Reporting Issues
When reporting issues, please include all of the following information:
- Grammar/Language
- PHP Version
- Phiki version
- Minimum input text required to reproduce the issue
If you know an issue is related to Phiki and not the Torchlight renderer, please create an issue here. If you are not sure, feel free to create an issue in this repository and it will eventually end up in the right place.
Some issues may be difficult to resolve and take time to implement. Everyone involved thanks you in advance for your patience.
Contributing
Community contributions are welcome! However, if you are contributing additional themes or grammars, please take care to ensure their license allows it.
If you spot a grammar or theme that is being improperly used, please create an issue and it will be addressed.
Credits
- Aaron Francis
- John Koster
- Ryan Chandler for building Phiki, making this project feasible.
License
The Torchlight Engine is free software, released under the MIT license.
Themes and grammars may be governed by their own license.