Skip to main content

Mathfield API Reference

Conversion

convertAsciiMathToLatex()

function convertAsciiMathToLatex(ascii): string

Convert an AsciiMath string to a LaTeX string.

convertAsciiMathToLatex("1/2");
// -> "\\frac{1}{2}"

ascii: string

string

convertLatexToAsciiMath()

function convertLatexToAsciiMath(latex, parseMode): string

Convert a LaTeX string to a string of AsciiMath.

convertLatexToAsciiMath("\\frac{1}{2}");
// -> "1/2"

latex: string

parseMode: ParseMode= 'math'

string

convertLatexToMarkup()

function convertLatexToMarkup(text, options?): string

Convert a LaTeX string to a string of HTML markup.

Note

This function does not interact with the DOM. It does not load fonts or inject stylesheets in the document. It can safely be used on the server side.

To get the output of this function to correctly display in a document, use the mathlive static style sheet by adding the following to the <head> of the document:

<link
rel="stylesheet"
href="https://unpkg.com/mathlive/dist/mathlive-static.css"
/>

text: string

A string of valid LaTeX. It does not have to start with a mode token such as $$ or \(.

options?: Partial<LayoutOptions>

string

Keywords

convert, latex, markup

convertLatexToMathMl()

function convertLatexToMathMl(latex, options): string

Convert a LaTeX string to a string of MathML markup.

latex: string

A string of valid LaTeX. It does not have to start with a mode token such as a $$ or \(.

options= {}

options.generateID?: boolean

If true, add an "extid" attribute to the MathML nodes with a value matching the atomID. This can be used to map items on the screen with their MathML representation or vice-versa.

string

convertLatexToSpeakableText()

function convertLatexToSpeakableText(latex): string

Convert a LaTeX string to a textual representation ready to be spoken

latex: string

A string of valid LaTeX. It does not have to start with a mode token such as a $$ or \(.

string

The spoken representation of the input LaTeX.

Example

console.log(convertLatexToSpeakableText('\\frac{1}{2}'));
// 'half'

Keywords

convert, latex, speech, speakable, text, speakable text

convertMathJsonToLatex()

function convertMathJsonToLatex(json): string

Convert a MathJSON expression to a LaTeX string.

convertMathJsonToLatex(["Add", 1, 2]);
// -> "1 + 2"

json: Expression

string

Editing Commands

Commands

To perform editing commands on a mathfield, use MathfieldElement.executeCommand with the commands below.

const mf = document.getElementById('mathfield');
mf.executeCommand('selectAll');
mf.executeCommand('copyToClipboard');

Some commands require an argument, for example to insert a character:

mf.executeCommand('insert("x")' });

The argument can be specified in parentheses after the command name, or using an array:

mf.executeCommand(['switchMode', 'latex']);
// Same as mf.executeCommand('switchMode("latex")');

Commands (and executeCommand()) return true if they resulted in a dirty state.

Command

executeCommand

Array

Commands.addColumnAfter()
addColumnAfter: (model) => boolean;

model: Model

boolean

Commands.addColumnBefore()
addColumnBefore: (model) => boolean;

model: Model

boolean

Commands.addRowAfter()
addRowAfter: (model) => boolean;

model: Model

boolean

Commands.addRowBefore()
addRowBefore: (model) => boolean;

model: Model

boolean

Commands.removeColumn()
removeColumn: (model) => boolean;

model: Model

boolean

Commands.removeRow()
removeRow: (model) => boolean;

model: Model

boolean

Commands.setEnvironment()
setEnvironment: (model, environment) => boolean;

model: Model

environment: TabularEnvironment

boolean

Auto-complete

Commands.complete()
complete: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.nextSuggestion()
nextSuggestion: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.previousSuggestion()
previousSuggestion: (mathfield) => boolean;

mathfield: Mathfield

boolean

Clipboard

Commands.copyToClipboard()
copyToClipboard: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.cutToClipboard()
cutToClipboard: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.pasteFromClipboard()
pasteFromClipboard: (mathfield) => boolean;

mathfield: Mathfield

boolean

Deleting

Commands.deleteAll()
deleteAll: (model) => boolean;

model: Model

boolean

Commands.deleteBackward()
deleteBackward: (model) => boolean;

model: Model

boolean

Commands.deleteForward()
deleteForward: (model) => boolean;

model: Model

boolean

Commands.deleteNextWord()
deleteNextWord: (model) => boolean;

model: Model

boolean

Commands.deletePreviousWord()
deletePreviousWord: (model) => boolean;

model: Model

boolean

Commands.deleteToGroupEnd()
deleteToGroupEnd: (model) => boolean;

model: Model

boolean

Commands.deleteToGroupStart()
deleteToGroupStart: (model) => boolean;

model: Model

boolean

Commands.deleteToMathFieldEnd()
deleteToMathFieldEnd: (model) => boolean;

model: Model

boolean

Commands.deleteToMathFieldStart()
deleteToMathFieldStart: (model) => boolean;

model: Model

boolean

Other

Commands.applyStyle()
applyStyle: (mathfield, style) => boolean;

mathfield: Mathfield

style: Style

boolean

Commands.commit()
commit: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.dispatchEvent()
dispatchEvent: (mathfield, name, detail) => boolean;

Dispatch a custom event on the host (mathfield)

mathfield: Mathfield

name: string

detail: number

boolean

Commands.insert()
insert: (mathfield, s, options) => boolean;

mathfield: Mathfield

s: string

options: InsertOptions

boolean

Commands.insertDecimalSeparator()
insertDecimalSeparator: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.performWithFeedback()
performWithFeedback: (mathfield, command) => boolean;

Perform a command and include interactive feedback such as sound and haptic feedback.

This is useful to simulate user interaction, for example for commands from the virtual keyboard

mathfield: Mathfield

command: string

boolean

Commands.plonk()
plonk: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.speak()
speak: (mathfield, scope, options) => boolean;

mathfield: Mathfield

scope: SpeechScope

How much of the formula should be spoken:

allthe entire formula
selectionthe selection portion of the formula
leftthe element to the left of the selection
rightthe element to the right of the selection
groupthe group (numerator, root, etc..) the selection is in
parentthe parent of the selection

options

options.withHighlighting: boolean

In addition to speaking the requested portion of the formula, visually highlight it as it is read (read aloud functionality)

boolean

Commands.switchMode()
switchMode: (mathfield, mode) => boolean;

mathfield: Mathfield

mode: ParseMode

boolean

Commands.toggleContextMenu()
toggleContextMenu: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.toggleKeystrokeCaption()
toggleKeystrokeCaption: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.typedText()
typedText: (text, options) => boolean;

text: string

options

options.feedback: boolean

If true, provide audio and haptic feedback

options.focus: boolean

If true, the mathfield will be focused

options.simulateKeystroke: boolean

If true, generate some synthetic keystrokes (useful to trigger inline shortcuts, for example).

boolean

Prompt

Commands.insertPrompt()
insertPrompt: (mathfield, id?, options?) => boolean;

mathfield: Mathfield

id?: string

options?: InsertOptions

boolean

Scrolling

Commands.scrollIntoView()
scrollIntoView: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.scrollToEnd()
scrollToEnd: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.scrollToStart()
scrollToStart: (mathfield) => boolean;

mathfield: Mathfield

boolean

Selection

Commands.extendSelectionBackward()
extendSelectionBackward: (model) => boolean;

model: Model

boolean

Commands.extendSelectionDownward()
extendSelectionDownward: (model) => boolean;

model: Model

boolean

Commands.extendSelectionForward()
extendSelectionForward: (model) => boolean;

model: Model

boolean

Commands.extendSelectionUpward()
extendSelectionUpward: (model) => boolean;

model: Model

boolean

Commands.extendToGroupEnd()
extendToGroupEnd: (model) => boolean;

model: Model

boolean

Commands.extendToGroupStart()
extendToGroupStart: (model) => boolean;

model: Model

boolean

Commands.extendToMathFieldEnd()
extendToMathFieldEnd: (model) => boolean;

model: Model

boolean

Commands.extendToMathFieldStart()
extendToMathFieldStart: (model) => boolean;

model: Model

boolean

Commands.extendToNextBoundary()
extendToNextBoundary: (model) => boolean;

model: Model

boolean

Commands.extendToNextWord()
extendToNextWord: (model) => boolean;

model: Model

boolean

Commands.extendToPreviousBoundary()
extendToPreviousBoundary: (model) => boolean;

model: Model

boolean

Commands.extendToPreviousWord()
extendToPreviousWord: (model) => boolean;

model: Model

boolean

Commands.moveAfterParent()
moveAfterParent: (model) => boolean;

model: Model

boolean

Commands.moveBeforeParent()
moveBeforeParent: (model) => boolean;

model: Model

boolean

Commands.moveDown()
moveDown: (model) => boolean;

model: Model

boolean

Commands.moveToGroupEnd()
moveToGroupEnd: (model) => boolean;

model: Model

boolean

Commands.moveToGroupStart()
moveToGroupStart: (model) => boolean;

model: Model

boolean

Commands.moveToMathfieldEnd()
moveToMathfieldEnd: (model) => boolean;

model: Model

boolean

Commands.moveToMathfieldStart()
moveToMathfieldStart: (model) => boolean;

model: Model

boolean

Commands.moveToNextChar()
moveToNextChar: (model) => boolean;

model: Model

boolean

Commands.moveToNextGroup()
moveToNextGroup: (model) => boolean;

model: Model

boolean

Commands.moveToNextPlaceholder()
moveToNextPlaceholder: (model) => boolean;

model: Model

boolean

Commands.moveToNextWord()
moveToNextWord: (model) => boolean;

model: Model

boolean

Commands.moveToOpposite()
moveToOpposite: (model) => boolean;

model: Model

boolean

Commands.moveToPreviousChar()
moveToPreviousChar: (model) => boolean;

model: Model

boolean

Commands.moveToPreviousGroup()
moveToPreviousGroup: (model) => boolean;

model: Model

boolean

Commands.moveToPreviousPlaceholder()
moveToPreviousPlaceholder: (model) => boolean;

model: Model

boolean

Commands.moveToPreviousWord()
moveToPreviousWord: (model) => boolean;

model: Model

boolean

Commands.moveToSubscript()
moveToSubscript: (model) => boolean;

model: Model

boolean

Commands.moveToSuperscript()
moveToSuperscript: (model) => boolean;

model: Model

boolean

Commands.moveUp()
moveUp: (model) => boolean;

model: Model

boolean

Commands.selectAll()
selectAll: (model) => boolean;

model: Model

boolean

Commands.selectGroup()
selectGroup: (model) => boolean;

model: Model

boolean

Undo/Redo

Commands.redo()
redo: (mathfield) => boolean;

mathfield: Mathfield

boolean

Commands.undo()
undo: (mathfield) => boolean;

mathfield: Mathfield

boolean

VirtualKeyboardCommands

VirtualKeyboardCommands.hideVirtualKeyboard()
hideVirtualKeyboard: () => boolean;

boolean

VirtualKeyboardCommands.showVirtualKeyboard()
showVirtualKeyboard: () => boolean;

boolean

VirtualKeyboardCommands.switchKeyboardLayer()
switchKeyboardLayer: (mathfield, layer) => boolean;

mathfield: undefined

layer: string

boolean

VirtualKeyboardCommands.toggleVirtualKeyboard()
toggleVirtualKeyboard: () => boolean;

boolean

Selector

type Selector: Keys<Commands>;

Macros

MacroDefinition

type MacroDefinition: object;

See Also

Type declaration

MacroDefinition.args?
optional args: number;
MacroDefinition.captureSelection?
optional captureSelection: boolean;
MacroDefinition.def
def: string;

Definition of the macro as a LaTeX expression

MacroDefinition.expand?
optional expand: boolean;

MacroDictionary

type MacroDictionary: Record<string, string | Partial<MacroDefinition> | MacroPackageDefinition>;

A dictionary of LaTeX macros to be used to interpret and render the content.

For example:

mf.macros = { smallfrac: "^{#1}\\!\\!/\\!_{#2}" };

The code above will support the following notation:

\smallfrac{5}{16}

See Also

MacroPackageDefinition

type MacroPackageDefinition: object;

Type declaration

MacroPackageDefinition.captureSelection?
optional captureSelection: boolean;
MacroPackageDefinition.package
package: Record<string, string | MacroDefinition>;
MacroPackageDefinition.primitive?
optional primitive: boolean;

NormalizedMacroDictionary

type NormalizedMacroDictionary: Record<string, MacroDefinition>;

MathJSON

Expression

type Expression: number | string | object | [Expression, ...Expression[]];

Options

MathfieldHooks

These hooks provide an opportunity to intercept or modify an action. When their return value is a boolean, it indicates if the default handling should proceed.

MathfieldHooks.onExport()
onExport: (from, latex, range) => string;

from: Mathfield

latex: string

range: Range

string

MathfieldHooks.onInlineShortcut()
onInlineShortcut: (sender, symbol) => string;

sender: Mathfield

symbol: string

string

MathfieldHooks.onInsertStyle
onInsertStyle: InsertStyleHook;
MathfieldHooks.onScrollIntoView()
onScrollIntoView: (sender) => void;

sender: Mathfield

void

ContentChangeOptions

type ContentChangeOptions: object;

Type declaration

ContentChangeOptions.data?
optional data: string | null;
ContentChangeOptions.dataTransfer?
optional dataTransfer: DataTransfer | null;
ContentChangeOptions.inputType?
optional inputType: ContentChangeType;

ContentChangeType

type ContentChangeType: 
| "insertText"
| "insertLineBreak"
| "insertFromPaste"
| "historyUndo"
| "historyRedo"
| "deleteByCut"
| "deleteContent"
| "deleteContentBackward"
| "deleteContentForward"
| "deleteWordBackward"
| "deleteWordForward"
| "deleteSoftLineBackward"
| "deleteSoftLineForward"
| "deleteHardLineBackward"
| "deleteHardLineForward";

EditingOptions

type EditingOptions: object;

Type declaration

EditingOptions.contentPlaceholder
contentPlaceholder: string;
EditingOptions.environmentPopoverPolicy
environmentPopoverPolicy: "auto" | "on" | "off";
EditingOptions.isImplicitFunction()
isImplicitFunction: (name) => boolean;

Return true if the latex command is a function that could take implicit arguments. By default, this includes trigonometric function, so \sin x is interpreted as \sin(x).

This affects editing, for example how the / key is interpreted after such as symbol.

name: string

boolean

EditingOptions.mathModeSpace
mathModeSpace: string;
EditingOptions.mathVirtualKeyboardPolicy
mathVirtualKeyboardPolicy: "auto" | "manual" | "sandboxed";
EditingOptions.placeholderSymbol
placeholderSymbol: string;
EditingOptions.popoverPolicy
popoverPolicy: "auto" | "off";
EditingOptions.readOnly
readOnly: boolean;

When true, the user cannot edit the mathfield. The mathfield can still be modified programatically.

Default: false

EditingOptions.removeExtraneousParentheses
removeExtraneousParentheses: boolean;
EditingOptions.scriptDepth
scriptDepth: number | [number, number];
EditingOptions.smartFence
smartFence: boolean;
EditingOptions.smartMode
smartMode: boolean;
EditingOptions.smartSuperscript
smartSuperscript: boolean;

InlineShortcutDefinition

type InlineShortcutDefinition: string | object;

An inline shortcut can be specified as a simple string or as an object literal with additional options:

    config.inlineShortcuts = {
half: '\\frac{1}{2}',
in: {
after: 'space+letter+digit+symbol+fence',
value: '\\in',
},
};

When using a string, the shortcut applies regardless of the characters surrounding it.

When using an object literal the value key is required an indicate the shortcut substitution.

The "after" key, if present, indicate in what context (preceding characters) the shortcut will apply. One or more values can be specified, separated by a '|' character. If any of the values match, the shortcut is applicable.

Possible values are:

"space"A spacing command, such as \quad
"nothing"The begining of a group
"surd"A square root or n-th root
"frac"A fraction
"function"A function such as \sin or f
"letter"A letter, such as x or n
"digit"0 through 9
"binop"A binary operator, such as +
"relop"A relational operator, such as =
"punct"A punctuation mark, such as ,
"array"An array, such as a matrix or cases statement
"openfence"An opening fence, such as (
"closefence"A closing fence such as }
"text"Some plain text

InlineShortcutDefinitions

type InlineShortcutDefinitions: Record<string, InlineShortcutDefinition>;

InlineShortcutsOptions

type InlineShortcutsOptions: object;

Type declaration

InlineShortcutsOptions.inlineShortcutTimeout
inlineShortcutTimeout: number;
InlineShortcutsOptions.inlineShortcuts
inlineShortcuts: InlineShortcutDefinitions;

Keybinding

type Keybinding: object;

A keybinding associates a combination of physical keyboard keys with a command.

For example:

{
"key": "cmd+a",
"command": "selectAll",
},
{
"key": 'ctrl+[Digit2]',
"ifMode": 'math',
"command": ['insert', '\\sqrt{#0}'],
}

Type declaration

Keybinding.command
command: 
| Selector
| string[]
| [string, any]
| [string, any, any]
| [string, any, any, any];

The command is a single selector, or a selector with arguments

Keybinding.ifLayout?
optional ifLayout: string[];
Keybinding.ifMode?
optional ifMode: ParseMode;

If specified, this indicates in which mode this keybinding will apply. If none is specified, the keybinding will apply in every mode.

Keybinding.ifPlatform?
optional ifPlatform: 
| "macos"
| "!macos"
| "windows"
| "!windows"
| "linux"
| "!linux"
| "ios"
| "!ios"
| "android"
| "!android"
| "chromeos"
| "!chromeos";

If specified, this indicates the OS platform to which this keybinding apply.

For example, if set to !macos this key binding will apply to every platform, except macOS.

Keybinding.key
key: string;

The pressed keys that will trigger this keybinding.

The key is made up of modifiers and the key itself.

The following modifiers can be used:

PlatformModifiers
macOS, iOSctrl, shift, alt, cmd
Windowsctrl, shift, alt, win
Linux, Android, ChromeOSctrl, shift, alt, meta

If the cmd modifier is used, the keybinding will only apply on macOS. If the win modifier is used, the keybinding will only apply to Windows. If the meta modifier is used, the keybinding will apply to platforms other than macOS or Windows.

The alt key is the option key on Apple keyboards.

The following values for keys can be used:

  • az, 09
  • `, -, =, [, ], \, ;, ', ,, ., /
  • left, up, right, down, pageup, pagedown, end, home
  • tab, enter, escape, space, backspace, delete
  • f1f19
  • pausebreak, capslock, insert
  • numpad0numpad9, numpad_multiply, numpad_add, numpad_separator
  • numpad_subtract, numpad_decimal, numpad_divide

The values will be remapped based on the current keyboard layout. So, for example if a is used, on a French AZERTY keyboard the keybinding will be associated with the key labeled 'A' (event though it corresponds to the key labeled 'Q' on a US QWERTY keyboard).

To associate keybindings with physical keys independent of the keyboard layout, use the following keycodes:

  • [KeyA][KeyZ], [Digit0][Digit9]
  • [Backquote], [Minus], [Equal], [BracketLeft], [BracketRight], [Backslash], [Semicolon], [Quote], [Comma], [Period], [Slash]
  • [ArrowLeft], [ArrowUp], [ArrowRight], [ArrowDown], [PageUp], [PageDown], [End], [Home]
  • [Tab], [Enter], [Escape], [Space], [Backspace], [Delete]
  • [F1][F19]
  • [Pause], [CapsLock], [Insert]
  • [Numpad0][Numpad9], [NumpadMultiply], [NumpadAdd], [NumpadComma]
  • [NumpadSubtract], [NumpadDecimal], [NumpadDivide]

For example, using [KeyQ] will map to the the key labeled 'Q' on a QWERTY keyboard, and to the key labeled 'A' on an AZERTY keyboard.

As a general guideline, it is preferable to use the key values az for keybinding that are pseudo-mnemotechnic. For the other, it is generally preferable to use the keycodes.

Consider the key combination: alt+2. With an AZERTY (French) layout, the digits (i.e. '2') are only accessible when shifted. The '2' key produces 'é' when not shifted. It is therefore impossible on an AZERTY keyboard to produce the alt+2 key combination, at best it would be alt+shift+2. To indicate that the intended key combination should be alt and the key on the keyboard which has the position of the 2 key on a US keyboard, a key code should be used instead: alt+[Digit2]. This will correspond to a key combination that can be generated on any keyboard.

KeyboardLayoutName

type KeyboardLayoutName: 
| "apple.en-intl"
| "apple.french"
| "apple.german"
| "apple.spanish"
| "dvorak"
| "windows.en-intl"
| "windows.french"
| "windows.german"
| "windows.spanish"
| "linux.en"
| "linux.french"
| "linux.german"
| "linux.spanish";

See setKeyboardLayout.

NamePlatformDisplay name
"apple.en-intl"AppleEnglish (International)
"apple.french"AppleFrench (AZERTY)
"apple.german"AppleGerman (QWERTZ)
"dvorak"English (Dvorak)
"windows.en-intl"WindowsEnglish (International)
"windows.french"WindowsFrench (AZERTY)
"windows.german"WindowsGerman (QWERTZ)
"linux.en"LinuxEnglish
"linux.french"LinuxFrench (AZERTY)
"linux.german"LinuxGerman (QWERTZ)

KeyboardOptions

type KeyboardOptions: object;

Type declaration

KeyboardOptions.keybindings
keybindings: Readonly<Keybinding[]>;

LayoutOptions

type LayoutOptions: object;

Type declaration

LayoutOptions.backgroundColorMap()
backgroundColorMap: (name) => string | undefined;

name: string

string | undefined

LayoutOptions.colorMap()
colorMap: (name) => string | undefined;

name: string

string | undefined

LayoutOptions.defaultMode
defaultMode: "inline-math" | "math" | "text";
LayoutOptions.letterShapeStyle
letterShapeStyle: 
| "auto"
| "tex"
| "iso"
| "french"
| "upright";
LayoutOptions.macros
macros: MacroDictionary;
LayoutOptions.maxMatrixCols
maxMatrixCols: number;
LayoutOptions.minFontScale
minFontScale: number;
LayoutOptions.registers
registers: Registers;

LaTeX global registers override.

MathfieldOptions

type MathfieldOptions: LayoutOptions & EditingOptions & InlineShortcutsOptions & KeyboardOptions & MathfieldHooks & object;

Keywords

security, trust, sanitize, errors

Type declaration

MathfieldOptions.originValidator
originValidator: OriginValidator;

Specify how origin of message from postMessage should be validated.

Default: "none"

MathfieldOptions.virtualKeyboardTargetOrigin
virtualKeyboardTargetOrigin: string;

Specify the targetOrigin parameter for postMessage to send control messages from child to parent frame to remote control of mathfield component.

Default: window.origin

OriginValidator

type OriginValidator: (origin) => boolean | "same-origin" | "none";

Specify behavior for origin validation.

ValueDescription
"same-origin"The origin of received message must be the same of hosted window, instead exception will throw.
(origin: string) => booleanThe callback to verify origin to be expected validation. When callback return false value, message will rejected and exception will throw.
"none"No origin validation for post messages.

setKeyboardLayout()

function setKeyboardLayout(name): void

Change the current physical keyboard layout.

Note that this affects some keybindings, but not general text input.

If set to auto the keyboard layout is guessed.

name: "auto" | KeyboardLayoutName

void

setKeyboardLayoutLocale()

function setKeyboardLayoutLocale(locale): void

Change the current physical keyboard layout to a layout that matches the specified locale, if one is available.

Note that this affects some keybindings, but not general text input.

locale: string

void

Other

MathfieldElement

The MathfieldElement class represent a DOM element that displays math equations.

It is a subclass of the standard HTMLElement class and as such inherits all of its properties and methods.

It inherits many useful properties and methods from HTMLElement such as style, tabIndex, addEventListener(), getAttribute(), etc...

It is typically used to render a single equation.

To render multiple equations, use multiple instances of MathfieldElement.

The MathfieldElement class provides special properties and methods to control the display and behavior of <math-field> elements.

You will usually instantiate a MathfieldElement using the <math-field> tag in HTML. However, if necessary you can also create it programmatically using new MathfieldElement().

// 1. Create a new MathfieldElement
const mf = new MathfieldElement();

// 2. Attach it to the DOM
document.body.appendChild(mf);

// Modifying options after construction mf.smartFence = true;


#### MathfieldElement CSS Variables

To customize the appearance of the mathfield, declare the following CSS
variables (custom properties) in a ruleset that applies to the mathfield.

```css
math-field {
--hue: 10 // Set the highlight color and caret to a reddish hue
}

Alternatively you can set these CSS variables programatically:

document.body.style.setProperty("--hue", "10");
CSS VariableUsage
--hueHue of the highlight color and the caret
--contains-highlight-background-colorBackround property for items that contain the caret
--primary-colorPrimary accent color, used for example in the virtual keyboard
--text-font-familyThe font stack used in text mode
--smart-fence-opacityOpacity of a smart fence (default is 50%)
--smart-fence-colorColor of a smart fence (default is current color)

You can customize the appearance and zindex of the virtual keyboard panel with some CSS variables associated with a selector that applies to the virtual keyboard panel container.

Read more about customizing the virtual keyboard appearance

MathfieldElement CSS Parts

To style the virtual keyboard toggle, use the virtual-keyboard-toggle CSS part. To use it, define a CSS rule with a ::part() selector for example:

math-field::part(virtual-keyboard-toggle) {
color: red;
}

MathfieldElement Attributes

An attribute is a key-value pair set as part of the tag:

<math-field letter-shape-style="tex"></math-field>

The supported attributes are listed in the table below with their corresponding property.

The property can also be changed directly on the MathfieldElement object:

 getElementById('mf').value = "\\sin x";
getElementById('mf').letterShapeStyle = "text";

The values of attributes and properties are reflected, which means you can change one or the other, for example:

getElementById('mf').setAttribute('letter-shape-style',  'french');
console.log(getElementById('mf').letterShapeStyle);
// Result: "french"
getElementById('mf').letterShapeStyle ='tex;
console.log(getElementById('mf').getAttribute('letter-shape-style');
// Result: 'tex'

An exception is the value property, which is not reflected on the value attribute: for consistency with other DOM elements, the value attribute remains at its initial value.

AttributeProperty
disabledmf.disabled
default-modemf.defaultMode
letter-shape-stylemf.letterShapeStyle
min-font-scalemf.minFontScale
max-matrix-colsmf.maxMatrixCols
popover-policymf.popoverPolicy
math-mode-spacemf.mathModeSpace
read-onlymf.readOnly
remove-extraneous-parenthesesmf.removeExtraneousParentheses
smart-fencemf.smartFence
smart-modemf.smartMode
smart-superscriptmf.smartSuperscript
inline-shortcut-timeoutmf.inlineShortcutTimeout
script-depthmf.scriptDepth
valuevalue
math-virtual-keyboard-policymathVirtualKeyboardPolicy

See MathfieldOptions for more details about these options.

In addition, the following global attributes can also be used:

  • class
  • data-*
  • hidden
  • id
  • item*
  • style
  • tabindex

MathfieldElement Events

Listen to these events by using addEventListener(). For events with additional arguments, the arguments are available in event.detail.

Event NameDescription
beforeinputThe value of the mathfield is about to be modified.
inputThe value of the mathfield has been modified. This happens on almost every keystroke in the mathfield. The evt.data property includes a copy of evt.inputType. See InputEvent
changeThe user has committed the value of the mathfield. This happens when the user presses Return or leaves the mathfield.
selection-changeThe selection (or caret position) in the mathfield has changed
mode-changeThe mode (math, text) of the mathfield has changed
undo-state-changeThe state of the undo stack has changed. The evt.detail.type indicate if a snapshot was taken or an undo performed.
read-aloud-status-changeThe status of a read aloud operation has changed
before-virtual-keyboard-toggleThe visibility of the virtual keyboard panel is about to change. The evt.detail.visible property indicate if the keyboard will be visible or not. Listen for this event on window.mathVirtualKeyboard
virtual-keyboard-toggleThe visibility of the virtual keyboard panel has changed. Listen for this event on window.mathVirtualKeyboard
geometrychangeThe geometry of the virtual keyboard has changed. The evt.detail.boundingRect property is the new bounding rectangle of the virtual keyboard. Listen for this event on window.mathVirtualKeyboard
blurThe mathfield is losing focus
focusThe mathfield is gaining focus
move-outThe user has pressed an arrow key or the tab key, but there is nowhere to go. This is an opportunity to change the focus to another element if desired.
`detail: {direction: 'forward'
keypressThe user pressed a physical keyboard key
mountThe element has been attached to the DOM
unmountThe element is about to be removed from the DOM

@category Web Component @keywords zindex, events, attribute, attributes, property, properties, parts, variables, css, mathfield, mathfieldelement

Extends

  • HTMLElement

Implements

  • Mathfield

Accessing and changing the content

MathfieldElement.errors
get errors(): readonly LatexSyntaxError[]

Return an array of LaTeX syntax errors, if any.

readonly LatexSyntaxError[]

MathfieldElement.expression
get expression(): any

If the Compute Engine library is available, return a boxed MathJSON expression representing the value of the mathfield.

To load the Compute Engine library, use:

import 'https://unpkg.com/@cortex-js/compute-engine?module';
set expression(mathJson): void

mathJson: any

any

MathfieldElement.value
get value(): string

The content of the mathfield as a LaTeX expression.

document.querySelector('mf').value = '\\frac{1}{\\pi}'
set value(value): void

value: string

string

MathfieldElement.applyStyle()
applyStyle(style, options?): void

Update the style (color, bold, italic, etc...) of the selection or sets the style to be applied to future input.

If there is no selection and no range is specified, the style will apply to the next character typed.

If a range is specified, the style is applied to the range, otherwise, if there is a selection, the style is applied to the selection.

If the operation is "toggle" and the range already has this style, remove it. If the range has the style partially applied (i.e. only some sections), remove it from those sections, and apply it to the entire range.

If the operation is "set", the style is applied to the range, whether it already has the style or not.

The default operation is "set".

style: Readonly<Style>

options?: Range | object

void

MathfieldElement.getValue()
getValue(format)
getValue(format?): string

Return a textual representation of the content of the mathfield.

format?: OutputFormat

The format of the result. If using math-json the Compute Engine library must be loaded, for example with:

import "https://unpkg.com/@cortex-js/compute-engine?module";

Default: "latex"

string

getValue(start, end, format)
getValue(
start,
end,
format?): string

start: number

end: number

format?: OutputFormat

string

getValue(range, format)
getValue(range, format?): string

range: Range

format?: OutputFormat

string

getValue(selection, format)
getValue(selection, format?): string

selection: Selection

format?: OutputFormat

string

MathfieldElement.insert()
insert(s, options?): boolean

Insert a block of text at the current insertion point.

This method can be called explicitly or invoked as a selector with executeCommand("insert").

After the insertion, the selection will be set according to the options.selectionMode.

s: string

options?: InsertOptions

boolean

MathfieldElement.queryStyle()
queryStyle(style): "some" | "all" | "none"

If there is a selection, return if all the atoms in the selection, some of them or none of them match the style argument.

If there is no selection, return 'all' if the current implicit style (determined by a combination of the style of the previous atom and the current style) matches the style argument, 'none' if it does not.

style: Readonly<Style>

"some" | "all" | "none"

MathfieldElement.setValue()
setValue(value?, options?): void

Set the content of the mathfield to the text interpreted as a LaTeX expression.

value?: string

options?: InsertOptions

void

Commands

Execute a command defined by a selector.

mfe.executeCommand('add-column-after');
mfe.executeCommand(['switch-mode', 'math']);
MathfieldElement.executeCommand()
executeCommand(selector)
executeCommand(selector): boolean

selector: Selector

A selector, or an array whose first element is a selector, and whose subsequent elements are arguments to the selector.

Selectors can be passed either in camelCase or kebab-case.

// Both calls do the same thing
mfe.executeCommand('selectAll');
mfe.executeCommand('select-all');

boolean

executeCommand(selector, args)
executeCommand(selector, ...args): boolean

selector: Selector

• ...args: unknown[]

boolean

executeCommand(selector)
executeCommand(selector): boolean

selector: [Selector, ...unknown[]]

boolean

Customization

MathfieldElement.backgroundColorMap
get backgroundColorMap(): (name) => string
set backgroundColorMap(value): void

value

Function

name: string

string

MathfieldElement.keybindings
get keybindings(): readonly Keybinding[]
set keybindings(value): void

value: readonly Keybinding[]

readonly Keybinding[]

MathfieldElement.mathVirtualKeyboardPolicy
get mathVirtualKeyboardPolicy(): VirtualKeyboardPolicy
set mathVirtualKeyboardPolicy(value): void

value: VirtualKeyboardPolicy

VirtualKeyboardPolicy

MathfieldElement.menuItems
get menuItems(): readonly MenuItem[]
set menuItems(menuItems): void

menuItems: readonly MenuItem[]

readonly MenuItem[]

MathfieldElement.registers
get registers(): Registers

TeX registers represent "variables" and "constants".

Changing the values of some registers can modify the layout of math expressions.

The following registers might be of interest:

  • thinmuskip: space between items of math lists
  • medmuskip: space between binary operations
  • thickmuskip: space between relational operators
  • nulldelimiterspace: minimum space to leave blank in delimiter constructions, for example around a fraction
  • delimitershortfall: maximum space to overlap adjacent elements when a delimiter is too short
  • jot: space between lines in an array, or between rows in a multiline construct
  • arraycolsep: space between columns in an array
  • arraystretch: factor by which to stretch the height of each row in an array

To modify a register, use:

mf.registers.arraystretch = 1.5;
mf.registers.thinmuskip = { dimension: 2, unit: "mu" };
mf.registers.medmuskip = "3mu";
set registers(value): void

value: Registers

Registers

Customization

When true and an open fence is entered via typedText() it will generate a contextually appropriate markup, for example using \left...\right if applicable.

When false, the literal value of the character will be inserted instead.

MathfieldElement.smartFence
get smartFence(): boolean
set smartFence(value): void

value: boolean

boolean

Customization

A LaTeX string displayed inside the mathfield when there is no content.

MathfieldElement.placeholder
get placeholder(): string
set placeholder(value): void

value: string

string

Customization

A dictionary of LaTeX macros to be used to interpret and render the content.

For example, to add a new macro to the default macro dictionary:

mf.macros = {
...mf.macros,
smallfrac: '^{#1}\\!\\!/\\!_{#2}',
};

Note that ...mf.macros is used to keep the existing macros and add to them. Otherwise, all the macros are replaced with the new definition.

The code above will support the following notation:

\smallfrac{5}{16}
MathfieldElement.macros
get macros(): Readonly<MacroDictionary>
set macros(value): void

value: MacroDictionary

Readonly<MacroDictionary>

Customization

If "auto" a popover with commands to edit an environment (matrix) is displayed when the virtual keyboard is displayed.

Default: "auto"

MathfieldElement.environmentPopoverPolicy
get environmentPopoverPolicy(): "auto" | "off" | "on"
set environmentPopoverPolicy(value): void

value: "auto" | "off" | "on"

"auto" | "off" | "on"

Customization

If "auto" a popover with suggestions may be displayed when a LaTeX command is input.

Default: "auto"

MathfieldElement.popoverPolicy
get popoverPolicy(): "auto" | "off"
set popoverPolicy(value): void

value: "auto" | "off"

"auto" | "off"

Customization

If true, extra parentheses around a numerator or denominator are removed automatically.

Default: true

MathfieldElement.removeExtraneousParentheses
get removeExtraneousParentheses(): boolean
set removeExtraneousParentheses(value): void

value: boolean

boolean

Customization

Map a color name as used in commands such as \textcolor{}{} or \colorbox{}{} to a CSS color value.

Use this option to override the standard mapping of colors such as "yellow" or "red".

If the name is not one you expected, return undefined and the default color mapping will be applied.

If a backgroundColorMap() function is not provided, the colorMap() function will be used instead.

If colorMap() is not provided, default color mappings are applied.

The following color names have been optimized for a legible foreground and background values, and are recommended:

  • red, orange, yellow, lime, green, teal, blue, indigo, purple, magenta, black, dark-grey, grey, light-grey, white
MathfieldElement.colorMap
get colorMap(): (name) => string
set colorMap(value): void

value

Function

name: string

string

Customization

Maximum time, in milliseconds, between consecutive characters for them to be considered part of the same shortcut sequence.

A value of 0 is the same as infinity: any consecutive character will be candidate for an inline shortcut, regardless of the interval between this character and the previous one.

A value of 750 will indicate that the maximum interval between two characters to be considered part of the same inline shortcut sequence is 3/4 of a second.

This is useful to enter "+-" as a sequence of two characters, while also supporting the "±" shortcut with the same sequence.

The first result can be entered by pausing slightly between the first and second character if this option is set to a value of 250 or so.

Note that some operations, such as clicking to change the selection, or losing the focus on the mathfield, will automatically timeout the shortcuts.

MathfieldElement.inlineShortcutTimeout
get inlineShortcutTimeout(): number
set inlineShortcutTimeout(value): void

value: number

number

Customization

Set the minimum relative font size for nested superscripts and fractions. The value should be a number between 0 and 1. The size is in releative em units relative to the font size of the math-field element. Specifying a value of 0 allows the math-field to use its default sizing logic.

Default: 0

MathfieldElement.minFontScale
get minFontScale(): number
set minFontScale(value): void

value: number

number

Customization

Sets the maximum number of columns for the matrix environment. The default is 10 columns to match the behavior of the amsmath matrix environment. Default: 10

MathfieldElement.maxMatrixCols
get maxMatrixCols(): number
set maxMatrixCols(value): void

value: number

number

Customization

The LaTeX string to insert when the spacebar is pressed (on the physical or virtual keyboard).

Use "\;" for a thick space, "\:" for a medium space, "\," for a thin space.

Do not use " " (a regular space), as whitespace is skipped by LaTeX so this will do nothing.

Default: "" (empty string)

MathfieldElement.mathModeSpace
get mathModeSpace(): string
set mathModeSpace(value): void

value: string

string

Customization

The keys of this object literal indicate the sequence of characters that will trigger an inline shortcut.

MathfieldElement.inlineShortcuts
get inlineShortcuts(): Readonly<InlineShortcutDefinitions>
set inlineShortcuts(value): void

value: InlineShortcutDefinitions

Readonly<InlineShortcutDefinitions>

Customization

The mode of the element when it is empty:

  • "math": equivalent to \displaystyle (display math mode)
  • "inline-math": equivalent to \inlinestyle (inline math mode)
  • "text": text mode
MathfieldElement.defaultMode
get defaultMode(): "text" | "math" | "inline-math"
set defaultMode(value): void

value: "text" | "math" | "inline-math"

"text" | "math" | "inline-math"

Customization

The symbol used to represent a placeholder in an expression.

Default: U+25A2 WHITE SQUARE WITH ROUNDED CORNERS

MathfieldElement.placeholderSymbol
get placeholderSymbol(): string
set placeholderSymbol(value): void

value: string

string

Customization

This option controls how many levels of subscript/superscript can be entered. For example, if scriptDepth is "1", there can be one level of superscript or subscript. Attempting to enter a superscript while inside a superscript will be rejected. Setting a value of 0 will prevent entry of any superscript or subscript (but not limits for sum, integrals, etc...)

This can make it easier to enter equations that fit what's expected for the domain where the mathfield is used.

To control the depth of superscript and subscript independently, provide an array: the first element indicate the maximum depth for subscript and the second element the depth of superscript. Thus, a value of [0, 1] would suppress the entry of subscripts, and allow one level of superscripts.

MathfieldElement.scriptDepth
get scriptDepth(): number | [number, number]
set scriptDepth(value): void

value: number | [number, number]

number | [number, number]

Customization

When true and a digit is entered in an empty superscript, the cursor leaps automatically out of the superscript. This makes entry of common polynomials easier and faster. If entering other characters (for example "n+1") the navigation out of the superscript must be done manually (by using the cursor keys or the spacebar to leap to the next insertion point).

When false, the navigation out of the superscript must always be done manually.

MathfieldElement.smartSuperscript
get smartSuperscript(): boolean
set smartSuperscript(value): void

value: boolean

boolean

Customization

When true, during text input the field will switch automatically between 'math' and 'text' mode depending on what is typed and the context of the formula. If necessary, what was previously typed will be 'fixed' to account for the new info.

For example, when typing "if x >0":

TypeInterpretation
imath mode, imaginary unit
iftext mode, english word "if"
if xall in text mode, maybe the next word is xylophone?
if x >"if" stays in text mode, but now "x >" is in math mode
if x > 0"if" in text mode, "x > 0" in math mode

Default: false

Manually switching mode (by typing alt/option+=) will temporarily turn off smart mode.

Examples

  • slope = rise/run
  • If x > 0, then f(x) = sin(x)
  • x^2 + sin (x) when x > 0
  • When x&lt;0, x^{2n+1}&lt;0
  • Graph x^2 -x+3 =0 for 0&lt;=x&lt;=5
  • Divide by x-3 and then add x^2-1 to both sides
  • Given g(x) = 4x – 3, when does g(x)=0?
  • Let D be the set {(x,y)|0&lt;=x&lt;=1 and 0&lt;=y&lt;=x}
  • \int\_{the unit square} f(x,y) dx dy
  • For all n in NN
MathfieldElement.smartMode
get smartMode(): boolean
set smartMode(value): void

value: boolean

boolean

Customization

Control the letter shape style:

letterShapeStylexyzABCαβɣΓΔΘ
isoitititit
texitititup
frenchitupupup
uprightupupupup

(it) = italic (up) = upright

The default letter shape style is auto, which indicates that french should be used if the locale is "french", and tex otherwise.

Historical Note

Where do the "french" rules come from? The TeX standard font, Computer Modern, is based on Monotype 155M, itself based on the Porson greek font which was one of the most widely used Greek fonts in english-speaking countries. This font had upright capitals, but slanted lowercase. In France, the traditional font for greek was Didot, which has both upright capitals and lowercase.

As for roman uppercase, they are recommended by "Lexique des règles typographiques en usage à l’Imprimerie Nationale". It should be noted that this convention is not universally followed.

MathfieldElement.letterShapeStyle
get letterShapeStyle(): 
| "auto"
| "tex"
| "iso"
| "french"
| "upright"
set letterShapeStyle(value): void

value: | "auto" | "tex" | "iso" | "french" | "upright"

| "auto" | "tex" | "iso" | "french" | "upright"

Focus

MathfieldElement.blur()
blur(): void

Remove the focus from the mathfield (will no longer respond to keyboard input).

void

MathfieldElement.focus()
focus(): void

Sets the focus to the mathfield (will respond to keyboard input).

void

MathfieldElement.hasFocus()
hasFocus(): boolean

Return true if the mathfield is currently focused (responds to keyboard input).

boolean

Hooks

MathfieldElement.onInsertStyle
get onInsertStyle(): InsertStyleHook
set onInsertStyle(value): void

value: InsertStyleHook

InsertStyleHook

Hooks

A hook invoked when a string of characters that could be interpreted as shortcut has been typed.

If not a special shortcut, return the empty string "".

Use this handler to detect multi character symbols, and return them wrapped appropriately, for example \mathrm{${symbol}}.

MathfieldElement.onInlineShortcut
get onInlineShortcut(): (sender, symbol) => string
set onInlineShortcut(value): void

value

Function

sender: Mathfield

symbol: string

string

Hooks

A hook invoked when scrolling the mathfield into view is necessary.

Use when scrolling the page would not solve the problem, e.g. when the mathfield is in another div that has scrollable content.

MathfieldElement.onScrollIntoView
get onScrollIntoView(): (sender) => void
set onScrollIntoView(value): void

value

Function

sender: Mathfield

void

Hooks

This hook is invoked when the user has requested to export the content of the mathfield, for example when pressing ctrl/command+C.

This hook should return as a string what should be exported.

The range argument indicates which portion of the mathfield should be exported. It is not always equal to the current selection, but it can be used to export a format other than LaTeX.

By default this is:

 return `\\begin{equation*}${latex}\\end{equation*}`;
MathfieldElement.onExport
get onExport(): (from, latex, range) => string
set onExport(value): void

value

Function

from: Mathfield

latex: string

range: Range

string

Localization

MathfieldElement.decimalSeparator
get static decimalSeparator(): "," | "."

The symbol used to separate the integer part from the fractional part of a number.

When "," is used, the corresponding LaTeX string is {,}, in order to ensure proper spacing (otherwise an extra gap is displayed after the comma).

This affects:

  • what happens when the , key is pressed (if decimalSeparator is ",", the {,} LaTeX string is inserted when following some digits)
  • the label and behavior of the "." key in the default virtual keyboard

Default: "."

set static decimalSeparator(value): void

value: "," | "."

"," | "."

MathfieldElement.fractionNavigationOrder
get static fractionNavigationOrder(): "denominator-numerator" | "numerator-denominator"

When using the keyboard to navigate a fraction, the order in which the numerator and navigator are traversed:

  • "numerator-denominator": first the elements in the numerator, then the elements in the denominator.
  • "denominator-numerator": first the elements in the denominator, then the elements in the numerator. In some East-Asian cultures, fractions are read and written denominator first ("fēnzhī"). With this option the keyboard navigation follows this convention.

Default: "numerator-denominator"

set static fractionNavigationOrder(s): void

s: "denominator-numerator" | "numerator-denominator"

"denominator-numerator" | "numerator-denominator"

MathfieldElement.locale
get static locale(): string

The locale (language + region) to use for string localization.

If none is provided, the locale of the browser is used.

set static locale(value): void

value: string

string

MathfieldElement.strings
get static strings(): Readonly<Record<string, Record<string, string>>>

An object whose keys are a locale string, and whose values are an object of string identifier to localized string.

Example

mf.strings = {
"fr-CA": {
"tooltip.undo": "Annuler",
"tooltip.redo": "Refaire",
}
}

If the locale is already supported, this will override the existing strings. If the locale is not supported, it will be added.

set static strings(value): void

value: Record<string, Record<string, string>>

Readonly<Record<string, Record<string, string>>>

Other

new MathfieldElement()
new MathfieldElement()
new MathfieldElement(options?): MathfieldElement

To create programmatically a new mathfield use:

let mfe = new MathfieldElement();

// Set initial value and options
mfe.value = "\\frac{\\sin(x)}{\\cos(x)}";

// Options can be set either as an attribute (for simple options)...
mfe.setAttribute("letter-shape-style", "french");

// ... or using properties
mfe.letterShapeStyle = "french";

// Attach the element to the DOM
document.body.appendChild(mfe);

options?: Partial<MathfieldOptions>

MathfieldElement

MathfieldElement.createHTML()
static createHTML: (html) => any;

Support for Trusted Type.

This optional function will be called before a string of HTML is injected in the DOM, allowing that string to be sanitized according to a policy defined by the host.

html: string

any

MathfieldElement.readAloudHook()
static readAloudHook: (element, text) => void = defaultReadAloudHook;

element: HTMLElement

text: string

void

MathfieldElement.restoreFocusWhenDocumentFocused
static restoreFocusWhenDocumentFocused: boolean = true;

When switching from a tab to one that contains a mathfield that was previously focused, restore the focus to the mathfield.

This is behavior consistent with <textarea>, however it can be disabled if it is not desired.

MathfieldElement.speakHook()
static speakHook: (text) => void = defaultSpeakHook;

text: string

void

MathfieldElement.version
static version: string = '0.104.0';
MathfieldElement.disabled
get disabled(): boolean
set disabled(value): void

value: boolean

boolean

MathfieldElement.form
get form(): HTMLFormElement

HTMLFormElement

MathfieldElement.isSelectionEditable
get isSelectionEditable(): boolean

boolean

MathfieldElement.mode
get mode(): ParseMode
set mode(value): void

value: ParseMode

ParseMode

MathfieldElement.name
get name(): string

string

MathfieldElement.readOnly
get readOnly(): boolean
set readOnly(value): void

value: boolean

boolean

MathfieldElement.readonly
get readonly(): boolean
set readonly(value): void

value: boolean

boolean

MathfieldElement.type
get type(): string

string

MathfieldElement.computeEngine
get static computeEngine(): ComputeEngine

A custom compute engine instance. If none is provided, a default one is used. If null is specified, no compute engine is used.

set static computeEngine(value): void

value: ComputeEngine

ComputeEngine

MathfieldElement.fontsDirectory
get static fontsDirectory(): string

A URL fragment pointing to the directory containing the fonts necessary to render a formula.

These fonts are available in the /dist/fonts directory of the SDK.

Customize this value to reflect where you have copied these fonts, or to use the CDN version.

The default value is "./fonts". Use null to prevent any fonts from being loaded.

Changing this setting after the mathfield has been created will have no effect.

{
// Use the CDN version
fontsDirectory: ''
}
{
// Use a directory called "fonts", located next to the
// `mathlive.js` (or `mathlive.mjs`) file.
fontsDirectory: './fonts'
}
{
// Use a directory located at the root of your website
fontsDirectory: 'https://example.com/fonts'
}
set static fontsDirectory(value): void

value: string

string

MathfieldElement.formAssociated
get static formAssociated(): boolean

boolean

MathfieldElement.isFunction
get static isFunction(): (command) => boolean
set static isFunction(value): void

value

Function

command: string

boolean

MathfieldElement.plonkSound
get static plonkSound(): string

Sound played to provide feedback when a command has no effect, for example when pressing the spacebar at the root level.

The property is either:

  • a string, the name of an audio file in the soundsDirectory directory
  • null to turn off the sound
set static plonkSound(value): void

value: string

string

MathfieldElement.speechEngine
get static speechEngine(): "amazon" | "local"

Indicates which speech engine to use for speech output.

Use local to use the OS-specific TTS engine.

Use amazon for Amazon Text-to-Speech cloud API. You must include the AWS API library and configure it with your API key before use.

See mathfield/guides/speech/ | Guide: Speech

set static speechEngine(value): void

value: "amazon" | "local"

"amazon" | "local"

MathfieldElement.speechEngineRate
get static speechEngineRate(): string

Sets the speed of the selected voice.

One of x-slow, slow, medium, fast, x-fast or a value as a percentage.

Range is 20% to 200% For example 200% to indicate a speaking rate twice the default rate.

set static speechEngineRate(value): void

value: string

string

MathfieldElement.speechEngineVoice
get static speechEngineVoice(): string

Indicates the voice to use with the speech engine.

This is dependent on the speech engine. For Amazon Polly, see here: https://docs.aws.amazon.com/polly/latest/dg/voicelist.html

set static speechEngineVoice(value): void

value: string

string

MathfieldElement.textToSpeechMarkup
get static textToSpeechMarkup(): "" | "ssml" | "ssml_step" | "mac"

The markup syntax to use for the output of conversion to spoken text.

Possible values are ssml for the SSML markup or mac for the macOS markup, i.e. &#91;&#91;ltr&#93;&#93;.

set static textToSpeechMarkup(value): void

value: "" | "ssml" | "ssml_step" | "mac"

"" | "ssml" | "ssml_step" | "mac"

MathfieldElement.textToSpeechRules
get static textToSpeechRules(): "sre" | "mathlive"

Specify which set of text to speech rules to use.

A value of mathlive indicates that the simple rules built into MathLive should be used.

A value of sre indicates that the Speech Rule Engine from Volker Sorge should be used.

(Caution) SRE is not included or loaded by MathLive. For this option to work SRE should be loaded separately.

See mathfield/guides/speech/ | Guide: Speech

set static textToSpeechRules(value): void

value: "sre" | "mathlive"

"sre" | "mathlive"

MathfieldElement.textToSpeechRulesOptions
get static textToSpeechRulesOptions(): Readonly<Record<string, string>>

A set of key/value pairs that can be used to configure the speech rule engine.

Which options are available depends on the speech rule engine in use. There are no options available with MathLive's built-in engine. The options for the SRE engine are documented here

set static textToSpeechRulesOptions(value): void

value: Record<string, string>

Readonly<Record<string, string>>

MathfieldElement.getElementInfo()
getElementInfo(offset): ElementInfo

offset: number

ElementInfo

MathfieldElement.getPromptState()
getPromptState(id): ["correct" | "incorrect", boolean]

id: string

["correct" | "incorrect", boolean]

MathfieldElement.showMenu()
showMenu(_): boolean

_

_.location

_.location.x: number

_.location.y: number

_.modifiers: KeyboardModifiers

boolean

MathfieldElement.loadSound()
static loadSound(sound): Promise<void>

sound: | "keypress" | "plonk" | "delete" | "spacebar" | "return"

Promise<void>

MathfieldElement.openUrl()
static openUrl(href): void

href: string

void

MathfieldElement.playSound()
static playSound(name): Promise<void>

name: | "keypress" | "plonk" | "delete" | "spacebar" | "return"

Promise<void>

Prompts

MathfieldElement.getPromptRange()
getPromptRange(id): Range

Return the selection range for the specified prompt.

This can be used for example to select the content of the prompt.

mf.selection = mf.getPromptRange('my-prompt-id');

id: string

Range

MathfieldElement.getPromptValue()
getPromptValue(placeholderId, format?): string

Return the content of the \placeholder{} command with the placeholderId

placeholderId: string

format?: OutputFormat

string

MathfieldElement.getPrompts()
getPrompts(filter?): string[]

Return the id of the prompts matching the filter.

filter?

filter.correctness?: "undefined" | "correct" | "incorrect"

filter.id?: string

filter.locked?: boolean

string[]

MathfieldElement.setPromptState()
setPromptState(
id,
state,
locked?): void

id: string

state: "undefined" | "correct" | "incorrect"

locked?: boolean

void

MathfieldElement.setPromptValue()
setPromptValue(
id,
content,
insertOptions): void

id: string

content: string

insertOptions: Omit<InsertOptions, "insertionMode">

void

Selection

MathfieldElement.lastOffset
get lastOffset(): number

The last valid offset.

number

MathfieldElement.position
get position(): number

The position of the caret/insertion point, from 0 to lastOffset.

set position(offset): void

offset: number

number

MathfieldElement.selection
get selection(): Readonly<Selection>

An array of ranges representing the selection.

It is guaranteed there will be at least one element. If a discontinuous selection is present, the result will include more than one element.

set selection(sel): void

sel: number | Selection

Readonly<Selection>

MathfieldElement.selectionIsCollapsed
get selectionIsCollapsed(): boolean

boolean

MathfieldElement.getOffsetFromPoint()
getOffsetFromPoint(
x,
y,
options?): number

The offset closest to the location (x, y) in viewport coordinate.

bias: if 0, the vertical midline is considered to the left or right sibling. If -1, the left sibling is favored, if +1, the right sibling is favored.

x: number

y: number

options?

options.bias?: -1 | 0 | 1

number

MathfieldElement.select()
select(): void

Select the content of the mathfield.

void

Undo

MathfieldElement.canRedo()
canRedo(): boolean

Return whether there are redoable items

boolean

MathfieldElement.canUndo()
canUndo(): boolean

Return whether there are undoable items

boolean

MathfieldElement.resetUndo()
resetUndo(): void

Reset the undo stack

void

Virtual Keyboard

MathfieldElement.keypressVibration
static keypressVibration: boolean = true;

When a key on the virtual keyboard is pressed, produce a short haptic feedback, if the device supports it.

MathfieldElement.mathVirtualKeyboardPolicy
get mathVirtualKeyboardPolicy(): VirtualKeyboardPolicy
set mathVirtualKeyboardPolicy(value): void

value: VirtualKeyboardPolicy

VirtualKeyboardPolicy

MathfieldElement.virtualKeyboardTargetOrigin
get virtualKeyboardTargetOrigin(): string
set virtualKeyboardTargetOrigin(value): void

value: string

string

MathfieldElement.keypressSound
get static keypressSound(): Readonly<object>

When a key on the virtual keyboard is pressed, produce a short audio feedback.

If the property is set to a string, the same sound is played in all cases. Otherwise, a distinct sound is played:

  • delete a sound played when the delete key is pressed
  • return ... when the return/tab key is pressed
  • spacebar ... when the spacebar is pressed
  • default ... when any other key is pressed. This property is required, the others are optional. If they are missing, this sound is played as well.

The value of the properties should be either a string, the name of an audio file in the soundsDirectory directory or null to suppress the sound.

set static keypressSound(value): void

value: string | object

Readonly<object>

keypressSound.default
default: string;
keypressSound.delete
delete: string;
keypressSound.return
return: string;
keypressSound.spacebar
spacebar: string;
MathfieldElement.soundsDirectory
get static soundsDirectory(): string

A URL fragment pointing to the directory containing the optional sounds used to provide feedback while typing.

Some default sounds are available in the /dist/sounds directory of the SDK.

Use null to prevent any sound from being loaded.

set static soundsDirectory(value): void

value: string

string

Style

Use a Style object literal to modify the visual appearance of a mathfield or a portion of a mathfield.

You can control the color ("ink") and background color ("paper"), the font variant, weight (FontSeries), size and more.

See Also

Style.backgroundColor?
optional backgroundColor: string;
Style.color?
optional color: string;
Style.fontFamily?
optional fontFamily: FontFamily;
Style.fontSeries?
optional fontSeries: FontSeries;
Style.fontShape?
optional fontShape: FontShape;
Style.fontSize?
optional fontSize: "auto" | FontSize;
Style.variant?
optional variant: Variant;
Style.variantStyle?
optional variantStyle: VariantStyle;

ApplyStyleOptions

type ApplyStyleOptions: object;

Type declaration

ApplyStyleOptions.operation?
optional operation: "set" | "toggle";
ApplyStyleOptions.range?
optional range: Range;
ApplyStyleOptions.silenceNotifications?
optional silenceNotifications: boolean;

ElementInfo

type ElementInfo: object;

Some additional information about an element in the formula

Type declaration

ElementInfo.bounds?
optional bounds: DOMRect;

The bounding box of the element

ElementInfo.data?
optional data: Record<string, string | undefined>;

HTML attributes associated with element or its ancestores, set with \htmlData

ElementInfo.depth?
optional depth: number;

The depth in the expression tree. 0 for top-level elements

ElementInfo.id?
optional id: string;

id associated with this element or its ancestor, set with \htmlId or \cssId

ElementInfo.latex?
optional latex: string;

A LaTeX representation of the element

ElementInfo.mode?
optional mode: ParseMode;

The mode (math, text or LaTeX)

ElementInfo.style?
optional style: Style;

The style (color, weight, variant, etc...) of this element.

FontFamily

type FontFamily: "none" | "roman" | "monospace" | "sans-serif";

FontSeries

type FontSeries: 
| "auto"
| "m"
| "b"
| "l"
| "";

FontShape

type FontShape: 
| "auto"
| "n"
| "it"
| "sl"
| "sc"
| "";

FontSize

type FontSize: 
| 1
| 2
| 3
| 4
| 5
| 6
| 7
| 8
| 9
| 10;

InsertOptions

type InsertOptions: object;

Type declaration

InsertOptions.feedback?
optional feedback: boolean;

If true, provide audio and haptic feedback

InsertOptions.focus?
optional focus: boolean;

If true, the mathfield will be focused after the insertion

InsertOptions.format?
optional format: OutputFormat | "auto";

The format of the input string:

"auto"The string is LaTeX fragment or command) (default)
"latex"The string is a LaTeX fragment
InsertOptions.insertionMode?
optional insertionMode: "replaceSelection" | "replaceAll" | "insertBefore" | "insertAfter";
InsertOptions.mode?
optional mode: ParseMode | "auto";

If "auto" or omitted, the current mode is used

InsertOptions.scrollIntoView?
optional scrollIntoView: boolean;

If true, scroll the mathfield into view after insertion such that the insertion point is visible

InsertOptions.selectionMode?
optional selectionMode: "placeholder" | "after" | "before" | "item";

Describes where the selection will be after the insertion:

"placeholder"The selection will be the first available placeholder in the text that has been inserted (default)
"after"The selection will be an insertion point after the inserted text
"before"The selection will be an insertion point before the inserted text
"item"The inserted text will be selected
InsertOptions.silenceNotifications?
optional silenceNotifications: boolean;
InsertOptions.style?
optional style: Style;

InsertStyleHook()

type InsertStyleHook: (sender, at, info) => Readonly<Style>;

sender: Mathfield

at: Offset

info

info.after: Offset

info.before: Offset

Readonly<Style>

LatexSyntaxError<T>

type LatexSyntaxError<T>: object;

Type parameters

T = ParserErrorCode

Type declaration

LatexSyntaxError.after?
optional after: string;
LatexSyntaxError.arg?
optional arg: string;
LatexSyntaxError.before?
optional before: string;
LatexSyntaxError.code
code: T;
LatexSyntaxError.latex?
optional latex: string;

MathstyleName

type MathstyleName: "displaystyle" | "textstyle" | "scriptstyle" | "scriptscriptstyle";

Offset

type Offset: number;

A position of the caret/insertion point from the beginning of the formula.

OutputFormat

type OutputFormat: 
| "ascii-math"
| "latex"
| "latex-expanded"
| "latex-unstyled"
| "latex-without-placeholders"
| "math-json"
| "math-ml"
| "plain-text"
| "spoken"
| "spoken-text"
| "spoken-ssml"
| "spoken-ssml-with-highlighting";
FormatDescription
"ascii-math"A string of ASCIIMath.
"latex"LaTeX rendering of the content, with LaTeX macros not expanded.
"latex-expanded"All macros are recursively expanded to their definition.
"latex-unstyled"Styling (background color, color) is ignored
"latex-without-placeholders"Replace \placeholder commands with their body
"math-json"A MathJSON abstract syntax tree, as an object literal formated as a JSON string. Note: you must import the CortexJS Compute Engine to obtain a result.
"math-ml"A string of MathML markup.
' "plain-text"A plain text rendering of the content.
"spoken"Spoken text rendering, using the default format defined in config, which could be either text or SSML markup.
"spoken-text"A plain spoken text rendering of the content.
"spoken-ssml"A SSML (Speech Synthesis Markup Language) version of the content, which can be used with some text-to-speech engines such as AWS.
"spoken-ssml-with-highlighting"Like "spoken-ssml" but with additional annotations necessary for synchronized highlighting (read aloud).
  • To use the"math-json" format the Compute Engine library must be loaded. Use for example:
import "https://unpkg.com/@cortex-js/compute-engine?module";

ParserErrorCode

type ParserErrorCode: 
| "unknown-command"
| "invalid-command"
| "unbalanced-braces"
| "unknown-environment"
| "unbalanced-environment"
| "unbalanced-mode-shift"
| "missing-argument"
| "too-many-infix-commands"
| "unexpected-command-in-string"
| "missing-unit"
| "unexpected-delimiter"
| "unexpected-token"
| "unexpected-end-of-string"
| "improper-alphabetic-constant";

Error codes returned by the mf.errors property.

unknown-commandThere is no definition available for this LaTeX command, e.g. \zin
unknown-environmentThere is no definition available for this environment, e.g. \begin{foo}
invalid-commandThis command is not valid in the current context (e.g. text command in math mode)
unbalanced-bracesThere are too many or too few { or }
unbalanced-environmentAn environment was open but never closed (\begin{array}) or the \end command does not match the \begin command (\begin{array*}\end{array})
unbalanced-mode-shiftA $, $$, \( or \[ was not balanced
missing-argumentA required argument is missing, e.g. \frac{2}
too-many-infix-commandsA group can include only one infix command (i.e. \choose, \atop). In general it's best to avoid infix commands.
unexpected-command-in-stringA command expected a string argument, but there was a command instead
missing-unitAn argument requiring a dimension was missing an unit.
unexpected-delimiterAn invalid symbol or command was used as a delimiter.
unexpected-tokenAn unexpected character was encountered.
unexpected-end-of-stringThe end of the string was reached, but some required arguments were missing.
improper-alphabetic-constantThe alphabetic constant prefix ` was not followed by a letter or single character command.

Range

type Range: [Offset, Offset];

A pair of offsets (boundary points) that can be used to denote a fragment of an expression.

A range is said to be collapsed when start and end are equal.

When specifying a range, a negative offset can be used to indicate an offset from the last valid offset, i.e. -1 is the last valid offset, -2 is one offset before that, etc...

A normalized range will always be such that start <= end, start >= 0, end >= 0, start < lastOffset, end < lastOffset. All the methods return a normalized range.

See Also

Selection

type Selection: object;

A selection is a set of ranges (to support discontinuous selection, for example when selecting a column in a matrix).

If there is a single range and that range is collapsed, the selection is collapsed.

A selection can also have a direction. While many operations are insensitive to the direction, a few are. For example, when selecting a fragment of an expression from left to right, the direction of this range will be "forward". Pressing the left arrow key will sets the insertion at the start of the range. Conversely, if the selection is made from right to left, the direction is "backward" and pressing the left arrow key will set the insertion point at the end of the range.

See Also

Type declaration

Selection.direction?
optional direction: "forward" | "backward" | "none";
Selection.ranges
ranges: Range[];

Variant

type Variant: 
| "ams"
| "double-struck"
| "calligraphic"
| "script"
| "fraktur"
| "sans-serif"
| "monospace"
| "normal"
| "main"
| "math";

Variants indicate a stylistic alternate for some characters.

Typically, those are controlled with explicit commands, such as \mathbb{} or \mathfrak{}. This type is used with the MathfieldElement.applyStyle method to change the styling of a range of selected characters.

In mathematical notation these variants are used not only for visual presentation, but they may have semantic significance.

For example,

  • the set ℂ should not be confused with
  • the physical unit 𝖢 (Coulomb).

When rendered, these variants can map to some built-in fonts.

LaTeX supports a limited set of characters. However, MathLive will map characters not supported by LaTeX fonts (double-stuck variant for digits for example) to a Unicode character (see Mathematical Alphanumeric Symbols on Wikipedia ).

normal is a synthetic variant that maps either to main (upright) or math (italic) depending on the symbol and the letterShapeStyle.

The math variant has italic characters as well as slightly different letter shape and spacing (a bit more space after the "f" for example), so it's not equivalent to a main variant with italic variant style applied.

See Also

VariantStyle

type VariantStyle: 
| "up"
| "bold"
| "italic"
| "bolditalic"
| "";

Some variants support stylistic variations.

Note that these stylistic variations support a limited set of characters, typically just uppercase and lowercase letters, and digits 0-9 in some cases.

variantupbolditalicbolditalic
normalABCabc012𝐀𝐁𝐂𝐚𝐛𝐜𝟎𝟏𝟐𝐴𝐵𝐶𝑎𝑏𝑐𝑨𝑩𝑪𝒂𝒃𝒄
double-struck𝔸𝔹ℂ𝕒𝕓𝕔𝟘𝟙𝟚n/an/an/a
calligraphic𝒜ℬ𝒞𝒶𝒷𝒸𝓐𝓑𝓒𝓪𝓫𝓬n/an/a
fraktur𝔄𝔅ℭ𝔞𝔟𝔠𝕬𝕭𝕮𝖆𝖇𝖈n/an/a
sans-serif𝖠𝖡𝖢𝖺𝖻𝖼𝟢𝟣𝟤𝗔𝗕𝗖𝗮𝗯𝗰𝟬𝟭𝟮𝘈𝘉𝘊𝘢𝘣𝘤𝘼𝘽𝘾𝙖𝙗𝙘
monospace𝙰𝙱𝙲𝚊𝚋𝚌n/an/an/a

version

const version: object;

Current version: 0.104.0

The version string of the SDK using the semver convention:

MAJOR.MINOR.PATCH

  • MAJOR is incremented for incompatible API changes
  • MINOR is incremented for new features
  • PATCH is incremented for bug fixes

Type declaration

version.mathlive
mathlive: string = '0.104.0';

validateLatex()

function validateLatex(s): LatexSyntaxError[]

s: string

LatexSyntaxError[]

Registers

Dimension

type Dimension: object;

A dimension is used to specify the size of things

Type declaration

Dimension.dimension
dimension: number;
Dimension.unit?
optional unit: DimensionUnit;

DimensionUnit

type DimensionUnit: 
| "pt"
| "mm"
| "cm"
| "ex"
| "px"
| "em"
| "bp"
| "dd"
| "pc"
| "in"
| "mu"
| "fil"
| "fill"
| "filll";

Glue

type Glue: object;

Glue represents flexible spacing, that is a dimension that can grow (by the grow property) or shrink (by the shrink property).

Type declaration

Glue.glue
glue: Dimension;
Glue.grow?
optional grow: Dimension;
Glue.shrink?
optional shrink: Dimension;

LatexValue

type LatexValue: object & 
| Dimension
| Glue
| object
| object
| object;

A LaTeX expression represent a sequence of tokens that can be evaluated to a value, such as a dimension.

Type declaration

LatexValue.relax?
optional relax: boolean;

Registers

type Registers: Record<string, number | string | LatexValue>;

TeX registers represent "variables" and "constants".

Changing the values of some registers can modify the layout of math expressions.

The following registers might be of interest:

  • thinmuskip: space between items of math lists
  • medmuskip: space between binary operations
  • thickmuskip: space between relational operators
  • nulldelimiterspace: minimum space to leave blank in delimiter constructions, for example around a fraction
  • delimitershortfall: maximum space to overlap adjacent elements when a delimiter is too short
  • jot: space between lines in an array, or between rows in a multiline construct
  • arraycolsep: space between columns in an array
  • arraystretch: factor by which to stretch the height of each row in an array

To modify a register, use:

mf.registers.arraystretch = 1.5;
mf.registers.thinmuskip = { dimension: 2, unit: "mu" };
mf.registers.medmuskip = "3mu";

Speech

SpeechScope

type SpeechScope: 
| "all"
| "selection"
| "left"
| "right"
| "group"
| "parent";

How much of the formula should be spoken:

allthe entire formula
selectionthe selection portion of the formula
leftthe element to the left of the selection
rightthe element to the right of the selection
groupthe group (numerator, root, etc..) the selection is in
parentthe parent of the selection

Static Rendering

StaticRenderOptions

type StaticRenderOptions: Partial<LayoutOptions> & object;

Type declaration

StaticRenderOptions.TeX?
optional TeX: object;
TeX.className?
optional className: object;
TeX.className.display?
optional display: string;
TeX.className.inline?
optional inline: string;
TeX.delimiters?
optional delimiters: object;

Delimiter pairs that will trigger a render of the content in display style or inline, respectively.

Default: {display: [ ['$$', '$$'], ['\\[', '\\]'] ] ], inline: [ ['\\(','\\)'] ] ]}

TeX.delimiters.display
display: [string, string][];
TeX.delimiters.inline
inline: [string, string][];
TeX.processEnvironments?
optional processEnvironments: boolean;

If true, math expression that start with \begin{ will automatically be rendered.

Default: true.

StaticRenderOptions.asciiMath?
optional asciiMath: object;
asciiMath.delimiters?
optional delimiters: object;
asciiMath.delimiters.display?
optional display: [string, string][];
asciiMath.delimiters.inline?
optional inline: [string, string][];
StaticRenderOptions.ignoreClass?
optional ignoreClass: string;

A string used as a regular expression of class names of elements whose content will not be scanned for delimiter

Default: "tex2jax_ignore"

StaticRenderOptions.processClass?
optional processClass: string;

A string used as a regular expression of class names of elements whose content will be scanned for delimiters, even if their tag name or parent class name would have prevented them from doing so.

Default: "tex2jax_process"

StaticRenderOptions.processMathJSONScriptType?
optional processMathJSONScriptType: string;

<script> tags with this type will be processed as MathJSON.

Default: "math/json"

StaticRenderOptions.processScriptType?
optional processScriptType: string;

<script> tags with this type will be processed as LaTeX.

Default: "math/tex"

StaticRenderOptions.readAloud?
optional readAloud: boolean;

If true, generate markup that can be read aloud later using speak

Default: false

StaticRenderOptions.renderAccessibleContent?
optional renderAccessibleContent: string;

The format(s) in which to render the math for screen readers:

  • "mathml" MathML
  • "speakable-text" Spoken representation

You can pass an empty string to turn off the rendering of accessible content. You can pass multiple values separated by spaces, e.g "mathml speakable-text"

Default: "mathml"

StaticRenderOptions.skipTags?
optional skipTags: string[];

An array of tag names whose content will not be scanned for delimiters (unless their class matches the processClass pattern below).

Default: ['math-field', 'noscript', 'style', 'textarea', 'pre', 'code', 'annotation', 'annotation-xml']

renderMathInDocument()

function renderMathInDocument(options?): void

Transform all the elements in the document body that contain LaTeX code into typeset math.

Caution

This is a very expensive call, as it needs to parse the entire DOM tree to determine which elements need to be processed. In most cases this should only be called once per document, once the DOM has been loaded.

To render a specific element, use renderMathInElement()

options?: StaticRenderOptions

void

Example

import { renderMathInDocument } from 'https://unpkg.com/mathlive?module';
renderMathInDocument();

Keywords

render, document, autorender

renderMathInElement()

function renderMathInElement(element, options?): void

Transform all the children of element that contain LaTeX code into typeset math, recursively.

element: string | HTMLElement

An HTML DOM element, or a string containing the ID of an element.

options?: StaticRenderOptions

void

Example

import { renderMathInElement } from 'https://unpkg.com/mathlive?module';
renderMathInElement("formula");

Keywords

render, element, htmlelement

Virtual Keyboard

NormalizedVirtualKeyboardLayer

NormalizedVirtualKeyboardLayer.backdrop?
optional backdrop: string;
NormalizedVirtualKeyboardLayer.container?
optional container: string;
NormalizedVirtualKeyboardLayer.id?
optional id: string;
NormalizedVirtualKeyboardLayer.markup?
optional markup: string;
NormalizedVirtualKeyboardLayer.rows?
optional rows: Partial<VirtualKeyboardKeycap>[][];
NormalizedVirtualKeyboardLayer.style?
optional style: string;

VirtualKeyboardInterface

This interface is implemented by:

  • VirtualKeyboard: when the browsing context is a top-level document
  • VirtualKeyboardProxy: when the browsing context is an iframe

Extends

VirtualKeyboardInterface.boundingRect
readonly boundingRect: DOMRect;
VirtualKeyboardInterface.isShifted
readonly isShifted: boolean;
VirtualKeyboardInterface.normalizedLayouts
readonly normalizedLayouts: VirtualKeyboardLayoutCore & object[];

This property is the "expanded" version of the layouts property. It is normalized to include all the default values for the properties of the layout and layers.

VirtualKeyboardInterface.originValidator
originValidator: OriginValidator;

Specify behavior how origin of message from postMessage should be validated.

Default: "none"

VirtualKeyboardInterface.targetOrigin
targetOrigin: string;

Specify the targetOrigin parameter for postMessage to send control messages from parent to child frame to remote control of mathfield component.

Default: globalThis.origin

VirtualKeyboardInterface.visible
visible: boolean;
VirtualKeyboardInterface.alphabeticLayout
set alphabeticLayout(value): void

Layout of the alphabetic layers: AZERTY, QWERTY, etc...

value: AlphabeticKeyboardLayout

VirtualKeyboardInterface.container
set container(value): void

Element the virtual keyboard element gets appended to.

When using full screen elements that contain mathfield, set this property to the full screen element to ensure the virtual keyboard will be visible.

Default: document.body

value: HTMLElement

VirtualKeyboardInterface.editToolbar
set editToolbar(value): void

Configuration of the action toolbar, displayed on the right-hand side.

Use "none" to disable the right hand side toolbar of the virtual keyboard.

value: EditToolbarOptions

VirtualKeyboardInterface.layouts
get layouts(): readonly (VirtualKeyboardLayout | VirtualKeyboardName)[]

A layout is made up of one or more layers (think of the main layer and the shift layer on a hardware keyboard).

A layout has a name and styling information.

In addition, a layout can be represented as a standard name which includes "numeric", "functions", "symbols", "alphabetic" and `"greek".

*See mathfield/guides/virtual-keyboards | Guide: Virtual Keyboards

set layouts(value): void

value: VirtualKeyboardLayout | VirtualKeyboardName | VirtualKeyboardLayout | VirtualKeyboardName[] | readonly VirtualKeyboardLayout | VirtualKeyboardName[]

readonly (VirtualKeyboardLayout | VirtualKeyboardName)[]

VirtualKeyboardInterface.connect()
connect(): void

void

VirtualKeyboardInterface.disconnect()
disconnect(): void

void

VirtualKeyboardInterface.executeCommand()
executeCommand(command): boolean

command: string | [string, ...any[]]

boolean

VirtualKeyboardInterface.getKeycap()
getKeycap(keycap): Partial<VirtualKeyboardKeycap>

Some keycaps can be customized: [left], [right], [up], [down], [return], [action], [space], [tab], [backspace], [shift], [undo], [redo], [foreground-color], [background-color], [hide-keyboard], [.], [,], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [+], [-], [*], [/], [^], [_], [=], [.], [(], [)],

keycap: string

Partial<VirtualKeyboardKeycap>

VirtualKeyboardInterface.hide()
hide(options?): void

options?

options.animate?: boolean

void

VirtualKeyboardInterface.setKeycap()
setKeycap(keycap, value): void

keycap: string

value: Partial<VirtualKeyboardKeycap>

void

VirtualKeyboardInterface.show()
show(options?): void

options?

options.animate?: boolean

void

VirtualKeyboardInterface.update()
update(mf): void

mf: MathfieldProxy

void

VirtualKeyboardInterface.updateToolbar()
updateToolbar(mf): void

The content or selection of the mathfield has changed and the toolbar may need to be updated accordingly

mf: MathfieldProxy

void

VirtualKeyboardKeycap

VirtualKeyboardKeycap.aside
aside: string;

Markup displayed with the key label (for example to explain what the symbol of the key is)

VirtualKeyboardKeycap.class
class: string;

CSS classes to apply to the keycap.

  • tex: use the TeX font for its label. Using the tex class is not necessary if using the latex property to define the label.
  • shift: a shift key
  • small: display the label in a smaller size
  • action: an “action” keycap (for arrows, return, etc…)
  • separator w5: a half-width blank used as a separator. Other widths include w15 (1.5 width), w20 (double width) and w50 (five-wide, used for the space bar).
  • bottom, left, right: alignment of the label
VirtualKeyboardKeycap.command
command: 
| string
| string[]
| [string, any]
| [string, any, any]
| [string, any, any, any];

Command to perform when the keycap is pressed

VirtualKeyboardKeycap.insert
insert: string;

LaTeX fragment to insert when the keycap is pressed (ignored if command is specified)

VirtualKeyboardKeycap.key
key: string;

Key to insert when keycap is pressed (ignored if command, insert or latex is specified)

VirtualKeyboardKeycap.label
label: string;

The HTML markup displayed for the keycap

VirtualKeyboardKeycap.latex
latex: string;

Label of the key as a LaTeX expression, also the LaTeX inserted if no command or insert property is specified.

VirtualKeyboardKeycap.layer
layer: string;

Name of the layer to shift to when the key is pressed

VirtualKeyboardKeycap.shift
shift: string | Partial<VirtualKeyboardKeycap>;

Variant of the keycap when the shift key is pressed

VirtualKeyboardKeycap.stickyVariantPanel
stickyVariantPanel: boolean;

Open variants panel without long press and does not close automatically

VirtualKeyboardKeycap.tooltip
tooltip: string;
VirtualKeyboardKeycap.variants
variants: string | (string | Partial<VirtualKeyboardKeycap>)[];

A set of keycap variants displayed on a long press

variants: [
'\\alpha', // Same label as value inserted
{ latex: '\\beta', label: 'beta' }
]

VirtualKeyboardKeycap.width
width: 
| 0.5
| 1
| 1.5
| 2
| 5;

Width of the keycap, as a multiple of the standard keycap width

VirtualKeyboardLayer

VirtualKeyboardLayer.backdrop?
optional backdrop: string;

A CSS class name to customize the appearance of the background of the layer

VirtualKeyboardLayer.container?
optional container: string;

A CSS class name to customize the appearance of the container the layer

VirtualKeyboardLayer.id?
optional id: string;

A unique string identifying the layer

VirtualKeyboardLayer.markup?
optional markup: string;
VirtualKeyboardLayer.rows?
optional rows: (string | Partial<VirtualKeyboardKeycap>)[][];

The rows of keycaps in this layer

VirtualKeyboardLayer.style?
optional style: string;

The CSS stylesheet associated with this layer

VirtualKeyboardOptions

Extended by

VirtualKeyboardOptions.normalizedLayouts
readonly normalizedLayouts: VirtualKeyboardLayoutCore & object[];

This property is the "expanded" version of the layouts property. It is normalized to include all the default values for the properties of the layout and layers.

VirtualKeyboardOptions.originValidator
originValidator: OriginValidator;

Specify behavior how origin of message from postMessage should be validated.

Default: "none"

VirtualKeyboardOptions.targetOrigin
targetOrigin: string;

Specify the targetOrigin parameter for postMessage to send control messages from parent to child frame to remote control of mathfield component.

Default: globalThis.origin

VirtualKeyboardOptions.alphabeticLayout
set alphabeticLayout(value): void

Layout of the alphabetic layers: AZERTY, QWERTY, etc...

value: AlphabeticKeyboardLayout

VirtualKeyboardOptions.container
set container(value): void

Element the virtual keyboard element gets appended to.

When using full screen elements that contain mathfield, set this property to the full screen element to ensure the virtual keyboard will be visible.

Default: document.body

value: HTMLElement

VirtualKeyboardOptions.editToolbar
set editToolbar(value): void

Configuration of the action toolbar, displayed on the right-hand side.

Use "none" to disable the right hand side toolbar of the virtual keyboard.

value: EditToolbarOptions

VirtualKeyboardOptions.layouts
get layouts(): readonly (VirtualKeyboardLayout | VirtualKeyboardName)[]

A layout is made up of one or more layers (think of the main layer and the shift layer on a hardware keyboard).

A layout has a name and styling information.

In addition, a layout can be represented as a standard name which includes "numeric", "functions", "symbols", "alphabetic" and `"greek".

*See mathfield/guides/virtual-keyboards | Guide: Virtual Keyboards

set layouts(value): void

value: VirtualKeyboardLayout | VirtualKeyboardName | VirtualKeyboardLayout | VirtualKeyboardName[] | readonly VirtualKeyboardLayout | VirtualKeyboardName[]

readonly (VirtualKeyboardLayout | VirtualKeyboardName)[]

VirtualKeyboardOptions.getKeycap()
getKeycap(keycap): Partial<VirtualKeyboardKeycap>

Some keycaps can be customized: [left], [right], [up], [down], [return], [action], [space], [tab], [backspace], [shift], [undo], [redo], [foreground-color], [background-color], [hide-keyboard], [.], [,], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [+], [-], [*], [/], [^], [_], [=], [.], [(], [)],

keycap: string

Partial<VirtualKeyboardKeycap>

VirtualKeyboardOptions.setKeycap()
setKeycap(keycap, value): void

keycap: string

value: Partial<VirtualKeyboardKeycap>

void

AlphabeticKeyboardLayout

type AlphabeticKeyboardLayout: 
| "auto"
| "qwerty"
| "azerty"
| "qwertz"
| "dvorak"
| "colemak";

EditToolbarOptions

type EditToolbarOptions: "none" | "default";

NormalizedVirtualKeyboardLayout

type NormalizedVirtualKeyboardLayout: VirtualKeyboardLayoutCore & object;

Type declaration

NormalizedVirtualKeyboardLayout.layers
layers: NormalizedVirtualKeyboardLayer[];

VirtualKeyboardLayout

type VirtualKeyboardLayout: VirtualKeyboardLayoutCore & object | object | object;

VirtualKeyboardLayoutCore

type VirtualKeyboardLayoutCore: object;

Type declaration

VirtualKeyboardLayoutCore.displayEditToolbar?
optional displayEditToolbar: boolean;

If false, do not include the edit toolbar in the layout

VirtualKeyboardLayoutCore.displayShiftedKeycaps?
optional displayShiftedKeycaps: boolean;

If false, keycaps that have a shifted variant will be displayed as if they don't

VirtualKeyboardLayoutCore.id?
optional id: string;

A unique string identifying the layout

VirtualKeyboardLayoutCore.label?
optional label: string;

A human readable string displayed in the layout switcher toolbar

VirtualKeyboardLayoutCore.labelClass?
optional labelClass: string;
VirtualKeyboardLayoutCore.tooltip?
optional tooltip: string;

A human readable tooltip associated with the label

VirtualKeyboardMessage

type VirtualKeyboardMessage: 
| object
| object
| object
| object
| object
| object;

VirtualKeyboardMessageAction

type VirtualKeyboardMessageAction: 
| "connect"
| "disconnect"
| "proxy-created"
| "execute-command"
| "show"
| "hide"
| "update-setting"
| "update-toolbar"
| "synchronize-proxy"
| "geometry-changed"
| "update-state"
| "focus"
| "blur";

VirtualKeyboardName

type VirtualKeyboardName: 
| "default"
| "compact"
| "minimalist"
| "numeric-only"
| "numeric"
| "symbols"
| "alphabetic"
| "greek";

VirtualKeyboardPolicy

type VirtualKeyboardPolicy: "auto" | "manual" | "sandboxed";
  • "auto": the virtual keyboard is triggered when a mathfield is focused on a touch capable device.
  • "manual": the virtual keyboard is not triggered automatically
  • "sandboxed": the virtual keyboard is displayed in the current browsing context (iframe) if it has a defined container or is the top-level browsing context.

Web Component

MathfieldElementAttributes

These attributes of the <math-field> element correspond to the [MathfieldOptions] properties.

Indexable

[key: string]: unknown

MathfieldElementAttributes.default-mode
default-mode: string;
MathfieldElementAttributes.inline-shortcut-timeout
inline-shortcut-timeout: string;

Maximum time, in milliseconds, between consecutive characters for them to be considered part of the same shortcut sequence.

A value of 0 is the same as infinity: any consecutive character will be candidate for an inline shortcut, regardless of the interval between this character and the previous one.

A value of 750 will indicate that the maximum interval between two characters to be considered part of the same inline shortcut sequence is 3/4 of a second.

This is useful to enter "+-" as a sequence of two characters, while also supporting the "±" shortcut with the same sequence.

The first result can be entered by pausing slightly between the first and second character if this option is set to a value of 250 or so.

Note that some operations, such as clicking to change the selection, or losing the focus on the mathfield, will automatically timeout the shortcuts.

MathfieldElementAttributes.letter-shape-style
letter-shape-style: string;
MathfieldElementAttributes.math-mode-space
math-mode-space: string;

The LaTeX string to insert when the spacebar is pressed (on the physical or virtual keyboard). Empty by default. Use \; for a thick space, \: for a medium space, \, for a thin space.

MathfieldElementAttributes.math-virtual-keyboard-policy
math-virtual-keyboard-policy: VirtualKeyboardPolicy;
  • "auto": the virtual keyboard is triggered when a mathfield is focused on a touch capable device.
  • "manual": the virtual keyboard is not triggered automatically
  • "sandboxed": the virtual keyboard is displayed in the current browsing context (iframe) if it has a defined container or is the top-level browsing context.
MathfieldElementAttributes.max-matrix-cols
max-matrix-cols: number;
MathfieldElementAttributes.min-font-scale
min-font-scale: number;
MathfieldElementAttributes.placeholder
placeholder: string;

When the mathfield is empty, display this placeholder LaTeX string instead

MathfieldElementAttributes.popover-policy
popover-policy: string;
MathfieldElementAttributes.read-only
read-only: boolean;

When true, the user cannot edit the mathfield.

MathfieldElementAttributes.remove-extraneous-parentheses
remove-extraneous-parentheses: boolean;
MathfieldElementAttributes.script-depth
script-depth: string;
MathfieldElementAttributes.smart-fence
smart-fence: string;

When on and an open fence is entered via typedText() it will generate a contextually appropriate markup, for example using \left...\right if applicable.

When off, the literal value of the character will be inserted instead.

MathfieldElementAttributes.smart-mode
smart-mode: string;

When on, during text input the field will switch automatically between 'math' and 'text' mode depending on what is typed and the context of the formula. If necessary, what was previously typed will be 'fixed' to account for the new info.

For example, when typing "if x >0":

TypeInterpretation
"i"math mode, imaginary unit
"if"text mode, english word "if"
"if x"all in text mode, maybe the next word is xylophone?
"if x >""if" stays in text mode, but now "x >" is in math mode
"if x > 0""if" in text mode, "x > 0" in math mode

Smart Mode is off by default.

Manually switching mode (by typing alt/option+=) will temporarily turn off smart mode.

Examples

  • slope = rise/run
  • If x > 0, then f(x) = sin(x)
  • x^2 + sin (x) when x > 0
  • When x<0, x^&#007b;2n+1&#007d;<0
  • Graph x^2 -x+3 =0 for 0<=x<=5
  • Divide by x-3 and then add x^2-1 to both sides
  • Given g(x) = 4x – 3, when does g(x)=0?
  • Let D be the set &#007b;(x,y)|0<=x<=1 and 0<=y<=x&#007d;
  • \int_&#007b;the unit square&#007d; f(x,y) dx dy
  • For all n in NN
MathfieldElementAttributes.smart-superscript
smart-superscript: string;

When on, when a digit is entered in an empty superscript, the cursor leaps automatically out of the superscript. This makes entry of common polynomials easier and faster. If entering other characters (for example "n+1") the navigation out of the superscript must be done manually (by using the cursor keys or the spacebar to leap to the next insertion point).

When off, the navigation out of the superscript must always be done manually.

MathfieldElementAttributes.virtual-keyboard-target-origin
virtual-keyboard-target-origin: string;

Specify the targetOrigin parameter for postMessage to send control messages from child to parent frame to remote control of mathfield component.

Default: window.origin

MoveOutEvent

type MoveOutEvent: object;

Event re-targeting

Some events bubble up through the DOM tree, so that they are detectable by any element on the page.

Bubbling events fired from within shadow DOM are re-targeted so that, to any listener external to your component, they appear to come from your component itself.

Custom Event Bubbling

By default, a bubbling custom event fired inside shadow DOM will stop bubbling when it reaches the shadow root.

To make a custom event pass through shadow DOM boundaries, you must set both the composed and bubbles flags to true.

The move-out event signals that the user pressed an arrow key or tab key but there was no navigation possible inside the mathfield.

This event provides an opportunity to handle this situation, for example by focusing an element adjacent to the mathfield.

If the event is canceled (i.e. evt.preventDefault() is called inside your event handler), the default behavior is to play a "plonk" sound.

Type declaration

MoveOutEvent.direction
direction: "forward" | "backward" | "upward" | "downward";