Texy! is sexy!
- Typesets quotes, dashes and non-breaking spaces for you
- Always produces well-formed HTML, even from broken input
- Safely handles comments and posts from visitors
- Reads Markdown and also offers the richer Texy syntax
Installation
Download and install the library using Composer:
composer require texy/markdown
This gives you Texy together with Markdown support. If you only want to write in Texy syntax,
composer require texy/texy is enough. Texy 4.0 requires PHP 8.4 or later.
The First Article
Imagine you have a blog and write your articles in Markdown. The beginning of one of them might look like this:
# How We Dried Plums
This year we picked **over 40 kg** of plums. What to do with them? Grandma says: "Dry them, and do it properly."
We bought the dryer at the [shop by the station](https://example.com/dryer) for $60-80.
How much code does it take to turn this into HTML? Surprisingly little:
require __DIR__ . '/vendor/autoload.php';
$markdown = new Texy\Markdown\Markdown;
$markdown->config->locale = 'en'; // the article is in English
$html = $markdown->toHtml($text); // $text holds the article above
The locale line tells Texy which language the article is written in, so it can pick the matching quotes. English
is the default for Markdown, so here you could leave the line out; with 'cs' you would get Czech quotes instead. And
this is the result:
<h1>How We Dried Plums</h1>
<p>This year we picked <strong>over 40 kg</strong> of plums. What to do with
them? Grandma says: “Dry them, and do it properly.”</p>
<p>We bought the dryer at the <a href="https://example.com/dryer">shop by the
station</a> for $60–80.</p>
The heading, the bold text and the link are exactly what you expect from Markdown. But notice what you never typed: the quotes
are curly, the price range has an en dash instead of a hyphen, and a non-breaking space keeps the number together with its unit.
We show it here as to make it visible; the real output contains the character itself.
Texy reads Markdown as defined by the CommonMark specification, along with the GitHub Flavored Markdown extensions such as
tables, task lists and strikethrough. You turn them on by creating the object with Texy\Markdown\Markdown::gfm()
instead of new Texy\Markdown\Markdown. Texy passes all 652 examples of the CommonMark specification and all
24 examples of the GFM extensions. Everything you can write in Markdown is listed on the Markdown Syntax page.
Typography
Texy polishes your text the way a typesetter would, and all you type are the characters on your keyboard:
- it replaces straight quotes
"…"and'…'with the quotes used in the text's language: in English “…” and ‘…’, in Czech „…“ and ‚…‘ - it replaces a hyphen between numbers
9-17with an en dash9–17 - it replaces three dots
...with an ellipsis… - it puts a non-breaking space between a number and its unit, and in Czech, Slovak and Polish also after one-letter prepositions
and conjunctions such as
k,s,vorz, so that a line never breaks between them and the word they belong to - it hyphenates overly long Czech and Slovak words by syllables, so that narrow columns aren't left full of gaps
Texy knows the quotation marks of 18 languages, and you set the language with a single line, as the first article showed. Hyphenation of long words is off by default for Markdown, and turning it on is just as easy:
$markdown->config->hyphenation = true;
Other replacements, such as the arrow -->, the × sign in dimensions like 10x20, or
(C), are described in Texy Syntax. They apply to
Markdown just the same.
Broken HTML
Markdown lets you write HTML right in the text. What if the author forgets to close a tag, or closes tags in the wrong order?
Grandma <b>surely <i>loved it</b>.
Texy fixes it according to the rules of HTML:
<p>Grandma <b>surely <i>loved it</i></b><i>.</i></p>
It always does this, so a single unclosed tag can never break the rest of the page.
Visitor Comments
You want comments under your articles. Anyone can post there, so you set up a separate object for them, in safe mode. Separate, so that the strict rules for comments don't apply to your own articles:
$comments = new Texy\Markdown\Markdown;
$comments->config->locale = 'en';
Texy\Markdown\Configurator::safeMode($comments);
$html = $comments->toHtml($comment); // $comment is the text of the comment
Let's see what it does with a comment whose author tries to sneak in a script:
Great recipe! <script>alert(1)</script> Check out [my website](https://example.org).
<p>Great recipe! <script>alert(1)</script> Check out <a
href="https://example.org" rel="nofollow">my website</a>.</p>
The script won't run, but it doesn't vanish without a trace either: readers see exactly what the author wrote, just as harmless
text. The link stays and gets rel="nofollow", so search engines won't treat spam in your comments as your
endorsement. Safe mode never creates links to dangerous URLs, such as javascript:, in the first place.
What exactly safe mode does and how to fine-tune it is described on the Configuration page.
Custom Extensions
Want to embed a YouTube video in an article? You can teach Texy new things without touching its code. Just tell it how to
render an image whose URL starts with youtube::
use Texy\Nodes\ImageNode;
use Texy\Output\Html;
$markdown->htmlOutput->addRenderer(function (ImageNode $node, Html\Renderer $renderer, ?Closure $previous) {
if (!str_starts_with($node->url ?? '', 'youtube:')) {
return null; // Texy renders other images as usual
}
return new Html\Element('iframe', [
'src' => 'https://www.youtube.com/embed/' . substr($node->url, 8),
'width' => $node->width ?: 640,
'height' => $node->height ?: 360,
'allowfullscreen' => true,
]);
});
Texy calls the function for every image in the text. If the image's URL doesn't start with youtube:, the function
returns null and the image is rendered the usual way. Otherwise it returns an Html\Element, an HTML tag
that Texy outputs in place of the image. We don't need the $renderer and $previous parameters here;
you'll find out what they are for on the page linked below.
The author of the article then simply writes . How to change the rendering of
any element is described on the Customizing Elements page.
You can even extend Markdown with a completely new syntax, just as GitHub extended it with tables and task lists. For example,
@@jane in a comment could become a link to that user's profile, as the Adding Custom Syntax page shows.
When Markdown Isn't Enough
An image with dimensions and a description, aligned right, with a CSS class and a caption below it? In Markdown you would have to write HTML. That's why Texy also has its own syntax, which at its core is as simple as Markdown but is built for things like this. In Texy syntax, that image takes a single line:
[* dryer.jpg 300x200 .(Dryer in the attic)[photo] >] *** Photo: Jane Smith
Text in Texy syntax is converted by the Texy\Texy object, the engine Markdown itself is built on. No other package
is needed. Unlike Markdown, it defaults to Czech, so for English text you would add
$texy->config->locale = 'en' as in the first article; this example comes out the same either way:
$texy = new Texy\Texy;
$html = $texy->toHtml($text);
<figure style="float:right"><img src="dryer.jpg" alt="Dryer in the attic"
class="photo" width="300" height="200">
<figcaption>Photo: Jane Smith</figcaption>
</figure>
300x200 are the dimensions, the text in parentheses describes the image for those who can't see it,
[photo] adds a class, > aligns it right, and *** is followed by the visible caption. The
part starting with the dot is called a modifier, and you can attach it the same way to a paragraph, a heading, a link or a
table cell.
Texy syntax also handles tables with merged cells, table captions, and headings that balance themselves: whichever underline the author starts the article with, its most important heading gets the level you set in the configuration. You'll find everything on the Texy Syntax page.
Source Text Tools
Your blog has moved to HTTPS, but dozens of articles stored as .md files still link to
http://my-blog.com. Searching and replacing across files is a gamble: you'll also replace URLs in code samples that
you want to leave alone.
Texy gives you a document tree in which every link knows precisely where its URL sits in the source text. You change just the URL, and the rest of the text stays exactly as it was:
$source = Texy\Markdown\Markdown::normalize(file_get_contents($file));
$document = $markdown->parse($source);
$rewriter = new Texy\Rewriter($source);
foreach ($document->find(Texy\Nodes\LinkNode::class) as $link) {
if ($link->urlRange === null) {
continue; // a link whose URL is not written in the source text
}
$url = substr($source, $link->urlRange->offset, $link->urlRange->length);
if (str_starts_with($url, 'http://my-blog.com')) {
$rewriter->replace($link->urlRange, 'https://' . substr($url, 7));
}
}
file_put_contents($file, $rewriter->getResult());
Here we call parse() instead of toHtml(); it only parses the text into a tree and produces no HTML.
Before that, normalize() unifies line endings and similar details so that the positions in the tree match the text
exactly. A URL in a code sample isn't a link, so it stays as it was. The one exception is link definitions, the
[name]: http://… lines: their URLs aren't in the tree, so you have to handle them separately. Files in Texy syntax
work the same way, just with Texy\Texy::normalize() and $texy->parse().
The same foundation lets you build bulk rewrites, editor support, or a documentation checker that reports errors with line
numbers. And because both languages share one tree, you can convert an article from Markdown to Texy syntax with a single call to
$markdown->toTexy($text). The Source Text Tools page
shows how.
In Latte Templates
Do you write templates in Latte? Texy provides a filter for them, so you can convert an article right in the template:
{$article->text|texy}
How to register the filter and how to convert Markdown with it is described on the Texy in Latte page.
Written in Texy
This manual is written in Texy syntax, and so is the Nette documentation at nette.org. The source of every page is on GitHub, so you can see what any page looks like before it is converted to HTML.
History
Texy was created by David Grudl in 2004 as one of the first text formatters for PHP. It originally ran on PHP 4, has gone through many versions since, and today takes advantage of what PHP 8 offers.
Version 4.0 turned it into an engine: the text is first parsed into a document tree, and only that tree is turned into HTML, plain text, or back into source text. Markdown and Texy syntax are built on the same core, so they get the same typography, the same HTML fixes and the same tools. How it works inside is described on the Architecture and Principles page.