FxEditor
User guideQuickstartExamplesAPIFxTeX
OverviewAPIExamplesRight-click menuSupported commandsAccessibilityFxTeX Packages
Using packagesmhchemchemfigphysicspictureFxTeX Server
OverviewAPIAccess and keysSelf-hostingSpeedPlugins
OverviewLicensing
How licensing worksfxEditor API
Use the fxEditor API to build a custom equation editor in your web page. This reference covers setup, licence activation, toolbar configuration and the methods for reading and updating equations.
Prerequisites
Add to <head>:
<script src="https://fxeditor.codecogs.com/fxeditor.api.min.js"
crossorigin="anonymous"></script>
Add to <body>:
<div id="toolbar"></div>
<div id="latexInput"></div>
<img id="output"/>
<script type="text/javascript">
EqEditor.init({ licence: 'fx_pk_your-key-here' }).then(() => {
textarea = new EqEditor.LaTeXView('latexInput')
.addToolbar(new EqEditor.Toolbar('toolbar'), true)
.addOutput(new EqEditor.Output('output'));
});
</script>
Activating with a licence key
fxEditor renders its equations with fxTeX Pro, the WebAssembly build of the
CodeCogs converter, and that build is opened with your licence key. Every page that uses the
editor does this once, with EqEditor.init(), before it builds anything that shows an
equation:
const ready = EqEditor.init({ licence: 'fx_pk_your-key-here' });
// The toolbar can be built straight away - its buttons need no converter.
const toolbar = EqEditor.Toolbar.link('toolbar');
// Anything that renders an equation waits for the key to be accepted.
await ready;
EqEditor.LaTeXView.link('latexInput')
.addToolbar(toolbar, true)
.addOutput(new EqEditor.Output('output'));
Your key is in the licence manager, alongside a copy of this snippet with it filled in. It is safe to put in a page: the key only opens the editor on the domain it was issued for, so copying it to another site achieves nothing. Once per page is enough — every editor on the page then shares it, however many there are.
Options
| licence | Your licence key. Required. |
| script | Where to load fxTeX Pro from. Leave it out: the default,
https://fxtex.codecogs.com/licence/fxtexpro.min.js, is right for every page except one using a
self-hosted fxTeX Server, which names its own. |
| integrity | A subresource-integrity hash for a script you host yourself. |
If it fails
init() returns a promise that rejects with an error whose reason says
what went wrong. The same message then appears in place of every equation the editor draws, so a
problem is visible rather than silent:
| bad-key | The key is not one we issued, or has been mistyped. |
| domain | The page is not on the domain the licence is for, or one of its subdomains. |
| expired | The licence has lapsed. Renew it in the licence manager. |
| network | fxTeX Pro could not be downloaded — often a Content Security Policy that does not allow https://fxtex.codecogs.com. |
EqEditor.init({ licence: 'fx_pk_your-key-here' })
.catch(err => console.warn('fxEditor could not start:', err.reason, err.message));
Each page that starts fxEditor or fxTeX Pro under your licence counts as one service load, the measure licences are sized in. See licence options.
Converting without an editor
To put equations into a page your own code builds — a quiz, a results table, a preview
— ask for a converter once init() has resolved. It turns LaTeX into the same
MathML the editor draws:
await EqEditor.init({ licence: 'fx_pk_your-key-here' });
const conv = EqEditor.newConverter();
conv.setInline(true);
document.getElementById('answer').innerHTML = conv.convert('\\frac{a}{b}');
It is fxTeX Pro's converter, with the settings — inline layout, spoken text and the
rest — described under Converting with your
own settings, apart from setFontSize() and errors(), which it does
not have; size its equations with CSS instead. And one difference for the better: each
newConverter() keeps its own settings, so nothing you set on it reaches the editor or
any other converter on the page. Load
fxeditor.css as well, which styles the equations it returns.
Toolbar
constructor
-
new Toolbar(toolbarElementId: string, design?: any, scale?: number): Toolbar
Parameters
- toolbarElementId: string
Id of the layer into which the toolbar is placed.
Optionaldesign: any = 'default'The name of a standard toolbar design, or the panels to use: an array of rows, each an array of panel names, either as it is or as a JSON string.
Optionalscale: number = 1Optional scaling of the toolbar buttons, e.g. 1.2 for a fifth larger.
Returns Toolbar
- toolbarElementId: string
add La Te X View
-
addLaTeXView(textArea: LaTeXView, reverseLink?: boolean): Toolbar
Connects a LaTeXView with the current Toolbar, and makes it the one the toolbar's buttons insert into. With several LaTeXViews connected, the buttons go to whichever last had focus. For example:
<div id="editor"></div>
<div id="input"></div>
<script>
EqEditor.Toolbar.link('editor')
.addLaTeXView(EqEditor.LaTeXView.link('input'));
</script>Parameters
- textArea: LaTeXView
The LaTeXView object to associate with the Toolbar.
OptionalreverseLink: boolean = trueIf true it also adds the Toolbar to the LaTeXView, which is what lets the LaTeXView take the toolbar back when it gains focus.
Returns Toolbar
This Toolbar, in support of chaining commands together.
Formerly called
addTextArea(), which still works as an alias of this method. - textArea: LaTeXView
add Math View
-
addMathView(mathView: MathView, reverseLink?: boolean): Toolbar
Connects a MathView with the current Toolbar, the same way addLaTeXView() does for a LaTeXView - so the toolbar's buttons insert into the MathView whenever it has focus. It also makes the MathView the toolbar's target now; to link one without that, use
mathView.addToolbar(toolbar, false).var toolbar = EqEditor.Toolbar.link('toolbar');
toolbar.addMathView(EqEditor.MathView.link('mathview'));Parameters
- mathView: MathView
The MathView object to associate with the Toolbar.
OptionalreverseLink: boolean = trueIf true it also adds the Toolbar to the MathView.
Returns Toolbar
This Toolbar, in support of chaining commands together.
- mathView: MathView
append Panel
-
appendPanel(id: number, panel: string | object): Toolbar
Appends a panel to the end of an existing toolbar row: one of the built-in panels by name (e.g. "matrix"), or one of your own, written exactly as the built-in panels are.
A panel of your own is an object with these properties - the same ones as the files in src/toolbar/panels, so any built-in panel can be copied and edited to make a new one:
- label {string} - [optional] The panel's name, as read to a screen reader. Also names
the panel's element (e.g. "Accents" gives id="accents") unless
nameis given. - button {object} - [optional] The box every button is drawn into: { width, height } in pixels. Each face is scaled to fit it.
- rows {number} - [optional] How many rows are always visible; the rest drop down. Default 2.
- columns {number} - [optional] Buttons per row.
- scale {number} - [optional] Draws every face at this much of the size it would be fitted to, e.g. 0.9 for a panel that looks heavy beside its neighbours. Default 1.
- hspace {number} - [optional] Gap between buttons, in pixels.
- fixedScale {boolean} - [optional] false fits each face to its own cell rather than scaling the whole panel by one factor. Default true.
- class {string} - [optional] A CSS class put on each button.
- name {string} - [optional] The id of the panel's element, if not taken from
label. - buttons {array} - The buttons, filled down each column in turn (see below).
A button is one of:
- A string of LaTeX - "\pm" - which is both what the button inserts and what it draws.
- An object:
- insert {string} - The LaTeX to insert. The cursor goes inside its first {} group ("\frac{}{}" leaves it in the numerator), or after it if it has none; a selection is wrapped wherever the cursor would have gone.
- face {string} - [optional] What the button draws, when that differs from what it inserts: an accent inserts "\dot{}" and draws "\dot{a}".
- caret {number} - [optional] Where the cursor goes, from the start of the insert; negative counts back from its end.
- wrap {number} - [optional] Where a selection is placed, from the start of the insert; negative counts back from its end. "\sqrt[]{}" with wrap -1 puts the selection in the radicand while the cursor goes to the index.
- color {string} - [optional] A colour swatch instead of a drawn face.
- scale {number} - [optional] This one button's size, as a fraction of its cell.
- width {number} - [optional] This one button's own box width, in pixels, for a face far wider than the rest of the panel.
- op {string} - [optional] What the button does: "insert" (the default), "matrix"
or "equations", or "picture" and "chemfig" to open the picture editor or the
Chemistry Structure Editor. "matrix" and "equations" ask for a size first, in a
picker that opens under the panel, then insert a block of that size:
- "matrix" takes args [type, start, end] and inserts start + "\begin{" + type + "matrix}...\end{" + type + "matrix}" + end, e.g. ["p", "", ""] for a pmatrix, or ["", "\left.", "\right|"].
- "equations" takes args [env, first, middle, last] and inserts one line per
row in \begin{env*}...\end{env*}:
firstbegins the first line,middlethe ones between andlastthe final one, each defaulting to the one before - e.g. ["align", "y &= ", " &+ "] or ["cases", "& \text{if}\;x= "]. Give these aface, since there is nothing to draw it from.
- args {array} - [optional] The arguments for "matrix" and "equations", as above.
- null, for a gap that keeps the place of the buttons after it.
A panel made from the same buttons as a built-in one is drawn from the same generated pictures, so it looks exactly like it. One with any other face is drawn by the browser, as MathML, throughout.
EqEditor.Toolbar.link('toolbar','[["operators"]]')
.addLaTeXView(textarea)
.appendPanel(0, "matrix")
.appendPanel(0, {
"label": "Accents",
"scale": 1.1,
"button": { "width": 17, "height": 20 },
"rows": 2,
"columns": 2,
"buttons": [
{ "insert": "{}\\'", "face": "a'" },
{ "insert": "\\dot{}", "face": "\\dot{a}" },
{ "insert": "\\hat{}", "face": "\\hat{a}" }
]
})
.appendPanel(0, {
"label": "Signs",
"button": { "width": 18, "height": 20 },
"buttons": [ "\\pm", "\\mp", "\\times", "\\ast" ]
});Parameters
- id: number
The row of the toolbar to append to. Rows are numbered from 0.
- panel: string | object
The name of a standard panel, or an object describing a panel of your own (see above).
Returns Toolbar
This Toolbar, in support of chaining commands together.
- label {string} - [optional] The panel's name, as read to a screen reader. Also names
the panel's element (e.g. "Accents" gives id="accents") unless
destroy
-
destroy(): void
Takes this toolbar off the page and lets it go: empties its element of the panels it built, stops listening to the document and window, and forgets it as one of the page's toolbars. For a page that builds editors and later removes them, where every toolbar ever built would otherwise go on handling the document's clicks and keys for the life of the page.
The element stays; it is the page's. Calling this twice does nothing.
const toolbar = EqEditor.Toolbar.link('toolbar').addLaTeXView(textarea);
// ... later, when the dialog closes:
toolbar.destroy();Returns void
get Panel
-
getPanel(panelName: string): HTMLDivElement
Returns the HTMLDivElement for an equation editor toolbar panel, given its name. This is typically required when dynamically moving a panel from the 'inactive' toolbar onto the main toolbar.
Only the panels a Toolbar has but does not show are found here: those of the 'sidebar' and 'inactive' sets in toolbars.json ('greekupper' and 'greeklower' as shipped). Each is built the first time it is asked for, and the same element is returned after that.
Parameters
- panelName: string
The name of the panel to retrieve.
Returns HTMLDivElement
The panel's element, or null for a name in neither set.
- panelName: string
move To
-
moveTo(toolbarElementId: string): Toolbar
Moves the toolbar from one location on the page to another. This is useful when a single toolbar is shared between several inputs and should appear beside whichever one the user is currently editing. For example:
<div id="editor1"></div>
<div id="input1" onClick="tb.moveTo('editor1')"></div>
<div id="editor2"></div>
<div id="input2" onClick="tb.moveTo('editor2')"></div>
<script>
var tb = EqEditor.Toolbar.link('editor1')
.addLaTeXView(EqEditor.LaTeXView.link('input1'))
.addLaTeXView(EqEditor.LaTeXView.link('input2'));
</script>Parameters
- toolbarElementId: string
Id of the layer into which the toolbar is to be moved.
Returns Toolbar
This Toolbar, in support of chaining commands together.
- toolbarElementId: string
set Active La Te X View
-
setActiveLaTeXView(target: ToolbarTarget): Toolbar
Makes the specified LaTeXView (or MathView) active, so that it receives input from the toolbar. A connected LaTeXView or MathView does this itself when it gains focus.
Parameters
- target: ToolbarTarget
The LaTeXView or MathView to make active.
Returns Toolbar
This Toolbar, in support of chaining commands together.
Formerly called
setActiveTextArea(), which still works as an alias of this method. - target: ToolbarTarget
Staticlink
-
link(toolbarElementId: string, design?: any, scale?: number): Toolbar
Parameters
- toolbarElementId: string
- design: any = 'default'
- scale: number = 1
Returns Toolbar
LaTeXView
The LaTeXView class manages the connection between the equation editor Toolbar and the editable
areas in which the LaTeX markup is shown and edited. An editable area is an ordinary HTML
div element, which the LaTeXView turns into a contenteditable region when it is linked.
The key features a LaTeXView provides are:
- syntax highlighting of the equation as it is typed;
- auto-suggestion of LaTeX commands, with a rendered preview of each candidate;
- undo/redo history, when a History menu is attached;
- optional restriction of the variables and commands a user is allowed to enter.
A LaTeXView is usually paired with a Toolbar, which provides visual assistance. Several LaTeXViews may be attached to a single Toolbar, and conversely several Toolbars may be attached to a single LaTeXView.
A LaTeXView can also be linked to one or more Output regions, which present a rendered version of the equation, or supply the LaTeX in a form suitable for pasting into another system (for example a forum, a wiki, or Google Docs). A mathview.MathView may be linked in the same way, giving a WYSIWYG view of the same equation that stays in step with the markup in both directions.
<div id="toolbar"></div>
<div id="input" placeholder="Write LaTeX here"></div>
<img id="output"/>
<script>
EqEditor.LaTeXView.link('input', true)
.addToolbar(new EqEditor.Toolbar('toolbar'))
.addOutput(new EqEditor.Output('output'));
</script>
A page usually links its LaTeXView, and whatever renders alongside it - a MathView, a PredictorView, Outputs - once converter.init has resolved, as example/index.html does; the Toolbar can be built before.
Formerly called TextArea. That name is kept as an alias of this class, so existing pages that
call EqEditor.TextArea.link(...) or new EqEditor.TextArea(...) carry on working unchanged.
LaTeXView
constructor
-
new LaTeXView(textAreaId: string, focus?: boolean, wrap?: boolean): LaTeXView
Creates an instance of LaTeXView for LaTeX input and associates it with an HTML element. To provide some introductory text, use the
placeholderattribute as illustrated in the example below. Any introductory text is removed as soon as the user starts typing.<div id="input" placeholder="Write LaTeX here"></div>
<script>
var ta = new EqEditor.LaTeXView('input', true);
</script>Parameters
- textAreaId: string
Id of the target div to be used for editing.
Optionalfocus: boolean = falsePuts the cursor in the text area straight away. Left false, the LaTeXView does not take focus, or scroll the page, as it is created.
Optionalwrap: boolean = trueWraps long equations onto multiple lines and makes the area vertically resizable. Pass false to keep the equation on a single scrolling line.
Returns LaTeXView
- textAreaId: string
add History Menu
-
addHistoryMenu(history: History): LaTeXView
Adds history, with undo and redo, to the LaTeXView. This requires a History menu to provide the necessary controls.
<div id="history"></div>
<div id="input"></div>
<script>
EqEditor.LaTeXView.link('input')
.addHistoryMenu(new EqEditor.History('history'));
</script>Parameters
- history: History
The history menu object.
Returns LaTeXView
This LaTeXView, in support of chaining commands together.
- history: History
add Output
-
addOutput(out: LaTeXViewOutput): LaTeXView
Connects an Output to this LaTeXView. Every connected Output is refreshed whenever the equation changes. A mathview.MathView and a predictor.PredictorView register through this same call when they are linked to the LaTeXView, though their own
addLaTeXView()is the call to make for those.EqEditor.LaTeXView.link('input')
.addOutput(EqEditor.Output.link('preview').setFormat('svg'))
.addOutput(EqEditor.Output.link('code', 'html'));Adding the same Output twice has no further effect.
Parameters
- out: LaTeXViewOutput
The Output to attach.
Returns LaTeXView
This LaTeXView, in support of chaining commands together.
- out: LaTeXViewOutput
add Toolbar
-
addToolbar(toolbar: Toolbar, activate?: boolean): LaTeXView
Connects a Toolbar to this LaTeXView, so the toolbar's buttons insert into it. Whichever LaTeXView last had focus is the one a shared Toolbar sends its buttons to.
var tb = EqEditor.Toolbar.link('toolbar');
EqEditor.LaTeXView.link('input1').addToolbar(tb);
EqEditor.LaTeXView.link('input2').addToolbar(tb, false);toolbar.Toolbar.addLaTeXView makes the same link from the toolbar's side.
Parameters
- toolbar: Toolbar
The Toolbar component.
Optionalactivate: boolean = trueMakes this LaTeXView the toolbar's target now, rather than when it next takes focus.
Returns LaTeXView
This LaTeXView, in support of chaining commands together.
- toolbar: Toolbar
apply Edit
-
applyEdit(edit: TextEdit, caret?: number, takeFocus?: boolean): void
Replaces part of the equation - the characters from
fromup toto- withtext, as one step that one Undo takes back. Only the change is recorded in the history, not the equation.var ta = EqEditor.LaTeXView.link('input');
ta.applyEdit({ from: 4, to: 7, text: '\\beta' });Parameters
- edit: TextEdit
Offsets into the equation as it stands, and what goes between them.
fromequal totoinserts; an emptytextdeletes. Optionalcaret: numberWhere to leave the cursor. Defaults to the end of the inserted text.
OptionaltakeFocus: boolean = trueAs for LaTeXView.replaceAll.
Returns void
- edit: TextEdit
call Outputs
-
callOutputs(func: string, ...args: any[]): void
Provides a convenient method of executing any Output class function across all of the Output areas associated with the LaTeXView. This is particularly useful when you have several outputs and need them all to change together.
For example, say you want to change the format for all the outputs:
<select id="format" onchange="textarea.callOutputs('setFormat', this.value);">
<option value="svg">svg</option>
<option value="png">png</option>
<option value="gif">gif</option>
<option value="pdf">pdf</option>
<option value="mathml">mathml</option>
</select>Any further arguments are passed on:
textarea.callOutputs('setFormat', 'svg', false). A MathView or PredictorView linked to the LaTeXView has none of an Output's methods, and is skipped.Parameters
- func: string
The name of an Output method.
- ...args: any[]
The arguments to call it with.
Returns void
Throws
Error if the LaTeXView has Outputs but none of them has a method of that name.
- func: string
clear
-
clear(): void
Clears the input box (LaTeXView), removing the equation and resetting the cursor. The LaTeXView takes focus, and every connected Output is updated. The clearing can be undone.
Returns void
close
-
close(): void
Call when a LaTeXView is being taken off the page - a dialog closing, say, or a per-cell editor in a table. It hides the suggestion list and removes the listeners the LaTeXView added, so that it and everything it refers to can be garbage collected. The element itself is left where it is. Closing twice is harmless.
Returns void
edit Chemfig
-
editChemfig(): void
Opens the Chemistry Structure Editor: on the \chemfig{...} the cursor is in, or on a new structure to insert at the cursor. Needs fxTeX Pro's chemfig package to show it -
packages: ['chemfig']to converter.init.Returns void
edit Picture
-
editPicture(): void
Opens the picture editor: on the picture environment the cursor is in, or on a new picture to insert at the cursor - what the toolbar's picture button calls. Needs fxTeX Pro's picture package to draw:
packages: ['picture']to converter.init.Returns void
focus
-
focus(): void
Moves keyboard focus into this LaTeXView.
Returns void
get Answers
-
getAnswers(): string[]
What has been typed into each slot of a locked equation, in the order the slots appear in the LaTeX - the student's answers, ready to mark. A slot left empty gives "". For
\frac{}{2}=5filled in as\frac{8}{2}=5, this returns["8"].var answers = textarea.getAnswers(); // e.g. ["8"]Returns string[]
One entry per slot, or an empty list if the equation is not locked - see LaTeXView.structural_lock.
get La Te X View
-
getLaTeXView(): HTMLElement
Returns the HTML element backing this LaTeXView. Typically you will then read its
textContentto retrieve the LaTeX formula.The following example illustrates how a button onclick action can retrieve the content of a LaTeXView.
<div id="input"></div>
<button onclick="alert(textarea.getLaTeXView().textContent)">Show LaTeX</button>
<script>
var textarea = EqEditor.LaTeXView.link('input');
</script>Returns HTMLElement
The editable
divthe LaTeXView was linked to.Formerly called
getTextArea(), which still works as an alias of this method.
has Focus
-
hasFocus(): boolean
Whether keyboard focus is inside this LaTeXView.
Returns boolean
insert
-
insert(txt: string, newCaretPos?: number, selectedInsertPos?: number): void
Inserts LaTeX into the LaTeXView at the current cursor position. Any text that is selected is wrapped by the insertion rather than replaced: selecting "x" and inserting
\sqrt{}gives\sqrt{x}. This is what every toolbar button calls.The following example inserts a fraction and places the cursor between the first curly braces:
<div id="input"></div>
<script>
var a = EqEditor.LaTeXView.link('input', true);
a.insert('\\frac{}{}', 6);
</script>Parameters
- txt: string
New text to insert. Remember that a backslash must be escaped in JavaScript string literals, i.e. '\frac{}{}' rather than '\frac{}{}'.
OptionalnewCaretPos: number = nullWhere to place the cursor, counted from the start of the inserted text; 0 is the start, and a negative number counts back from its end. null puts the cursor inside the first
{}group, or, if the text has none, adds a space after it and puts the cursor after that.OptionalselectedInsertPos: number = nullWhere any currently selected text should be placed within the inserted text, counted the same way. null puts it where the cursor would have gone, so
\frac{}{}takes the selection as its numerator. With a selection, the cursor then goes to the first group still empty, or after the whole insertion.
Returns void
- txt: string
is La Te X View Empty
-
isLaTeXViewEmpty(): boolean
Returns true if the current LaTeXView is empty, false otherwise.
Formerly called
isTextAreaEmpty(), which still works as an alias of this method.Returns boolean
is Structure Locked
-
isStructureLocked(): boolean
Whether the equation is locked to its structure - see LaTeXView.structural_lock.
Returns boolean
make Array Matrix
-
makeArrayMatrix(type: string, start: string, end: string): void
Inserts a matrix of the dimensions picked in the toolbar's matrix panel (LaTeXView.curMatrixDims), as
start+\begin{typematrix}...\end{typematrix}+end. Called by the toolbar; a page has little reason to call it directly.Parameters
- type: string
The start of the environment's name: 'p' for pmatrix, 'b' for bmatrix, '' for a plain matrix.
- start: string
What goes before the matrix, e.g. '' or '\left.'.
- end: string
What goes after it, e.g. '' or '\right|'.
Returns void
- type: string
make Equations Matrix
-
makeEquationsMatrix(
type: string,
firstLine?: string,
middleLine?: string,
lastLine?: string,
): voidInserts a block of equations, one line for each row of the dimensions picked in the toolbar's matrix panel (LaTeXView.curMatrixDims), inside
\begin{type*}...\end{type*}. Called by the toolbar; a page has little reason to call it directly.Parameters
- type: string
The environment, without its star, e.g. 'align' or 'cases'.
OptionalfirstLine: string = ""What the first line begins with.
OptionalmiddleLine: string = nullWhat each line between the first and last begins with. Defaults to
firstLine.OptionallastLine: string = nullWhat the last line begins with. Defaults to
middleLine.
Returns void
- type: string
notify History Menus
-
notifyHistoryMenus(): void
Notifies all connected History Menus of changes, so their buttons are enabled or disabled to match. The LaTeXView does this itself whenever its history changes.
Returns void
notify Outputs
-
notifyOutputs(): void
Notifies all connected Outputs of changes. The LaTeXView does this itself after every edit; call it only if you have changed the editable element's content by some other means.
Returns void
push To History
-
pushToHistory(): void
Records the LaTeXView's current text as a step in its undo history, if it differs from the last one recorded. Every edit made through the LaTeXView already does this; call it only after changing the editable element's content by some other means.
Only what changed is kept, not the whole equation: the span between what the text starts and ends with in common with the last step.
Returns void
redo History
-
redoHistory(takeFocus?: boolean): void
Reverts an undone change, i.e. redoes the most recently undone action. This is what the History menu's redo button calls.
Parameters
OptionaltakeFocus: boolean = trueFalse to restore the equation and its cursor position without moving focus or the page's selection into this LaTeXView - as a linked MathView does when it is redoing through this one's history.
Returns void
remove Output
-
removeOutput(out: LaTeXViewOutput): LaTeXView
Stops updating an Output, MathView or PredictorView added with LaTeXView.addOutput. A MathView's destroy() calls it for you; a page swapping one Output for another calls it for the old one, which the LaTeXView would otherwise go on updating and keeping alive.
textarea.removeOutput(oldOutput).addOutput(newOutput);Parameters
- out: LaTeXViewOutput
The Output (or MathView) to detach.
Returns LaTeXView
This LaTeXView, in support of chaining commands together.
- out: LaTeXViewOutput
replace All
-
replaceAll(text: string, caret: number, takeFocus?: boolean): void
Parameters
- text: string
- caret: number
- takeFocus: boolean = true
Returns void
set Autocomplete
-
setAutocomplete(enabled: boolean): LaTeXView
Enables or disables auto-insertion of matching close brackets when an open bracket is typed. It is enabled by default. The History menu carries a switch that sets the same thing.
Parameters
- enabled: boolean
Pass true to enable auto-bracket completion, false to disable it.
Returns LaTeXView
This LaTeXView, in support of chaining commands together.
- enabled: boolean
set Restricted Commands
-
setRestrictedCommands(words: string[]): LaTeXView
Assigns the LaTeX commands that may be used within the formula. Any command breaking this condition is given the CSS class "CCrestricted", which by default shows it in red with a double underline. Override the CSS for "CCrestricted" to achieve alternative effects. The autosuggest list offers only the commands allowed.
EqEditor.LaTeXView.link('input')
.setRestrictedCommands(['frac', 'sqrt', 'alpha', 'beta']);Parameters
- words: string[]
The command names allowed, without their backslash. Each is a regular expression, matched against the whole name, so
['.*']allows every command.
Returns LaTeXView
This LaTeXView, in support of chaining commands together.
- words: string[]
set Restricted Variables
-
setRestrictedVariables(words: string[]): LaTeXView
Assigns the variables that may be used within the formula. Any variable breaking this condition is given the CSS class "CCrestricted", which by default shows it in red with a double underline. Use LaTeXView.validate to test the equation as a whole.
The words are also offered by the autosuggest list.
The following example allows the variable 'bill', and any that start with 'j' and end with 's':
var textarea = EqEditor.LaTeXView.link('latexInput', true)
.addOutput(new EqEditor.Output('output'))
.setRestrictedVariables(['bill', 'j\\w+s']);Parameters
- words: string[]
Array of allowable words. Each is a regular expression, matched against the whole word.
Returns LaTeXView
This LaTeXView, in support of chaining commands together.
- words: string[]
set Restrict Mode
-
setRestrictMode(mode: number): LaTeXView
Restricts keyboard input. This is useful in assessment settings, where the equation must be built from a controlled set of toolbar buttons rather than typed freely.
There are three modes:
- 0 - allows all text and key operations (the default);
- 1 - for an equation built from the toolbar: Backspace and Delete remove whole words, the arrow keys step through the equation's structure, Space opens the command list, and a backslash no longer opens it.
Any mode above 0 currently behaves as 1.
EqEditor.LaTeXView.link('input')
.addToolbar(EqEditor.Toolbar.link('toolbar'))
.setRestrictMode(1);Parameters
- mode: number
One of 0, 1 or 2.
Returns LaTeXView
This LaTeXView, in support of chaining commands together.
structural_ lock
-
structural_lock(on?: boolean): LaTeXView
Locks the equation to its structure, or unlocks it.
Locked, the empty slots in the equation as it stands - each empty
{}or[], each empty matrix cell, and each box drawn after an operator with nothing to operate on - are the only places that can be edited, and they take only plain characters and single symbols: letters, digits, "." and the like, and commands such as\alphaor\le. Nothing can be typed or deleted anywhere else, and nothing can be added that is structure of its own - no braces, brackets, scripts, or commands that take an argument. A slot stays editable once something is in it.This is for exercises: the educator writes the structure, and the student fills it in.
var ta = EqEditor.LaTeXView.link('input');
ta.insert('\\frac{}{2}=5', 0);
ta.structural_lock(true);A MathView linked to this LaTeXView is locked with it, by the same lock. To lock every equation on a page at once, use structural_lock.
Locking clears the undo history, so the structure cannot be undone away, and locking an equation that is already locked leaves it as it is - what has been typed into its slots stays editable. To change the structure, unlock it, change it, and lock it again.
Parameters
Optionalon: boolean = trueTrue to lock the equation to its current structure, false to unlock it.
Returns LaTeXView
This LaTeXView, in support of chaining commands together.
undo History
-
undoHistory(takeFocus?: boolean): void
Undoes the last action. Repeated calls unwind further changes to the input area. This is what the History menu's undo button calls. Under a structure lock the equation as it was locked cannot be undone.
Parameters
OptionaltakeFocus: boolean = trueAs for LaTeXView.redoHistory.
Returns void
update Matrix Dims
-
updateMatrixDims(text: string): void
Changes the dimensions of an existing selected matrix
Parameters
- text: string
The selected text
Returns void
- text: string
validate
-
validate(): boolean
Checks the equation to ensure it contains only the variables and commands permitted by LaTeXView.setRestrictedVariables and LaTeXView.setRestrictedCommands.
Note that every token must be a permitted variable or a permitted command: a number, operator, bracket or space anywhere in the equation also makes this false.
Returns boolean
True if every token is permitted, false otherwise.
Staticlink
-
link(textAreaId: string, focus?: boolean, wrap?: boolean): LaTeXView
Static constructor.
Returns a new instance of LaTeXView linked to the specified HTML element. The advantage of this over the constructor with 'new' is that it allows you to chain additional requirements together, as shown in the example:
<div id="toolbar"></div>
<div id="input"></div>
<script>
EqEditor.LaTeXView.link('input', true)
.addToolbar(new EqEditor.Toolbar('toolbar'));
</script>Parameters
- textAreaId: string
Id of the target div to be used for editing.
Optionalfocus: boolean = falsePuts the cursor in the text area straight away.
Optionalwrap: boolean = trueWraps long equations onto multiple lines and makes the area vertically resizable. Pass false to keep the equation on a single scrolling line.
Returns LaTeXView
The new LaTeXView, ready for further chained calls.
- textAreaId: string
MathView
A MathView is a WYSIWYG view of an equation: the maths is drawn as live MathML and edited in place, with a caret you can click to position and arrow keys you can navigate with, rather than typed as markup.
A MathView plugs into a Toolbar exactly as a LaTeXView does, so every toolbar button inserts into whichever of the two currently has focus. It also registers as one of a LaTeXView's Outputs, so a page can show the markup and the rendered equation side by side and have an edit in either one appear immediately in the other.
This means a page can offer three arrangements from the same objects:
- MathView only - a WYSIWYG editor, with the LaTeX hidden from the user entirely;
- LaTeXView only - the classic markup editor with syntax highlighting;
- both - the two linked together, each reflecting edits made in the other.
<div id="toolbar"></div>
<div id="mathview"></div>
<div id="input"></div>
<script>
var ta = EqEditor.LaTeXView.link('input');
EqEditor.MathView.link('mathview', true)
.addLaTeXView(ta)
.addToolbar(new EqEditor.Toolbar('toolbar'));
</script>
The view renders with fxTeX Pro, so create it once converter.init has resolved, as example/index.html does.
Editing is by whole construct rather than by character: pressing Backspace just after
\frac{x}{2} removes the fraction entirely, while pressing it inside the fraction removes only
the x. Empty arguments are drawn as grey boxes, so an inserted \frac{}{} shows you the two
blanks that are waiting to be filled in.
MathView
constructor
-
new MathView(mathViewElementId: string, focus?: boolean): MathView
Creates a WYSIWYG MathML view inside the given container element, e.g.
<div id="mathview"></div>
<div id="input"></div>
<script>
var mv = new EqEditor.MathView('mathview');
mv.addLaTeXView(new EqEditor.LaTeXView('input'));
</script>A MathView needs no LaTeXView: on its own it is a WYSIWYG editor, read with MathView.getLatex and loaded with MathView.setLatex.
Parameters
- mathViewElementId: string
Id of the container div the view is placed into.
Optionalfocus: boolean = falseActivates the cursor within the view.
Returns MathView
- mathViewElementId: string
add La Te X View
-
addLaTeXView(textArea: LaTeXView, reverseLink?: boolean): MathView
Links this view to a LaTeXView that holds its LaTeX, so an edit in either appears at once in the other, and the two share one undo history and one structure lock. The view shows the LaTeXView's equation from its next change; to load one into both, use MathView.setLatex after linking them.
EqEditor.MathView.link('mathview')
.addLaTeXView(EqEditor.LaTeXView.link('input'));Parameters
- textArea: LaTeXView
The LaTeXView to hold this view's LaTeX.
OptionalreverseLink: boolean = trueIf true, also registers this view as one of the LaTeXView's Outputs, so it is notified whenever that LaTeXView changes.
Returns MathView
This MathView, in support of chaining commands together.
Formerly called
addTextArea(), which still works as an alias of this method. - textArea: LaTeXView
add Toolbar
-
addToolbar(toolbar: Toolbar, activate?: boolean): MathView
Connects a Toolbar to this view, the same way api.LaTeXView.addToolbar does - so the Toolbar's buttons insert into this view whenever it has focus. With a linked LaTeXView sharing the Toolbar, pass
activatefalse to leave the buttons going to the LaTeXView until the view is clicked, as example/index.html does.var toolbar = EqEditor.Toolbar.link('toolbar');
EqEditor.MathView.link('mathview')
.addLaTeXView(textarea)
.addToolbar(toolbar, false);Parameters
- toolbar: Toolbar
The Toolbar component.
Optionalactivate: boolean = trueImmediately makes this view the Toolbar's active target.
Returns MathView
This MathView, in support of chaining commands together.
- toolbar: Toolbar
clear
-
clear(): void
Empties the view, and a linked LaTeXView with it, removing the equation and resetting the cursor to the start. Takes no focus - see MathView.setLatex.
Returns void
connect La Te X View
-
connectLaTeXView(_textAreaId: string): void
Part of the contract api.LaTeXView.addOutput expects. Does nothing: the LaTeXView is handed over by MathView.addLaTeXView.
Formerly called
connectTextArea(), which still works as an alias of this method.Parameters
- _textAreaId: string
Returns void
destroy
-
destroy(): void
Takes this view off the page and lets it go: removes what it added to its element, stops listening to the window and to the linked LaTeXView's pane, and unlinks it from that LaTeXView so the LaTeXView no longer updates it. For a page that builds editors and later removes them - a dialog, a single-page app - where every one ever built would otherwise go on receiving the window's mouse and resize events for the life of the page.
The element it was linked to stays; it is the page's. Calling this twice does nothing. A toolbar that was driving it should be given another target, or destroyed with it.
const view = EqEditor.MathView.link('mathview').addLaTeXView(textarea);
// ... later, when the dialog closes:
view.destroy();Returns void
edit Chemfig
-
editChemfig(): void
Opens the Chemistry Structure Editor: on the \chemfig{...} the cursor is in, or on a new structure to insert at the cursor. What the chemistry panel's editor button calls; a double-click on a structure in the view opens it the same way. Needs fxTeX Pro's chemfig package to show it -
packages: ['chemfig']to converter.init.Returns void
edit Picture
-
editPicture(): void
Opens the picture editor: on the picture the cursor is in, or on a new one to insert at the cursor. What the toolbar's picture button calls; a double-click on a picture in the view opens it the same way. Needs fxTeX Pro's picture package to draw -
packages: ['picture']to converter.init.Returns void
focus
-
focus(): void
Moves keyboard focus into this view.
Returns void
get Answers
-
getAnswers(): string[]
What has been typed into each slot of a locked equation, in the order the slots appear in the LaTeX - the student's answers - the same as api.LaTeXView.getAnswers. A slot left empty gives "".
Returns string[]
One entry per slot, or an empty list if the equation is not locked.
get Cursor Offset
-
getCursorOffset(): number
Where the cursor is, as a character offset into the LaTeX getLatex() returns.
The same number the linked LaTeXView reports, because both panes count into the same string - so anything following the editor can ask either one. Provided for a view used on its own, with no markup pane to ask instead.
Returns number
The cursor's offset into the equation.
get Latex
-
getLatex(): string
Returns the equation's current LaTeX. This is the value to read when submitting a form, or when handing the equation to a rendering service.
Returns string
The LaTeX of the equation currently shown.
has Focus
-
hasFocus(): boolean
Whether keyboard focus is inside this view.
Returns boolean
insert
-
insert(txt: string, newCaretPos?: number, selectedInsertPos?: number): void
Inserts LaTeX into the equation at the cursor, wrapping anything selected - the same as api.LaTeXView.insert, and what every toolbar button calls when this view is the toolbar's target.
mathview.insert('\\frac{}{}'); // the cursor goes into the numeratorParameters
- txt: string
The LaTeX to insert. Remember that a backslash must be escaped in a JavaScript string literal.
OptionalnewCaretPos: number = nullWhere to place the cursor, counted from the start of the inserted text; negative counts back from its end. null puts it inside the first empty
{}pair, or after the insertion if there is none.OptionalselectedInsertPos: number = nullWhere any selected text is placed within the inserted text, counted the same way; null puts it where the cursor would have gone.
Returns void
- txt: string
insert Frac
-
insertFrac(): void
Inserts an empty fraction,
\frac{}{}, leaving the cursor in the numerator.Returns void
insert Int
-
insertInt(): void
Inserts an integral with empty limits,
\int_{}^{}, leaving the cursor in the lower one.Returns void
insert Paren
-
insertParen(): void
Inserts an auto-sized bracket pair,
\left({}\right).Returns void
insert Script
-
insertScript(): void
Inserts an empty superscript,
^{}, leaving the cursor inside it.Returns void
insert Sqrt
-
insertSqrt(): void
Inserts an empty square root,
\sqrt{}.Returns void
is Structure Locked
-
isStructureLocked(): boolean
Whether the equation is locked to its structure - see MathView.structural_lock.
Returns boolean
make Array Matrix
-
makeArrayMatrix(...args: any[]): void
Inserts a matrix from the toolbar's matrix panel - see api.LaTeXView.makeArrayMatrix. Works only in a view linked to a LaTeXView.
Parameters
- ...args: any[]
Returns void
make Equations Matrix
-
makeEquationsMatrix(...args: any[]): void
Inserts a block of equations from the toolbar's matrix panel - see api.LaTeXView.makeEquationsMatrix. Works only in a view linked to a LaTeXView.
Parameters
- ...args: any[]
Returns void
notify Outputs
-
notifyOutputs(): void
Notifies the Outputs of the linked LaTeXView, if there is one, of a change.
Returns void
set Inline
-
setInline(flag?: boolean): MathView
Shows the equation as an inline one or as a display one, the same distinction output.Output.setInline makes for the exported formats.
The visible difference is
display="block"on the<math>root: a display equation gets its own centred line, an inline one sits where it is put, on the baseline of whatever text surrounds it. Call it alongside Output.setInline() so what is on screen and what gets exported agree.Display style is left on either way - full-size fraction numerators, and a large operator's limits above and below rather than beside. That is deliberate and it is about editing rather than presentation: in text style MathML drops an
<mfrac>'s numerator and denominator a script level, so a fraction inside a fraction is drawn smaller than the one containing it, and the inner one is exactly what somebody is usually trying to click into.mathview.setInline(true);Parameters
Optionalflag: boolean = trueTrue for an inline equation, false for a display one.
Returns MathView
This MathView, in support of chaining commands together.
set Latex
-
setLatex(latex: string): void
Replaces the equation wholesale and puts the cursor at the end. Use this to pre-load the view with an existing equation. A linked LaTeXView is given the same equation.
EqEditor.MathView.link('mathview').setLatex('x^2+y^2=r^2');Loading an equation is not editing it, so this takes no focus - a view that has focus keeps it, and one that has not is left alone. To put the reader in the view as well, pass
trueto MathView.link or call focus().Parameters
- latex: string
The LaTeX to display. Pass an empty string to clear the view.
Returns void
- latex: string
structural_ lock
-
structural_lock(on?: boolean): MathView
Locks the equation to its structure, or unlocks it - see api.LaTeXView.structural_lock, which this is the same as. Locked, only the slots that are empty now can be edited, and they take only plain characters and single symbols.
A view linked to a LaTeXView shares its lock: locking either one locks both. A view on its own has a lock of its own. To lock every equation on a page at once, use api.structural_lock.
var mv = EqEditor.MathView.link('mathview');
mv.setLatex('\\frac{}{2}=5');
mv.structural_lock(true);Parameters
Optionalon: boolean = trueTrue to lock the equation to its current structure, false to unlock it.
Returns MathView
This MathView, in support of chaining commands together.
update Output
-
updateOutput(): void
Re-renders this view from the linked LaTeXView's current LaTeX, and puts this view's cursor where that LaTeXView's is. The LaTeXView calls this after every change.
Returns void
Staticlink
-
link(mathViewElementId: string, focus?: boolean): MathView
Static constructor. Returns a new instance of MathView linked to the specified element, allowing chained setup, e.g.
<div id="mathview"></div>
<div id="input"></div>
<script>
EqEditor.MathView.link('mathview')
.addLaTeXView(EqEditor.LaTeXView.link('input'));
</script>Parameters
- mathViewElementId: string
Id of the container div the view is placed into.
Optionalfocus: boolean = falseActivates the cursor within the view.
Returns MathView
The new MathView, ready for further chained calls.
- mathViewElementId: string
Output
The Output class presents the equation in an editable api.LaTeXView in a variety of forms. Its most common use is to show the rendered equation as an image, but it will equally write the equation out as code for pasting into a web page, blog, forum, wiki or document.
Two settings decide what an Output produces:
- Output.setFormat - what the equation is rendered as: MathML, SVG, PNG, GIF or PDF;
- Output.setWrapper - how it is written out: as LaTeX, as the URL of the rendered equation, as HTML, or in a template of your own for any other system.
One or more Outputs are attached to a LaTeXView with api.LaTeXView.addOutput. Each Output can then be configured independently with its own format, size, DPI, background colour and inline setting, so a single equation can drive several previews at once.
An image is drawn by the rendering service (see Output.setRenderURL), so it needs nothing loaded on the page. MathML - the 'mathml' format with the 'html' wrapper - is converted on the page by fxTeX Pro, so an Output that produces it should be created once converter.init has resolved.
<div id="entry"></div>
<img id="output"/>
<script>
EqEditor.LaTeXView.link('entry')
.addOutput(EqEditor.Output.link('output')
.setFormat('svg')
.setSize('Large'));
</script>
Output
constructor
-
new Output(divOutputId?: string, wrapper?: string): Output
Creates an Output, which presents the equation from an associated LaTeXView in an HTML element on the page, e.g.:
<div id="entry"></div>
<img id="output"/>
<script>
EqEditor.LaTeXView.link('entry')
.addOutput(new EqEditor.Output('output'));
</script>An
imgelement always shows the rendered equation. Any other element shows the equation written out by the wrapper - see Output.setWrapper.Parameters
- divOutputId: string = null
The id of the element the Output will render into, or null for an Output that is only read from, with Output.getCode or Output.getEquationURL.
- wrapper: string = null
How the equation is written out - see Output.setWrapper. Defaults to 'latex'.
Returns Output
- divOutputId: string = null
add Export Area
-
addExportArea(divElementId: string, wrapper?: string): Output
Connects an export area to this Output. The named element is filled with the equation written out by a wrapper, and refreshed whenever the equation changes - which is how a page offers a "copy this into your forum post" box beside the preview. A
textareaorinputhas its value set; any other element its text.EqEditor.Output.link('output')
.addExportArea('forum-code', '[tex]%1[/tex]')
.addExportArea('page-code', 'html');Parameters
- divElementId: string
The id of the export area element.
Optionalwrapper: string = ...How the equation is written out - see Output.setWrapper. Defaults to this Output's own wrapper at the time it is added.
Returns Output
This Output, in support of chaining commands together.
- divElementId: string
connect La Te X View
-
connectLaTeXView(textAreaId: string): void
Links this Output to a LaTeXView, so it displays the formatted equation for that text. You will not usually call this directly - api.LaTeXView.addOutput does it for you.
Parameters
- textAreaId: string
The id of the LaTeXView's element.
Formerly called
connectTextArea(), which still works as an alias of this method.
Returns void
- textAreaId: string
download
-
download(filename?: string): void
Downloads the current equation as a file in the Output's current format, from the rendering service (see Output.getEquationURL).
<button onclick="output.setFormat('pdf').download()">Download PDF</button>Parameters
Optionalfilename: string = ...Name to save the file under. Defaults to "equation." followed by the current format, e.g. "equation.svg". Browsers ignore a requested filename when the rendering service is on a different origin to the page, in which case the name comes from the service's own Content-Disposition header.
Returns void
get Code
-
getCode(): string
Returns the current equation written out by the wrapper - see Output.setWrapper - ready to paste into a web page, a forum or a document. An empty equation gives an empty string.
An Output with no element of its own is enough to read from:
var out = EqEditor.Output.link().setFormat('mathml').setWrapper('html');
EqEditor.LaTeXView.link('input').addOutput(out);
...
var mathml = out.getCode();Returns string
The equation, as code.
get Equation URL
-
getEquationURL(download?: boolean): string
Returns the URL that renders the current equation in the current format, size, DPI, background and inline setting. The equation is fully URL encoded, so the URL can be used as it is in an
imgelement, a link or a stylesheet.Parameters
Optionaldownload: boolean = falseIf true, returns a URL that downloads the rendered equation as a file; otherwise returns a URL that displays it.
Returns string
The URL.
get Inline
-
getInline(): boolean
Returns true if the equation is being rendered inline (vertically aligned with the surrounding text) rather than as a display equation.
Returns boolean
get Latex
-
getLatex(): string
Returns the equation's LaTeX in a compact form, with every redundant space removed - see compactLatex. An empty equation, or an Output not yet attached to a LaTeXView, gives an empty string.
Returns string
get Scale
-
getScale(): number
This equation's size on the page against a normal one - see Output.setScale.
Returns number
get Supported Colors
-
getSupportedColors(): any[]
Returns the supported background colours, as an array of
{value, desc}pairs.Returns any[]
get Supported Formats
-
getSupportedFormats(): string[]
Returns the formats Output.setFormat accepts: ['mathml', 'svg', 'png', 'gif', 'pdf'].
Returns string[]
get Supported Sizes
-
getSupportedSizes(): string[]
Returns the sizes Output.setSize accepts, smallest first: the LaTeX size commands ['tiny', 'scriptsize', 'footnotesize', 'small', 'normalsize', 'large', 'Large', 'LARGE', 'huge', 'Huge'].
Returns string[]
image Html
-
imageHtml(): Promise<string>
The equation as an
<img class="fxtex">, sized by Output.imageSize - for a caller that can wait for it before inserting. When no size can be read it is the plain<img>.Returns Promise<string>
Resolves to the HTML of the
imgelement. Never rejects.
image Size
-
imageSize(): Promise<{ height: string; width: string }>
The size, in em, to give an
<img>of the equation's image (Output.getEquationURL): its natural size - the image server's 16px to the em, so a normal equation is 1em of the text around it - times the equation's scale (see Output.setScale). In em, so it follows the site's .fxtex rule and the text it is in, where the SVG's own pixel size would not.Fetches the SVG to read its size; the image's own request then comes from the cache.
output.imageSize().then(function (size) {
if (size) { img.style.width = size.width; img.style.height = size.height; }
});Returns Promise<{ height: string; width: string }>
Resolves to
{ width, height }, each a CSS length in em, or to null for any format but 'svg', or when the size cannot be read. Never rejects.
set Background
-
setBackground(backgroundColor: string): Output
Sets the background colour of the rendered equation. Leave it empty for a transparent background, which is usually what you want when the equation sits on a coloured page.
EqEditor.Output.link('output')
.setBackground('red');Any colour the rendering service reads will do: a CSS colour name (
'red','lavender') or hex ('#ffe4e1','ffe4e1','#fee'). Output.getSupportedColors lists a few, for a menu.Parameters
- backgroundColor: string
A CSS colour name or hex colour, or '' for transparent.
Returns Output
This Output, in support of chaining commands together.
- backgroundColor: string
set Dpi
-
setDpi(dpi: string | number): Output
Sets the resolution of a PNG, in dots per inch, where 96 is the equation's normal size on screen and 288 three times as sharp. It applies to the 'png' format only: SVG and MathML have no resolution, and the rendering service draws GIF and PDF at a fixed one.
The rendering service reads it from a
\dpi{N}it is sent ahead of the equation - see Output.getEquationURL. Until this is called none is sent and the service uses its own default.EqEditor.Output.link('output')
.setFormat('png')
.setDpi(300);Parameters
- dpi: string | number
A whole number of dots per inch, or 0 for the service's default.
Returns Output
This Output, in support of chaining commands together.
- dpi: string | number
set Foreground
-
setForeground(foregroundColor: string): Output
Sets the colour the rendered equation is drawn in - what a
\\colorin the equation itself then overrides. Leave it empty for the service's default, black.EqEditor.Output.link('output')
.setForeground('#1c7ed6');Parameters
- foregroundColor: string
A CSS colour name or hex colour, or '' for the default.
Returns Output
This Output, in support of chaining commands together.
- foregroundColor: string
set Format
-
setFormat(format: string, speech?: boolean): Output
Sets the format the equation is rendered as:
- mathml - MathML, which carries the mathematics rather than a picture of it;
- svg - a scalable vector image (the default);
- png - a bitmap image, at the resolution set by Output.setDpi;
- gif - a bitmap image;
- pdf - a PDF document.
MathML and SVG include generated spoken text by default, so a screen reader reads the mathematics rather than spelling out the LaTeX. Pass
speechfalse to leave it out, for a smaller result.EqEditor.Output.link('output')
.setFormat('svg', false);An
imgelement can only show an svg, png or gif.Parameters
- format: string
One of ['mathml', 'svg', 'png', 'gif', 'pdf'].
Optionalspeech: boolean = trueInclude spoken text. Applies only to 'mathml' and 'svg'.
Returns Output
This Output, in support of chaining commands together.
set Inline
-
setInline(flag?: boolean): Output
Sets the inline mode of the Output. An inline equation is vertically aligned to sit on the baseline of the surrounding text, rather than being rendered as a standalone display equation. It also changes what the 'latex' wrapper writes:
$...$rather than\[...\].EqEditor.Output.link('output')
.setInline(true);Parameters
Optionalflag: boolean = trueTrue to render inline, false for a display equation.
Returns Output
This Output, in support of chaining commands together.
set Render URL
-
setRenderURL(renderURL: string): Output
Sets the URL of the rendering service used to draw the equation. The default is 'https://fxtex.codecogs.com'; you would typically change this to point at your own installation of the rendering service.
<div id="entry"></div>
<img id="output"/>
<script>
EqEditor.LaTeXView.link('entry')
.addOutput(EqEditor.Output.link('output')
.setRenderURL('https://fxtex.example.com')
.setFormat('png'));
</script>Parameters
- renderURL: string
Base URL of a CodeCogs equation rendering service.
Returns Output
This Output, in support of chaining commands together.
- renderURL: string
set Scale
-
setScale(scale?: number): Output
Sets this equation's size on the page, against a normal equation: 1 (the default) is the normal size, 1.5 half as big again. Unlike Output.setSize it does not change what the equation is drawn at, only how big it is shown.
Normal is whatever the page makes it - every inserted equation carries class="fxtex", so a site sizes all of them with one rule (
.fxtex { font-size: 120% }) - and this scales one equation on top of that. It applies to:- MathML from the 'html' wrapper, which is put inside
<mstyle mathsize="150%">; - the size Output.imageSize and Output.imageHtml give an image, in em.
It does not change the image URL, so an
imgthe Output is linked to is unaffected, and it does not refresh the Output by itself. Output.scaleOf reads it back from an equation already on the page.Parameters
Optionalscale: number = 1The size against a normal equation. Anything not above 0 means 1.
Returns Output
This Output, in support of chaining commands together.
- MathML from the 'html' wrapper, which is put inside
set Size
-
setSize(size: string): Output
Sets the size the equation is drawn at, as one of the LaTeX size commands - see Output.getSupportedSizes. 'normalsize' is the default.
EqEditor.Output.link('output')
.setSize('Large');The size goes in front of the equation wherever it is written out: the rendered picture's URL, the MathML (as
\Large x^2would be) and the latex wrapper's\[\Large x^2\].To scale an equation on a page without changing what it is drawn at, use Output.setScale instead.
Parameters
- size: string
One of ['tiny', 'scriptsize', 'footnotesize', 'small', 'normalsize', 'large', 'Large', 'LARGE', 'huge', 'Huge'].
Returns Output
This Output, in support of chaining commands together.
- size: string
set Wrapper
-
setWrapper(wrapper: string): Output
Sets how the equation is written out, by Output.getCode and in any element other than an
img. Either one of the core wrappers:- latex - the LaTeX, inside
\[...\], or$...$when the Output is inline (the default); - url - the URL of the rendered equation - see Output.getEquationURL;
- html - HTML for a web page: an
imgelement showing the rendered equation, or for the 'mathml' format the MathML itself;
or a template of your own, in which these placeholders are replaced:
- %1 - the LaTeX as it is, e.g.
a<b & c; - %2 - the LaTeX HTML encoded, e.g.
a<b & c, for an HTML attribute or element; - %3 - the LaTeX fully URL encoded, e.g.
a%3Cb%20%26%20c, for a URL of your own; - %4 - the URL of the rendered equation, as Output.getEquationURL returns it.
Templates for some common systems:
System Template WordPress [latex]%1[/latex]phpBB [tex]%1[/tex]Doxygen \f[%1\f]Doxygen (inline) \f$%1\f$Forums using pre<pre xml:lang="latex">%2</pre>Markdown (GitHub) $$%1$$Markdown image MediaWiki <math>%1</math>TiddlyWiki [img[%4]]BBCode image [img]%4[/img]HTML image, fixed <img src="https://fxtex.codecogs.com/svg.image?%3" alt="%2"/>HTML image, linked <a href="%4"><img src="%4" alt="%2"/></a>EqEditor.Output.link('code')
.setWrapper('[latex]%1[/latex]');Remember to escape a backslash in a JavaScript string: the Doxygen template is written
'\\f[%1\\f]'.Parameters
- wrapper: string
One of ['latex', 'url', 'html'], or a template using %1 to %4.
Returns Output
This Output, in support of chaining commands together.
- latex - the LaTeX, inside
update Output
-
updateOutput(): void
Updates the Output to show the equation as it is now, in the LaTeXView it is attached to - including an edit made through a mathview.MathView linked to that LaTeXView - along with every export area added with Output.addExportArea.
You will not usually call this directly: the LaTeXView calls it after every change to the equation. Typing is batched, so the Output catches up a second after the last keystroke rather than on every one.
Returns void
Staticlatex To Math ML
-
latexToMathML(
latex: string,
withSpeech?: boolean,
inline?: boolean,
namespaced?: boolean,
scale?: number,
): stringConverts a LaTeX string straight to presentation MathML, without needing an Output bound to a LaTeXView first - for example in a CKEditor or TinyMCE plugin that stores the source LaTeX and regenerates its markup on the way out. The conversion is fxTeX Pro's, so call it once converter.init has resolved; before that it gives MathML saying so.
await EqEditor.init({ licence: 'fx_pk_...' });
var mathml = EqEditor.Output.latexToMathML('\\frac{a}{b}', true);Parameters
- latex: string
The equation source.
OptionalwithSpeech: boolean = falseWrap it with the generated spoken text, so a screen reader reads the mathematics rather than spelling out the source.
Optionalinline: boolean = falseProduce an inline equation - no display="block" on the root, limits beside a large operator rather than above and below it - for MathML that has to sit in a line of running text rather than on a line of its own.
Optionalnamespaced: boolean = falsePut xmlns="http://www.w3.org/1998/Math/MathML" on the root, for MathML going into an XML document or a file of its own. HTML5 needs none - a
Optionalscale: number = 1Its size against a normal equation - see Output.setScale.
Returns string
The MathML, or an empty string for an empty equation.
- latex: string
Staticlink
-
link(divOutputId?: string, wrapper?: string): Output
Static constructor. Returns a new Output linked to the given element, the same as
new EqEditor.Output(...), in a form that reads well with settings chained onto it:<div id="entry"></div>
<img id="output"/>
<script>
EqEditor.LaTeXView.link('entry')
.addOutput(EqEditor.Output.link('output')
.setFormat('png')
.setSize('LARGE'));
</script>Parameters
- divOutputId: string = null
The id of the element the Output will render into, or null (the default) for an Output that is only read from - see the constructor.
- wrapper: string = null
How the equation is written out - see Output.setWrapper. Defaults to 'latex'.
Returns Output
The new Output, ready for further chained calls.
- divOutputId: string = null
Staticscale Of
-
scaleOf(el: Element): number
The scale an inserted equation was given - see Output.setScale - read back from it, for an editor reopening it: an
<img>from its width in em against its natural width (so the image must have loaded); MathML from the<mstyle mathsize>around its content.var out = EqEditor.Output.link().setScale(EqEditor.Output.scaleOf(equationElement));Parameters
- el: Element
The inserted equation: an
img, amathelement, or an element holding one.
Returns number
The scale, or 1 for anything else or an equation inserted without one.
- el: Element
History
The History class draws the undo, redo and clear buttons that accompany a LaTeXView, together with the toggle that enables or disables automatic bracket completion.
Attach it with LaTeXView.addHistoryMenu; the buttons enable and disable themselves as the undo stack changes. One History may serve several LaTeXViews, acting on whichever last had focus.
<div id="history"></div>
<div id="input"></div>
<script>
EqEditor.LaTeXView.link('input', true)
.addHistoryMenu(new EqEditor.History('history'));
</script>
History
constructor
-
new History(historyMenuId: string): History
Creates an instance of History and renders its buttons into the given element.
Parameters
- historyMenuId: string
The id of the div the history menu is rendered into.
Returns History
- historyMenuId: string
set Active La Te X View
-
setActiveLaTeXView(textArea: LaTeXView): void
Connects the History buttons to the given LaTeXView. You will not usually call this directly - LaTeXView.addHistoryMenu does it for you, and a LaTeXView calls it again whenever it gains focus.
Parameters
- textArea: LaTeXView
The LaTeXView object to connect with.
Formerly called
setActiveTextArea(), which still works as an alias of this method.
Returns void
- textArea: LaTeXView
newConverter()
-
newConverter(): Converter
Returns a new converter, for code running alongside the editor that needs equations of its own converted - the editor's own fxTeX Pro, with settings of its own. Call it once EqEditor.init() has resolved: before that, or if init() failed, the converter answers every equation with an
<merror>saying why.EqEditor.init({ licence: 'fx_pk_...' }).then(function () {
var conv = EqEditor.newConverter();
conv.setSpeech(true, 'verbose');
conv.setSpeechMarkup('hidden');
var mathml = conv.convert('\\frac{a}{b}');
var spoken = conv.getSpeech();
});Not for a page without an editor. That page has no use for the editor's bundle - it only passes this request on to fxTeX Pro - so it loads fxTeX Pro itself and converts with it directly, with fxtex.css to style what it draws:
<link rel="stylesheet" href="https://fxtex.codecogs.com/fxtex.css">
<script src="https://fxtex.codecogs.com/fx_pk_.../fxtexpro.min.js"></script>
<script>
fxTeXPro.ready.then(function () {
fxTeXPro.unlock('fx_pk_...');
var conv = fxTeXPro.converter();
conv.setSpeech(true, 'verbose');
var mathml = conv.convert('\\frac{a}{b}');
});
</script>A page that only shows equations already written into it needs neither:
fxtex.min.jsandfxTeX.autoRender()draw them where they stand.Returns Converter
A converter with its own settings, all at their defaults.
Converter
Turns LaTeX into MathML for code that runs alongside the editor - what newConverter returns. Use it where the editor's page needs equations of its own besides the editor's: a plugin's preview, a list of saved equations beside the editor, a custom view of what is typed. A page without an editor loads fxTeX Pro on its own instead - see newConverter.
Each converter keeps its own settings, and a setting stays made until it is changed, so set them once and call convert as often as needed. Out of the box a converter produces a block (display) equation with no spoken text.
The MathML it returns is drawn by the browser. Its root carries class="fxtex", which the
editor's stylesheet styles - so load fxeditor.css on the page, as an editor page does.
convert
-
convert(latex: string): string
Converts one LaTeX string, with the settings made so far, and returns the markup: a
<math>element, or a<span>around one when spoken text is attached as'hidden'or'wrapper'. Put it in the page withinnerHTML.LaTeX that cannot be read comes back as MathML holding an
<merror>. So does every equation when init() has not finished, or failed, with the reason in place of the maths.Parameters
- latex: string
The equation, without delimiters:
\frac{a}{b}, not$\frac{a}{b}$.
Returns string
- latex: string
get Speech
-
getSpeech(): string
The spoken text of the most recent convert, or
""when speech is off. Read it straight after converting: converters share one engine, so another converter's next convert() replaces it.Returns string
set Cursor
-
setCursor(pos: number): void
Where the caret is in the LaTeX, as a character offset, or -1 for none (the default). A command whose name ends exactly there is left as typed, so
\fracis not a fraction until the caret has moved on. For a page that follows someone typing; otherwise leave it at -1.Parameters
- pos: number
Returns void
set Display Style
-
setDisplayStyle(on: boolean): void
truesets an inline equation at full size, as a block one is - a fraction's numerator and denominator are not shrunk to fit the line. Off by default.Parameters
- on: boolean
Returns void
set Emit Positions
-
setEmitPositions(on: boolean): void
Marks every part of the output with the position in the LaTeX it came from, and draws each empty argument as a box to type into. The editor's own maths view uses it; a page displaying finished equations leaves it off. Off by default.
Parameters
- on: boolean
Returns void
set Inline
-
setInline(on: boolean): void
truefor an equation that sits in a line of text;false(the default) for a block equation set on its own line.Parameters
- on: boolean
Returns void
set Speech
-
setSpeech(on: boolean, verbosity?: SpeechVerbosity): void
Adds spoken text to each equation for screen readers, and chooses how much:
'terse'(the default) or'verbose'. Off by default. setSpeechMarkup chooses how the text is attached; getSpeech returns it.Parameters
- on: boolean
Optionalverbosity: SpeechVerbosity
Returns void
set Speech Markup
-
setSpeechMarkup(mode: "label" | "none" | "hidden" | "wrapper"): void
How the spoken text is attached to the markup convert returns, when speech is on:
'hidden'(the default) - a visually hidden<span>beside the<math>, which screen readers read in its place.'wrapper'- a<span role="math">around the<math>, with the text as itsaria-label.'label'- anaria-labelon the<math>element itself.'none'- nothing attached; read it from getSpeech and use it yourself.
Parameters
- mode: "label" | "none" | "hidden" | "wrapper"
Returns void
Parameter Details
Two settings on the Output class decide what it produces: the format the equation is
rendered as, and the wrapper that writes it out. getCode() returns the
equation written out by both.
const output = EqEditor.Output.link()
.setFormat('mathml', true) // MathML, with spoken text for a screen reader
.setWrapper('html'); // ...as markup to put in a page
textarea.addOutput(output);
output.getCode();
format
Set with setFormat(format, speech). speech (default true) adds generated
spoken text, and applies to mathml and svg only.
| mathml | Presentation MathML | The equation itself rather than a picture of it, so it scales, reflows and can be selected. |
| svg | Scalable vector image | The default. |
| png | Bitmap image | At the resolution set by setDpi(). |
| gif | Bitmap image | |
| PDF document |
wrapper
Set with setWrapper(wrapper), or passed as the second argument when an Output is
created. One of three core wrappers:
| latex | LaTeX (the default) | \[1+\sin(x)\], or $1+\sin(x)$ when the Output is inline |
| url | URL of the rendered equation | https://fxtex.codecogs.com/svg.image?1%2B%5Csin%28x%29 |
| html | HTML for a web page | <img src="https://fxtex.codecogs.com/svg.image?1%2B%5Csin%28x%29" alt="1+\sin(x)"/>, or for the mathml format the MathML itself |
Or a template of your own, in which these placeholders are replaced:
| %1 | The LaTeX as it is | a<b & c |
| %2 | The LaTeX HTML encoded | a<b & c |
| %3 | The LaTeX URL encoded | a%3Cb%20%26%20c |
| %4 | The URL of the rendered equation | https://fxtex.codecogs.com/svg.image?a%3Cb%20%26%20c |
Templates for some common systems:
| WordPress | [latex]%1[/latex] |
| phpBB | [tex]%1[/tex] |
| Doxygen | \f[%1\f] |
| Doxygen (inline) | \f$%1\f$ |
| Forums using pre | <pre xml:lang="latex">%2</pre> |
| Markdown (GitHub) | $$%1$$ |
| Markdown image |  |
| MediaWiki | <math>%1</math> |
| TiddlyWiki | [img[%4]] |
| BBCode image | [img]%4[/img] |
| HTML image, fixed | <img src="https://fxtex.codecogs.com/svg.image?%3" alt="%2"/> |
| HTML image, linked | <a href="%4"><img src="%4" alt="%2"/></a> |
In a JavaScript string a backslash is written twice: setWrapper('\\f[%1\\f]').
size
Set with setSize(size): one of the LaTeX size commands, smallest first —
tiny, scriptsize, footnotesize, small, normalsize
(the default), large, Large, LARGE, huge, Huge.
To show an equation bigger on a page without changing what it is drawn at, use
setScale() instead.
dpi
Set with setDpi(dpi): the resolution of a PNG, in dots per inch, where 96 is the
equation’s normal size on screen and 288 three times as sharp. It applies to the
png format only — SVG and MathML have no resolution, and GIF and PDF are drawn at a
fixed one. Until it is set the rendering service uses its own default.
More
Examples — these options, arranged into working editors.
Design — which toolbar panels to include, and in what order.
User guide — what the finished editor looks like to the person using it.
fxTeX — displaying equations your users have already written.

Places the Equation Editor toolbar on the page, e.g.
You can use one of the standard toolbar designs: 'default' or 'full' (two rows, at present the same) or 'mini' (one row).
Alternatively you can select the panels you require, in any order. Each inner array is one row of the toolbar, so the example below produces a single row of six panels:
The available panel names are: 'accents', 'accents_ext', 'arrows', 'binary', 'brackets', 'chemfig', 'chemfig_ext', 'colors', 'editors', 'foreign', 'geometry', 'greeklower', 'greekupper', 'matrix', 'mhchem', 'mhchem_arrows', 'operators', 'operators_core', 'picture', 'relations', 'spaces', 'style', 'subsupset', 'symbols'
and, for a class at one level of school or university, a single panel of the operators, brackets and matrices that level uses - the levels fxQuiz uses, and one above them: 'primary', 'lower_secondary', 'secondary', 'upper_secondary', 'university'
'editors' (Advanced Editors) holds just the picture editor and the Chemistry Structure Editor.
The mhchem and chemfig panels need the matching package named to converter.init.