mathlive

Modules

module "mathfield-element"

module "mathfield-element"interface MathfieldElementAttributes

default-mode: string
fonts-directory: string
horizontal-spacing-scale: string
ignore-spacebar-in-math-mode: boolean
inline-shortcut-timeout: string
keypress-vibration: boolean
letter-shape-style: string
locale: string
read-only: boolean
remove-extraneous-parentheses: boolean
shared-virtual-keyboard-target-origin: string
smart-fence: boolean
smart-mode: boolean
smart-superscript: boolean
speech-engine: string
speech-engine-rate: string
speech-engine-voice: string
text-to-speech-markup: string
text-to-speech-rules: string
use-shared-virtual-keyboard: boolean
virtual-keyboard-layout: string
virtual-keyboard-mode: string
virtual-keyboard-theme: string
virtual-keyboards: string

module "mathfield-element"class MathfieldElement

ExtendsHTMLElement

ImplementsMathfield

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

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

To create a new MathfieldElement:

// 1. Create a new MathfieldElement
const mfe = new MathfieldElement();
// 2. Attach it to the DOM
document.body.appendChild(mfe);

The MathfieldElement constructor has an optional argument of MathfieldOptions to configure the element. The options can also be modified later:

// Setting options during construction
const mfe = new MathfieldElement({smartFence: false});
// Modifying options after construction
mfe.setOptions({smartFence: true});

CSS Variables

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

math-field {
 --hue: 10       // Set the highlight color and caret to a reddish hue
}
CSS VariableUsage
--hueHue of the highlight color and the caret
--highlightColor of the selection
--highlight-inactiveColor of the selection, when the mathfield is not focused
--caretColor of the caret/insertion point
--primaryPrimary accent color, used for example in the virtual keyboard
--text-font-familyThe font stack used in text mode
--keyboard-zindexThe z-index attribute of the virtual keyboard panel

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;
}

Attributes

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

<math-field locale="fr"></math-field>

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

The property can be changed either directly on the MathfieldElement object, or using setOptions() if it is prefixed with options., for example

 getElementById('mf').value = '\\sin x';
 getElementById('mf').setOptions({horizontalSpacingScale: 1.1});

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

getElementById('mf').setAttribute('virtual-keyboard-mode',  'manual');
console.log(getElementById('mf').getOption('virtualKeyboardMode'));
// Result: "manual"
getElementById('mf').setOptions({virtualKeyboardMode: 'onfocus');
console.log(getElementById('mf').getAttribute('virtual-keyboard-mode');
// Result: 'onfocus'

An exception is the value property, which is not reflected on the value attribute: the value attribute remains at its initial value.

AttributeProperty
disableddisabled
default-modeoptions.defaultMode
fonts-directoryoptions.fontsDirectory
sounds-directoryoptions.soundsDirectory
horizontal-spacing-scaleoptions.horizontalSpacingScale
ignore-spacebar-in-math-modeoptions.ignoreSpacbarInMathMode
inline-shortcut-timeoutoptions.inlineShortcutTimeout
keypress-vibrationoptions.keypressVibration
letter-shape-styleoptions.letterShapeStyle
localeoptions.locale
read-onlyoptions.readOnly
remove-extraneous-parenthesesoptions.removeExtraneousParentheses
smart-fenceoptions.smartFence
smart-modeoptions.smartMode
smart-superscriptoptions.superscript
speech-engineoptions.speechEngine
speech-engine-rateoptions.speechEngineRate
speech-engine-voiceoptions.speechEngineVoice
text-to-speech-markupoptions.textToSpeechMarkup
text-to-speech-rulesoptions.textToSpeechRules
valuevalue
virtual-keyboard-layoutoptions.keyboardLayout
virtual-keyboard-modeoptions.keyboardMode
virtual-keyboard-themeoptions.keyboardTheme
virtual-keyboardsoptions.keyboards

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

Events

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

Event NameDescription
inputThe value of the mathfield has been modified. This happens on almost every keystroke in the mathfield.
changeThe user has commited 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
read-aloud-status-changeThe status of a read aloud operation has changed
virtual-keyboard-toggleThe visibility of the virtual keyboard panel has changed
blurThe mathfield is losing focus
focusThe mathfield is gaining focus
focus-outThe user is navigating out of the mathfield, typically using the keyboard
`detail: {direction: ‘forward’
math-errorA parsing or configuration error happened
`detail: ErrorListener<ParserErrorCode
keystrokeThe user typed a keystroke with a physical keyboard
detail: {keystroke: string, event: KeyboardEvent}
mountThe element has been attached to the DOM
unmountThe element is about to be removed from the DOM

class MathfieldElementnew MathfieldElement

To create programmatically a new mahfield 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('virtual-keyboard-layout', 'dvorak');
// ... or using `setOptions()`
mfe.setOptions({
virtualKeyboardMode: 'manual',
});
// Attach the element to the DOM
document.body.appendChild(mfe);

Accessing and changing the content

Selection

Other

Focus

Options

Accessing and changing the content

class MathfieldElementget/set value

value: string

The content of the mathfield as a Latex expression.

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

class MathfieldElementapplyStyle

Updates 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’.

applyStyle(style: Style, options?: Range | {operation?: "set" | "toggle"; range?: Range}): void
style: Style
options:
  • | Range
  • | {operation?: "set" | "toggle"; range?: Range}

class MathfieldElementgetValue

getValue(format?: OutputFormat): string
format: OutputFormat
string

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

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

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

class MathfieldElementinsert

Inserts 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.

insert(s: string, options?: InsertOptions): boolean
s: string
options: InsertOptions
boolean

class MathfieldElementsetValue

setValue(value?: string, options?: InsertOptions): void
value: string
options: InsertOptions

Selection

class MathfieldElementget/set caretPoint

caretPoint: {x: number; y: number}

The bottom location of the caret (insertion point) in viewport coordinates.

See also setCaretPoint

class MathfieldElementget lastOffset

lastOffset: Offset  read only

The last valid offset.

class MathfieldElementget/set position

position: Offset

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

class MathfieldElementget/set selection

selection: 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.

class MathfieldElementselect

Select the content of the mathfield.

select(): void

class MathfieldElementsetCaretPoint

x and y are in viewport coordinates.

Return true if the location of the point is a valid caret location.

See also caretPoint

setCaretPoint(x: number, y: number): boolean
x: number
y: number
boolean

Other

class MathfieldElementget/set disabled

disabled: boolean

class MathfieldElementget/set mode

mode: ParseMode

class MathfieldElementexecuteCommand

Execute a Commands defined by a selector.

mfe.executeCommand('add-column-after');
mfe.executeCommand(['switch-mode', 'math']);
executeCommand(command: Selector | [Selector, any]): boolean
command:

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

class MathfieldElementfind

Return an array of ranges matching the argument.

An array is always returned, but it has no element if there are no matching items.

find(pattern: string | RegExp, options?: FindOptions): Range[]
pattern:
options: FindOptions
Range[]

class MathfieldElementreplace

Replace the pattern items matching the pattern with the replacement value.

If replacement is a function, the function is called for each match and the function return value will be used as the replacement.

replace(pattern: string | RegExp, replacement: string | ReplacementFunction, options?: FindOptions): void
pattern:
replacement:
options: FindOptions

Focus

class MathfieldElementblur

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

blur(): void

class MathfieldElementfocus

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

focus(): void

class MathfieldElementhasFocus

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

hasFocus(): boolean
boolean

Options

class MathfieldElementgetOption

getOption(key: extends keyof MathfieldOptions): MathfieldOptions[ extends keyof MathfieldOptions]
key: extends keyof MathfieldOptions
MathfieldOptions[ extends keyof MathfieldOptions]

class MathfieldElementgetOptions

getOptions(keys: extends keyof MathfieldOptions[]): Pick<MathfieldOptions, extends keyof MathfieldOptions>
keys: extends keyof MathfieldOptions[]
Pick<MathfieldOptions, extends keyof MathfieldOptions>

class MathfieldElementsetOptions

setOptions(options: Partial<MathfieldOptions>): void
options: Partial<MathfieldOptions>

class MathfieldElementMathfieldElement._mathfield

any

namespace JSXinterface IntrinsicElements

math-field: MathfieldElementAttributes

module "mathfield-element"Types

module "mathfield-element"FocusOutEvent

The focus-out event signals that the mathfield has lost focus through keyboard navigation with arrow keys or the tab key.

The event detail.direction property indicates the direction the cursor was moving which can be useful to decide which element to focus next.

The event is cancelable, which will prevent the field from losing focus.

mfe.addEventListener('focus-out', (ev) => {
 console.log("Losing focus ", ev.detail.direction);
});

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

module "mathfield-element"KeystrokeEvent

The keystroke event is fired when a keystroke is about to be procesed. The event is cancellable, which wills suprress further handling of the event.


event?: KeyboardEvent;

The native keyboard event

keystroke: string;

A string descring the keystroke, for example `“Alt-KeyU”. See W3C UIEvents for more information on the format of the descriptor.

module "mathfield-element"MathErrorEvent

The math-error custom event signals an error while parsing an expression.

document.getElementById('mf').addEventListener('math-error', (ev) => {
 const err = ev.detail;
 console.warn(err.code + (err.arg ? ': ' + err.arg : '') +
        '\n%c|  ' + err.before + '%c' + err.after +
        '\n%c|  ' + String(' ').repeat(err.before.length) +
        '▲',
        'font-weight: bold',
        'font-weight: normal; color: rgba(160, 160, 160)',
        'font-weight: bold; color: hsl(4deg, 90%, 50%)'
    );
});

after?: string;
arg?: string;
before?: string;
code: ParserErrorCode | MathfieldErrorCode;
latex?: string;

module "options"

module "options"Functions

module "options"setKeyboardLayout

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.

setKeyboardLayout(name: KeyboardLayoutName | "auto"): void
name:

module "options"setKeyboardLayoutLocale

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.

setKeyboardLayoutLocale(locale: string): void
locale: string

module "options"interface MathfieldHooks

These methods provide an opportunity to intercept or modify an action. Their return value indicate whether the default handling should proceed.

deprecated

Use corresponding events of MathfieldEvent instead


onKeystroke: (sender: Mathfield, keystroke: string, ev: KeyboardEvent): boolean

A hook invoked when a keystroke is about to be processed.

  • keystroke: a string describing the keystroke
  • ev: the native keyboard event

Return false to stop the handling of the event.

onMoveOutOf: (sender: Mathfield, direction: "forward" | "backward" | "upward" | "downward"): boolean

A hook invoked when keyboard navigation would cause the insertion point to leave the mathfield.

  • direction indicates the direction of the navigation, either "forward" or "backward" or "upward" or "downward".

Return false to prevent the move, true to wrap around to the start of the field.

By default, the insertion point will wrap around.

onTabOutOf: (sender: Mathfield, direction: "forward" | "backward"): boolean

A hook invoked when pressing tab (or shift-tab) would cause the insertion point to leave the mathfield.

direction indicates the direction of the navigation.

By default, the insertion point jumps to the next/previous focussable element.

module "options"interface MathfieldListeners

The methods provide a notification that an event is about to occur or has occured.

In general instead of using this interface you should be listening to the corresponding event on MathfieldElement, i.e.

mfe.addEventListener('input', (ev) => {
console.log(ev.target.value);
});

deprecated

Use corresponding events of MathfieldEvent instead


onBlur: (sender: Mathfield): void

The mathfield has lost keyboard focus

onCommit: (sender: Mathfield): void
onContentDidChange: (sender: Mathfield): void
onContentWillChange: (sender: Mathfield): void
onFocus: (sender: Mathfield): void

The mathfield has gained keyboard focus

onModeChange: (sender: Mathfield, mode: ParseMode): void
onReadAloudStatus: (sender: Mathfield): void
onSelectionDidChange: (sender: Mathfield): void
onSelectionWillChange: (sender: Mathfield): void
onUndoStateDidChange: UndoStateChangeListener
onUndoStateWillChange: UndoStateChangeListener

module "options"interface VirtualKeyboardDefinition

classes?: string
command?: string | string[]
label: string
layer?: string
layers?: string[]
tooltip?: string

module "options"interface VirtualKeyboardKeycap

altKeys?: string

A named set of alternate keys to display when there is a long press on the key.

aside?: string

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

class?: string

CSS class to apply to the keycap.

command?: string

Command to perform when the keycap is pressed

insert?: string

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

key?: string

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

label?: string

The string displayed for the keycap

latex?: string

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

shifted?: string

Markup for the label of the key when the shift key is pressed

shiftedCommand?: string

Command to perform when the shifted key is pressed

module "options"interface VirtualKeyboardLayer

backdrop?: string
container?: string
rows?: VirtualKeyboardKeycap[][]
styles?: string

module "options"Types

module "options"CoreOptions

createHTML: (html: string): 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.

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’.

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 top your website
     fontsDirectory: 'https://example.com/fonts'
}

namespace: string;
deprecated

Namespace that is added to data- attributes to avoid collisions with other libraries.

The namespace should be a string of lowercase letters.

It is empty by default.

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.

module "options"EditingOptions

ignoreSpacebarInMathMode: boolean;

When true and the spacebar is pressed, no space is inserted.

When false, a space is inserted when the spacebar is pressed.

readOnly: boolean;

When true, the user cannot edit the mathfield.

removeExtraneousParentheses: boolean;

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

scriptDepth: number | [number, number];

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.

smartFence: boolean;

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.

smartMode: boolean;

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
“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^{2n+1}<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 {(x,y)|0<=x<=1 and 0<=y<=x}
  • \int_{the unit square} f(x,y) dx dy
  • For all n in NN
smartSuperscript: boolean;

When true, 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 false, the navigation out of the superscript must always be done manually.

module "options"InlineShortcutDefinition

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: {
         mode: 'math',
         after: 'space+letter+digit+symbol+fence',
         value: '\\in',
     },
 };

When using a string, the shortcut will apply in any mode, and regardless of the characters surrounding it.

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

The mode key, if present, indicate which mode this shortcut will apply in, either 'math' or 'text'. If the key is not present the shortcut apply in all modes.

The 'after' key, if present, indicate in what context (surrounding characters) the shortcut will apply. One or more values can be specified, separated by a ‘+’ sign. If any of the values match, the shortcut will be 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

  • | string
  • | {after?: string; mode?: ParseMode; value: string}

module "options"InlineShortcutsOptions

inlineShortcutTimeout: number;

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.

inlineShortcuts: Record<string, InlineShortcutDefinition>;

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

string | {after?: string; mode?: ParseMode; value: string}

overrideDefaultInlineShortcuts: boolean;
deprecated

deprecated

Use:

mf.setConfig(
     'inlineShortcuts',
     {   ...mf.getConfig('inlineShortcuts'),
         ...newShortcuts
     }
)

to add newShortcuts to the default ones

module "options"Keybinding

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}'],
}

command: Selector | [Selector, any];

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

ifMode?: ParseMode;

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

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.

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.

If a keybinding is invalid (impossible to produce) with the current keyboard layout, an error will be generated, and the onError listener will be called with a invalid-keybinding error code.

module "options"KeyboardLayoutName

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)

"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"

module "options"KeyboardOptions

keybindings: Keybinding[];

module "options"LayoutOptions

defaultMode: "math" | "text";
horizontalSpacingScale: number;

Scaling factor to be applied to horizontal spacing between elements of the formula. A value greater than 1.0 can be used to improve the legibility.

letterShapeStyle: "auto" | "tex" | "iso" | "french" | "upright";

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.

macros: MacroDictionary;

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.setConfig({
macros: {
...mf.getOption('macros'),
smallfrac: '^{#1}\\!\\!/\\!_{#2}',
},
});

Note that getOption() is called 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}

module "options"LocalizationOptions

locale: string;

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

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

strings: 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

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

This will override the default localized strings.

module "options"MathfieldConfig

deprecated

Use MathfieldOptions


module "options"MathfieldOptions


  • LayoutOptions &
  • EditingOptions &
  • LocalizationOptions &
  • InlineShortcutsOptions &
  • KeyboardOptions &
  • VirtualKeyboardOptions &
  • TextToSpeechOptions &
  • CoreOptions &
  • MathfieldHooks &
  • MathfieldListeners &
  • onError: ErrorListener<ParserErrorCode | MathfieldErrorCode>;

    An optional listener function that will be invoked when an error is encountered.

    This could be a Latex parsing error, for the initial value of the mathfield, a value inserted programmatically later, or through a user interaction (pasting in the mathfield for example). See ParserErrorCode for the list of possible parsing errors.

    This could also be another kind of error, such as an invalid keybinding.

    originValidator: OriginValidator;

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

    Default: 'same-origin'

    sharedVirtualKeyboardTargetOrigin: 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

    substituteTextArea: string | (): HTMLElement;

    This function provides the option of substituting the focusable DOM element used to capture keyboard input.

    An (invisible) DOM element is used to capture the keyboard events. By default, this element is a <textarea> on desktop and a <span> on mobile devices, to prevent the device virtual keyboard from being displayed.

    Alternatively, the ID of a DOM element can be provided.

    useSharedVirtualKeyboard: boolean;

    When true, use a shared virtual keyboard for all the mathfield elements in the page, even across iframes.

    When setting this option to true, you must create the shared virtual keyboard in the the parent document:

    import { makeSharedVirtualKeyboard } from 'mathlive';
    
        makeSharedVirtualKeyboard({
            virtualKeyboardToolbar: 'none',
        });
    

    Default: false

module "options"OriginValidator

Specify behaviour for origin validation.

ValueDescription
'same-origin'The origin of received message must be the same of hosted window, instead exception will thow.
'(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.

  • | (origin: string): boolean
  • | "same-origin"
  • | "none"

module "options"RemoteVirtualKeyboardOptions

  • CoreOptions &
  • VirtualKeyboardOptions &
  • originValidator: OriginValidator;

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

    Default: 'same-origin'

    targetOrigin: string;

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

    Default: window.origin

module "options"TextToSpeechOptions

readAloudHook: (element: HTMLElement, text: string, config: MathfieldOptions): void;
speakHook: (text: string, config: Partial<MathfieldOptions>): void;
speechEngine: "local" | "amazon";

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 speech example

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.

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

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;.

textToSpeechRules: "mathlive" | "sre";

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 speech example

textToSpeechRulesOptions: 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

module "options"UndoStateChangeListener

(target: Mathfield, action: "undo" | "redo" | "snapshot"): void

module "options"VirtualKeyboardOptions

customVirtualKeyboardLayers: Record<string, string | VirtualKeyboardLayer>;

Some additional custom virtual keyboard layers.

A keyboard is made up of one or more layers (think of the main layer and the shift layer on a hardware keyboard). Each key in this object define a new keyboard layer (or replace an existing one). The value of the key should be some HTML markup.

See virtual keyboard example

customVirtualKeyboards: Record<string, VirtualKeyboardDefinition>;
keypressSound: string | HTMLAudioElement| {default: string | HTMLAudioElement; delete?: string | HTMLAudioElement; return?: string | HTMLAudioElement; spacebar?: string | HTMLAudioElement};

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

If the property is set to a string or HTMLAudioElement, 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 key 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 an HTMLAudioElement.

keypressVibration: boolean;

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

plonkSound?: string | HTMLAudioElement;

Sound which will be 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, or an HTMLAudioElement.

virtualKeyboardLayout: "auto" | "qwerty" | "azerty" | "qwertz" | "dvorak" | "colemak";
virtualKeyboardMode: "auto" | "manual" | "onfocus" | "off";
  • 'manual': pressing the virtual keyboard toggle button will show or hide the virtual keyboard. If hidden, the virtual keyboard is not shown when the field is focused until the toggle button is pressed.
  • 'onfocus': the virtual keyboard will be displayed whenever the field is focused and hidden when the field loses focus. In that case, the virtual keyboard toggle button is not displayed.
  • 'off': the virtual keyboard toggle button is not displayed, and the virtual keyboard is never triggered.

If the setting is empty, it will default to 'onfocus' on touch-capable devices and to 'off' otherwise.

virtualKeyboardTheme: "material" | "apple" | "";

The visual theme used for the virtual keyboard.

If empty, the theme will switch automatically based on the device it’s running on. The two supported themes are ‘material’ and ‘apple’ (the default).

virtualKeyboardToggleGlyph: string;

If specified, the markup to be used to display the virtual keyboard toggle glyph. If none is specified a default keyboard icon is used.

virtualKeyboardToolbar?: VirtualKeyboardToolbarOptions;

The right hand side toolbar configuration.

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

virtualKeyboards: "all" | "numeric" | "roman" | "greek" | "functions" | "symbols" | "latex" | string;

A space separated list of the keyboards that should be available. The keyboard 'all' is synonym with 'numeric', 'functions'``,‘symbols’`` 'roman' and 'greek',

The keyboards will be displayed in the order indicated.

module "options"VirtualKeyboardToolbarOptions

"none" | "default"

module "mathlive"

Use MathLive to render and edit mathematical formulas.

Read Getting Started for more info.

<script type="module">
// Load the `Mathlive` module from a CDN
import { convertLatexToSpeakableText } from 'https://unpkg.com/mathlive/dist/mathlive.min.mjs';

console.log(convertLatexToSpeakableText('e^{i\\pi}+1=0'));
</script>

version

0.59.0

module "mathlive"Functions

Converting

Rendering

Other

Converting

module "mathlive"astToLatex

Converts a MathJSON Abstract Syntax Tree to a LaTeX string.

See Also: latexToAST()

deprecated

Use MathJSON

deprecated
astToLatex(mathJson: any, options?: {beginRepeatingDigits?: string; decimalMarker?: string; endRepeatingDigits?: string; exponentMarker?: string; exponentProduct?: string; groupSeparator?: string; precision?: number; product?: string}): string
mathJson: any
options:
beginRepeatingDigits?: string;

The format used for numbers using the scientific notation. Default = "auto" * / scientificNotation?: ‘auto’ | ‘engineering’ | ‘on’; /** The string used at the begining of repeating digits. Default = "\\overline{"

decimalMarker?: string;

The character used as the decimal marker. Default = ".".

endRepeatingDigits?: string;

The string used at the end of repeating digits. Default = "}"

exponentMarker?: string;

The character used to indicate an exponent. Default = ""

exponentProduct?: string;

The character used before an exponent indicator. Default = "\\cdot "

groupSeparator?: string;

The character used to separate group of numbers, typically thousands. Default = "\\, "

precision?: number;

The number of digits used in the representation of numbers. Default = 14

product?: string;

The character used to indicate product. Other option would be "\\times ". Default = "\\cdot "

string

The LaTeX representation of the Abstract Syntax Tree, if valid.

module "mathlive"convertLatexToMarkup

Convert a LaTeX string to a string of HTML markup.

Note

This function does not interact with the DOM. It can be used on the server side. The function does not load fonts or inject stylesheets in the document. 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" />
convertLatexToMarkup(text: string, options?: {letterShapeStyle?: "tex" | "french" | "iso" | "upright" | "auto"; macros?: MacroDictionary; mathstyle?: "displaystyle" | "textstyle"; onError?: ErrorListener<ParserErrorCode>}): string
text: string

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

options:
letterShapeStyle?: "tex" | "french" | "iso" | "upright" | "auto";
macros?: MacroDictionary;

A dictionary of LaTeX macros

mathstyle?: "displaystyle" | "textstyle";

If 'displaystyle' the “display” mode of TeX is used to typeset the formula, which is most appropriate for formulas that are displayed in a standalone block.

If 'textstyle' is used, the “text” mode of TeX is used, which is most appropriate when displaying math “inline” with other text (on the same line).

onError?: ErrorListener<ParserErrorCode>;

A function invoked when a syntax error is encountered. An attempt to recover will be made even when an error is reported.

string