📜 ⬆️ ⬇️

TeX-like markup on Javascript

When writing the console-like forum , the question was asked: “which markup should I use?”. Among the options were the standard bb code ([b] bold [/ b]), wiki markup (* bold *), or TeX-like markup (\ b {bold}). After a brief meeting, the choice was on TeX-like. A small library was written, which, in my opinion, is quite interesting, expandable and flexible. Those who wish to see an example can follow the link freecr.ru/TeX

The library is expanded with plugins. There are two types of plugins - "tag" and "rule". “Tag” is, in fact, the TeX tag itself, and the rule is a function applied to text that is not in tags. For example, to highlight urls in the text: “So at www.example.com we see \ b {sample site}”.
Example of adding a rule:

TeX.addRule ({
name : 'liveUrls' ,
func : function ( string ) {
var urlRE = /((git|svn|ftp|http|https):\/\/(www\.)?|www.)(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi;
return string .replace(urlRE, function (url) {
var urlFull = (url.indexOf( 'www' ) === 0) ? "http://" + url : url;
return "<a class='url' href='" + urlFull + "'>" + url + "</a>" ;
});
}
})
;

The tag is added according to this very principle:
TeX.addTag ({
name : 'b' ,
args : [1],
func : function (args) {
return "<b>" + TeX.markup(args[0]) + "</b>" ;
}
});


* This source code was highlighted with Source Code Highlighter .


The only significant difference is the presence of the args property of the tag. It can accept an array of numbers, or the string 'unlimited'. Thus, we indicate how many parameters an argument can take: for example, code can accept two parameters - the language and the code itself, or one - only the code. Then the value will be args: [1, 2] and it will take an array of arguments with one or two values.
')
All the characters inside the tag are not processed by any rules, because if you want them to be processed, you can call TeX.markup recursively for the corresponding argument.

I think the most understandable principles of operation will be on the example of code:
Liba itself: http://pastebin.com/f46087804

Plugins: http://pastebin.com/f7840dc97

Well, for the seed - an example of a more advanced plug-in that implements the CCS-highlighting, a la:
\ style {float: right} {border: dotted red 2px} {background: #fcc} {text-align: justify} {padding: 25px 100px} {display: block} {text is here}

http://pastebin.com/f4e75d3f6

License - LGPL.
Liba is quite fresh and little tested, so improper work is possible.

Source: https://habr.com/ru/post/67388/


All Articles