Latest commit

History

History
3323 lines (2177 loc) · 76.1 KB

File metadata and controls

3323 lines (2177 loc) · 76.1 KB

@borgar/fx

Modules

fx

A tokenizer, parser, and other utilities to work with Excel formula code.

The base entry-point methods expect and return the variant of references that uses contexts. If you are using xlsx files or otherwise want to work with the xlsx-file variant of references you should use the fx/xlsx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Type Aliases

Variables

Functions

addA1RangeBounds()

functionaddA1RangeBounds(range: RangeA1): RangeA1;

Fill the any missing bounds in range objects. Top will be set to 0, bottom to 1048575, left to 0, and right to 16383, if they are null or undefined.

addA1RangeBounds({top: 0,left: 0,bottom: 1,$top: true,$left: false,$bottom: false,});// => {// top: 0,// left: 0,// bottom: 1,// right: 16383, // ← Added// $top: true,// $left: false,// $bottom: false,// $right: false // ← Added// }

Parameters

ParameterTypeDescription
rangeRangeA1The range part of a reference object.

Returns

RangeA1

The same range with missing bounds filled in.

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Returns a new array of tokens with values and position data updated.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

fromCol()

functionfromCol(columnString: string): number;

Convert a column string representation to a 0 based offset number ("C" = 2).

The method expects a valid column identifier made up of only A-Z letters, which may be either upper or lower case. Other input will return garbage.

Parameters

ParameterTypeDescription
columnStringstringThe column string identifier

Returns

number

Zero based column index number

isArrayNode()

functionisArrayNode(node?: Node): node is ArrayExpression;

Determines whether the specified node is a ArrayExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ArrayExpression

True if the specified token is a ArrayExpression, False otherwise.

isBinaryNode()

functionisBinaryNode(node?: Node): node is BinaryExpression;

Determines whether the specified node is a BinaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is BinaryExpression

True if the specified token is a BinaryExpression, False otherwise.

isCallNode()

functionisCallNode(node?: Node): node is CallExpression;

Determines whether the specified node is a CallExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is CallExpression

True if the specified token is a CallExpression, False otherwise.

isError()

functionisError(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an error.

Returns true if the input is a token of type ERROR (#VALUE!). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is error, False otherwise.

isErrorNode()

functionisErrorNode(node?: Node): node is ErrorLiteral;

Determines whether the specified node is an ErrorLiteral.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ErrorLiteral

True if the specified token is an ErrorLiteral, False otherwise.

isExpressionNode()

functionisExpressionNode(node?: Node): node is AstExpression;

Determines whether the specified node is a AstExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is AstExpression

True if the specified token is a AstExpression, False otherwise.

isFunction()

functionisFunction(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a function.

Returns true if the input is a token of type FUNCTION. In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is function, False otherwise.

isFxPrefix()

functionisFxPrefix(token?: Pick<Token,"type">): boolean;

Returns true if the input is a token of type FX_PREFIX (leading = in formula). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is effects prefix, False otherwise.

isIdentifierNode()

functionisIdentifierNode(node?: Node): node is Identifier;

Determines whether the specified node is an Identifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Identifier

True if the specified token is an Identifier, False otherwise.

isLambdaNode()

functionisLambdaNode(node?: Node): node is LambdaExpression;

Determines whether the specified node is a LambdaExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LambdaExpression

True if the specified token is a LambdaExpression, False otherwise.

isLetDeclaratorNode()

functionisLetDeclaratorNode(node?: Node): node is LetDeclarator;

Determines whether the specified node is a LetDeclarator.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetDeclarator

True if the specified token is a LetDeclarator, False otherwise.

isLetNode()

functionisLetNode(node?: Node): node is LetExpression;

Determines whether the specified node is a LetExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetExpression

True if the specified token is a LetExpression, False otherwise.

isLiteral()

functionisLiteral(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a literal.

Returns true if the input is a token of type BOOLEAN (TRUE or FALSE), ERROR (#VALUE!), NUMBER (123.4), or STRING ("lorem ipsum"). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is literal, False otherwise.

isLiteralNode()

functionisLiteralNode(node?: Node): node is Literal;

Determines whether the specified node is a Literal.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Literal

True if the specified token is a Literal, False otherwise.

isOperator()

functionisOperator(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an operator.

Returns true if the input is a token of type OPERATOR (+ or :). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is operator, False otherwise.

isRange()

functionisRange(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a range.

Returns true if the input is a token that has a type of either REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), or REF_BEAM (A:A or 1:1). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">A token

Returns

boolean

True if the specified token is range, False otherwise.

isReference()

functionisReference(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a reference.

Returns true if the input is a token of type REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), REF_BEAM (A:A or 1:1), or REF_NAMED (myrange). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is reference, False otherwise.

isReferenceNode()

functionisReferenceNode(node?: Node): node is ReferenceIdentifier;

Determines whether the specified node is a ReferenceIdentifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ReferenceIdentifier

True if the specified token is a ReferenceIdentifier, False otherwise.

isUnaryNode()

functionisUnaryNode(node?: Node): node is UnaryExpression;

Determines whether the specified node is a UnaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is UnaryExpression

True if the specified token is a UnaryExpression, False otherwise.

isWhitespace()

functionisWhitespace(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is whitespace.

Returns true if the input is a token of type WHITESPACE () or NEWLINE (\n). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is whitespace, False otherwise.

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parse()

functionparse(tokenlist: Token[],options?: OptsParse): AstExpression;

Parses a string formula or list of tokens into an AST.

The parser assumes mergeRefs and negativeNumbers were true when the tokens were generated. It does not yet recognize reference context tokens or know how to deal with unary minuses in arrays.

The AST Abstract Syntax Tree's format is documented in AST_format.md.

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.
optionsOptsParseOptions for the parsers behavior.

Returns

AstExpression

An AST of nodes.

See

parseA1Range()

functionparseA1Range(rangeString: string,allowTernary?: boolean): RangeA1;

Parse A1-style range string into a RangeA1 object.

Parameters

ParameterTypeDefault valueDescription
rangeStringstringundefinedA1-style range string.
allowTernary?booleantruePermit ternary ranges like A2:A or B2:2.

Returns

RangeA1

A reference object.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1|ReferenceName;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// context: [ 'Sheet1' ],// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1 | ReferenceName

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Range()

functionparseR1C1Range(rangeString: string): RangeR1C1;

Parse R1C1-style range string into a RangeR1C1 object.

Parameters

ParameterTypeDescription
rangeStringstringR1C1-style range string.

Returns

RangeR1C1

A reference object.

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceName|ReferenceR1C1;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceName | ReferenceR1C1

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStruct;

Parse a structured reference string into an object representing it.

parseStructRef('workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]');// => {// context: [ 'workbook.xlsx' ],// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStruct

An object representing a valid reference or undefined if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1|ReferenceName): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({context: ['Sheet1'],range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1 | ReferenceNameA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceName|ReferenceR1C1): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({context: ['Sheet1'],range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceName | ReferenceR1C1A reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStruct,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({context: ['workbook.xlsx'],sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

See

OptsStringifyStructRef

stringifyTokens()

functionstringifyTokens(tokens: Token[]): string;

Collapses a list of tokens into a formula string.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens.

Returns

string

A formula string.

toCol()

functiontoCol(columnIndex: number): string;

Convert a 0 based offset number to a column string representation (0 = "A", 2 = "C").

The method expects a number between 0 and 16383. Other input will return garbage.

Parameters

ParameterTypeDescription
columnIndexnumberZero based column index number

Returns

string

The column string identifier

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parsers will need to handle this.

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

translateFormulaToA1()

functiontranslateFormulaToA1(formula: string,anchorCell: string,options?: OptsTranslateFormulaToA1): string;

Translates ranges in a formula from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so you can set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Parameters

ParameterTypeDescription
formulastringAn Excel formula string that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateFormulaToA1Translation options.

Returns

string

A formula string.

See

OptsTranslateFormulaToA1

translateFormulaToR1C1()

functiontranslateFormulaToR1C1(formula: string,anchorCell: string,options?: OptsTranslateToR1C1): string;

Translates ranges in a formula from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
formulastringAn Excel formula that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
options?OptsTranslateToR1C1The options

Returns

string

A formula string.

See

OptsTranslateToR1C1

translateTokensToA1()

functiontranslateTokensToA1(tokens: Token[],anchorCell: string,options?: OptsTranslateTokensToA1): Token[];

Translates ranges in a list of tokens from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so may set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Note that if you are passing in a list of tokens that was not created using mergeRefs and you disable edge wrapping (or you simply set both options to false), you can end up with a formula such as =#REF!:B2 or =Sheet3!#REF!:F3. These are valid formulas in the Excel formula language and Excel will accept them, but they are not supported in Google Sheets.

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateTokensToA1Translation options.

Returns

Token[]

A token list.

See

OptsTranslateTokensToA1

translateTokensToR1C1()

functiontranslateTokensToR1C1(tokens: Token[],anchorCell: string): Token[];

Translates ranges in a list of tokens from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).

Returns

Token[]

A token list.

ArrayExpression

typeArrayExpression={elements: (|ReferenceIdentifier|Literal|ErrorLiteral|CallExpression)[][];loc?: SourceLocation;type: "ArrayExpression";}&Node;

An array expression. Excel does not have empty or sparse arrays and restricts array elements to literals. Google Sheets allows ReferenceIdentifiers and CallExpressions as elements of arrays, the fx parser has options for this but they are off by default.

Type Declaration

NameTypeDescription
elements( | ReferenceIdentifier | Literal | ErrorLiteral | CallExpression)[][]The elements of the array.
loc?SourceLocationThe original source position of the node.
type"ArrayExpression"The type of this AST node.

AstExpression

typeAstExpression=|ReferenceIdentifier|Literal|ErrorLiteral|UnaryExpression|BinaryExpression|CallExpression|ArrayExpression|LambdaExpression|LetExpression;

Represents an evaluate-able expression.

BinaryExpression

typeBinaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: BinaryOperator;type: "BinaryExpression";}&Node;

A binary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorBinaryOperatorThe expression's operator.
type"BinaryExpression"The type of this AST node.

BinaryOperator

typeBinaryOperator=|"="|"<"|">"|"<="|">="|"<>"|"-"|"+"|"*"|"/"|"^"|":"|" "|","|"&";

A binary operator token.

Note that Excels union operator is whitespace so a parser must take care to normalize this to a single space.

CallExpression

typeCallExpression={arguments: AstExpression[];callee: Identifier;loc?: SourceLocation;type: "CallExpression";}&Node;

A function call expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the function.
calleeIdentifierThe function being called.
loc?SourceLocationThe original source position of the node.
type"CallExpression"The type of this AST node.

ErrorLiteral

typeErrorLiteral={loc?: SourceLocation;raw: string;type: "ErrorLiteral";value: string;}&Node;

An Error expression.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"ErrorLiteral"The type of this AST node.
valuestringThe value of the error.

Identifier

typeIdentifier={loc?: SourceLocation;name: string;type: "Identifier";}&Node;

An identifier. These appear on CallExpression, LambdaExpression, and LetExpression and will always be a static string representing the name of a function call or parameter.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
namestringThe identifying name.
type"Identifier"The type of this AST node.

LambdaExpression

typeLambdaExpression={body: AstExpression|null;loc?: SourceLocation;params: Identifier[];type: "LambdaExpression";}&Node;

A LAMBDA expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LAMBDA's expression.
loc?SourceLocationThe original source position of the node.
paramsIdentifier[]The LAMBDA's parameters.
type"LambdaExpression"The type of this AST node.

LetDeclarator

typeLetDeclarator={id: Identifier;init: AstExpression|null;loc?: SourceLocation;type: "LetDeclarator";}&Node;

A LET parameter declaration.

Type Declaration

NameTypeDescription
idIdentifierThe name of the variable.
initAstExpression | nullThe variable's initializing expression.
loc?SourceLocationThe original source position of the node.
type"LetDeclarator"The type of this AST node.

LetExpression

typeLetExpression={body: AstExpression|null;declarations: LetDeclarator[];loc?: SourceLocation;type: "LetExpression";}&Node;

A LET expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LET's scoped expression.
declarationsLetDeclarator[]The LET's variable declarations.
loc?SourceLocationThe original source position of the node.
type"LetExpression"The type of this AST node.

Literal

typeLiteral={loc?: SourceLocation;raw: string;type: "Literal";value: string|number|boolean;}&Node;

A literal token. Captures numbers, strings, and booleans. Literal errors have their own variant type.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"Literal"The type of this AST node.
valuestring | number | booleanThe value of the literal.

Node

typeNode={loc?: SourceLocation;type: string;};

All AST nodes are represented by Node objects. They may have any prototype inheritance but implement the same basic interface.

The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements.

Properties

PropertyTypeDescription
loc?SourceLocationThe original source position of the node.
typestringThe type of this AST node.

OptsFixRanges

typeOptsFixRanges={addBounds?: boolean;thisRow?: boolean;};

Options for fixTokenRanges and fixFormulaRanges.

Properties

PropertyTypeDefault valueDescription
addBounds?booleanfalseFill in any undefined bounds of range objects. Top to 0, bottom to 1048575, left to 0, and right to 16383.
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsParse

typeOptsParse={looseRefCalls?: boolean;permitArrayCalls?: boolean;permitArrayRanges?: boolean;};

Options for parse.

Properties

PropertyTypeDefault valueDescription
looseRefCalls?booleanfalsePermits any function call where otherwise only functions that return references would be permitted.
permitArrayCalls?booleanfalseFunction calls are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.
permitArrayRanges?booleanfalseRanges are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.

OptsParseA1Ref

typeOptsParseA1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseA1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsParseR1C1Ref

typeOptsParseR1C1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseR1C1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsStringifyStructRef

typeOptsStringifyStructRef={thisRow?: boolean;};

Options for stringifyStructRef

Properties

PropertyTypeDefault valueDescription
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsTokenize

typeOptsTokenize={allowTernary?: boolean;mergeRefs?: boolean;negativeNumbers?: boolean;r1c1?: boolean;withLocation?: boolean;};

Options for tokenize.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be returned as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2). This is the same as calling mergeRefTokens
negativeNumbers?booleantrueMerges unary minuses with their immediately following number tokens (-,1) => -1 (alternatively these will be unary operations in the tree).
r1c1?booleanfalseRanges are expected to be in the R1C1 style format rather than the more popular A1 style.
withLocation?booleantrueNodes will include source position offsets to the tokens: { loc: [ start, end ] }

OptsTranslateFormulaToA1

typeOptsTranslateFormulaToA1={allowTernary?: boolean;mergeRefs?: boolean;wrapEdges?: boolean;};

Options for translateFormulaToA1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be treated as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2).
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

OptsTranslateToR1C1

typeOptsTranslateToR1C1={allowTernary?: boolean;};

Options for translateFormulaToR1C1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsTranslateTokensToA1

typeOptsTranslateTokensToA1={wrapEdges?: boolean;};

Options for translateTokensToA1

Properties

PropertyTypeDefault valueDescription
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

RangeA1

typeRangeA1={$bottom?: boolean|null;$left?: boolean|null;$right?: boolean|null;$top?: boolean|null;bottom?: number|null;left: number|null;right?: number|null;top: number|null;trim?: "head"|"tail"|"both"|null;};

A range in A1 style coordinates.

Properties

PropertyTypeDescription
$bottom?boolean | nullSignifies that bottom is a "locked" value
$left?boolean | nullSignifies that left is a "locked" value
$right?boolean | nullSignifies that right is a "locked" value
$top?boolean | nullSignifies that top is a "locked" value
bottom?number | nullBottom row of the range
leftnumber | nullLeft column of the range
right?number | nullRight column of the range
topnumber | nullTop row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

RangeR1C1

typeRangeR1C1={$c0?: boolean|null;$c1?: boolean|null;$r0?: boolean|null;$r1?: boolean|null;c0?: number|null;c1?: number|null;r0?: number|null;r1?: number|null;trim?: "head"|"tail"|"both"|null;};

A range in R1C1 style coordinates.

Properties

PropertyTypeDescription
$c0?boolean | nullSignifies that c0 is an absolute value
$c1?boolean | nullSignifies that c1 is an absolute value
$r0?boolean | nullSignifies that r0 is an absolute value
$r1?boolean | nullSignifies that r1 is an absolute value
c0?number | nullLeft column of the range
c1?number | nullRight column of the range
r0?number | nullTop row of the range
r1?number | nullBottom row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

ReferenceA1

typeReferenceA1={context?: string[];range: RangeA1;};

A reference containing an A1 style range. See Prefixes.md for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeA1The reference's range

ReferenceA1Xlsx

typeReferenceA1Xlsx={range: RangeA1;sheetName?: string;workbookName?: string;};

A reference containing an A1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeA1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceIdentifier

typeReferenceIdentifier={kind: "name"|"range"|"beam"|"table";loc?: SourceLocation;type: "ReferenceIdentifier";value: string;}&Node;

An identifier for a range or a name.

Type Declaration

NameTypeDescription
kind"name" | "range" | "beam" | "table"The kind of reference the value holds.
loc?SourceLocationThe original source position of the node.
type"ReferenceIdentifier"The type of this AST node.
valuestringThe untouched reference value.

ReferenceName

typeReferenceName={context?: string[];name: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
namestringThe reference's name

ReferenceNameXlsx

typeReferenceNameXlsx={name: string;sheetName?: string;workbookName?: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
namestringThe reference's name
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceR1C1

typeReferenceR1C1={context?: string[];range: RangeR1C1;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeR1C1The reference's range

ReferenceR1C1Xlsx

typeReferenceR1C1Xlsx={range: RangeR1C1;sheetName?: string;workbookName?: string;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeR1C1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceStruct

typeReferenceStruct={columns?: string[];context?: string[];sections?: string[];table?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
context?string[]A collection of scopes for the reference
sections?string[]The sections this reference targets
table?stringThe table this reference targets

ReferenceStructXlsx

typeReferenceStructXlsx={columns?: string[];sections?: string[];sheetName?: string;table?: string;workbookName?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
sections?string[]The sections this reference targets
sheetName?stringA context sheet scope
table?stringThe table this reference targets
workbookName?stringA context workbook scope

SourceLocation

typeSourceLocation=number[];

Represents the source location information of the node. If the node contains no information about the source location, the field is null; otherwise it is an array consisting of a two numbers: A start offset (the position of the first character of the parsed source region) and an end offset (the position of the first character after the parsed source region).

Token

typeToken=Record<string,unknown>&{loc?: number[];type: string;unterminated?: boolean;value: string;};

A formula language token.

Type Declaration

NameTypeDescription
loc?number[]Source position offsets to the token
typestringThe type of the token
unterminated?booleanSignifies an unterminated string token
valuestringThe value of the token

TokenEnhanced

typeTokenEnhanced=Token&{depth?: number;error?: boolean;groupId?: string;index: number;};

A token with extra meta data.

Type Declaration

NameTypeDescription
depth?numberThis token's level of nesting inside parentheses
error?booleanToken is of unknown type or a paren without a match
groupId?stringThe ID of a group which this token belongs (e.g. matching parens)
indexnumberA zero based position in a token list

UnaryExpression

typeUnaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: UnaryOperator;type: "UnaryExpression";}&Node;

A unary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorUnaryOperatorThe expression's operator.
type"UnaryExpression"The type of this AST node.

UnaryOperator

typeUnaryOperator="+"|"-"|"%"|"#"|"@";

A unary operator token.

MAX_COLS

constMAX_COLS: number;

The maximum number of columns a spreadsheet reference may hold (16383).

MAX_ROWS

constMAX_ROWS: number;

The maximum number of rows a spreadsheet reference may hold (1048575).

nodeTypes

constnodeTypes: Readonly<{ARRAY: "ArrayExpression";BINARY: "BinaryExpression";CALL: "CallExpression";ERROR: "ErrorLiteral";IDENTIFIER: "Identifier";LAMBDA: "LambdaExpression";LET: "LetExpression";LET_DECL: "LetDeclarator";LITERAL: "Literal";REFERENCE: "ReferenceIdentifier";UNARY: "UnaryExpression";}>;

A dictionary of the types used to identify AST node variants.

tokenTypes

consttokenTypes: Readonly<{BOOLEAN: "bool";CONTEXT: "context";CONTEXT_QUOTE: "context_quote";ERROR: "error";FUNCTION: "func";FX_PREFIX: "fx_prefix";NEWLINE: "newline";NUMBER: "number";OPERATOR: "operator";REF_BEAM: "range_beam";REF_NAMED: "range_named";REF_RANGE: "range";REF_STRUCT: "structured";REF_TERNARY: "range_ternary";STRING: "string";UNKNOWN: "unknown";WHITESPACE: "whitespace";}>;

A dictionary of the types used to identify token variants.

fx/xlsx

A tokenizer, parser, and other utilities to work with Excel formula code.

The xslx entry-point methods expect and return the variant of references that uses properties. If you are not using xlsx files you should use the fx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Functions

References

addA1RangeBounds

Re-exports addA1RangeBounds


ArrayExpression

Re-exports ArrayExpression


AstExpression

Re-exports AstExpression


BinaryExpression

Re-exports BinaryExpression


BinaryOperator

Re-exports BinaryOperator


CallExpression

Re-exports CallExpression


ErrorLiteral

Re-exports ErrorLiteral


fromCol

Re-exports fromCol


Identifier

Re-exports Identifier


isArrayNode

Re-exports isArrayNode


isBinaryNode

Re-exports isBinaryNode


isCallNode

Re-exports isCallNode


isError

Re-exports isError


isErrorNode

Re-exports isErrorNode


isExpressionNode

Re-exports isExpressionNode


isFunction

Re-exports isFunction


isFxPrefix

Re-exports isFxPrefix


isIdentifierNode

Re-exports isIdentifierNode


isLambdaNode

Re-exports isLambdaNode


isLetDeclaratorNode

Re-exports isLetDeclaratorNode


isLetNode

Re-exports isLetNode


isLiteral

Re-exports isLiteral


isLiteralNode

Re-exports isLiteralNode


isOperator

Re-exports isOperator


isRange

Re-exports isRange


isReference

Re-exports isReference


isReferenceNode

Re-exports isReferenceNode


isUnaryNode

Re-exports isUnaryNode


isWhitespace

Re-exports isWhitespace


LambdaExpression

Re-exports LambdaExpression


LetDeclarator

Re-exports LetDeclarator


LetExpression

Re-exports LetExpression


Literal

Re-exports Literal


MAX_COLS

Re-exports MAX_COLS


MAX_ROWS

Re-exports MAX_ROWS


Node

Re-exports Node


nodeTypes

Re-exports nodeTypes


OptsFixRanges

Re-exports OptsFixRanges


OptsParse

Re-exports OptsParse


OptsParseA1Ref

Re-exports OptsParseA1Ref


OptsParseR1C1Ref

Re-exports OptsParseR1C1Ref


OptsStringifyStructRef

Re-exports OptsStringifyStructRef


OptsTokenize

Re-exports OptsTokenize


OptsTranslateFormulaToA1

Re-exports OptsTranslateFormulaToA1


OptsTranslateTokensToA1

Re-exports OptsTranslateTokensToA1


OptsTranslateToR1C1

Re-exports OptsTranslateToR1C1


parse

Re-exports parse


parseA1Range

Re-exports parseA1Range


parseR1C1Range

Re-exports parseR1C1Range


RangeA1

Re-exports RangeA1


RangeR1C1

Re-exports RangeR1C1


ReferenceA1

Re-exports ReferenceA1


ReferenceA1Xlsx

Re-exports ReferenceA1Xlsx


ReferenceIdentifier

Re-exports ReferenceIdentifier


ReferenceName

Re-exports ReferenceName


ReferenceNameXlsx

Re-exports ReferenceNameXlsx


ReferenceR1C1

Re-exports ReferenceR1C1


ReferenceR1C1Xlsx

Re-exports ReferenceR1C1Xlsx


ReferenceStruct

Re-exports ReferenceStruct


ReferenceStructXlsx

Re-exports ReferenceStructXlsx


SourceLocation

Re-exports SourceLocation


stringifyTokens

Re-exports stringifyTokens


toCol

Re-exports toCol


Token

Re-exports Token


TokenEnhanced

Re-exports TokenEnhanced


tokenTypes

Re-exports tokenTypes


translateFormulaToA1

Re-exports translateFormulaToA1


translateFormulaToR1C1

Re-exports translateFormulaToR1C1


translateTokensToA1

Re-exports translateTokensToA1


translateTokensToR1C1

Re-exports translateTokensToR1C1


UnaryExpression

Re-exports UnaryExpression


UnaryOperator

Re-exports UnaryOperator

addTokenMeta()

functionaddTokenMeta(tokenlist: Token[],context?: {sheetName?: string;workbookName?: string;}): TokenEnhanced[];

Runs through a list of tokens and adds extra attributes such as matching parens and ranges.

The context parameter defines default reference attributes: { workbookName: 'report.xlsx', sheetName: 'Sheet1' }. If supplied, these are used to match A1 to Sheet1!A1.

All tokens will be tagged with a .depth number value to indicating the level of nesting in parentheses as well as an .index number indicating their zero based position in the list.

The returned output will be the same array of tokens but the following properties will added to tokens (as applicable):

Parentheses ( )

Matching parens will be tagged with .groupId string identifier as well as a .depth number value (indicating the level of nesting).

Closing parens without a counterpart will be tagged with .error (boolean true).

Curly brackets { }

Matching curly brackets will be tagged with .groupId string identifier. These may not be nested in Excel.

Closing curly brackets without a counterpart will be tagged with .error (boolean true).

Ranges (REF_RANGE or REF_BEAM type tokens)

All ranges will be tagged with .groupId string identifier regardless of the number of times they occur.

Tokens of type UNKNOWN

All will be tagged with .error (boolean true).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens (from tokenize())
context?{ sheetName?: string; workbookName?: string; }A context used to match A1 to Sheet1!A1.
context.sheetName?stringAn implied sheet name ('Sheet1')
context.workbookName?stringAn implied workbook name ('report.xlsx')

Returns

TokenEnhanced[]

The input array with the enchanced tokens

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens and returns a new array of tokens with values and position-data updated.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Unlike Excel, fx does not normalize sheet or workbook names of references.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1Xlsx|ReferenceNameXlsx;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// workbookName: '',// sheetName: 'Sheet1',// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1Xlsx | ReferenceNameXlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceNameXlsx|ReferenceR1C1Xlsx;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceNameXlsx | ReferenceR1C1Xlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStructXlsx;

Parse a structured reference string into an object representing it.

parseStructRef('[workbook.xlsx]!tableName[[#Data],[Column1]:[Column2]]');// => {// workbookName: 'workbook.xlsx',// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStructXlsx

An object representing a valid reference or null if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1Xlsx|ReferenceNameXlsx): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({sheetName: 'Sheet1',range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1Xlsx | ReferenceNameXlsxA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceNameXlsx|ReferenceR1C1Xlsx): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({sheetName: 'Sheet1',range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceNameXlsx | ReferenceR1C1XlsxA reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStructXlsx,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({workbookName: 'workbook.xlsx',sheetName: '',sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructXlsxA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

History
3323 lines (2177 loc) · 76.1 KB

File metadata and controls

3323 lines (2177 loc) · 76.1 KB

@borgar/fx

Modules

fx

A tokenizer, parser, and other utilities to work with Excel formula code.

The base entry-point methods expect and return the variant of references that uses contexts. If you are using xlsx files or otherwise want to work with the xlsx-file variant of references you should use the fx/xlsx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Type Aliases

Variables

Functions

addA1RangeBounds()

functionaddA1RangeBounds(range: RangeA1): RangeA1;

Fill the any missing bounds in range objects. Top will be set to 0, bottom to 1048575, left to 0, and right to 16383, if they are null or undefined.

addA1RangeBounds({top: 0,left: 0,bottom: 1,$top: true,$left: false,$bottom: false,});// => {// top: 0,// left: 0,// bottom: 1,// right: 16383, // ← Added// $top: true,// $left: false,// $bottom: false,// $right: false // ← Added// }

Parameters

ParameterTypeDescription
rangeRangeA1The range part of a reference object.

Returns

RangeA1

The same range with missing bounds filled in.

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Returns a new array of tokens with values and position data updated.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

fromCol()

functionfromCol(columnString: string): number;

Convert a column string representation to a 0 based offset number ("C" = 2).

The method expects a valid column identifier made up of only A-Z letters, which may be either upper or lower case. Other input will return garbage.

Parameters

ParameterTypeDescription
columnStringstringThe column string identifier

Returns

number

Zero based column index number

isArrayNode()

functionisArrayNode(node?: Node): node is ArrayExpression;

Determines whether the specified node is a ArrayExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ArrayExpression

True if the specified token is a ArrayExpression, False otherwise.

isBinaryNode()

functionisBinaryNode(node?: Node): node is BinaryExpression;

Determines whether the specified node is a BinaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is BinaryExpression

True if the specified token is a BinaryExpression, False otherwise.

isCallNode()

functionisCallNode(node?: Node): node is CallExpression;

Determines whether the specified node is a CallExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is CallExpression

True if the specified token is a CallExpression, False otherwise.

isError()

functionisError(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an error.

Returns true if the input is a token of type ERROR (#VALUE!). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is error, False otherwise.

isErrorNode()

functionisErrorNode(node?: Node): node is ErrorLiteral;

Determines whether the specified node is an ErrorLiteral.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ErrorLiteral

True if the specified token is an ErrorLiteral, False otherwise.

isExpressionNode()

functionisExpressionNode(node?: Node): node is AstExpression;

Determines whether the specified node is a AstExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is AstExpression

True if the specified token is a AstExpression, False otherwise.

isFunction()

functionisFunction(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a function.

Returns true if the input is a token of type FUNCTION. In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is function, False otherwise.

isFxPrefix()

functionisFxPrefix(token?: Pick<Token,"type">): boolean;

Returns true if the input is a token of type FX_PREFIX (leading = in formula). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is effects prefix, False otherwise.

isIdentifierNode()

functionisIdentifierNode(node?: Node): node is Identifier;

Determines whether the specified node is an Identifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Identifier

True if the specified token is an Identifier, False otherwise.

isLambdaNode()

functionisLambdaNode(node?: Node): node is LambdaExpression;

Determines whether the specified node is a LambdaExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LambdaExpression

True if the specified token is a LambdaExpression, False otherwise.

isLetDeclaratorNode()

functionisLetDeclaratorNode(node?: Node): node is LetDeclarator;

Determines whether the specified node is a LetDeclarator.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetDeclarator

True if the specified token is a LetDeclarator, False otherwise.

isLetNode()

functionisLetNode(node?: Node): node is LetExpression;

Determines whether the specified node is a LetExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetExpression

True if the specified token is a LetExpression, False otherwise.

isLiteral()

functionisLiteral(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a literal.

Returns true if the input is a token of type BOOLEAN (TRUE or FALSE), ERROR (#VALUE!), NUMBER (123.4), or STRING ("lorem ipsum"). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is literal, False otherwise.

isLiteralNode()

functionisLiteralNode(node?: Node): node is Literal;

Determines whether the specified node is a Literal.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Literal

True if the specified token is a Literal, False otherwise.

isOperator()

functionisOperator(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an operator.

Returns true if the input is a token of type OPERATOR (+ or :). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is operator, False otherwise.

isRange()

functionisRange(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a range.

Returns true if the input is a token that has a type of either REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), or REF_BEAM (A:A or 1:1). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">A token

Returns

boolean

True if the specified token is range, False otherwise.

isReference()

functionisReference(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a reference.

Returns true if the input is a token of type REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), REF_BEAM (A:A or 1:1), or REF_NAMED (myrange). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is reference, False otherwise.

isReferenceNode()

functionisReferenceNode(node?: Node): node is ReferenceIdentifier;

Determines whether the specified node is a ReferenceIdentifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ReferenceIdentifier

True if the specified token is a ReferenceIdentifier, False otherwise.

isUnaryNode()

functionisUnaryNode(node?: Node): node is UnaryExpression;

Determines whether the specified node is a UnaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is UnaryExpression

True if the specified token is a UnaryExpression, False otherwise.

isWhitespace()

functionisWhitespace(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is whitespace.

Returns true if the input is a token of type WHITESPACE () or NEWLINE (\n). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is whitespace, False otherwise.

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parse()

functionparse(tokenlist: Token[],options?: OptsParse): AstExpression;

Parses a string formula or list of tokens into an AST.

The parser assumes mergeRefs and negativeNumbers were true when the tokens were generated. It does not yet recognize reference context tokens or know how to deal with unary minuses in arrays.

The AST Abstract Syntax Tree's format is documented in AST_format.md.

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.
optionsOptsParseOptions for the parsers behavior.

Returns

AstExpression

An AST of nodes.

See

parseA1Range()

functionparseA1Range(rangeString: string,allowTernary?: boolean): RangeA1;

Parse A1-style range string into a RangeA1 object.

Parameters

ParameterTypeDefault valueDescription
rangeStringstringundefinedA1-style range string.
allowTernary?booleantruePermit ternary ranges like A2:A or B2:2.

Returns

RangeA1

A reference object.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1|ReferenceName;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// context: [ 'Sheet1' ],// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1 | ReferenceName

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Range()

functionparseR1C1Range(rangeString: string): RangeR1C1;

Parse R1C1-style range string into a RangeR1C1 object.

Parameters

ParameterTypeDescription
rangeStringstringR1C1-style range string.

Returns

RangeR1C1

A reference object.

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceName|ReferenceR1C1;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceName | ReferenceR1C1

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStruct;

Parse a structured reference string into an object representing it.

parseStructRef('workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]');// => {// context: [ 'workbook.xlsx' ],// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStruct

An object representing a valid reference or undefined if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1|ReferenceName): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({context: ['Sheet1'],range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1 | ReferenceNameA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceName|ReferenceR1C1): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({context: ['Sheet1'],range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceName | ReferenceR1C1A reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStruct,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({context: ['workbook.xlsx'],sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

See

OptsStringifyStructRef

stringifyTokens()

functionstringifyTokens(tokens: Token[]): string;

Collapses a list of tokens into a formula string.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens.

Returns

string

A formula string.

toCol()

functiontoCol(columnIndex: number): string;

Convert a 0 based offset number to a column string representation (0 = "A", 2 = "C").

The method expects a number between 0 and 16383. Other input will return garbage.

Parameters

ParameterTypeDescription
columnIndexnumberZero based column index number

Returns

string

The column string identifier

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parsers will need to handle this.

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

translateFormulaToA1()

functiontranslateFormulaToA1(formula: string,anchorCell: string,options?: OptsTranslateFormulaToA1): string;

Translates ranges in a formula from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so you can set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Parameters

ParameterTypeDescription
formulastringAn Excel formula string that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateFormulaToA1Translation options.

Returns

string

A formula string.

See

OptsTranslateFormulaToA1

translateFormulaToR1C1()

functiontranslateFormulaToR1C1(formula: string,anchorCell: string,options?: OptsTranslateToR1C1): string;

Translates ranges in a formula from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
formulastringAn Excel formula that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
options?OptsTranslateToR1C1The options

Returns

string

A formula string.

See

OptsTranslateToR1C1

translateTokensToA1()

functiontranslateTokensToA1(tokens: Token[],anchorCell: string,options?: OptsTranslateTokensToA1): Token[];

Translates ranges in a list of tokens from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so may set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Note that if you are passing in a list of tokens that was not created using mergeRefs and you disable edge wrapping (or you simply set both options to false), you can end up with a formula such as =#REF!:B2 or =Sheet3!#REF!:F3. These are valid formulas in the Excel formula language and Excel will accept them, but they are not supported in Google Sheets.

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateTokensToA1Translation options.

Returns

Token[]

A token list.

See

OptsTranslateTokensToA1

translateTokensToR1C1()

functiontranslateTokensToR1C1(tokens: Token[],anchorCell: string): Token[];

Translates ranges in a list of tokens from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).

Returns

Token[]

A token list.

ArrayExpression

typeArrayExpression={elements: (|ReferenceIdentifier|Literal|ErrorLiteral|CallExpression)[][];loc?: SourceLocation;type: "ArrayExpression";}&Node;

An array expression. Excel does not have empty or sparse arrays and restricts array elements to literals. Google Sheets allows ReferenceIdentifiers and CallExpressions as elements of arrays, the fx parser has options for this but they are off by default.

Type Declaration

NameTypeDescription
elements( | ReferenceIdentifier | Literal | ErrorLiteral | CallExpression)[][]The elements of the array.
loc?SourceLocationThe original source position of the node.
type"ArrayExpression"The type of this AST node.

AstExpression

typeAstExpression=|ReferenceIdentifier|Literal|ErrorLiteral|UnaryExpression|BinaryExpression|CallExpression|ArrayExpression|LambdaExpression|LetExpression;

Represents an evaluate-able expression.

BinaryExpression

typeBinaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: BinaryOperator;type: "BinaryExpression";}&Node;

A binary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorBinaryOperatorThe expression's operator.
type"BinaryExpression"The type of this AST node.

BinaryOperator

typeBinaryOperator=|"="|"<"|">"|"<="|">="|"<>"|"-"|"+"|"*"|"/"|"^"|":"|" "|","|"&";

A binary operator token.

Note that Excels union operator is whitespace so a parser must take care to normalize this to a single space.

CallExpression

typeCallExpression={arguments: AstExpression[];callee: Identifier;loc?: SourceLocation;type: "CallExpression";}&Node;

A function call expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the function.
calleeIdentifierThe function being called.
loc?SourceLocationThe original source position of the node.
type"CallExpression"The type of this AST node.

ErrorLiteral

typeErrorLiteral={loc?: SourceLocation;raw: string;type: "ErrorLiteral";value: string;}&Node;

An Error expression.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"ErrorLiteral"The type of this AST node.
valuestringThe value of the error.

Identifier

typeIdentifier={loc?: SourceLocation;name: string;type: "Identifier";}&Node;

An identifier. These appear on CallExpression, LambdaExpression, and LetExpression and will always be a static string representing the name of a function call or parameter.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
namestringThe identifying name.
type"Identifier"The type of this AST node.

LambdaExpression

typeLambdaExpression={body: AstExpression|null;loc?: SourceLocation;params: Identifier[];type: "LambdaExpression";}&Node;

A LAMBDA expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LAMBDA's expression.
loc?SourceLocationThe original source position of the node.
paramsIdentifier[]The LAMBDA's parameters.
type"LambdaExpression"The type of this AST node.

LetDeclarator

typeLetDeclarator={id: Identifier;init: AstExpression|null;loc?: SourceLocation;type: "LetDeclarator";}&Node;

A LET parameter declaration.

Type Declaration

NameTypeDescription
idIdentifierThe name of the variable.
initAstExpression | nullThe variable's initializing expression.
loc?SourceLocationThe original source position of the node.
type"LetDeclarator"The type of this AST node.

LetExpression

typeLetExpression={body: AstExpression|null;declarations: LetDeclarator[];loc?: SourceLocation;type: "LetExpression";}&Node;

A LET expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LET's scoped expression.
declarationsLetDeclarator[]The LET's variable declarations.
loc?SourceLocationThe original source position of the node.
type"LetExpression"The type of this AST node.

Literal

typeLiteral={loc?: SourceLocation;raw: string;type: "Literal";value: string|number|boolean;}&Node;

A literal token. Captures numbers, strings, and booleans. Literal errors have their own variant type.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"Literal"The type of this AST node.
valuestring | number | booleanThe value of the literal.

Node

typeNode={loc?: SourceLocation;type: string;};

All AST nodes are represented by Node objects. They may have any prototype inheritance but implement the same basic interface.

The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements.

Properties

PropertyTypeDescription
loc?SourceLocationThe original source position of the node.
typestringThe type of this AST node.

OptsFixRanges

typeOptsFixRanges={addBounds?: boolean;thisRow?: boolean;};

Options for fixTokenRanges and fixFormulaRanges.

Properties

PropertyTypeDefault valueDescription
addBounds?booleanfalseFill in any undefined bounds of range objects. Top to 0, bottom to 1048575, left to 0, and right to 16383.
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsParse

typeOptsParse={looseRefCalls?: boolean;permitArrayCalls?: boolean;permitArrayRanges?: boolean;};

Options for parse.

Properties

PropertyTypeDefault valueDescription
looseRefCalls?booleanfalsePermits any function call where otherwise only functions that return references would be permitted.
permitArrayCalls?booleanfalseFunction calls are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.
permitArrayRanges?booleanfalseRanges are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.

OptsParseA1Ref

typeOptsParseA1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseA1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsParseR1C1Ref

typeOptsParseR1C1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseR1C1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsStringifyStructRef

typeOptsStringifyStructRef={thisRow?: boolean;};

Options for stringifyStructRef

Properties

PropertyTypeDefault valueDescription
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsTokenize

typeOptsTokenize={allowTernary?: boolean;mergeRefs?: boolean;negativeNumbers?: boolean;r1c1?: boolean;withLocation?: boolean;};

Options for tokenize.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be returned as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2). This is the same as calling mergeRefTokens
negativeNumbers?booleantrueMerges unary minuses with their immediately following number tokens (-,1) => -1 (alternatively these will be unary operations in the tree).
r1c1?booleanfalseRanges are expected to be in the R1C1 style format rather than the more popular A1 style.
withLocation?booleantrueNodes will include source position offsets to the tokens: { loc: [ start, end ] }

OptsTranslateFormulaToA1

typeOptsTranslateFormulaToA1={allowTernary?: boolean;mergeRefs?: boolean;wrapEdges?: boolean;};

Options for translateFormulaToA1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be treated as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2).
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

OptsTranslateToR1C1

typeOptsTranslateToR1C1={allowTernary?: boolean;};

Options for translateFormulaToR1C1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsTranslateTokensToA1

typeOptsTranslateTokensToA1={wrapEdges?: boolean;};

Options for translateTokensToA1

Properties

PropertyTypeDefault valueDescription
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

RangeA1

typeRangeA1={$bottom?: boolean|null;$left?: boolean|null;$right?: boolean|null;$top?: boolean|null;bottom?: number|null;left: number|null;right?: number|null;top: number|null;trim?: "head"|"tail"|"both"|null;};

A range in A1 style coordinates.

Properties

PropertyTypeDescription
$bottom?boolean | nullSignifies that bottom is a "locked" value
$left?boolean | nullSignifies that left is a "locked" value
$right?boolean | nullSignifies that right is a "locked" value
$top?boolean | nullSignifies that top is a "locked" value
bottom?number | nullBottom row of the range
leftnumber | nullLeft column of the range
right?number | nullRight column of the range
topnumber | nullTop row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

RangeR1C1

typeRangeR1C1={$c0?: boolean|null;$c1?: boolean|null;$r0?: boolean|null;$r1?: boolean|null;c0?: number|null;c1?: number|null;r0?: number|null;r1?: number|null;trim?: "head"|"tail"|"both"|null;};

A range in R1C1 style coordinates.

Properties

PropertyTypeDescription
$c0?boolean | nullSignifies that c0 is an absolute value
$c1?boolean | nullSignifies that c1 is an absolute value
$r0?boolean | nullSignifies that r0 is an absolute value
$r1?boolean | nullSignifies that r1 is an absolute value
c0?number | nullLeft column of the range
c1?number | nullRight column of the range
r0?number | nullTop row of the range
r1?number | nullBottom row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

ReferenceA1

typeReferenceA1={context?: string[];range: RangeA1;};

A reference containing an A1 style range. See Prefixes.md for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeA1The reference's range

ReferenceA1Xlsx

typeReferenceA1Xlsx={range: RangeA1;sheetName?: string;workbookName?: string;};

A reference containing an A1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeA1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceIdentifier

typeReferenceIdentifier={kind: "name"|"range"|"beam"|"table";loc?: SourceLocation;type: "ReferenceIdentifier";value: string;}&Node;

An identifier for a range or a name.

Type Declaration

NameTypeDescription
kind"name" | "range" | "beam" | "table"The kind of reference the value holds.
loc?SourceLocationThe original source position of the node.
type"ReferenceIdentifier"The type of this AST node.
valuestringThe untouched reference value.

ReferenceName

typeReferenceName={context?: string[];name: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
namestringThe reference's name

ReferenceNameXlsx

typeReferenceNameXlsx={name: string;sheetName?: string;workbookName?: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
namestringThe reference's name
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceR1C1

typeReferenceR1C1={context?: string[];range: RangeR1C1;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeR1C1The reference's range

ReferenceR1C1Xlsx

typeReferenceR1C1Xlsx={range: RangeR1C1;sheetName?: string;workbookName?: string;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeR1C1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceStruct

typeReferenceStruct={columns?: string[];context?: string[];sections?: string[];table?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
context?string[]A collection of scopes for the reference
sections?string[]The sections this reference targets
table?stringThe table this reference targets

ReferenceStructXlsx

typeReferenceStructXlsx={columns?: string[];sections?: string[];sheetName?: string;table?: string;workbookName?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
sections?string[]The sections this reference targets
sheetName?stringA context sheet scope
table?stringThe table this reference targets
workbookName?stringA context workbook scope

SourceLocation

typeSourceLocation=number[];

Represents the source location information of the node. If the node contains no information about the source location, the field is null; otherwise it is an array consisting of a two numbers: A start offset (the position of the first character of the parsed source region) and an end offset (the position of the first character after the parsed source region).

Token

typeToken=Record<string,unknown>&{loc?: number[];type: string;unterminated?: boolean;value: string;};

A formula language token.

Type Declaration

NameTypeDescription
loc?number[]Source position offsets to the token
typestringThe type of the token
unterminated?booleanSignifies an unterminated string token
valuestringThe value of the token

TokenEnhanced

typeTokenEnhanced=Token&{depth?: number;error?: boolean;groupId?: string;index: number;};

A token with extra meta data.

Type Declaration

NameTypeDescription
depth?numberThis token's level of nesting inside parentheses
error?booleanToken is of unknown type or a paren without a match
groupId?stringThe ID of a group which this token belongs (e.g. matching parens)
indexnumberA zero based position in a token list

UnaryExpression

typeUnaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: UnaryOperator;type: "UnaryExpression";}&Node;

A unary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorUnaryOperatorThe expression's operator.
type"UnaryExpression"The type of this AST node.

UnaryOperator

typeUnaryOperator="+"|"-"|"%"|"#"|"@";

A unary operator token.

MAX_COLS

constMAX_COLS: number;

The maximum number of columns a spreadsheet reference may hold (16383).

MAX_ROWS

constMAX_ROWS: number;

The maximum number of rows a spreadsheet reference may hold (1048575).

nodeTypes

constnodeTypes: Readonly<{ARRAY: "ArrayExpression";BINARY: "BinaryExpression";CALL: "CallExpression";ERROR: "ErrorLiteral";IDENTIFIER: "Identifier";LAMBDA: "LambdaExpression";LET: "LetExpression";LET_DECL: "LetDeclarator";LITERAL: "Literal";REFERENCE: "ReferenceIdentifier";UNARY: "UnaryExpression";}>;

A dictionary of the types used to identify AST node variants.

tokenTypes

consttokenTypes: Readonly<{BOOLEAN: "bool";CONTEXT: "context";CONTEXT_QUOTE: "context_quote";ERROR: "error";FUNCTION: "func";FX_PREFIX: "fx_prefix";NEWLINE: "newline";NUMBER: "number";OPERATOR: "operator";REF_BEAM: "range_beam";REF_NAMED: "range_named";REF_RANGE: "range";REF_STRUCT: "structured";REF_TERNARY: "range_ternary";STRING: "string";UNKNOWN: "unknown";WHITESPACE: "whitespace";}>;

A dictionary of the types used to identify token variants.

fx/xlsx

A tokenizer, parser, and other utilities to work with Excel formula code.

The xslx entry-point methods expect and return the variant of references that uses properties. If you are not using xlsx files you should use the fx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Functions

References

addA1RangeBounds

Re-exports addA1RangeBounds


ArrayExpression

Re-exports ArrayExpression


AstExpression

Re-exports AstExpression


BinaryExpression

Re-exports BinaryExpression


BinaryOperator

Re-exports BinaryOperator


CallExpression

Re-exports CallExpression


ErrorLiteral

Re-exports ErrorLiteral


fromCol

Re-exports fromCol


Identifier

Re-exports Identifier


isArrayNode

Re-exports isArrayNode


isBinaryNode

Re-exports isBinaryNode


isCallNode

Re-exports isCallNode


isError

Re-exports isError


isErrorNode

Re-exports isErrorNode


isExpressionNode

Re-exports isExpressionNode


isFunction

Re-exports isFunction


isFxPrefix

Re-exports isFxPrefix


isIdentifierNode

Re-exports isIdentifierNode


isLambdaNode

Re-exports isLambdaNode


isLetDeclaratorNode

Re-exports isLetDeclaratorNode


isLetNode

Re-exports isLetNode


isLiteral

Re-exports isLiteral


isLiteralNode

Re-exports isLiteralNode


isOperator

Re-exports isOperator


isRange

Re-exports isRange


isReference

Re-exports isReference


isReferenceNode

Re-exports isReferenceNode


isUnaryNode

Re-exports isUnaryNode


isWhitespace

Re-exports isWhitespace


LambdaExpression

Re-exports LambdaExpression


LetDeclarator

Re-exports LetDeclarator


LetExpression

Re-exports LetExpression


Literal

Re-exports Literal


MAX_COLS

Re-exports MAX_COLS


MAX_ROWS

Re-exports MAX_ROWS


Node

Re-exports Node


nodeTypes

Re-exports nodeTypes


OptsFixRanges

Re-exports OptsFixRanges


OptsParse

Re-exports OptsParse


OptsParseA1Ref

Re-exports OptsParseA1Ref


OptsParseR1C1Ref

Re-exports OptsParseR1C1Ref


OptsStringifyStructRef

Re-exports OptsStringifyStructRef


OptsTokenize

Re-exports OptsTokenize


OptsTranslateFormulaToA1

Re-exports OptsTranslateFormulaToA1


OptsTranslateTokensToA1

Re-exports OptsTranslateTokensToA1


OptsTranslateToR1C1

Re-exports OptsTranslateToR1C1


parse

Re-exports parse


parseA1Range

Re-exports parseA1Range


parseR1C1Range

Re-exports parseR1C1Range


RangeA1

Re-exports RangeA1


RangeR1C1

Re-exports RangeR1C1


ReferenceA1

Re-exports ReferenceA1


ReferenceA1Xlsx

Re-exports ReferenceA1Xlsx


ReferenceIdentifier

Re-exports ReferenceIdentifier


ReferenceName

Re-exports ReferenceName


ReferenceNameXlsx

Re-exports ReferenceNameXlsx


ReferenceR1C1

Re-exports ReferenceR1C1


ReferenceR1C1Xlsx

Re-exports ReferenceR1C1Xlsx


ReferenceStruct

Re-exports ReferenceStruct


ReferenceStructXlsx

Re-exports ReferenceStructXlsx


SourceLocation

Re-exports SourceLocation


stringifyTokens

Re-exports stringifyTokens


toCol

Re-exports toCol


Token

Re-exports Token


TokenEnhanced

Re-exports TokenEnhanced


tokenTypes

Re-exports tokenTypes


translateFormulaToA1

Re-exports translateFormulaToA1


translateFormulaToR1C1

Re-exports translateFormulaToR1C1


translateTokensToA1

Re-exports translateTokensToA1


translateTokensToR1C1

Re-exports translateTokensToR1C1


UnaryExpression

Re-exports UnaryExpression


UnaryOperator

Re-exports UnaryOperator

addTokenMeta()

functionaddTokenMeta(tokenlist: Token[],context?: {sheetName?: string;workbookName?: string;}): TokenEnhanced[];

Runs through a list of tokens and adds extra attributes such as matching parens and ranges.

The context parameter defines default reference attributes: { workbookName: 'report.xlsx', sheetName: 'Sheet1' }. If supplied, these are used to match A1 to Sheet1!A1.

All tokens will be tagged with a .depth number value to indicating the level of nesting in parentheses as well as an .index number indicating their zero based position in the list.

The returned output will be the same array of tokens but the following properties will added to tokens (as applicable):

Parentheses ( )

Matching parens will be tagged with .groupId string identifier as well as a .depth number value (indicating the level of nesting).

Closing parens without a counterpart will be tagged with .error (boolean true).

Curly brackets { }

Matching curly brackets will be tagged with .groupId string identifier. These may not be nested in Excel.

Closing curly brackets without a counterpart will be tagged with .error (boolean true).

Ranges (REF_RANGE or REF_BEAM type tokens)

All ranges will be tagged with .groupId string identifier regardless of the number of times they occur.

Tokens of type UNKNOWN

All will be tagged with .error (boolean true).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens (from tokenize())
context?{ sheetName?: string; workbookName?: string; }A context used to match A1 to Sheet1!A1.
context.sheetName?stringAn implied sheet name ('Sheet1')
context.workbookName?stringAn implied workbook name ('report.xlsx')

Returns

TokenEnhanced[]

The input array with the enchanced tokens

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens and returns a new array of tokens with values and position-data updated.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Unlike Excel, fx does not normalize sheet or workbook names of references.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1Xlsx|ReferenceNameXlsx;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// workbookName: '',// sheetName: 'Sheet1',// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1Xlsx | ReferenceNameXlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceNameXlsx|ReferenceR1C1Xlsx;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceNameXlsx | ReferenceR1C1Xlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStructXlsx;

Parse a structured reference string into an object representing it.

parseStructRef('[workbook.xlsx]!tableName[[#Data],[Column1]:[Column2]]');// => {// workbookName: 'workbook.xlsx',// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStructXlsx

An object representing a valid reference or null if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1Xlsx|ReferenceNameXlsx): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({sheetName: 'Sheet1',range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1Xlsx | ReferenceNameXlsxA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceNameXlsx|ReferenceR1C1Xlsx): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({sheetName: 'Sheet1',range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceNameXlsx | ReferenceR1C1XlsxA reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStructXlsx,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({workbookName: 'workbook.xlsx',sheetName: '',sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructXlsxA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
3323 lines (2177 loc) · 76.1 KB

File metadata and controls

3323 lines (2177 loc) · 76.1 KB

@borgar/fx

Modules

fx

A tokenizer, parser, and other utilities to work with Excel formula code.

The base entry-point methods expect and return the variant of references that uses contexts. If you are using xlsx files or otherwise want to work with the xlsx-file variant of references you should use the fx/xlsx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Type Aliases

Variables

Functions

addA1RangeBounds()

functionaddA1RangeBounds(range: RangeA1): RangeA1;

Fill the any missing bounds in range objects. Top will be set to 0, bottom to 1048575, left to 0, and right to 16383, if they are null or undefined.

addA1RangeBounds({top: 0,left: 0,bottom: 1,$top: true,$left: false,$bottom: false,});// => {// top: 0,// left: 0,// bottom: 1,// right: 16383, // ← Added// $top: true,// $left: false,// $bottom: false,// $right: false // ← Added// }

Parameters

ParameterTypeDescription
rangeRangeA1The range part of a reference object.

Returns

RangeA1

The same range with missing bounds filled in.

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Returns a new array of tokens with values and position data updated.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

fromCol()

functionfromCol(columnString: string): number;

Convert a column string representation to a 0 based offset number ("C" = 2).

The method expects a valid column identifier made up of only A-Z letters, which may be either upper or lower case. Other input will return garbage.

Parameters

ParameterTypeDescription
columnStringstringThe column string identifier

Returns

number

Zero based column index number

isArrayNode()

functionisArrayNode(node?: Node): node is ArrayExpression;

Determines whether the specified node is a ArrayExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ArrayExpression

True if the specified token is a ArrayExpression, False otherwise.

isBinaryNode()

functionisBinaryNode(node?: Node): node is BinaryExpression;

Determines whether the specified node is a BinaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is BinaryExpression

True if the specified token is a BinaryExpression, False otherwise.

isCallNode()

functionisCallNode(node?: Node): node is CallExpression;

Determines whether the specified node is a CallExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is CallExpression

True if the specified token is a CallExpression, False otherwise.

isError()

functionisError(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an error.

Returns true if the input is a token of type ERROR (#VALUE!). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is error, False otherwise.

isErrorNode()

functionisErrorNode(node?: Node): node is ErrorLiteral;

Determines whether the specified node is an ErrorLiteral.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ErrorLiteral

True if the specified token is an ErrorLiteral, False otherwise.

isExpressionNode()

functionisExpressionNode(node?: Node): node is AstExpression;

Determines whether the specified node is a AstExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is AstExpression

True if the specified token is a AstExpression, False otherwise.

isFunction()

functionisFunction(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a function.

Returns true if the input is a token of type FUNCTION. In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is function, False otherwise.

isFxPrefix()

functionisFxPrefix(token?: Pick<Token,"type">): boolean;

Returns true if the input is a token of type FX_PREFIX (leading = in formula). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is effects prefix, False otherwise.

isIdentifierNode()

functionisIdentifierNode(node?: Node): node is Identifier;

Determines whether the specified node is an Identifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Identifier

True if the specified token is an Identifier, False otherwise.

isLambdaNode()

functionisLambdaNode(node?: Node): node is LambdaExpression;

Determines whether the specified node is a LambdaExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LambdaExpression

True if the specified token is a LambdaExpression, False otherwise.

isLetDeclaratorNode()

functionisLetDeclaratorNode(node?: Node): node is LetDeclarator;

Determines whether the specified node is a LetDeclarator.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetDeclarator

True if the specified token is a LetDeclarator, False otherwise.

isLetNode()

functionisLetNode(node?: Node): node is LetExpression;

Determines whether the specified node is a LetExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetExpression

True if the specified token is a LetExpression, False otherwise.

isLiteral()

functionisLiteral(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a literal.

Returns true if the input is a token of type BOOLEAN (TRUE or FALSE), ERROR (#VALUE!), NUMBER (123.4), or STRING ("lorem ipsum"). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is literal, False otherwise.

isLiteralNode()

functionisLiteralNode(node?: Node): node is Literal;

Determines whether the specified node is a Literal.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Literal

True if the specified token is a Literal, False otherwise.

isOperator()

functionisOperator(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an operator.

Returns true if the input is a token of type OPERATOR (+ or :). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is operator, False otherwise.

isRange()

functionisRange(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a range.

Returns true if the input is a token that has a type of either REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), or REF_BEAM (A:A or 1:1). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">A token

Returns

boolean

True if the specified token is range, False otherwise.

isReference()

functionisReference(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a reference.

Returns true if the input is a token of type REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), REF_BEAM (A:A or 1:1), or REF_NAMED (myrange). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is reference, False otherwise.

isReferenceNode()

functionisReferenceNode(node?: Node): node is ReferenceIdentifier;

Determines whether the specified node is a ReferenceIdentifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ReferenceIdentifier

True if the specified token is a ReferenceIdentifier, False otherwise.

isUnaryNode()

functionisUnaryNode(node?: Node): node is UnaryExpression;

Determines whether the specified node is a UnaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is UnaryExpression

True if the specified token is a UnaryExpression, False otherwise.

isWhitespace()

functionisWhitespace(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is whitespace.

Returns true if the input is a token of type WHITESPACE () or NEWLINE (\n). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is whitespace, False otherwise.

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parse()

functionparse(tokenlist: Token[],options?: OptsParse): AstExpression;

Parses a string formula or list of tokens into an AST.

The parser assumes mergeRefs and negativeNumbers were true when the tokens were generated. It does not yet recognize reference context tokens or know how to deal with unary minuses in arrays.

The AST Abstract Syntax Tree's format is documented in AST_format.md.

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.
optionsOptsParseOptions for the parsers behavior.

Returns

AstExpression

An AST of nodes.

See

parseA1Range()

functionparseA1Range(rangeString: string,allowTernary?: boolean): RangeA1;

Parse A1-style range string into a RangeA1 object.

Parameters

ParameterTypeDefault valueDescription
rangeStringstringundefinedA1-style range string.
allowTernary?booleantruePermit ternary ranges like A2:A or B2:2.

Returns

RangeA1

A reference object.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1|ReferenceName;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// context: [ 'Sheet1' ],// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1 | ReferenceName

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Range()

functionparseR1C1Range(rangeString: string): RangeR1C1;

Parse R1C1-style range string into a RangeR1C1 object.

Parameters

ParameterTypeDescription
rangeStringstringR1C1-style range string.

Returns

RangeR1C1

A reference object.

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceName|ReferenceR1C1;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceName | ReferenceR1C1

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStruct;

Parse a structured reference string into an object representing it.

parseStructRef('workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]');// => {// context: [ 'workbook.xlsx' ],// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStruct

An object representing a valid reference or undefined if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1|ReferenceName): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({context: ['Sheet1'],range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1 | ReferenceNameA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceName|ReferenceR1C1): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({context: ['Sheet1'],range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceName | ReferenceR1C1A reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStruct,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({context: ['workbook.xlsx'],sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

See

OptsStringifyStructRef

stringifyTokens()

functionstringifyTokens(tokens: Token[]): string;

Collapses a list of tokens into a formula string.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens.

Returns

string

A formula string.

toCol()

functiontoCol(columnIndex: number): string;

Convert a 0 based offset number to a column string representation (0 = "A", 2 = "C").

The method expects a number between 0 and 16383. Other input will return garbage.

Parameters

ParameterTypeDescription
columnIndexnumberZero based column index number

Returns

string

The column string identifier

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parsers will need to handle this.

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

translateFormulaToA1()

functiontranslateFormulaToA1(formula: string,anchorCell: string,options?: OptsTranslateFormulaToA1): string;

Translates ranges in a formula from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so you can set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Parameters

ParameterTypeDescription
formulastringAn Excel formula string that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateFormulaToA1Translation options.

Returns

string

A formula string.

See

OptsTranslateFormulaToA1

translateFormulaToR1C1()

functiontranslateFormulaToR1C1(formula: string,anchorCell: string,options?: OptsTranslateToR1C1): string;

Translates ranges in a formula from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
formulastringAn Excel formula that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
options?OptsTranslateToR1C1The options

Returns

string

A formula string.

See

OptsTranslateToR1C1

translateTokensToA1()

functiontranslateTokensToA1(tokens: Token[],anchorCell: string,options?: OptsTranslateTokensToA1): Token[];

Translates ranges in a list of tokens from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so may set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Note that if you are passing in a list of tokens that was not created using mergeRefs and you disable edge wrapping (or you simply set both options to false), you can end up with a formula such as =#REF!:B2 or =Sheet3!#REF!:F3. These are valid formulas in the Excel formula language and Excel will accept them, but they are not supported in Google Sheets.

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateTokensToA1Translation options.

Returns

Token[]

A token list.

See

OptsTranslateTokensToA1

translateTokensToR1C1()

functiontranslateTokensToR1C1(tokens: Token[],anchorCell: string): Token[];

Translates ranges in a list of tokens from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).

Returns

Token[]

A token list.

ArrayExpression

typeArrayExpression={elements: (|ReferenceIdentifier|Literal|ErrorLiteral|CallExpression)[][];loc?: SourceLocation;type: "ArrayExpression";}&Node;

An array expression. Excel does not have empty or sparse arrays and restricts array elements to literals. Google Sheets allows ReferenceIdentifiers and CallExpressions as elements of arrays, the fx parser has options for this but they are off by default.

Type Declaration

NameTypeDescription
elements( | ReferenceIdentifier | Literal | ErrorLiteral | CallExpression)[][]The elements of the array.
loc?SourceLocationThe original source position of the node.
type"ArrayExpression"The type of this AST node.

AstExpression

typeAstExpression=|ReferenceIdentifier|Literal|ErrorLiteral|UnaryExpression|BinaryExpression|CallExpression|ArrayExpression|LambdaExpression|LetExpression;

Represents an evaluate-able expression.

BinaryExpression

typeBinaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: BinaryOperator;type: "BinaryExpression";}&Node;

A binary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorBinaryOperatorThe expression's operator.
type"BinaryExpression"The type of this AST node.

BinaryOperator

typeBinaryOperator=|"="|"<"|">"|"<="|">="|"<>"|"-"|"+"|"*"|"/"|"^"|":"|" "|","|"&";

A binary operator token.

Note that Excels union operator is whitespace so a parser must take care to normalize this to a single space.

CallExpression

typeCallExpression={arguments: AstExpression[];callee: Identifier;loc?: SourceLocation;type: "CallExpression";}&Node;

A function call expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the function.
calleeIdentifierThe function being called.
loc?SourceLocationThe original source position of the node.
type"CallExpression"The type of this AST node.

ErrorLiteral

typeErrorLiteral={loc?: SourceLocation;raw: string;type: "ErrorLiteral";value: string;}&Node;

An Error expression.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"ErrorLiteral"The type of this AST node.
valuestringThe value of the error.

Identifier

typeIdentifier={loc?: SourceLocation;name: string;type: "Identifier";}&Node;

An identifier. These appear on CallExpression, LambdaExpression, and LetExpression and will always be a static string representing the name of a function call or parameter.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
namestringThe identifying name.
type"Identifier"The type of this AST node.

LambdaExpression

typeLambdaExpression={body: AstExpression|null;loc?: SourceLocation;params: Identifier[];type: "LambdaExpression";}&Node;

A LAMBDA expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LAMBDA's expression.
loc?SourceLocationThe original source position of the node.
paramsIdentifier[]The LAMBDA's parameters.
type"LambdaExpression"The type of this AST node.

LetDeclarator

typeLetDeclarator={id: Identifier;init: AstExpression|null;loc?: SourceLocation;type: "LetDeclarator";}&Node;

A LET parameter declaration.

Type Declaration

NameTypeDescription
idIdentifierThe name of the variable.
initAstExpression | nullThe variable's initializing expression.
loc?SourceLocationThe original source position of the node.
type"LetDeclarator"The type of this AST node.

LetExpression

typeLetExpression={body: AstExpression|null;declarations: LetDeclarator[];loc?: SourceLocation;type: "LetExpression";}&Node;

A LET expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LET's scoped expression.
declarationsLetDeclarator[]The LET's variable declarations.
loc?SourceLocationThe original source position of the node.
type"LetExpression"The type of this AST node.

Literal

typeLiteral={loc?: SourceLocation;raw: string;type: "Literal";value: string|number|boolean;}&Node;

A literal token. Captures numbers, strings, and booleans. Literal errors have their own variant type.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"Literal"The type of this AST node.
valuestring | number | booleanThe value of the literal.

Node

typeNode={loc?: SourceLocation;type: string;};

All AST nodes are represented by Node objects. They may have any prototype inheritance but implement the same basic interface.

The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements.

Properties

PropertyTypeDescription
loc?SourceLocationThe original source position of the node.
typestringThe type of this AST node.

OptsFixRanges

typeOptsFixRanges={addBounds?: boolean;thisRow?: boolean;};

Options for fixTokenRanges and fixFormulaRanges.

Properties

PropertyTypeDefault valueDescription
addBounds?booleanfalseFill in any undefined bounds of range objects. Top to 0, bottom to 1048575, left to 0, and right to 16383.
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsParse

typeOptsParse={looseRefCalls?: boolean;permitArrayCalls?: boolean;permitArrayRanges?: boolean;};

Options for parse.

Properties

PropertyTypeDefault valueDescription
looseRefCalls?booleanfalsePermits any function call where otherwise only functions that return references would be permitted.
permitArrayCalls?booleanfalseFunction calls are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.
permitArrayRanges?booleanfalseRanges are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.

OptsParseA1Ref

typeOptsParseA1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseA1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsParseR1C1Ref

typeOptsParseR1C1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseR1C1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsStringifyStructRef

typeOptsStringifyStructRef={thisRow?: boolean;};

Options for stringifyStructRef

Properties

PropertyTypeDefault valueDescription
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsTokenize

typeOptsTokenize={allowTernary?: boolean;mergeRefs?: boolean;negativeNumbers?: boolean;r1c1?: boolean;withLocation?: boolean;};

Options for tokenize.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be returned as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2). This is the same as calling mergeRefTokens
negativeNumbers?booleantrueMerges unary minuses with their immediately following number tokens (-,1) => -1 (alternatively these will be unary operations in the tree).
r1c1?booleanfalseRanges are expected to be in the R1C1 style format rather than the more popular A1 style.
withLocation?booleantrueNodes will include source position offsets to the tokens: { loc: [ start, end ] }

OptsTranslateFormulaToA1

typeOptsTranslateFormulaToA1={allowTernary?: boolean;mergeRefs?: boolean;wrapEdges?: boolean;};

Options for translateFormulaToA1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be treated as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2).
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

OptsTranslateToR1C1

typeOptsTranslateToR1C1={allowTernary?: boolean;};

Options for translateFormulaToR1C1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsTranslateTokensToA1

typeOptsTranslateTokensToA1={wrapEdges?: boolean;};

Options for translateTokensToA1

Properties

PropertyTypeDefault valueDescription
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

RangeA1

typeRangeA1={$bottom?: boolean|null;$left?: boolean|null;$right?: boolean|null;$top?: boolean|null;bottom?: number|null;left: number|null;right?: number|null;top: number|null;trim?: "head"|"tail"|"both"|null;};

A range in A1 style coordinates.

Properties

PropertyTypeDescription
$bottom?boolean | nullSignifies that bottom is a "locked" value
$left?boolean | nullSignifies that left is a "locked" value
$right?boolean | nullSignifies that right is a "locked" value
$top?boolean | nullSignifies that top is a "locked" value
bottom?number | nullBottom row of the range
leftnumber | nullLeft column of the range
right?number | nullRight column of the range
topnumber | nullTop row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

RangeR1C1

typeRangeR1C1={$c0?: boolean|null;$c1?: boolean|null;$r0?: boolean|null;$r1?: boolean|null;c0?: number|null;c1?: number|null;r0?: number|null;r1?: number|null;trim?: "head"|"tail"|"both"|null;};

A range in R1C1 style coordinates.

Properties

PropertyTypeDescription
$c0?boolean | nullSignifies that c0 is an absolute value
$c1?boolean | nullSignifies that c1 is an absolute value
$r0?boolean | nullSignifies that r0 is an absolute value
$r1?boolean | nullSignifies that r1 is an absolute value
c0?number | nullLeft column of the range
c1?number | nullRight column of the range
r0?number | nullTop row of the range
r1?number | nullBottom row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

ReferenceA1

typeReferenceA1={context?: string[];range: RangeA1;};

A reference containing an A1 style range. See Prefixes.md for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeA1The reference's range

ReferenceA1Xlsx

typeReferenceA1Xlsx={range: RangeA1;sheetName?: string;workbookName?: string;};

A reference containing an A1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeA1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceIdentifier

typeReferenceIdentifier={kind: "name"|"range"|"beam"|"table";loc?: SourceLocation;type: "ReferenceIdentifier";value: string;}&Node;

An identifier for a range or a name.

Type Declaration

NameTypeDescription
kind"name" | "range" | "beam" | "table"The kind of reference the value holds.
loc?SourceLocationThe original source position of the node.
type"ReferenceIdentifier"The type of this AST node.
valuestringThe untouched reference value.

ReferenceName

typeReferenceName={context?: string[];name: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
namestringThe reference's name

ReferenceNameXlsx

typeReferenceNameXlsx={name: string;sheetName?: string;workbookName?: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
namestringThe reference's name
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceR1C1

typeReferenceR1C1={context?: string[];range: RangeR1C1;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeR1C1The reference's range

ReferenceR1C1Xlsx

typeReferenceR1C1Xlsx={range: RangeR1C1;sheetName?: string;workbookName?: string;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeR1C1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceStruct

typeReferenceStruct={columns?: string[];context?: string[];sections?: string[];table?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
context?string[]A collection of scopes for the reference
sections?string[]The sections this reference targets
table?stringThe table this reference targets

ReferenceStructXlsx

typeReferenceStructXlsx={columns?: string[];sections?: string[];sheetName?: string;table?: string;workbookName?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
sections?string[]The sections this reference targets
sheetName?stringA context sheet scope
table?stringThe table this reference targets
workbookName?stringA context workbook scope

SourceLocation

typeSourceLocation=number[];

Represents the source location information of the node. If the node contains no information about the source location, the field is null; otherwise it is an array consisting of a two numbers: A start offset (the position of the first character of the parsed source region) and an end offset (the position of the first character after the parsed source region).

Token

typeToken=Record<string,unknown>&{loc?: number[];type: string;unterminated?: boolean;value: string;};

A formula language token.

Type Declaration

NameTypeDescription
loc?number[]Source position offsets to the token
typestringThe type of the token
unterminated?booleanSignifies an unterminated string token
valuestringThe value of the token

TokenEnhanced

typeTokenEnhanced=Token&{depth?: number;error?: boolean;groupId?: string;index: number;};

A token with extra meta data.

Type Declaration

NameTypeDescription
depth?numberThis token's level of nesting inside parentheses
error?booleanToken is of unknown type or a paren without a match
groupId?stringThe ID of a group which this token belongs (e.g. matching parens)
indexnumberA zero based position in a token list

UnaryExpression

typeUnaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: UnaryOperator;type: "UnaryExpression";}&Node;

A unary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorUnaryOperatorThe expression's operator.
type"UnaryExpression"The type of this AST node.

UnaryOperator

typeUnaryOperator="+"|"-"|"%"|"#"|"@";

A unary operator token.

MAX_COLS

constMAX_COLS: number;

The maximum number of columns a spreadsheet reference may hold (16383).

MAX_ROWS

constMAX_ROWS: number;

The maximum number of rows a spreadsheet reference may hold (1048575).

nodeTypes

constnodeTypes: Readonly<{ARRAY: "ArrayExpression";BINARY: "BinaryExpression";CALL: "CallExpression";ERROR: "ErrorLiteral";IDENTIFIER: "Identifier";LAMBDA: "LambdaExpression";LET: "LetExpression";LET_DECL: "LetDeclarator";LITERAL: "Literal";REFERENCE: "ReferenceIdentifier";UNARY: "UnaryExpression";}>;

A dictionary of the types used to identify AST node variants.

tokenTypes

consttokenTypes: Readonly<{BOOLEAN: "bool";CONTEXT: "context";CONTEXT_QUOTE: "context_quote";ERROR: "error";FUNCTION: "func";FX_PREFIX: "fx_prefix";NEWLINE: "newline";NUMBER: "number";OPERATOR: "operator";REF_BEAM: "range_beam";REF_NAMED: "range_named";REF_RANGE: "range";REF_STRUCT: "structured";REF_TERNARY: "range_ternary";STRING: "string";UNKNOWN: "unknown";WHITESPACE: "whitespace";}>;

A dictionary of the types used to identify token variants.

fx/xlsx

A tokenizer, parser, and other utilities to work with Excel formula code.

The xslx entry-point methods expect and return the variant of references that uses properties. If you are not using xlsx files you should use the fx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Functions

References

addA1RangeBounds

Re-exports addA1RangeBounds


ArrayExpression

Re-exports ArrayExpression


AstExpression

Re-exports AstExpression


BinaryExpression

Re-exports BinaryExpression


BinaryOperator

Re-exports BinaryOperator


CallExpression

Re-exports CallExpression


ErrorLiteral

Re-exports ErrorLiteral


fromCol

Re-exports fromCol


Identifier

Re-exports Identifier


isArrayNode

Re-exports isArrayNode


isBinaryNode

Re-exports isBinaryNode


isCallNode

Re-exports isCallNode


isError

Re-exports isError


isErrorNode

Re-exports isErrorNode


isExpressionNode

Re-exports isExpressionNode


isFunction

Re-exports isFunction


isFxPrefix

Re-exports isFxPrefix


isIdentifierNode

Re-exports isIdentifierNode


isLambdaNode

Re-exports isLambdaNode


isLetDeclaratorNode

Re-exports isLetDeclaratorNode


isLetNode

Re-exports isLetNode


isLiteral

Re-exports isLiteral


isLiteralNode

Re-exports isLiteralNode


isOperator

Re-exports isOperator


isRange

Re-exports isRange


isReference

Re-exports isReference


isReferenceNode

Re-exports isReferenceNode


isUnaryNode

Re-exports isUnaryNode


isWhitespace

Re-exports isWhitespace


LambdaExpression

Re-exports LambdaExpression


LetDeclarator

Re-exports LetDeclarator


LetExpression

Re-exports LetExpression


Literal

Re-exports Literal


MAX_COLS

Re-exports MAX_COLS


MAX_ROWS

Re-exports MAX_ROWS


Node

Re-exports Node


nodeTypes

Re-exports nodeTypes


OptsFixRanges

Re-exports OptsFixRanges


OptsParse

Re-exports OptsParse


OptsParseA1Ref

Re-exports OptsParseA1Ref


OptsParseR1C1Ref

Re-exports OptsParseR1C1Ref


OptsStringifyStructRef

Re-exports OptsStringifyStructRef


OptsTokenize

Re-exports OptsTokenize


OptsTranslateFormulaToA1

Re-exports OptsTranslateFormulaToA1


OptsTranslateTokensToA1

Re-exports OptsTranslateTokensToA1


OptsTranslateToR1C1

Re-exports OptsTranslateToR1C1


parse

Re-exports parse


parseA1Range

Re-exports parseA1Range


parseR1C1Range

Re-exports parseR1C1Range


RangeA1

Re-exports RangeA1


RangeR1C1

Re-exports RangeR1C1


ReferenceA1

Re-exports ReferenceA1


ReferenceA1Xlsx

Re-exports ReferenceA1Xlsx


ReferenceIdentifier

Re-exports ReferenceIdentifier


ReferenceName

Re-exports ReferenceName


ReferenceNameXlsx

Re-exports ReferenceNameXlsx


ReferenceR1C1

Re-exports ReferenceR1C1


ReferenceR1C1Xlsx

Re-exports ReferenceR1C1Xlsx


ReferenceStruct

Re-exports ReferenceStruct


ReferenceStructXlsx

Re-exports ReferenceStructXlsx


SourceLocation

Re-exports SourceLocation


stringifyTokens

Re-exports stringifyTokens


toCol

Re-exports toCol


Token

Re-exports Token


TokenEnhanced

Re-exports TokenEnhanced


tokenTypes

Re-exports tokenTypes


translateFormulaToA1

Re-exports translateFormulaToA1


translateFormulaToR1C1

Re-exports translateFormulaToR1C1


translateTokensToA1

Re-exports translateTokensToA1


translateTokensToR1C1

Re-exports translateTokensToR1C1


UnaryExpression

Re-exports UnaryExpression


UnaryOperator

Re-exports UnaryOperator

addTokenMeta()

functionaddTokenMeta(tokenlist: Token[],context?: {sheetName?: string;workbookName?: string;}): TokenEnhanced[];

Runs through a list of tokens and adds extra attributes such as matching parens and ranges.

The context parameter defines default reference attributes: { workbookName: 'report.xlsx', sheetName: 'Sheet1' }. If supplied, these are used to match A1 to Sheet1!A1.

All tokens will be tagged with a .depth number value to indicating the level of nesting in parentheses as well as an .index number indicating their zero based position in the list.

The returned output will be the same array of tokens but the following properties will added to tokens (as applicable):

Parentheses ( )

Matching parens will be tagged with .groupId string identifier as well as a .depth number value (indicating the level of nesting).

Closing parens without a counterpart will be tagged with .error (boolean true).

Curly brackets { }

Matching curly brackets will be tagged with .groupId string identifier. These may not be nested in Excel.

Closing curly brackets without a counterpart will be tagged with .error (boolean true).

Ranges (REF_RANGE or REF_BEAM type tokens)

All ranges will be tagged with .groupId string identifier regardless of the number of times they occur.

Tokens of type UNKNOWN

All will be tagged with .error (boolean true).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens (from tokenize())
context?{ sheetName?: string; workbookName?: string; }A context used to match A1 to Sheet1!A1.
context.sheetName?stringAn implied sheet name ('Sheet1')
context.workbookName?stringAn implied workbook name ('report.xlsx')

Returns

TokenEnhanced[]

The input array with the enchanced tokens

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens and returns a new array of tokens with values and position-data updated.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Unlike Excel, fx does not normalize sheet or workbook names of references.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1Xlsx|ReferenceNameXlsx;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// workbookName: '',// sheetName: 'Sheet1',// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1Xlsx | ReferenceNameXlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceNameXlsx|ReferenceR1C1Xlsx;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceNameXlsx | ReferenceR1C1Xlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStructXlsx;

Parse a structured reference string into an object representing it.

parseStructRef('[workbook.xlsx]!tableName[[#Data],[Column1]:[Column2]]');// => {// workbookName: 'workbook.xlsx',// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStructXlsx

An object representing a valid reference or null if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1Xlsx|ReferenceNameXlsx): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({sheetName: 'Sheet1',range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1Xlsx | ReferenceNameXlsxA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceNameXlsx|ReferenceR1C1Xlsx): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({sheetName: 'Sheet1',range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceNameXlsx | ReferenceR1C1XlsxA reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStructXlsx,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({workbookName: 'workbook.xlsx',sheetName: '',sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructXlsxA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
3323 lines (2177 loc) · 76.1 KB

File metadata and controls

3323 lines (2177 loc) · 76.1 KB

@borgar/fx

Modules

fx

A tokenizer, parser, and other utilities to work with Excel formula code.

The base entry-point methods expect and return the variant of references that uses contexts. If you are using xlsx files or otherwise want to work with the xlsx-file variant of references you should use the fx/xlsx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Type Aliases

Variables

Functions

addA1RangeBounds()

functionaddA1RangeBounds(range: RangeA1): RangeA1;

Fill the any missing bounds in range objects. Top will be set to 0, bottom to 1048575, left to 0, and right to 16383, if they are null or undefined.

addA1RangeBounds({top: 0,left: 0,bottom: 1,$top: true,$left: false,$bottom: false,});// => {// top: 0,// left: 0,// bottom: 1,// right: 16383, // ← Added// $top: true,// $left: false,// $bottom: false,// $right: false // ← Added// }

Parameters

ParameterTypeDescription
rangeRangeA1The range part of a reference object.

Returns

RangeA1

The same range with missing bounds filled in.

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Returns a new array of tokens with values and position data updated.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

fromCol()

functionfromCol(columnString: string): number;

Convert a column string representation to a 0 based offset number ("C" = 2).

The method expects a valid column identifier made up of only A-Z letters, which may be either upper or lower case. Other input will return garbage.

Parameters

ParameterTypeDescription
columnStringstringThe column string identifier

Returns

number

Zero based column index number

isArrayNode()

functionisArrayNode(node?: Node): node is ArrayExpression;

Determines whether the specified node is a ArrayExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ArrayExpression

True if the specified token is a ArrayExpression, False otherwise.

isBinaryNode()

functionisBinaryNode(node?: Node): node is BinaryExpression;

Determines whether the specified node is a BinaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is BinaryExpression

True if the specified token is a BinaryExpression, False otherwise.

isCallNode()

functionisCallNode(node?: Node): node is CallExpression;

Determines whether the specified node is a CallExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is CallExpression

True if the specified token is a CallExpression, False otherwise.

isError()

functionisError(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an error.

Returns true if the input is a token of type ERROR (#VALUE!). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is error, False otherwise.

isErrorNode()

functionisErrorNode(node?: Node): node is ErrorLiteral;

Determines whether the specified node is an ErrorLiteral.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ErrorLiteral

True if the specified token is an ErrorLiteral, False otherwise.

isExpressionNode()

functionisExpressionNode(node?: Node): node is AstExpression;

Determines whether the specified node is a AstExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is AstExpression

True if the specified token is a AstExpression, False otherwise.

isFunction()

functionisFunction(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a function.

Returns true if the input is a token of type FUNCTION. In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is function, False otherwise.

isFxPrefix()

functionisFxPrefix(token?: Pick<Token,"type">): boolean;

Returns true if the input is a token of type FX_PREFIX (leading = in formula). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is effects prefix, False otherwise.

isIdentifierNode()

functionisIdentifierNode(node?: Node): node is Identifier;

Determines whether the specified node is an Identifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Identifier

True if the specified token is an Identifier, False otherwise.

isLambdaNode()

functionisLambdaNode(node?: Node): node is LambdaExpression;

Determines whether the specified node is a LambdaExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LambdaExpression

True if the specified token is a LambdaExpression, False otherwise.

isLetDeclaratorNode()

functionisLetDeclaratorNode(node?: Node): node is LetDeclarator;

Determines whether the specified node is a LetDeclarator.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetDeclarator

True if the specified token is a LetDeclarator, False otherwise.

isLetNode()

functionisLetNode(node?: Node): node is LetExpression;

Determines whether the specified node is a LetExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetExpression

True if the specified token is a LetExpression, False otherwise.

isLiteral()

functionisLiteral(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a literal.

Returns true if the input is a token of type BOOLEAN (TRUE or FALSE), ERROR (#VALUE!), NUMBER (123.4), or STRING ("lorem ipsum"). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is literal, False otherwise.

isLiteralNode()

functionisLiteralNode(node?: Node): node is Literal;

Determines whether the specified node is a Literal.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Literal

True if the specified token is a Literal, False otherwise.

isOperator()

functionisOperator(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an operator.

Returns true if the input is a token of type OPERATOR (+ or :). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is operator, False otherwise.

isRange()

functionisRange(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a range.

Returns true if the input is a token that has a type of either REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), or REF_BEAM (A:A or 1:1). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">A token

Returns

boolean

True if the specified token is range, False otherwise.

isReference()

functionisReference(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a reference.

Returns true if the input is a token of type REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), REF_BEAM (A:A or 1:1), or REF_NAMED (myrange). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is reference, False otherwise.

isReferenceNode()

functionisReferenceNode(node?: Node): node is ReferenceIdentifier;

Determines whether the specified node is a ReferenceIdentifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ReferenceIdentifier

True if the specified token is a ReferenceIdentifier, False otherwise.

isUnaryNode()

functionisUnaryNode(node?: Node): node is UnaryExpression;

Determines whether the specified node is a UnaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is UnaryExpression

True if the specified token is a UnaryExpression, False otherwise.

isWhitespace()

functionisWhitespace(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is whitespace.

Returns true if the input is a token of type WHITESPACE () or NEWLINE (\n). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is whitespace, False otherwise.

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parse()

functionparse(tokenlist: Token[],options?: OptsParse): AstExpression;

Parses a string formula or list of tokens into an AST.

The parser assumes mergeRefs and negativeNumbers were true when the tokens were generated. It does not yet recognize reference context tokens or know how to deal with unary minuses in arrays.

The AST Abstract Syntax Tree's format is documented in AST_format.md.

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.
optionsOptsParseOptions for the parsers behavior.

Returns

AstExpression

An AST of nodes.

See

parseA1Range()

functionparseA1Range(rangeString: string,allowTernary?: boolean): RangeA1;

Parse A1-style range string into a RangeA1 object.

Parameters

ParameterTypeDefault valueDescription
rangeStringstringundefinedA1-style range string.
allowTernary?booleantruePermit ternary ranges like A2:A or B2:2.

Returns

RangeA1

A reference object.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1|ReferenceName;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// context: [ 'Sheet1' ],// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1 | ReferenceName

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Range()

functionparseR1C1Range(rangeString: string): RangeR1C1;

Parse R1C1-style range string into a RangeR1C1 object.

Parameters

ParameterTypeDescription
rangeStringstringR1C1-style range string.

Returns

RangeR1C1

A reference object.

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceName|ReferenceR1C1;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceName | ReferenceR1C1

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStruct;

Parse a structured reference string into an object representing it.

parseStructRef('workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]');// => {// context: [ 'workbook.xlsx' ],// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStruct

An object representing a valid reference or undefined if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1|ReferenceName): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({context: ['Sheet1'],range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1 | ReferenceNameA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceName|ReferenceR1C1): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({context: ['Sheet1'],range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceName | ReferenceR1C1A reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStruct,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({context: ['workbook.xlsx'],sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

See

OptsStringifyStructRef

stringifyTokens()

functionstringifyTokens(tokens: Token[]): string;

Collapses a list of tokens into a formula string.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens.

Returns

string

A formula string.

toCol()

functiontoCol(columnIndex: number): string;

Convert a 0 based offset number to a column string representation (0 = "A", 2 = "C").

The method expects a number between 0 and 16383. Other input will return garbage.

Parameters

ParameterTypeDescription
columnIndexnumberZero based column index number

Returns

string

The column string identifier

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parsers will need to handle this.

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

translateFormulaToA1()

functiontranslateFormulaToA1(formula: string,anchorCell: string,options?: OptsTranslateFormulaToA1): string;

Translates ranges in a formula from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so you can set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Parameters

ParameterTypeDescription
formulastringAn Excel formula string that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateFormulaToA1Translation options.

Returns

string

A formula string.

See

OptsTranslateFormulaToA1

translateFormulaToR1C1()

functiontranslateFormulaToR1C1(formula: string,anchorCell: string,options?: OptsTranslateToR1C1): string;

Translates ranges in a formula from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
formulastringAn Excel formula that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
options?OptsTranslateToR1C1The options

Returns

string

A formula string.

See

OptsTranslateToR1C1

translateTokensToA1()

functiontranslateTokensToA1(tokens: Token[],anchorCell: string,options?: OptsTranslateTokensToA1): Token[];

Translates ranges in a list of tokens from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so may set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Note that if you are passing in a list of tokens that was not created using mergeRefs and you disable edge wrapping (or you simply set both options to false), you can end up with a formula such as =#REF!:B2 or =Sheet3!#REF!:F3. These are valid formulas in the Excel formula language and Excel will accept them, but they are not supported in Google Sheets.

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateTokensToA1Translation options.

Returns

Token[]

A token list.

See

OptsTranslateTokensToA1

translateTokensToR1C1()

functiontranslateTokensToR1C1(tokens: Token[],anchorCell: string): Token[];

Translates ranges in a list of tokens from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).

Returns

Token[]

A token list.

ArrayExpression

typeArrayExpression={elements: (|ReferenceIdentifier|Literal|ErrorLiteral|CallExpression)[][];loc?: SourceLocation;type: "ArrayExpression";}&Node;

An array expression. Excel does not have empty or sparse arrays and restricts array elements to literals. Google Sheets allows ReferenceIdentifiers and CallExpressions as elements of arrays, the fx parser has options for this but they are off by default.

Type Declaration

NameTypeDescription
elements( | ReferenceIdentifier | Literal | ErrorLiteral | CallExpression)[][]The elements of the array.
loc?SourceLocationThe original source position of the node.
type"ArrayExpression"The type of this AST node.

AstExpression

typeAstExpression=|ReferenceIdentifier|Literal|ErrorLiteral|UnaryExpression|BinaryExpression|CallExpression|ArrayExpression|LambdaExpression|LetExpression;

Represents an evaluate-able expression.

BinaryExpression

typeBinaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: BinaryOperator;type: "BinaryExpression";}&Node;

A binary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorBinaryOperatorThe expression's operator.
type"BinaryExpression"The type of this AST node.

BinaryOperator

typeBinaryOperator=|"="|"<"|">"|"<="|">="|"<>"|"-"|"+"|"*"|"/"|"^"|":"|" "|","|"&";

A binary operator token.

Note that Excels union operator is whitespace so a parser must take care to normalize this to a single space.

CallExpression

typeCallExpression={arguments: AstExpression[];callee: Identifier;loc?: SourceLocation;type: "CallExpression";}&Node;

A function call expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the function.
calleeIdentifierThe function being called.
loc?SourceLocationThe original source position of the node.
type"CallExpression"The type of this AST node.

ErrorLiteral

typeErrorLiteral={loc?: SourceLocation;raw: string;type: "ErrorLiteral";value: string;}&Node;

An Error expression.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"ErrorLiteral"The type of this AST node.
valuestringThe value of the error.

Identifier

typeIdentifier={loc?: SourceLocation;name: string;type: "Identifier";}&Node;

An identifier. These appear on CallExpression, LambdaExpression, and LetExpression and will always be a static string representing the name of a function call or parameter.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
namestringThe identifying name.
type"Identifier"The type of this AST node.

LambdaExpression

typeLambdaExpression={body: AstExpression|null;loc?: SourceLocation;params: Identifier[];type: "LambdaExpression";}&Node;

A LAMBDA expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LAMBDA's expression.
loc?SourceLocationThe original source position of the node.
paramsIdentifier[]The LAMBDA's parameters.
type"LambdaExpression"The type of this AST node.

LetDeclarator

typeLetDeclarator={id: Identifier;init: AstExpression|null;loc?: SourceLocation;type: "LetDeclarator";}&Node;

A LET parameter declaration.

Type Declaration

NameTypeDescription
idIdentifierThe name of the variable.
initAstExpression | nullThe variable's initializing expression.
loc?SourceLocationThe original source position of the node.
type"LetDeclarator"The type of this AST node.

LetExpression

typeLetExpression={body: AstExpression|null;declarations: LetDeclarator[];loc?: SourceLocation;type: "LetExpression";}&Node;

A LET expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LET's scoped expression.
declarationsLetDeclarator[]The LET's variable declarations.
loc?SourceLocationThe original source position of the node.
type"LetExpression"The type of this AST node.

Literal

typeLiteral={loc?: SourceLocation;raw: string;type: "Literal";value: string|number|boolean;}&Node;

A literal token. Captures numbers, strings, and booleans. Literal errors have their own variant type.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"Literal"The type of this AST node.
valuestring | number | booleanThe value of the literal.

Node

typeNode={loc?: SourceLocation;type: string;};

All AST nodes are represented by Node objects. They may have any prototype inheritance but implement the same basic interface.

The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements.

Properties

PropertyTypeDescription
loc?SourceLocationThe original source position of the node.
typestringThe type of this AST node.

OptsFixRanges

typeOptsFixRanges={addBounds?: boolean;thisRow?: boolean;};

Options for fixTokenRanges and fixFormulaRanges.

Properties

PropertyTypeDefault valueDescription
addBounds?booleanfalseFill in any undefined bounds of range objects. Top to 0, bottom to 1048575, left to 0, and right to 16383.
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsParse

typeOptsParse={looseRefCalls?: boolean;permitArrayCalls?: boolean;permitArrayRanges?: boolean;};

Options for parse.

Properties

PropertyTypeDefault valueDescription
looseRefCalls?booleanfalsePermits any function call where otherwise only functions that return references would be permitted.
permitArrayCalls?booleanfalseFunction calls are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.
permitArrayRanges?booleanfalseRanges are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.

OptsParseA1Ref

typeOptsParseA1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseA1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsParseR1C1Ref

typeOptsParseR1C1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseR1C1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsStringifyStructRef

typeOptsStringifyStructRef={thisRow?: boolean;};

Options for stringifyStructRef

Properties

PropertyTypeDefault valueDescription
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsTokenize

typeOptsTokenize={allowTernary?: boolean;mergeRefs?: boolean;negativeNumbers?: boolean;r1c1?: boolean;withLocation?: boolean;};

Options for tokenize.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be returned as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2). This is the same as calling mergeRefTokens
negativeNumbers?booleantrueMerges unary minuses with their immediately following number tokens (-,1) => -1 (alternatively these will be unary operations in the tree).
r1c1?booleanfalseRanges are expected to be in the R1C1 style format rather than the more popular A1 style.
withLocation?booleantrueNodes will include source position offsets to the tokens: { loc: [ start, end ] }

OptsTranslateFormulaToA1

typeOptsTranslateFormulaToA1={allowTernary?: boolean;mergeRefs?: boolean;wrapEdges?: boolean;};

Options for translateFormulaToA1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be treated as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2).
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

OptsTranslateToR1C1

typeOptsTranslateToR1C1={allowTernary?: boolean;};

Options for translateFormulaToR1C1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsTranslateTokensToA1

typeOptsTranslateTokensToA1={wrapEdges?: boolean;};

Options for translateTokensToA1

Properties

PropertyTypeDefault valueDescription
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

RangeA1

typeRangeA1={$bottom?: boolean|null;$left?: boolean|null;$right?: boolean|null;$top?: boolean|null;bottom?: number|null;left: number|null;right?: number|null;top: number|null;trim?: "head"|"tail"|"both"|null;};

A range in A1 style coordinates.

Properties

PropertyTypeDescription
$bottom?boolean | nullSignifies that bottom is a "locked" value
$left?boolean | nullSignifies that left is a "locked" value
$right?boolean | nullSignifies that right is a "locked" value
$top?boolean | nullSignifies that top is a "locked" value
bottom?number | nullBottom row of the range
leftnumber | nullLeft column of the range
right?number | nullRight column of the range
topnumber | nullTop row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

RangeR1C1

typeRangeR1C1={$c0?: boolean|null;$c1?: boolean|null;$r0?: boolean|null;$r1?: boolean|null;c0?: number|null;c1?: number|null;r0?: number|null;r1?: number|null;trim?: "head"|"tail"|"both"|null;};

A range in R1C1 style coordinates.

Properties

PropertyTypeDescription
$c0?boolean | nullSignifies that c0 is an absolute value
$c1?boolean | nullSignifies that c1 is an absolute value
$r0?boolean | nullSignifies that r0 is an absolute value
$r1?boolean | nullSignifies that r1 is an absolute value
c0?number | nullLeft column of the range
c1?number | nullRight column of the range
r0?number | nullTop row of the range
r1?number | nullBottom row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

ReferenceA1

typeReferenceA1={context?: string[];range: RangeA1;};

A reference containing an A1 style range. See Prefixes.md for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeA1The reference's range

ReferenceA1Xlsx

typeReferenceA1Xlsx={range: RangeA1;sheetName?: string;workbookName?: string;};

A reference containing an A1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeA1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceIdentifier

typeReferenceIdentifier={kind: "name"|"range"|"beam"|"table";loc?: SourceLocation;type: "ReferenceIdentifier";value: string;}&Node;

An identifier for a range or a name.

Type Declaration

NameTypeDescription
kind"name" | "range" | "beam" | "table"The kind of reference the value holds.
loc?SourceLocationThe original source position of the node.
type"ReferenceIdentifier"The type of this AST node.
valuestringThe untouched reference value.

ReferenceName

typeReferenceName={context?: string[];name: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
namestringThe reference's name

ReferenceNameXlsx

typeReferenceNameXlsx={name: string;sheetName?: string;workbookName?: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
namestringThe reference's name
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceR1C1

typeReferenceR1C1={context?: string[];range: RangeR1C1;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeR1C1The reference's range

ReferenceR1C1Xlsx

typeReferenceR1C1Xlsx={range: RangeR1C1;sheetName?: string;workbookName?: string;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeR1C1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceStruct

typeReferenceStruct={columns?: string[];context?: string[];sections?: string[];table?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
context?string[]A collection of scopes for the reference
sections?string[]The sections this reference targets
table?stringThe table this reference targets

ReferenceStructXlsx

typeReferenceStructXlsx={columns?: string[];sections?: string[];sheetName?: string;table?: string;workbookName?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
sections?string[]The sections this reference targets
sheetName?stringA context sheet scope
table?stringThe table this reference targets
workbookName?stringA context workbook scope

SourceLocation

typeSourceLocation=number[];

Represents the source location information of the node. If the node contains no information about the source location, the field is null; otherwise it is an array consisting of a two numbers: A start offset (the position of the first character of the parsed source region) and an end offset (the position of the first character after the parsed source region).

Token

typeToken=Record<string,unknown>&{loc?: number[];type: string;unterminated?: boolean;value: string;};

A formula language token.

Type Declaration

NameTypeDescription
loc?number[]Source position offsets to the token
typestringThe type of the token
unterminated?booleanSignifies an unterminated string token
valuestringThe value of the token

TokenEnhanced

typeTokenEnhanced=Token&{depth?: number;error?: boolean;groupId?: string;index: number;};

A token with extra meta data.

Type Declaration

NameTypeDescription
depth?numberThis token's level of nesting inside parentheses
error?booleanToken is of unknown type or a paren without a match
groupId?stringThe ID of a group which this token belongs (e.g. matching parens)
indexnumberA zero based position in a token list

UnaryExpression

typeUnaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: UnaryOperator;type: "UnaryExpression";}&Node;

A unary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorUnaryOperatorThe expression's operator.
type"UnaryExpression"The type of this AST node.

UnaryOperator

typeUnaryOperator="+"|"-"|"%"|"#"|"@";

A unary operator token.

MAX_COLS

constMAX_COLS: number;

The maximum number of columns a spreadsheet reference may hold (16383).

MAX_ROWS

constMAX_ROWS: number;

The maximum number of rows a spreadsheet reference may hold (1048575).

nodeTypes

constnodeTypes: Readonly<{ARRAY: "ArrayExpression";BINARY: "BinaryExpression";CALL: "CallExpression";ERROR: "ErrorLiteral";IDENTIFIER: "Identifier";LAMBDA: "LambdaExpression";LET: "LetExpression";LET_DECL: "LetDeclarator";LITERAL: "Literal";REFERENCE: "ReferenceIdentifier";UNARY: "UnaryExpression";}>;

A dictionary of the types used to identify AST node variants.

tokenTypes

consttokenTypes: Readonly<{BOOLEAN: "bool";CONTEXT: "context";CONTEXT_QUOTE: "context_quote";ERROR: "error";FUNCTION: "func";FX_PREFIX: "fx_prefix";NEWLINE: "newline";NUMBER: "number";OPERATOR: "operator";REF_BEAM: "range_beam";REF_NAMED: "range_named";REF_RANGE: "range";REF_STRUCT: "structured";REF_TERNARY: "range_ternary";STRING: "string";UNKNOWN: "unknown";WHITESPACE: "whitespace";}>;

A dictionary of the types used to identify token variants.

fx/xlsx

A tokenizer, parser, and other utilities to work with Excel formula code.

The xslx entry-point methods expect and return the variant of references that uses properties. If you are not using xlsx files you should use the fx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Functions

References

addA1RangeBounds

Re-exports addA1RangeBounds


ArrayExpression

Re-exports ArrayExpression


AstExpression

Re-exports AstExpression


BinaryExpression

Re-exports BinaryExpression


BinaryOperator

Re-exports BinaryOperator


CallExpression

Re-exports CallExpression


ErrorLiteral

Re-exports ErrorLiteral


fromCol

Re-exports fromCol


Identifier

Re-exports Identifier


isArrayNode

Re-exports isArrayNode


isBinaryNode

Re-exports isBinaryNode


isCallNode

Re-exports isCallNode


isError

Re-exports isError


isErrorNode

Re-exports isErrorNode


isExpressionNode

Re-exports isExpressionNode


isFunction

Re-exports isFunction


isFxPrefix

Re-exports isFxPrefix


isIdentifierNode

Re-exports isIdentifierNode


isLambdaNode

Re-exports isLambdaNode


isLetDeclaratorNode

Re-exports isLetDeclaratorNode


isLetNode

Re-exports isLetNode


isLiteral

Re-exports isLiteral


isLiteralNode

Re-exports isLiteralNode


isOperator

Re-exports isOperator


isRange

Re-exports isRange


isReference

Re-exports isReference


isReferenceNode

Re-exports isReferenceNode


isUnaryNode

Re-exports isUnaryNode


isWhitespace

Re-exports isWhitespace


LambdaExpression

Re-exports LambdaExpression


LetDeclarator

Re-exports LetDeclarator


LetExpression

Re-exports LetExpression


Literal

Re-exports Literal


MAX_COLS

Re-exports MAX_COLS


MAX_ROWS

Re-exports MAX_ROWS


Node

Re-exports Node


nodeTypes

Re-exports nodeTypes


OptsFixRanges

Re-exports OptsFixRanges


OptsParse

Re-exports OptsParse


OptsParseA1Ref

Re-exports OptsParseA1Ref


OptsParseR1C1Ref

Re-exports OptsParseR1C1Ref


OptsStringifyStructRef

Re-exports OptsStringifyStructRef


OptsTokenize

Re-exports OptsTokenize


OptsTranslateFormulaToA1

Re-exports OptsTranslateFormulaToA1


OptsTranslateTokensToA1

Re-exports OptsTranslateTokensToA1


OptsTranslateToR1C1

Re-exports OptsTranslateToR1C1


parse

Re-exports parse


parseA1Range

Re-exports parseA1Range


parseR1C1Range

Re-exports parseR1C1Range


RangeA1

Re-exports RangeA1


RangeR1C1

Re-exports RangeR1C1


ReferenceA1

Re-exports ReferenceA1


ReferenceA1Xlsx

Re-exports ReferenceA1Xlsx


ReferenceIdentifier

Re-exports ReferenceIdentifier


ReferenceName

Re-exports ReferenceName


ReferenceNameXlsx

Re-exports ReferenceNameXlsx


ReferenceR1C1

Re-exports ReferenceR1C1


ReferenceR1C1Xlsx

Re-exports ReferenceR1C1Xlsx


ReferenceStruct

Re-exports ReferenceStruct


ReferenceStructXlsx

Re-exports ReferenceStructXlsx


SourceLocation

Re-exports SourceLocation


stringifyTokens

Re-exports stringifyTokens


toCol

Re-exports toCol


Token

Re-exports Token


TokenEnhanced

Re-exports TokenEnhanced


tokenTypes

Re-exports tokenTypes


translateFormulaToA1

Re-exports translateFormulaToA1


translateFormulaToR1C1

Re-exports translateFormulaToR1C1


translateTokensToA1

Re-exports translateTokensToA1


translateTokensToR1C1

Re-exports translateTokensToR1C1


UnaryExpression

Re-exports UnaryExpression


UnaryOperator

Re-exports UnaryOperator

addTokenMeta()

functionaddTokenMeta(tokenlist: Token[],context?: {sheetName?: string;workbookName?: string;}): TokenEnhanced[];

Runs through a list of tokens and adds extra attributes such as matching parens and ranges.

The context parameter defines default reference attributes: { workbookName: 'report.xlsx', sheetName: 'Sheet1' }. If supplied, these are used to match A1 to Sheet1!A1.

All tokens will be tagged with a .depth number value to indicating the level of nesting in parentheses as well as an .index number indicating their zero based position in the list.

The returned output will be the same array of tokens but the following properties will added to tokens (as applicable):

Parentheses ( )

Matching parens will be tagged with .groupId string identifier as well as a .depth number value (indicating the level of nesting).

Closing parens without a counterpart will be tagged with .error (boolean true).

Curly brackets { }

Matching curly brackets will be tagged with .groupId string identifier. These may not be nested in Excel.

Closing curly brackets without a counterpart will be tagged with .error (boolean true).

Ranges (REF_RANGE or REF_BEAM type tokens)

All ranges will be tagged with .groupId string identifier regardless of the number of times they occur.

Tokens of type UNKNOWN

All will be tagged with .error (boolean true).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens (from tokenize())
context?{ sheetName?: string; workbookName?: string; }A context used to match A1 to Sheet1!A1.
context.sheetName?stringAn implied sheet name ('Sheet1')
context.workbookName?stringAn implied workbook name ('report.xlsx')

Returns

TokenEnhanced[]

The input array with the enchanced tokens

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens and returns a new array of tokens with values and position-data updated.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Unlike Excel, fx does not normalize sheet or workbook names of references.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1Xlsx|ReferenceNameXlsx;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// workbookName: '',// sheetName: 'Sheet1',// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1Xlsx | ReferenceNameXlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceNameXlsx|ReferenceR1C1Xlsx;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceNameXlsx | ReferenceR1C1Xlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStructXlsx;

Parse a structured reference string into an object representing it.

parseStructRef('[workbook.xlsx]!tableName[[#Data],[Column1]:[Column2]]');// => {// workbookName: 'workbook.xlsx',// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStructXlsx

An object representing a valid reference or null if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1Xlsx|ReferenceNameXlsx): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({sheetName: 'Sheet1',range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1Xlsx | ReferenceNameXlsxA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceNameXlsx|ReferenceR1C1Xlsx): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({sheetName: 'Sheet1',range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceNameXlsx | ReferenceR1C1XlsxA reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStructXlsx,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({workbookName: 'workbook.xlsx',sheetName: '',sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructXlsxA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

History
3323 lines (2177 loc) · 76.1 KB

File metadata and controls

3323 lines (2177 loc) · 76.1 KB

@borgar/fx

Modules

fx

A tokenizer, parser, and other utilities to work with Excel formula code.

The base entry-point methods expect and return the variant of references that uses contexts. If you are using xlsx files or otherwise want to work with the xlsx-file variant of references you should use the fx/xlsx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Type Aliases

Variables

Functions

addA1RangeBounds()

functionaddA1RangeBounds(range: RangeA1): RangeA1;

Fill the any missing bounds in range objects. Top will be set to 0, bottom to 1048575, left to 0, and right to 16383, if they are null or undefined.

addA1RangeBounds({top: 0,left: 0,bottom: 1,$top: true,$left: false,$bottom: false,});// => {// top: 0,// left: 0,// bottom: 1,// right: 16383, // ← Added// $top: true,// $left: false,// $bottom: false,// $right: false // ← Added// }

Parameters

ParameterTypeDescription
rangeRangeA1The range part of a reference object.

Returns

RangeA1

The same range with missing bounds filled in.

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Returns a new array of tokens with values and position data updated.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

fromCol()

functionfromCol(columnString: string): number;

Convert a column string representation to a 0 based offset number ("C" = 2).

The method expects a valid column identifier made up of only A-Z letters, which may be either upper or lower case. Other input will return garbage.

Parameters

ParameterTypeDescription
columnStringstringThe column string identifier

Returns

number

Zero based column index number

isArrayNode()

functionisArrayNode(node?: Node): node is ArrayExpression;

Determines whether the specified node is a ArrayExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ArrayExpression

True if the specified token is a ArrayExpression, False otherwise.

isBinaryNode()

functionisBinaryNode(node?: Node): node is BinaryExpression;

Determines whether the specified node is a BinaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is BinaryExpression

True if the specified token is a BinaryExpression, False otherwise.

isCallNode()

functionisCallNode(node?: Node): node is CallExpression;

Determines whether the specified node is a CallExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is CallExpression

True if the specified token is a CallExpression, False otherwise.

isError()

functionisError(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an error.

Returns true if the input is a token of type ERROR (#VALUE!). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is error, False otherwise.

isErrorNode()

functionisErrorNode(node?: Node): node is ErrorLiteral;

Determines whether the specified node is an ErrorLiteral.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ErrorLiteral

True if the specified token is an ErrorLiteral, False otherwise.

isExpressionNode()

functionisExpressionNode(node?: Node): node is AstExpression;

Determines whether the specified node is a AstExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is AstExpression

True if the specified token is a AstExpression, False otherwise.

isFunction()

functionisFunction(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a function.

Returns true if the input is a token of type FUNCTION. In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is function, False otherwise.

isFxPrefix()

functionisFxPrefix(token?: Pick<Token,"type">): boolean;

Returns true if the input is a token of type FX_PREFIX (leading = in formula). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is effects prefix, False otherwise.

isIdentifierNode()

functionisIdentifierNode(node?: Node): node is Identifier;

Determines whether the specified node is an Identifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Identifier

True if the specified token is an Identifier, False otherwise.

isLambdaNode()

functionisLambdaNode(node?: Node): node is LambdaExpression;

Determines whether the specified node is a LambdaExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LambdaExpression

True if the specified token is a LambdaExpression, False otherwise.

isLetDeclaratorNode()

functionisLetDeclaratorNode(node?: Node): node is LetDeclarator;

Determines whether the specified node is a LetDeclarator.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetDeclarator

True if the specified token is a LetDeclarator, False otherwise.

isLetNode()

functionisLetNode(node?: Node): node is LetExpression;

Determines whether the specified node is a LetExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetExpression

True if the specified token is a LetExpression, False otherwise.

isLiteral()

functionisLiteral(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a literal.

Returns true if the input is a token of type BOOLEAN (TRUE or FALSE), ERROR (#VALUE!), NUMBER (123.4), or STRING ("lorem ipsum"). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is literal, False otherwise.

isLiteralNode()

functionisLiteralNode(node?: Node): node is Literal;

Determines whether the specified node is a Literal.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Literal

True if the specified token is a Literal, False otherwise.

isOperator()

functionisOperator(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an operator.

Returns true if the input is a token of type OPERATOR (+ or :). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is operator, False otherwise.

isRange()

functionisRange(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a range.

Returns true if the input is a token that has a type of either REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), or REF_BEAM (A:A or 1:1). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">A token

Returns

boolean

True if the specified token is range, False otherwise.

isReference()

functionisReference(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a reference.

Returns true if the input is a token of type REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), REF_BEAM (A:A or 1:1), or REF_NAMED (myrange). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is reference, False otherwise.

isReferenceNode()

functionisReferenceNode(node?: Node): node is ReferenceIdentifier;

Determines whether the specified node is a ReferenceIdentifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ReferenceIdentifier

True if the specified token is a ReferenceIdentifier, False otherwise.

isUnaryNode()

functionisUnaryNode(node?: Node): node is UnaryExpression;

Determines whether the specified node is a UnaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is UnaryExpression

True if the specified token is a UnaryExpression, False otherwise.

isWhitespace()

functionisWhitespace(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is whitespace.

Returns true if the input is a token of type WHITESPACE () or NEWLINE (\n). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is whitespace, False otherwise.

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parse()

functionparse(tokenlist: Token[],options?: OptsParse): AstExpression;

Parses a string formula or list of tokens into an AST.

The parser assumes mergeRefs and negativeNumbers were true when the tokens were generated. It does not yet recognize reference context tokens or know how to deal with unary minuses in arrays.

The AST Abstract Syntax Tree's format is documented in AST_format.md.

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.
optionsOptsParseOptions for the parsers behavior.

Returns

AstExpression

An AST of nodes.

See

parseA1Range()

functionparseA1Range(rangeString: string,allowTernary?: boolean): RangeA1;

Parse A1-style range string into a RangeA1 object.

Parameters

ParameterTypeDefault valueDescription
rangeStringstringundefinedA1-style range string.
allowTernary?booleantruePermit ternary ranges like A2:A or B2:2.

Returns

RangeA1

A reference object.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1|ReferenceName;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// context: [ 'Sheet1' ],// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1 | ReferenceName

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Range()

functionparseR1C1Range(rangeString: string): RangeR1C1;

Parse R1C1-style range string into a RangeR1C1 object.

Parameters

ParameterTypeDescription
rangeStringstringR1C1-style range string.

Returns

RangeR1C1

A reference object.

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceName|ReferenceR1C1;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceName | ReferenceR1C1

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStruct;

Parse a structured reference string into an object representing it.

parseStructRef('workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]');// => {// context: [ 'workbook.xlsx' ],// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStruct

An object representing a valid reference or undefined if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1|ReferenceName): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({context: ['Sheet1'],range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1 | ReferenceNameA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceName|ReferenceR1C1): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({context: ['Sheet1'],range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceName | ReferenceR1C1A reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStruct,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({context: ['workbook.xlsx'],sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

See

OptsStringifyStructRef

stringifyTokens()

functionstringifyTokens(tokens: Token[]): string;

Collapses a list of tokens into a formula string.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens.

Returns

string

A formula string.

toCol()

functiontoCol(columnIndex: number): string;

Convert a 0 based offset number to a column string representation (0 = "A", 2 = "C").

The method expects a number between 0 and 16383. Other input will return garbage.

Parameters

ParameterTypeDescription
columnIndexnumberZero based column index number

Returns

string

The column string identifier

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parsers will need to handle this.

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

translateFormulaToA1()

functiontranslateFormulaToA1(formula: string,anchorCell: string,options?: OptsTranslateFormulaToA1): string;

Translates ranges in a formula from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so you can set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Parameters

ParameterTypeDescription
formulastringAn Excel formula string that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateFormulaToA1Translation options.

Returns

string

A formula string.

See

OptsTranslateFormulaToA1

translateFormulaToR1C1()

functiontranslateFormulaToR1C1(formula: string,anchorCell: string,options?: OptsTranslateToR1C1): string;

Translates ranges in a formula from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
formulastringAn Excel formula that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
options?OptsTranslateToR1C1The options

Returns

string

A formula string.

See

OptsTranslateToR1C1

translateTokensToA1()

functiontranslateTokensToA1(tokens: Token[],anchorCell: string,options?: OptsTranslateTokensToA1): Token[];

Translates ranges in a list of tokens from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so may set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Note that if you are passing in a list of tokens that was not created using mergeRefs and you disable edge wrapping (or you simply set both options to false), you can end up with a formula such as =#REF!:B2 or =Sheet3!#REF!:F3. These are valid formulas in the Excel formula language and Excel will accept them, but they are not supported in Google Sheets.

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateTokensToA1Translation options.

Returns

Token[]

A token list.

See

OptsTranslateTokensToA1

translateTokensToR1C1()

functiontranslateTokensToR1C1(tokens: Token[],anchorCell: string): Token[];

Translates ranges in a list of tokens from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).

Returns

Token[]

A token list.

ArrayExpression

typeArrayExpression={elements: (|ReferenceIdentifier|Literal|ErrorLiteral|CallExpression)[][];loc?: SourceLocation;type: "ArrayExpression";}&Node;

An array expression. Excel does not have empty or sparse arrays and restricts array elements to literals. Google Sheets allows ReferenceIdentifiers and CallExpressions as elements of arrays, the fx parser has options for this but they are off by default.

Type Declaration

NameTypeDescription
elements( | ReferenceIdentifier | Literal | ErrorLiteral | CallExpression)[][]The elements of the array.
loc?SourceLocationThe original source position of the node.
type"ArrayExpression"The type of this AST node.

AstExpression

typeAstExpression=|ReferenceIdentifier|Literal|ErrorLiteral|UnaryExpression|BinaryExpression|CallExpression|ArrayExpression|LambdaExpression|LetExpression;

Represents an evaluate-able expression.

BinaryExpression

typeBinaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: BinaryOperator;type: "BinaryExpression";}&Node;

A binary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorBinaryOperatorThe expression's operator.
type"BinaryExpression"The type of this AST node.

BinaryOperator

typeBinaryOperator=|"="|"<"|">"|"<="|">="|"<>"|"-"|"+"|"*"|"/"|"^"|":"|" "|","|"&";

A binary operator token.

Note that Excels union operator is whitespace so a parser must take care to normalize this to a single space.

CallExpression

typeCallExpression={arguments: AstExpression[];callee: Identifier;loc?: SourceLocation;type: "CallExpression";}&Node;

A function call expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the function.
calleeIdentifierThe function being called.
loc?SourceLocationThe original source position of the node.
type"CallExpression"The type of this AST node.

ErrorLiteral

typeErrorLiteral={loc?: SourceLocation;raw: string;type: "ErrorLiteral";value: string;}&Node;

An Error expression.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"ErrorLiteral"The type of this AST node.
valuestringThe value of the error.

Identifier

typeIdentifier={loc?: SourceLocation;name: string;type: "Identifier";}&Node;

An identifier. These appear on CallExpression, LambdaExpression, and LetExpression and will always be a static string representing the name of a function call or parameter.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
namestringThe identifying name.
type"Identifier"The type of this AST node.

LambdaExpression

typeLambdaExpression={body: AstExpression|null;loc?: SourceLocation;params: Identifier[];type: "LambdaExpression";}&Node;

A LAMBDA expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LAMBDA's expression.
loc?SourceLocationThe original source position of the node.
paramsIdentifier[]The LAMBDA's parameters.
type"LambdaExpression"The type of this AST node.

LetDeclarator

typeLetDeclarator={id: Identifier;init: AstExpression|null;loc?: SourceLocation;type: "LetDeclarator";}&Node;

A LET parameter declaration.

Type Declaration

NameTypeDescription
idIdentifierThe name of the variable.
initAstExpression | nullThe variable's initializing expression.
loc?SourceLocationThe original source position of the node.
type"LetDeclarator"The type of this AST node.

LetExpression

typeLetExpression={body: AstExpression|null;declarations: LetDeclarator[];loc?: SourceLocation;type: "LetExpression";}&Node;

A LET expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LET's scoped expression.
declarationsLetDeclarator[]The LET's variable declarations.
loc?SourceLocationThe original source position of the node.
type"LetExpression"The type of this AST node.

Literal

typeLiteral={loc?: SourceLocation;raw: string;type: "Literal";value: string|number|boolean;}&Node;

A literal token. Captures numbers, strings, and booleans. Literal errors have their own variant type.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"Literal"The type of this AST node.
valuestring | number | booleanThe value of the literal.

Node

typeNode={loc?: SourceLocation;type: string;};

All AST nodes are represented by Node objects. They may have any prototype inheritance but implement the same basic interface.

The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements.

Properties

PropertyTypeDescription
loc?SourceLocationThe original source position of the node.
typestringThe type of this AST node.

OptsFixRanges

typeOptsFixRanges={addBounds?: boolean;thisRow?: boolean;};

Options for fixTokenRanges and fixFormulaRanges.

Properties

PropertyTypeDefault valueDescription
addBounds?booleanfalseFill in any undefined bounds of range objects. Top to 0, bottom to 1048575, left to 0, and right to 16383.
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsParse

typeOptsParse={looseRefCalls?: boolean;permitArrayCalls?: boolean;permitArrayRanges?: boolean;};

Options for parse.

Properties

PropertyTypeDefault valueDescription
looseRefCalls?booleanfalsePermits any function call where otherwise only functions that return references would be permitted.
permitArrayCalls?booleanfalseFunction calls are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.
permitArrayRanges?booleanfalseRanges are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.

OptsParseA1Ref

typeOptsParseA1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseA1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsParseR1C1Ref

typeOptsParseR1C1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseR1C1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsStringifyStructRef

typeOptsStringifyStructRef={thisRow?: boolean;};

Options for stringifyStructRef

Properties

PropertyTypeDefault valueDescription
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsTokenize

typeOptsTokenize={allowTernary?: boolean;mergeRefs?: boolean;negativeNumbers?: boolean;r1c1?: boolean;withLocation?: boolean;};

Options for tokenize.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be returned as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2). This is the same as calling mergeRefTokens
negativeNumbers?booleantrueMerges unary minuses with their immediately following number tokens (-,1) => -1 (alternatively these will be unary operations in the tree).
r1c1?booleanfalseRanges are expected to be in the R1C1 style format rather than the more popular A1 style.
withLocation?booleantrueNodes will include source position offsets to the tokens: { loc: [ start, end ] }

OptsTranslateFormulaToA1

typeOptsTranslateFormulaToA1={allowTernary?: boolean;mergeRefs?: boolean;wrapEdges?: boolean;};

Options for translateFormulaToA1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be treated as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2).
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

OptsTranslateToR1C1

typeOptsTranslateToR1C1={allowTernary?: boolean;};

Options for translateFormulaToR1C1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsTranslateTokensToA1

typeOptsTranslateTokensToA1={wrapEdges?: boolean;};

Options for translateTokensToA1

Properties

PropertyTypeDefault valueDescription
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

RangeA1

typeRangeA1={$bottom?: boolean|null;$left?: boolean|null;$right?: boolean|null;$top?: boolean|null;bottom?: number|null;left: number|null;right?: number|null;top: number|null;trim?: "head"|"tail"|"both"|null;};

A range in A1 style coordinates.

Properties

PropertyTypeDescription
$bottom?boolean | nullSignifies that bottom is a "locked" value
$left?boolean | nullSignifies that left is a "locked" value
$right?boolean | nullSignifies that right is a "locked" value
$top?boolean | nullSignifies that top is a "locked" value
bottom?number | nullBottom row of the range
leftnumber | nullLeft column of the range
right?number | nullRight column of the range
topnumber | nullTop row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

RangeR1C1

typeRangeR1C1={$c0?: boolean|null;$c1?: boolean|null;$r0?: boolean|null;$r1?: boolean|null;c0?: number|null;c1?: number|null;r0?: number|null;r1?: number|null;trim?: "head"|"tail"|"both"|null;};

A range in R1C1 style coordinates.

Properties

PropertyTypeDescription
$c0?boolean | nullSignifies that c0 is an absolute value
$c1?boolean | nullSignifies that c1 is an absolute value
$r0?boolean | nullSignifies that r0 is an absolute value
$r1?boolean | nullSignifies that r1 is an absolute value
c0?number | nullLeft column of the range
c1?number | nullRight column of the range
r0?number | nullTop row of the range
r1?number | nullBottom row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

ReferenceA1

typeReferenceA1={context?: string[];range: RangeA1;};

A reference containing an A1 style range. See Prefixes.md for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeA1The reference's range

ReferenceA1Xlsx

typeReferenceA1Xlsx={range: RangeA1;sheetName?: string;workbookName?: string;};

A reference containing an A1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeA1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceIdentifier

typeReferenceIdentifier={kind: "name"|"range"|"beam"|"table";loc?: SourceLocation;type: "ReferenceIdentifier";value: string;}&Node;

An identifier for a range or a name.

Type Declaration

NameTypeDescription
kind"name" | "range" | "beam" | "table"The kind of reference the value holds.
loc?SourceLocationThe original source position of the node.
type"ReferenceIdentifier"The type of this AST node.
valuestringThe untouched reference value.

ReferenceName

typeReferenceName={context?: string[];name: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
namestringThe reference's name

ReferenceNameXlsx

typeReferenceNameXlsx={name: string;sheetName?: string;workbookName?: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
namestringThe reference's name
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceR1C1

typeReferenceR1C1={context?: string[];range: RangeR1C1;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeR1C1The reference's range

ReferenceR1C1Xlsx

typeReferenceR1C1Xlsx={range: RangeR1C1;sheetName?: string;workbookName?: string;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeR1C1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceStruct

typeReferenceStruct={columns?: string[];context?: string[];sections?: string[];table?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
context?string[]A collection of scopes for the reference
sections?string[]The sections this reference targets
table?stringThe table this reference targets

ReferenceStructXlsx

typeReferenceStructXlsx={columns?: string[];sections?: string[];sheetName?: string;table?: string;workbookName?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
sections?string[]The sections this reference targets
sheetName?stringA context sheet scope
table?stringThe table this reference targets
workbookName?stringA context workbook scope

SourceLocation

typeSourceLocation=number[];

Represents the source location information of the node. If the node contains no information about the source location, the field is null; otherwise it is an array consisting of a two numbers: A start offset (the position of the first character of the parsed source region) and an end offset (the position of the first character after the parsed source region).

Token

typeToken=Record<string,unknown>&{loc?: number[];type: string;unterminated?: boolean;value: string;};

A formula language token.

Type Declaration

NameTypeDescription
loc?number[]Source position offsets to the token
typestringThe type of the token
unterminated?booleanSignifies an unterminated string token
valuestringThe value of the token

TokenEnhanced

typeTokenEnhanced=Token&{depth?: number;error?: boolean;groupId?: string;index: number;};

A token with extra meta data.

Type Declaration

NameTypeDescription
depth?numberThis token's level of nesting inside parentheses
error?booleanToken is of unknown type or a paren without a match
groupId?stringThe ID of a group which this token belongs (e.g. matching parens)
indexnumberA zero based position in a token list

UnaryExpression

typeUnaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: UnaryOperator;type: "UnaryExpression";}&Node;

A unary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorUnaryOperatorThe expression's operator.
type"UnaryExpression"The type of this AST node.

UnaryOperator

typeUnaryOperator="+"|"-"|"%"|"#"|"@";

A unary operator token.

MAX_COLS

constMAX_COLS: number;

The maximum number of columns a spreadsheet reference may hold (16383).

MAX_ROWS

constMAX_ROWS: number;

The maximum number of rows a spreadsheet reference may hold (1048575).

nodeTypes

constnodeTypes: Readonly<{ARRAY: "ArrayExpression";BINARY: "BinaryExpression";CALL: "CallExpression";ERROR: "ErrorLiteral";IDENTIFIER: "Identifier";LAMBDA: "LambdaExpression";LET: "LetExpression";LET_DECL: "LetDeclarator";LITERAL: "Literal";REFERENCE: "ReferenceIdentifier";UNARY: "UnaryExpression";}>;

A dictionary of the types used to identify AST node variants.

tokenTypes

consttokenTypes: Readonly<{BOOLEAN: "bool";CONTEXT: "context";CONTEXT_QUOTE: "context_quote";ERROR: "error";FUNCTION: "func";FX_PREFIX: "fx_prefix";NEWLINE: "newline";NUMBER: "number";OPERATOR: "operator";REF_BEAM: "range_beam";REF_NAMED: "range_named";REF_RANGE: "range";REF_STRUCT: "structured";REF_TERNARY: "range_ternary";STRING: "string";UNKNOWN: "unknown";WHITESPACE: "whitespace";}>;

A dictionary of the types used to identify token variants.

fx/xlsx

A tokenizer, parser, and other utilities to work with Excel formula code.

The xslx entry-point methods expect and return the variant of references that uses properties. If you are not using xlsx files you should use the fx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Functions

References

addA1RangeBounds

Re-exports addA1RangeBounds


ArrayExpression

Re-exports ArrayExpression


AstExpression

Re-exports AstExpression


BinaryExpression

Re-exports BinaryExpression


BinaryOperator

Re-exports BinaryOperator


CallExpression

Re-exports CallExpression


ErrorLiteral

Re-exports ErrorLiteral


fromCol

Re-exports fromCol


Identifier

Re-exports Identifier


isArrayNode

Re-exports isArrayNode


isBinaryNode

Re-exports isBinaryNode


isCallNode

Re-exports isCallNode


isError

Re-exports isError


isErrorNode

Re-exports isErrorNode


isExpressionNode

Re-exports isExpressionNode


isFunction

Re-exports isFunction


isFxPrefix

Re-exports isFxPrefix


isIdentifierNode

Re-exports isIdentifierNode


isLambdaNode

Re-exports isLambdaNode


isLetDeclaratorNode

Re-exports isLetDeclaratorNode


isLetNode

Re-exports isLetNode


isLiteral

Re-exports isLiteral


isLiteralNode

Re-exports isLiteralNode


isOperator

Re-exports isOperator


isRange

Re-exports isRange


isReference

Re-exports isReference


isReferenceNode

Re-exports isReferenceNode


isUnaryNode

Re-exports isUnaryNode


isWhitespace

Re-exports isWhitespace


LambdaExpression

Re-exports LambdaExpression


LetDeclarator

Re-exports LetDeclarator


LetExpression

Re-exports LetExpression


Literal

Re-exports Literal


MAX_COLS

Re-exports MAX_COLS


MAX_ROWS

Re-exports MAX_ROWS


Node

Re-exports Node


nodeTypes

Re-exports nodeTypes


OptsFixRanges

Re-exports OptsFixRanges


OptsParse

Re-exports OptsParse


OptsParseA1Ref

Re-exports OptsParseA1Ref


OptsParseR1C1Ref

Re-exports OptsParseR1C1Ref


OptsStringifyStructRef

Re-exports OptsStringifyStructRef


OptsTokenize

Re-exports OptsTokenize


OptsTranslateFormulaToA1

Re-exports OptsTranslateFormulaToA1


OptsTranslateTokensToA1

Re-exports OptsTranslateTokensToA1


OptsTranslateToR1C1

Re-exports OptsTranslateToR1C1


parse

Re-exports parse


parseA1Range

Re-exports parseA1Range


parseR1C1Range

Re-exports parseR1C1Range


RangeA1

Re-exports RangeA1


RangeR1C1

Re-exports RangeR1C1


ReferenceA1

Re-exports ReferenceA1


ReferenceA1Xlsx

Re-exports ReferenceA1Xlsx


ReferenceIdentifier

Re-exports ReferenceIdentifier


ReferenceName

Re-exports ReferenceName


ReferenceNameXlsx

Re-exports ReferenceNameXlsx


ReferenceR1C1

Re-exports ReferenceR1C1


ReferenceR1C1Xlsx

Re-exports ReferenceR1C1Xlsx


ReferenceStruct

Re-exports ReferenceStruct


ReferenceStructXlsx

Re-exports ReferenceStructXlsx


SourceLocation

Re-exports SourceLocation


stringifyTokens

Re-exports stringifyTokens


toCol

Re-exports toCol


Token

Re-exports Token


TokenEnhanced

Re-exports TokenEnhanced


tokenTypes

Re-exports tokenTypes


translateFormulaToA1

Re-exports translateFormulaToA1


translateFormulaToR1C1

Re-exports translateFormulaToR1C1


translateTokensToA1

Re-exports translateTokensToA1


translateTokensToR1C1

Re-exports translateTokensToR1C1


UnaryExpression

Re-exports UnaryExpression


UnaryOperator

Re-exports UnaryOperator

addTokenMeta()

functionaddTokenMeta(tokenlist: Token[],context?: {sheetName?: string;workbookName?: string;}): TokenEnhanced[];

Runs through a list of tokens and adds extra attributes such as matching parens and ranges.

The context parameter defines default reference attributes: { workbookName: 'report.xlsx', sheetName: 'Sheet1' }. If supplied, these are used to match A1 to Sheet1!A1.

All tokens will be tagged with a .depth number value to indicating the level of nesting in parentheses as well as an .index number indicating their zero based position in the list.

The returned output will be the same array of tokens but the following properties will added to tokens (as applicable):

Parentheses ( )

Matching parens will be tagged with .groupId string identifier as well as a .depth number value (indicating the level of nesting).

Closing parens without a counterpart will be tagged with .error (boolean true).

Curly brackets { }

Matching curly brackets will be tagged with .groupId string identifier. These may not be nested in Excel.

Closing curly brackets without a counterpart will be tagged with .error (boolean true).

Ranges (REF_RANGE or REF_BEAM type tokens)

All ranges will be tagged with .groupId string identifier regardless of the number of times they occur.

Tokens of type UNKNOWN

All will be tagged with .error (boolean true).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens (from tokenize())
context?{ sheetName?: string; workbookName?: string; }A context used to match A1 to Sheet1!A1.
context.sheetName?stringAn implied sheet name ('Sheet1')
context.workbookName?stringAn implied workbook name ('report.xlsx')

Returns

TokenEnhanced[]

The input array with the enchanced tokens

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens and returns a new array of tokens with values and position-data updated.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Unlike Excel, fx does not normalize sheet or workbook names of references.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1Xlsx|ReferenceNameXlsx;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// workbookName: '',// sheetName: 'Sheet1',// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1Xlsx | ReferenceNameXlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceNameXlsx|ReferenceR1C1Xlsx;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceNameXlsx | ReferenceR1C1Xlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStructXlsx;

Parse a structured reference string into an object representing it.

parseStructRef('[workbook.xlsx]!tableName[[#Data],[Column1]:[Column2]]');// => {// workbookName: 'workbook.xlsx',// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStructXlsx

An object representing a valid reference or null if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1Xlsx|ReferenceNameXlsx): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({sheetName: 'Sheet1',range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1Xlsx | ReferenceNameXlsxA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceNameXlsx|ReferenceR1C1Xlsx): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({sheetName: 'Sheet1',range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceNameXlsx | ReferenceR1C1XlsxA reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStructXlsx,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({workbookName: 'workbook.xlsx',sheetName: '',sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructXlsxA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
3323 lines (2177 loc) · 76.1 KB

File metadata and controls

3323 lines (2177 loc) · 76.1 KB

@borgar/fx

Modules

fx

A tokenizer, parser, and other utilities to work with Excel formula code.

The base entry-point methods expect and return the variant of references that uses contexts. If you are using xlsx files or otherwise want to work with the xlsx-file variant of references you should use the fx/xlsx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Type Aliases

Variables

Functions

addA1RangeBounds()

functionaddA1RangeBounds(range: RangeA1): RangeA1;

Fill the any missing bounds in range objects. Top will be set to 0, bottom to 1048575, left to 0, and right to 16383, if they are null or undefined.

addA1RangeBounds({top: 0,left: 0,bottom: 1,$top: true,$left: false,$bottom: false,});// => {// top: 0,// left: 0,// bottom: 1,// right: 16383, // ← Added// $top: true,// $left: false,// $bottom: false,// $right: false // ← Added// }

Parameters

ParameterTypeDescription
rangeRangeA1The range part of a reference object.

Returns

RangeA1

The same range with missing bounds filled in.

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Returns a new array of tokens with values and position data updated.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

fromCol()

functionfromCol(columnString: string): number;

Convert a column string representation to a 0 based offset number ("C" = 2).

The method expects a valid column identifier made up of only A-Z letters, which may be either upper or lower case. Other input will return garbage.

Parameters

ParameterTypeDescription
columnStringstringThe column string identifier

Returns

number

Zero based column index number

isArrayNode()

functionisArrayNode(node?: Node): node is ArrayExpression;

Determines whether the specified node is a ArrayExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ArrayExpression

True if the specified token is a ArrayExpression, False otherwise.

isBinaryNode()

functionisBinaryNode(node?: Node): node is BinaryExpression;

Determines whether the specified node is a BinaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is BinaryExpression

True if the specified token is a BinaryExpression, False otherwise.

isCallNode()

functionisCallNode(node?: Node): node is CallExpression;

Determines whether the specified node is a CallExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is CallExpression

True if the specified token is a CallExpression, False otherwise.

isError()

functionisError(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an error.

Returns true if the input is a token of type ERROR (#VALUE!). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is error, False otherwise.

isErrorNode()

functionisErrorNode(node?: Node): node is ErrorLiteral;

Determines whether the specified node is an ErrorLiteral.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ErrorLiteral

True if the specified token is an ErrorLiteral, False otherwise.

isExpressionNode()

functionisExpressionNode(node?: Node): node is AstExpression;

Determines whether the specified node is a AstExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is AstExpression

True if the specified token is a AstExpression, False otherwise.

isFunction()

functionisFunction(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a function.

Returns true if the input is a token of type FUNCTION. In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is function, False otherwise.

isFxPrefix()

functionisFxPrefix(token?: Pick<Token,"type">): boolean;

Returns true if the input is a token of type FX_PREFIX (leading = in formula). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is effects prefix, False otherwise.

isIdentifierNode()

functionisIdentifierNode(node?: Node): node is Identifier;

Determines whether the specified node is an Identifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Identifier

True if the specified token is an Identifier, False otherwise.

isLambdaNode()

functionisLambdaNode(node?: Node): node is LambdaExpression;

Determines whether the specified node is a LambdaExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LambdaExpression

True if the specified token is a LambdaExpression, False otherwise.

isLetDeclaratorNode()

functionisLetDeclaratorNode(node?: Node): node is LetDeclarator;

Determines whether the specified node is a LetDeclarator.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetDeclarator

True if the specified token is a LetDeclarator, False otherwise.

isLetNode()

functionisLetNode(node?: Node): node is LetExpression;

Determines whether the specified node is a LetExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetExpression

True if the specified token is a LetExpression, False otherwise.

isLiteral()

functionisLiteral(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a literal.

Returns true if the input is a token of type BOOLEAN (TRUE or FALSE), ERROR (#VALUE!), NUMBER (123.4), or STRING ("lorem ipsum"). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is literal, False otherwise.

isLiteralNode()

functionisLiteralNode(node?: Node): node is Literal;

Determines whether the specified node is a Literal.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Literal

True if the specified token is a Literal, False otherwise.

isOperator()

functionisOperator(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an operator.

Returns true if the input is a token of type OPERATOR (+ or :). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is operator, False otherwise.

isRange()

functionisRange(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a range.

Returns true if the input is a token that has a type of either REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), or REF_BEAM (A:A or 1:1). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">A token

Returns

boolean

True if the specified token is range, False otherwise.

isReference()

functionisReference(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a reference.

Returns true if the input is a token of type REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), REF_BEAM (A:A or 1:1), or REF_NAMED (myrange). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is reference, False otherwise.

isReferenceNode()

functionisReferenceNode(node?: Node): node is ReferenceIdentifier;

Determines whether the specified node is a ReferenceIdentifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ReferenceIdentifier

True if the specified token is a ReferenceIdentifier, False otherwise.

isUnaryNode()

functionisUnaryNode(node?: Node): node is UnaryExpression;

Determines whether the specified node is a UnaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is UnaryExpression

True if the specified token is a UnaryExpression, False otherwise.

isWhitespace()

functionisWhitespace(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is whitespace.

Returns true if the input is a token of type WHITESPACE () or NEWLINE (\n). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is whitespace, False otherwise.

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parse()

functionparse(tokenlist: Token[],options?: OptsParse): AstExpression;

Parses a string formula or list of tokens into an AST.

The parser assumes mergeRefs and negativeNumbers were true when the tokens were generated. It does not yet recognize reference context tokens or know how to deal with unary minuses in arrays.

The AST Abstract Syntax Tree's format is documented in AST_format.md.

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.
optionsOptsParseOptions for the parsers behavior.

Returns

AstExpression

An AST of nodes.

See

parseA1Range()

functionparseA1Range(rangeString: string,allowTernary?: boolean): RangeA1;

Parse A1-style range string into a RangeA1 object.

Parameters

ParameterTypeDefault valueDescription
rangeStringstringundefinedA1-style range string.
allowTernary?booleantruePermit ternary ranges like A2:A or B2:2.

Returns

RangeA1

A reference object.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1|ReferenceName;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// context: [ 'Sheet1' ],// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1 | ReferenceName

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Range()

functionparseR1C1Range(rangeString: string): RangeR1C1;

Parse R1C1-style range string into a RangeR1C1 object.

Parameters

ParameterTypeDescription
rangeStringstringR1C1-style range string.

Returns

RangeR1C1

A reference object.

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceName|ReferenceR1C1;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceName | ReferenceR1C1

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStruct;

Parse a structured reference string into an object representing it.

parseStructRef('workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]');// => {// context: [ 'workbook.xlsx' ],// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStruct

An object representing a valid reference or undefined if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1|ReferenceName): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({context: ['Sheet1'],range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1 | ReferenceNameA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceName|ReferenceR1C1): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({context: ['Sheet1'],range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceName | ReferenceR1C1A reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStruct,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({context: ['workbook.xlsx'],sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

See

OptsStringifyStructRef

stringifyTokens()

functionstringifyTokens(tokens: Token[]): string;

Collapses a list of tokens into a formula string.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens.

Returns

string

A formula string.

toCol()

functiontoCol(columnIndex: number): string;

Convert a 0 based offset number to a column string representation (0 = "A", 2 = "C").

The method expects a number between 0 and 16383. Other input will return garbage.

Parameters

ParameterTypeDescription
columnIndexnumberZero based column index number

Returns

string

The column string identifier

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parsers will need to handle this.

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

translateFormulaToA1()

functiontranslateFormulaToA1(formula: string,anchorCell: string,options?: OptsTranslateFormulaToA1): string;

Translates ranges in a formula from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so you can set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Parameters

ParameterTypeDescription
formulastringAn Excel formula string that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateFormulaToA1Translation options.

Returns

string

A formula string.

See

OptsTranslateFormulaToA1

translateFormulaToR1C1()

functiontranslateFormulaToR1C1(formula: string,anchorCell: string,options?: OptsTranslateToR1C1): string;

Translates ranges in a formula from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
formulastringAn Excel formula that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
options?OptsTranslateToR1C1The options

Returns

string

A formula string.

See

OptsTranslateToR1C1

translateTokensToA1()

functiontranslateTokensToA1(tokens: Token[],anchorCell: string,options?: OptsTranslateTokensToA1): Token[];

Translates ranges in a list of tokens from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so may set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Note that if you are passing in a list of tokens that was not created using mergeRefs and you disable edge wrapping (or you simply set both options to false), you can end up with a formula such as =#REF!:B2 or =Sheet3!#REF!:F3. These are valid formulas in the Excel formula language and Excel will accept them, but they are not supported in Google Sheets.

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateTokensToA1Translation options.

Returns

Token[]

A token list.

See

OptsTranslateTokensToA1

translateTokensToR1C1()

functiontranslateTokensToR1C1(tokens: Token[],anchorCell: string): Token[];

Translates ranges in a list of tokens from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).

Returns

Token[]

A token list.

ArrayExpression

typeArrayExpression={elements: (|ReferenceIdentifier|Literal|ErrorLiteral|CallExpression)[][];loc?: SourceLocation;type: "ArrayExpression";}&Node;

An array expression. Excel does not have empty or sparse arrays and restricts array elements to literals. Google Sheets allows ReferenceIdentifiers and CallExpressions as elements of arrays, the fx parser has options for this but they are off by default.

Type Declaration

NameTypeDescription
elements( | ReferenceIdentifier | Literal | ErrorLiteral | CallExpression)[][]The elements of the array.
loc?SourceLocationThe original source position of the node.
type"ArrayExpression"The type of this AST node.

AstExpression

typeAstExpression=|ReferenceIdentifier|Literal|ErrorLiteral|UnaryExpression|BinaryExpression|CallExpression|ArrayExpression|LambdaExpression|LetExpression;

Represents an evaluate-able expression.

BinaryExpression

typeBinaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: BinaryOperator;type: "BinaryExpression";}&Node;

A binary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorBinaryOperatorThe expression's operator.
type"BinaryExpression"The type of this AST node.

BinaryOperator

typeBinaryOperator=|"="|"<"|">"|"<="|">="|"<>"|"-"|"+"|"*"|"/"|"^"|":"|" "|","|"&";

A binary operator token.

Note that Excels union operator is whitespace so a parser must take care to normalize this to a single space.

CallExpression

typeCallExpression={arguments: AstExpression[];callee: Identifier;loc?: SourceLocation;type: "CallExpression";}&Node;

A function call expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the function.
calleeIdentifierThe function being called.
loc?SourceLocationThe original source position of the node.
type"CallExpression"The type of this AST node.

ErrorLiteral

typeErrorLiteral={loc?: SourceLocation;raw: string;type: "ErrorLiteral";value: string;}&Node;

An Error expression.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"ErrorLiteral"The type of this AST node.
valuestringThe value of the error.

Identifier

typeIdentifier={loc?: SourceLocation;name: string;type: "Identifier";}&Node;

An identifier. These appear on CallExpression, LambdaExpression, and LetExpression and will always be a static string representing the name of a function call or parameter.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
namestringThe identifying name.
type"Identifier"The type of this AST node.

LambdaExpression

typeLambdaExpression={body: AstExpression|null;loc?: SourceLocation;params: Identifier[];type: "LambdaExpression";}&Node;

A LAMBDA expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LAMBDA's expression.
loc?SourceLocationThe original source position of the node.
paramsIdentifier[]The LAMBDA's parameters.
type"LambdaExpression"The type of this AST node.

LetDeclarator

typeLetDeclarator={id: Identifier;init: AstExpression|null;loc?: SourceLocation;type: "LetDeclarator";}&Node;

A LET parameter declaration.

Type Declaration

NameTypeDescription
idIdentifierThe name of the variable.
initAstExpression | nullThe variable's initializing expression.
loc?SourceLocationThe original source position of the node.
type"LetDeclarator"The type of this AST node.

LetExpression

typeLetExpression={body: AstExpression|null;declarations: LetDeclarator[];loc?: SourceLocation;type: "LetExpression";}&Node;

A LET expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LET's scoped expression.
declarationsLetDeclarator[]The LET's variable declarations.
loc?SourceLocationThe original source position of the node.
type"LetExpression"The type of this AST node.

Literal

typeLiteral={loc?: SourceLocation;raw: string;type: "Literal";value: string|number|boolean;}&Node;

A literal token. Captures numbers, strings, and booleans. Literal errors have their own variant type.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"Literal"The type of this AST node.
valuestring | number | booleanThe value of the literal.

Node

typeNode={loc?: SourceLocation;type: string;};

All AST nodes are represented by Node objects. They may have any prototype inheritance but implement the same basic interface.

The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements.

Properties

PropertyTypeDescription
loc?SourceLocationThe original source position of the node.
typestringThe type of this AST node.

OptsFixRanges

typeOptsFixRanges={addBounds?: boolean;thisRow?: boolean;};

Options for fixTokenRanges and fixFormulaRanges.

Properties

PropertyTypeDefault valueDescription
addBounds?booleanfalseFill in any undefined bounds of range objects. Top to 0, bottom to 1048575, left to 0, and right to 16383.
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsParse

typeOptsParse={looseRefCalls?: boolean;permitArrayCalls?: boolean;permitArrayRanges?: boolean;};

Options for parse.

Properties

PropertyTypeDefault valueDescription
looseRefCalls?booleanfalsePermits any function call where otherwise only functions that return references would be permitted.
permitArrayCalls?booleanfalseFunction calls are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.
permitArrayRanges?booleanfalseRanges are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.

OptsParseA1Ref

typeOptsParseA1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseA1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsParseR1C1Ref

typeOptsParseR1C1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseR1C1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsStringifyStructRef

typeOptsStringifyStructRef={thisRow?: boolean;};

Options for stringifyStructRef

Properties

PropertyTypeDefault valueDescription
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsTokenize

typeOptsTokenize={allowTernary?: boolean;mergeRefs?: boolean;negativeNumbers?: boolean;r1c1?: boolean;withLocation?: boolean;};

Options for tokenize.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be returned as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2). This is the same as calling mergeRefTokens
negativeNumbers?booleantrueMerges unary minuses with their immediately following number tokens (-,1) => -1 (alternatively these will be unary operations in the tree).
r1c1?booleanfalseRanges are expected to be in the R1C1 style format rather than the more popular A1 style.
withLocation?booleantrueNodes will include source position offsets to the tokens: { loc: [ start, end ] }

OptsTranslateFormulaToA1

typeOptsTranslateFormulaToA1={allowTernary?: boolean;mergeRefs?: boolean;wrapEdges?: boolean;};

Options for translateFormulaToA1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be treated as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2).
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

OptsTranslateToR1C1

typeOptsTranslateToR1C1={allowTernary?: boolean;};

Options for translateFormulaToR1C1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsTranslateTokensToA1

typeOptsTranslateTokensToA1={wrapEdges?: boolean;};

Options for translateTokensToA1

Properties

PropertyTypeDefault valueDescription
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

RangeA1

typeRangeA1={$bottom?: boolean|null;$left?: boolean|null;$right?: boolean|null;$top?: boolean|null;bottom?: number|null;left: number|null;right?: number|null;top: number|null;trim?: "head"|"tail"|"both"|null;};

A range in A1 style coordinates.

Properties

PropertyTypeDescription
$bottom?boolean | nullSignifies that bottom is a "locked" value
$left?boolean | nullSignifies that left is a "locked" value
$right?boolean | nullSignifies that right is a "locked" value
$top?boolean | nullSignifies that top is a "locked" value
bottom?number | nullBottom row of the range
leftnumber | nullLeft column of the range
right?number | nullRight column of the range
topnumber | nullTop row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

RangeR1C1

typeRangeR1C1={$c0?: boolean|null;$c1?: boolean|null;$r0?: boolean|null;$r1?: boolean|null;c0?: number|null;c1?: number|null;r0?: number|null;r1?: number|null;trim?: "head"|"tail"|"both"|null;};

A range in R1C1 style coordinates.

Properties

PropertyTypeDescription
$c0?boolean | nullSignifies that c0 is an absolute value
$c1?boolean | nullSignifies that c1 is an absolute value
$r0?boolean | nullSignifies that r0 is an absolute value
$r1?boolean | nullSignifies that r1 is an absolute value
c0?number | nullLeft column of the range
c1?number | nullRight column of the range
r0?number | nullTop row of the range
r1?number | nullBottom row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

ReferenceA1

typeReferenceA1={context?: string[];range: RangeA1;};

A reference containing an A1 style range. See Prefixes.md for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeA1The reference's range

ReferenceA1Xlsx

typeReferenceA1Xlsx={range: RangeA1;sheetName?: string;workbookName?: string;};

A reference containing an A1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeA1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceIdentifier

typeReferenceIdentifier={kind: "name"|"range"|"beam"|"table";loc?: SourceLocation;type: "ReferenceIdentifier";value: string;}&Node;

An identifier for a range or a name.

Type Declaration

NameTypeDescription
kind"name" | "range" | "beam" | "table"The kind of reference the value holds.
loc?SourceLocationThe original source position of the node.
type"ReferenceIdentifier"The type of this AST node.
valuestringThe untouched reference value.

ReferenceName

typeReferenceName={context?: string[];name: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
namestringThe reference's name

ReferenceNameXlsx

typeReferenceNameXlsx={name: string;sheetName?: string;workbookName?: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
namestringThe reference's name
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceR1C1

typeReferenceR1C1={context?: string[];range: RangeR1C1;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeR1C1The reference's range

ReferenceR1C1Xlsx

typeReferenceR1C1Xlsx={range: RangeR1C1;sheetName?: string;workbookName?: string;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeR1C1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceStruct

typeReferenceStruct={columns?: string[];context?: string[];sections?: string[];table?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
context?string[]A collection of scopes for the reference
sections?string[]The sections this reference targets
table?stringThe table this reference targets

ReferenceStructXlsx

typeReferenceStructXlsx={columns?: string[];sections?: string[];sheetName?: string;table?: string;workbookName?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
sections?string[]The sections this reference targets
sheetName?stringA context sheet scope
table?stringThe table this reference targets
workbookName?stringA context workbook scope

SourceLocation

typeSourceLocation=number[];

Represents the source location information of the node. If the node contains no information about the source location, the field is null; otherwise it is an array consisting of a two numbers: A start offset (the position of the first character of the parsed source region) and an end offset (the position of the first character after the parsed source region).

Token

typeToken=Record<string,unknown>&{loc?: number[];type: string;unterminated?: boolean;value: string;};

A formula language token.

Type Declaration

NameTypeDescription
loc?number[]Source position offsets to the token
typestringThe type of the token
unterminated?booleanSignifies an unterminated string token
valuestringThe value of the token

TokenEnhanced

typeTokenEnhanced=Token&{depth?: number;error?: boolean;groupId?: string;index: number;};

A token with extra meta data.

Type Declaration

NameTypeDescription
depth?numberThis token's level of nesting inside parentheses
error?booleanToken is of unknown type or a paren without a match
groupId?stringThe ID of a group which this token belongs (e.g. matching parens)
indexnumberA zero based position in a token list

UnaryExpression

typeUnaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: UnaryOperator;type: "UnaryExpression";}&Node;

A unary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorUnaryOperatorThe expression's operator.
type"UnaryExpression"The type of this AST node.

UnaryOperator

typeUnaryOperator="+"|"-"|"%"|"#"|"@";

A unary operator token.

MAX_COLS

constMAX_COLS: number;

The maximum number of columns a spreadsheet reference may hold (16383).

MAX_ROWS

constMAX_ROWS: number;

The maximum number of rows a spreadsheet reference may hold (1048575).

nodeTypes

constnodeTypes: Readonly<{ARRAY: "ArrayExpression";BINARY: "BinaryExpression";CALL: "CallExpression";ERROR: "ErrorLiteral";IDENTIFIER: "Identifier";LAMBDA: "LambdaExpression";LET: "LetExpression";LET_DECL: "LetDeclarator";LITERAL: "Literal";REFERENCE: "ReferenceIdentifier";UNARY: "UnaryExpression";}>;

A dictionary of the types used to identify AST node variants.

tokenTypes

consttokenTypes: Readonly<{BOOLEAN: "bool";CONTEXT: "context";CONTEXT_QUOTE: "context_quote";ERROR: "error";FUNCTION: "func";FX_PREFIX: "fx_prefix";NEWLINE: "newline";NUMBER: "number";OPERATOR: "operator";REF_BEAM: "range_beam";REF_NAMED: "range_named";REF_RANGE: "range";REF_STRUCT: "structured";REF_TERNARY: "range_ternary";STRING: "string";UNKNOWN: "unknown";WHITESPACE: "whitespace";}>;

A dictionary of the types used to identify token variants.

fx/xlsx

A tokenizer, parser, and other utilities to work with Excel formula code.

The xslx entry-point methods expect and return the variant of references that uses properties. If you are not using xlsx files you should use the fx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Functions

References

addA1RangeBounds

Re-exports addA1RangeBounds


ArrayExpression

Re-exports ArrayExpression


AstExpression

Re-exports AstExpression


BinaryExpression

Re-exports BinaryExpression


BinaryOperator

Re-exports BinaryOperator


CallExpression

Re-exports CallExpression


ErrorLiteral

Re-exports ErrorLiteral


fromCol

Re-exports fromCol


Identifier

Re-exports Identifier


isArrayNode

Re-exports isArrayNode


isBinaryNode

Re-exports isBinaryNode


isCallNode

Re-exports isCallNode


isError

Re-exports isError


isErrorNode

Re-exports isErrorNode


isExpressionNode

Re-exports isExpressionNode


isFunction

Re-exports isFunction


isFxPrefix

Re-exports isFxPrefix


isIdentifierNode

Re-exports isIdentifierNode


isLambdaNode

Re-exports isLambdaNode


isLetDeclaratorNode

Re-exports isLetDeclaratorNode


isLetNode

Re-exports isLetNode


isLiteral

Re-exports isLiteral


isLiteralNode

Re-exports isLiteralNode


isOperator

Re-exports isOperator


isRange

Re-exports isRange


isReference

Re-exports isReference


isReferenceNode

Re-exports isReferenceNode


isUnaryNode

Re-exports isUnaryNode


isWhitespace

Re-exports isWhitespace


LambdaExpression

Re-exports LambdaExpression


LetDeclarator

Re-exports LetDeclarator


LetExpression

Re-exports LetExpression


Literal

Re-exports Literal


MAX_COLS

Re-exports MAX_COLS


MAX_ROWS

Re-exports MAX_ROWS


Node

Re-exports Node


nodeTypes

Re-exports nodeTypes


OptsFixRanges

Re-exports OptsFixRanges


OptsParse

Re-exports OptsParse


OptsParseA1Ref

Re-exports OptsParseA1Ref


OptsParseR1C1Ref

Re-exports OptsParseR1C1Ref


OptsStringifyStructRef

Re-exports OptsStringifyStructRef


OptsTokenize

Re-exports OptsTokenize


OptsTranslateFormulaToA1

Re-exports OptsTranslateFormulaToA1


OptsTranslateTokensToA1

Re-exports OptsTranslateTokensToA1


OptsTranslateToR1C1

Re-exports OptsTranslateToR1C1


parse

Re-exports parse


parseA1Range

Re-exports parseA1Range


parseR1C1Range

Re-exports parseR1C1Range


RangeA1

Re-exports RangeA1


RangeR1C1

Re-exports RangeR1C1


ReferenceA1

Re-exports ReferenceA1


ReferenceA1Xlsx

Re-exports ReferenceA1Xlsx


ReferenceIdentifier

Re-exports ReferenceIdentifier


ReferenceName

Re-exports ReferenceName


ReferenceNameXlsx

Re-exports ReferenceNameXlsx


ReferenceR1C1

Re-exports ReferenceR1C1


ReferenceR1C1Xlsx

Re-exports ReferenceR1C1Xlsx


ReferenceStruct

Re-exports ReferenceStruct


ReferenceStructXlsx

Re-exports ReferenceStructXlsx


SourceLocation

Re-exports SourceLocation


stringifyTokens

Re-exports stringifyTokens


toCol

Re-exports toCol


Token

Re-exports Token


TokenEnhanced

Re-exports TokenEnhanced


tokenTypes

Re-exports tokenTypes


translateFormulaToA1

Re-exports translateFormulaToA1


translateFormulaToR1C1

Re-exports translateFormulaToR1C1


translateTokensToA1

Re-exports translateTokensToA1


translateTokensToR1C1

Re-exports translateTokensToR1C1


UnaryExpression

Re-exports UnaryExpression


UnaryOperator

Re-exports UnaryOperator

addTokenMeta()

functionaddTokenMeta(tokenlist: Token[],context?: {sheetName?: string;workbookName?: string;}): TokenEnhanced[];

Runs through a list of tokens and adds extra attributes such as matching parens and ranges.

The context parameter defines default reference attributes: { workbookName: 'report.xlsx', sheetName: 'Sheet1' }. If supplied, these are used to match A1 to Sheet1!A1.

All tokens will be tagged with a .depth number value to indicating the level of nesting in parentheses as well as an .index number indicating their zero based position in the list.

The returned output will be the same array of tokens but the following properties will added to tokens (as applicable):

Parentheses ( )

Matching parens will be tagged with .groupId string identifier as well as a .depth number value (indicating the level of nesting).

Closing parens without a counterpart will be tagged with .error (boolean true).

Curly brackets { }

Matching curly brackets will be tagged with .groupId string identifier. These may not be nested in Excel.

Closing curly brackets without a counterpart will be tagged with .error (boolean true).

Ranges (REF_RANGE or REF_BEAM type tokens)

All ranges will be tagged with .groupId string identifier regardless of the number of times they occur.

Tokens of type UNKNOWN

All will be tagged with .error (boolean true).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens (from tokenize())
context?{ sheetName?: string; workbookName?: string; }A context used to match A1 to Sheet1!A1.
context.sheetName?stringAn implied sheet name ('Sheet1')
context.workbookName?stringAn implied workbook name ('report.xlsx')

Returns

TokenEnhanced[]

The input array with the enchanced tokens

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens and returns a new array of tokens with values and position-data updated.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Unlike Excel, fx does not normalize sheet or workbook names of references.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1Xlsx|ReferenceNameXlsx;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// workbookName: '',// sheetName: 'Sheet1',// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1Xlsx | ReferenceNameXlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceNameXlsx|ReferenceR1C1Xlsx;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceNameXlsx | ReferenceR1C1Xlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStructXlsx;

Parse a structured reference string into an object representing it.

parseStructRef('[workbook.xlsx]!tableName[[#Data],[Column1]:[Column2]]');// => {// workbookName: 'workbook.xlsx',// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStructXlsx

An object representing a valid reference or null if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1Xlsx|ReferenceNameXlsx): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({sheetName: 'Sheet1',range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1Xlsx | ReferenceNameXlsxA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceNameXlsx|ReferenceR1C1Xlsx): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({sheetName: 'Sheet1',range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceNameXlsx | ReferenceR1C1XlsxA reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStructXlsx,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({workbookName: 'workbook.xlsx',sheetName: '',sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructXlsxA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
3323 lines (2177 loc) · 76.1 KB

File metadata and controls

3323 lines (2177 loc) · 76.1 KB

@borgar/fx

Modules

fx

A tokenizer, parser, and other utilities to work with Excel formula code.

The base entry-point methods expect and return the variant of references that uses contexts. If you are using xlsx files or otherwise want to work with the xlsx-file variant of references you should use the fx/xlsx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Type Aliases

Variables

Functions

addA1RangeBounds()

functionaddA1RangeBounds(range: RangeA1): RangeA1;

Fill the any missing bounds in range objects. Top will be set to 0, bottom to 1048575, left to 0, and right to 16383, if they are null or undefined.

addA1RangeBounds({top: 0,left: 0,bottom: 1,$top: true,$left: false,$bottom: false,});// => {// top: 0,// left: 0,// bottom: 1,// right: 16383, // ← Added// $top: true,// $left: false,// $bottom: false,// $right: false // ← Added// }

Parameters

ParameterTypeDescription
rangeRangeA1The range part of a reference object.

Returns

RangeA1

The same range with missing bounds filled in.

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Returns a new array of tokens with values and position data updated.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

fromCol()

functionfromCol(columnString: string): number;

Convert a column string representation to a 0 based offset number ("C" = 2).

The method expects a valid column identifier made up of only A-Z letters, which may be either upper or lower case. Other input will return garbage.

Parameters

ParameterTypeDescription
columnStringstringThe column string identifier

Returns

number

Zero based column index number

isArrayNode()

functionisArrayNode(node?: Node): node is ArrayExpression;

Determines whether the specified node is a ArrayExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ArrayExpression

True if the specified token is a ArrayExpression, False otherwise.

isBinaryNode()

functionisBinaryNode(node?: Node): node is BinaryExpression;

Determines whether the specified node is a BinaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is BinaryExpression

True if the specified token is a BinaryExpression, False otherwise.

isCallNode()

functionisCallNode(node?: Node): node is CallExpression;

Determines whether the specified node is a CallExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is CallExpression

True if the specified token is a CallExpression, False otherwise.

isError()

functionisError(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an error.

Returns true if the input is a token of type ERROR (#VALUE!). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is error, False otherwise.

isErrorNode()

functionisErrorNode(node?: Node): node is ErrorLiteral;

Determines whether the specified node is an ErrorLiteral.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ErrorLiteral

True if the specified token is an ErrorLiteral, False otherwise.

isExpressionNode()

functionisExpressionNode(node?: Node): node is AstExpression;

Determines whether the specified node is a AstExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is AstExpression

True if the specified token is a AstExpression, False otherwise.

isFunction()

functionisFunction(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a function.

Returns true if the input is a token of type FUNCTION. In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is function, False otherwise.

isFxPrefix()

functionisFxPrefix(token?: Pick<Token,"type">): boolean;

Returns true if the input is a token of type FX_PREFIX (leading = in formula). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is effects prefix, False otherwise.

isIdentifierNode()

functionisIdentifierNode(node?: Node): node is Identifier;

Determines whether the specified node is an Identifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Identifier

True if the specified token is an Identifier, False otherwise.

isLambdaNode()

functionisLambdaNode(node?: Node): node is LambdaExpression;

Determines whether the specified node is a LambdaExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LambdaExpression

True if the specified token is a LambdaExpression, False otherwise.

isLetDeclaratorNode()

functionisLetDeclaratorNode(node?: Node): node is LetDeclarator;

Determines whether the specified node is a LetDeclarator.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetDeclarator

True if the specified token is a LetDeclarator, False otherwise.

isLetNode()

functionisLetNode(node?: Node): node is LetExpression;

Determines whether the specified node is a LetExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetExpression

True if the specified token is a LetExpression, False otherwise.

isLiteral()

functionisLiteral(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a literal.

Returns true if the input is a token of type BOOLEAN (TRUE or FALSE), ERROR (#VALUE!), NUMBER (123.4), or STRING ("lorem ipsum"). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is literal, False otherwise.

isLiteralNode()

functionisLiteralNode(node?: Node): node is Literal;

Determines whether the specified node is a Literal.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Literal

True if the specified token is a Literal, False otherwise.

isOperator()

functionisOperator(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an operator.

Returns true if the input is a token of type OPERATOR (+ or :). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is operator, False otherwise.

isRange()

functionisRange(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a range.

Returns true if the input is a token that has a type of either REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), or REF_BEAM (A:A or 1:1). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">A token

Returns

boolean

True if the specified token is range, False otherwise.

isReference()

functionisReference(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a reference.

Returns true if the input is a token of type REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), REF_BEAM (A:A or 1:1), or REF_NAMED (myrange). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is reference, False otherwise.

isReferenceNode()

functionisReferenceNode(node?: Node): node is ReferenceIdentifier;

Determines whether the specified node is a ReferenceIdentifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ReferenceIdentifier

True if the specified token is a ReferenceIdentifier, False otherwise.

isUnaryNode()

functionisUnaryNode(node?: Node): node is UnaryExpression;

Determines whether the specified node is a UnaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is UnaryExpression

True if the specified token is a UnaryExpression, False otherwise.

isWhitespace()

functionisWhitespace(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is whitespace.

Returns true if the input is a token of type WHITESPACE () or NEWLINE (\n). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is whitespace, False otherwise.

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parse()

functionparse(tokenlist: Token[],options?: OptsParse): AstExpression;

Parses a string formula or list of tokens into an AST.

The parser assumes mergeRefs and negativeNumbers were true when the tokens were generated. It does not yet recognize reference context tokens or know how to deal with unary minuses in arrays.

The AST Abstract Syntax Tree's format is documented in AST_format.md.

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.
optionsOptsParseOptions for the parsers behavior.

Returns

AstExpression

An AST of nodes.

See

parseA1Range()

functionparseA1Range(rangeString: string,allowTernary?: boolean): RangeA1;

Parse A1-style range string into a RangeA1 object.

Parameters

ParameterTypeDefault valueDescription
rangeStringstringundefinedA1-style range string.
allowTernary?booleantruePermit ternary ranges like A2:A or B2:2.

Returns

RangeA1

A reference object.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1|ReferenceName;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// context: [ 'Sheet1' ],// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1 | ReferenceName

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Range()

functionparseR1C1Range(rangeString: string): RangeR1C1;

Parse R1C1-style range string into a RangeR1C1 object.

Parameters

ParameterTypeDescription
rangeStringstringR1C1-style range string.

Returns

RangeR1C1

A reference object.

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceName|ReferenceR1C1;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceName | ReferenceR1C1

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStruct;

Parse a structured reference string into an object representing it.

parseStructRef('workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]');// => {// context: [ 'workbook.xlsx' ],// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStruct

An object representing a valid reference or undefined if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1|ReferenceName): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({context: ['Sheet1'],range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1 | ReferenceNameA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceName|ReferenceR1C1): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({context: ['Sheet1'],range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceName | ReferenceR1C1A reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStruct,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({context: ['workbook.xlsx'],sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

See

OptsStringifyStructRef

stringifyTokens()

functionstringifyTokens(tokens: Token[]): string;

Collapses a list of tokens into a formula string.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens.

Returns

string

A formula string.

toCol()

functiontoCol(columnIndex: number): string;

Convert a 0 based offset number to a column string representation (0 = "A", 2 = "C").

The method expects a number between 0 and 16383. Other input will return garbage.

Parameters

ParameterTypeDescription
columnIndexnumberZero based column index number

Returns

string

The column string identifier

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parsers will need to handle this.

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

translateFormulaToA1()

functiontranslateFormulaToA1(formula: string,anchorCell: string,options?: OptsTranslateFormulaToA1): string;

Translates ranges in a formula from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so you can set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Parameters

ParameterTypeDescription
formulastringAn Excel formula string that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateFormulaToA1Translation options.

Returns

string

A formula string.

See

OptsTranslateFormulaToA1

translateFormulaToR1C1()

functiontranslateFormulaToR1C1(formula: string,anchorCell: string,options?: OptsTranslateToR1C1): string;

Translates ranges in a formula from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
formulastringAn Excel formula that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
options?OptsTranslateToR1C1The options

Returns

string

A formula string.

See

OptsTranslateToR1C1

translateTokensToA1()

functiontranslateTokensToA1(tokens: Token[],anchorCell: string,options?: OptsTranslateTokensToA1): Token[];

Translates ranges in a list of tokens from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so may set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Note that if you are passing in a list of tokens that was not created using mergeRefs and you disable edge wrapping (or you simply set both options to false), you can end up with a formula such as =#REF!:B2 or =Sheet3!#REF!:F3. These are valid formulas in the Excel formula language and Excel will accept them, but they are not supported in Google Sheets.

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateTokensToA1Translation options.

Returns

Token[]

A token list.

See

OptsTranslateTokensToA1

translateTokensToR1C1()

functiontranslateTokensToR1C1(tokens: Token[],anchorCell: string): Token[];

Translates ranges in a list of tokens from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).

Returns

Token[]

A token list.

ArrayExpression

typeArrayExpression={elements: (|ReferenceIdentifier|Literal|ErrorLiteral|CallExpression)[][];loc?: SourceLocation;type: "ArrayExpression";}&Node;

An array expression. Excel does not have empty or sparse arrays and restricts array elements to literals. Google Sheets allows ReferenceIdentifiers and CallExpressions as elements of arrays, the fx parser has options for this but they are off by default.

Type Declaration

NameTypeDescription
elements( | ReferenceIdentifier | Literal | ErrorLiteral | CallExpression)[][]The elements of the array.
loc?SourceLocationThe original source position of the node.
type"ArrayExpression"The type of this AST node.

AstExpression

typeAstExpression=|ReferenceIdentifier|Literal|ErrorLiteral|UnaryExpression|BinaryExpression|CallExpression|ArrayExpression|LambdaExpression|LetExpression;

Represents an evaluate-able expression.

BinaryExpression

typeBinaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: BinaryOperator;type: "BinaryExpression";}&Node;

A binary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorBinaryOperatorThe expression's operator.
type"BinaryExpression"The type of this AST node.

BinaryOperator

typeBinaryOperator=|"="|"<"|">"|"<="|">="|"<>"|"-"|"+"|"*"|"/"|"^"|":"|" "|","|"&";

A binary operator token.

Note that Excels union operator is whitespace so a parser must take care to normalize this to a single space.

CallExpression

typeCallExpression={arguments: AstExpression[];callee: Identifier;loc?: SourceLocation;type: "CallExpression";}&Node;

A function call expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the function.
calleeIdentifierThe function being called.
loc?SourceLocationThe original source position of the node.
type"CallExpression"The type of this AST node.

ErrorLiteral

typeErrorLiteral={loc?: SourceLocation;raw: string;type: "ErrorLiteral";value: string;}&Node;

An Error expression.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"ErrorLiteral"The type of this AST node.
valuestringThe value of the error.

Identifier

typeIdentifier={loc?: SourceLocation;name: string;type: "Identifier";}&Node;

An identifier. These appear on CallExpression, LambdaExpression, and LetExpression and will always be a static string representing the name of a function call or parameter.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
namestringThe identifying name.
type"Identifier"The type of this AST node.

LambdaExpression

typeLambdaExpression={body: AstExpression|null;loc?: SourceLocation;params: Identifier[];type: "LambdaExpression";}&Node;

A LAMBDA expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LAMBDA's expression.
loc?SourceLocationThe original source position of the node.
paramsIdentifier[]The LAMBDA's parameters.
type"LambdaExpression"The type of this AST node.

LetDeclarator

typeLetDeclarator={id: Identifier;init: AstExpression|null;loc?: SourceLocation;type: "LetDeclarator";}&Node;

A LET parameter declaration.

Type Declaration

NameTypeDescription
idIdentifierThe name of the variable.
initAstExpression | nullThe variable's initializing expression.
loc?SourceLocationThe original source position of the node.
type"LetDeclarator"The type of this AST node.

LetExpression

typeLetExpression={body: AstExpression|null;declarations: LetDeclarator[];loc?: SourceLocation;type: "LetExpression";}&Node;

A LET expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LET's scoped expression.
declarationsLetDeclarator[]The LET's variable declarations.
loc?SourceLocationThe original source position of the node.
type"LetExpression"The type of this AST node.

Literal

typeLiteral={loc?: SourceLocation;raw: string;type: "Literal";value: string|number|boolean;}&Node;

A literal token. Captures numbers, strings, and booleans. Literal errors have their own variant type.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"Literal"The type of this AST node.
valuestring | number | booleanThe value of the literal.

Node

typeNode={loc?: SourceLocation;type: string;};

All AST nodes are represented by Node objects. They may have any prototype inheritance but implement the same basic interface.

The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements.

Properties

PropertyTypeDescription
loc?SourceLocationThe original source position of the node.
typestringThe type of this AST node.

OptsFixRanges

typeOptsFixRanges={addBounds?: boolean;thisRow?: boolean;};

Options for fixTokenRanges and fixFormulaRanges.

Properties

PropertyTypeDefault valueDescription
addBounds?booleanfalseFill in any undefined bounds of range objects. Top to 0, bottom to 1048575, left to 0, and right to 16383.
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsParse

typeOptsParse={looseRefCalls?: boolean;permitArrayCalls?: boolean;permitArrayRanges?: boolean;};

Options for parse.

Properties

PropertyTypeDefault valueDescription
looseRefCalls?booleanfalsePermits any function call where otherwise only functions that return references would be permitted.
permitArrayCalls?booleanfalseFunction calls are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.
permitArrayRanges?booleanfalseRanges are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.

OptsParseA1Ref

typeOptsParseA1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseA1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsParseR1C1Ref

typeOptsParseR1C1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseR1C1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsStringifyStructRef

typeOptsStringifyStructRef={thisRow?: boolean;};

Options for stringifyStructRef

Properties

PropertyTypeDefault valueDescription
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsTokenize

typeOptsTokenize={allowTernary?: boolean;mergeRefs?: boolean;negativeNumbers?: boolean;r1c1?: boolean;withLocation?: boolean;};

Options for tokenize.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be returned as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2). This is the same as calling mergeRefTokens
negativeNumbers?booleantrueMerges unary minuses with their immediately following number tokens (-,1) => -1 (alternatively these will be unary operations in the tree).
r1c1?booleanfalseRanges are expected to be in the R1C1 style format rather than the more popular A1 style.
withLocation?booleantrueNodes will include source position offsets to the tokens: { loc: [ start, end ] }

OptsTranslateFormulaToA1

typeOptsTranslateFormulaToA1={allowTernary?: boolean;mergeRefs?: boolean;wrapEdges?: boolean;};

Options for translateFormulaToA1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be treated as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2).
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

OptsTranslateToR1C1

typeOptsTranslateToR1C1={allowTernary?: boolean;};

Options for translateFormulaToR1C1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsTranslateTokensToA1

typeOptsTranslateTokensToA1={wrapEdges?: boolean;};

Options for translateTokensToA1

Properties

PropertyTypeDefault valueDescription
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

RangeA1

typeRangeA1={$bottom?: boolean|null;$left?: boolean|null;$right?: boolean|null;$top?: boolean|null;bottom?: number|null;left: number|null;right?: number|null;top: number|null;trim?: "head"|"tail"|"both"|null;};

A range in A1 style coordinates.

Properties

PropertyTypeDescription
$bottom?boolean | nullSignifies that bottom is a "locked" value
$left?boolean | nullSignifies that left is a "locked" value
$right?boolean | nullSignifies that right is a "locked" value
$top?boolean | nullSignifies that top is a "locked" value
bottom?number | nullBottom row of the range
leftnumber | nullLeft column of the range
right?number | nullRight column of the range
topnumber | nullTop row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

RangeR1C1

typeRangeR1C1={$c0?: boolean|null;$c1?: boolean|null;$r0?: boolean|null;$r1?: boolean|null;c0?: number|null;c1?: number|null;r0?: number|null;r1?: number|null;trim?: "head"|"tail"|"both"|null;};

A range in R1C1 style coordinates.

Properties

PropertyTypeDescription
$c0?boolean | nullSignifies that c0 is an absolute value
$c1?boolean | nullSignifies that c1 is an absolute value
$r0?boolean | nullSignifies that r0 is an absolute value
$r1?boolean | nullSignifies that r1 is an absolute value
c0?number | nullLeft column of the range
c1?number | nullRight column of the range
r0?number | nullTop row of the range
r1?number | nullBottom row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

ReferenceA1

typeReferenceA1={context?: string[];range: RangeA1;};

A reference containing an A1 style range. See Prefixes.md for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeA1The reference's range

ReferenceA1Xlsx

typeReferenceA1Xlsx={range: RangeA1;sheetName?: string;workbookName?: string;};

A reference containing an A1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeA1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceIdentifier

typeReferenceIdentifier={kind: "name"|"range"|"beam"|"table";loc?: SourceLocation;type: "ReferenceIdentifier";value: string;}&Node;

An identifier for a range or a name.

Type Declaration

NameTypeDescription
kind"name" | "range" | "beam" | "table"The kind of reference the value holds.
loc?SourceLocationThe original source position of the node.
type"ReferenceIdentifier"The type of this AST node.
valuestringThe untouched reference value.

ReferenceName

typeReferenceName={context?: string[];name: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
namestringThe reference's name

ReferenceNameXlsx

typeReferenceNameXlsx={name: string;sheetName?: string;workbookName?: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
namestringThe reference's name
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceR1C1

typeReferenceR1C1={context?: string[];range: RangeR1C1;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeR1C1The reference's range

ReferenceR1C1Xlsx

typeReferenceR1C1Xlsx={range: RangeR1C1;sheetName?: string;workbookName?: string;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeR1C1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceStruct

typeReferenceStruct={columns?: string[];context?: string[];sections?: string[];table?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
context?string[]A collection of scopes for the reference
sections?string[]The sections this reference targets
table?stringThe table this reference targets

ReferenceStructXlsx

typeReferenceStructXlsx={columns?: string[];sections?: string[];sheetName?: string;table?: string;workbookName?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
sections?string[]The sections this reference targets
sheetName?stringA context sheet scope
table?stringThe table this reference targets
workbookName?stringA context workbook scope

SourceLocation

typeSourceLocation=number[];

Represents the source location information of the node. If the node contains no information about the source location, the field is null; otherwise it is an array consisting of a two numbers: A start offset (the position of the first character of the parsed source region) and an end offset (the position of the first character after the parsed source region).

Token

typeToken=Record<string,unknown>&{loc?: number[];type: string;unterminated?: boolean;value: string;};

A formula language token.

Type Declaration

NameTypeDescription
loc?number[]Source position offsets to the token
typestringThe type of the token
unterminated?booleanSignifies an unterminated string token
valuestringThe value of the token

TokenEnhanced

typeTokenEnhanced=Token&{depth?: number;error?: boolean;groupId?: string;index: number;};

A token with extra meta data.

Type Declaration

NameTypeDescription
depth?numberThis token's level of nesting inside parentheses
error?booleanToken is of unknown type or a paren without a match
groupId?stringThe ID of a group which this token belongs (e.g. matching parens)
indexnumberA zero based position in a token list

UnaryExpression

typeUnaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: UnaryOperator;type: "UnaryExpression";}&Node;

A unary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorUnaryOperatorThe expression's operator.
type"UnaryExpression"The type of this AST node.

UnaryOperator

typeUnaryOperator="+"|"-"|"%"|"#"|"@";

A unary operator token.

MAX_COLS

constMAX_COLS: number;

The maximum number of columns a spreadsheet reference may hold (16383).

MAX_ROWS

constMAX_ROWS: number;

The maximum number of rows a spreadsheet reference may hold (1048575).

nodeTypes

constnodeTypes: Readonly<{ARRAY: "ArrayExpression";BINARY: "BinaryExpression";CALL: "CallExpression";ERROR: "ErrorLiteral";IDENTIFIER: "Identifier";LAMBDA: "LambdaExpression";LET: "LetExpression";LET_DECL: "LetDeclarator";LITERAL: "Literal";REFERENCE: "ReferenceIdentifier";UNARY: "UnaryExpression";}>;

A dictionary of the types used to identify AST node variants.

tokenTypes

consttokenTypes: Readonly<{BOOLEAN: "bool";CONTEXT: "context";CONTEXT_QUOTE: "context_quote";ERROR: "error";FUNCTION: "func";FX_PREFIX: "fx_prefix";NEWLINE: "newline";NUMBER: "number";OPERATOR: "operator";REF_BEAM: "range_beam";REF_NAMED: "range_named";REF_RANGE: "range";REF_STRUCT: "structured";REF_TERNARY: "range_ternary";STRING: "string";UNKNOWN: "unknown";WHITESPACE: "whitespace";}>;

A dictionary of the types used to identify token variants.

fx/xlsx

A tokenizer, parser, and other utilities to work with Excel formula code.

The xslx entry-point methods expect and return the variant of references that uses properties. If you are not using xlsx files you should use the fx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Functions

References

addA1RangeBounds

Re-exports addA1RangeBounds


ArrayExpression

Re-exports ArrayExpression


AstExpression

Re-exports AstExpression


BinaryExpression

Re-exports BinaryExpression


BinaryOperator

Re-exports BinaryOperator


CallExpression

Re-exports CallExpression


ErrorLiteral

Re-exports ErrorLiteral


fromCol

Re-exports fromCol


Identifier

Re-exports Identifier


isArrayNode

Re-exports isArrayNode


isBinaryNode

Re-exports isBinaryNode


isCallNode

Re-exports isCallNode


isError

Re-exports isError


isErrorNode

Re-exports isErrorNode


isExpressionNode

Re-exports isExpressionNode


isFunction

Re-exports isFunction


isFxPrefix

Re-exports isFxPrefix


isIdentifierNode

Re-exports isIdentifierNode


isLambdaNode

Re-exports isLambdaNode


isLetDeclaratorNode

Re-exports isLetDeclaratorNode


isLetNode

Re-exports isLetNode


isLiteral

Re-exports isLiteral


isLiteralNode

Re-exports isLiteralNode


isOperator

Re-exports isOperator


isRange

Re-exports isRange


isReference

Re-exports isReference


isReferenceNode

Re-exports isReferenceNode


isUnaryNode

Re-exports isUnaryNode


isWhitespace

Re-exports isWhitespace


LambdaExpression

Re-exports LambdaExpression


LetDeclarator

Re-exports LetDeclarator


LetExpression

Re-exports LetExpression


Literal

Re-exports Literal


MAX_COLS

Re-exports MAX_COLS


MAX_ROWS

Re-exports MAX_ROWS


Node

Re-exports Node


nodeTypes

Re-exports nodeTypes


OptsFixRanges

Re-exports OptsFixRanges


OptsParse

Re-exports OptsParse


OptsParseA1Ref

Re-exports OptsParseA1Ref


OptsParseR1C1Ref

Re-exports OptsParseR1C1Ref


OptsStringifyStructRef

Re-exports OptsStringifyStructRef


OptsTokenize

Re-exports OptsTokenize


OptsTranslateFormulaToA1

Re-exports OptsTranslateFormulaToA1


OptsTranslateTokensToA1

Re-exports OptsTranslateTokensToA1


OptsTranslateToR1C1

Re-exports OptsTranslateToR1C1


parse

Re-exports parse


parseA1Range

Re-exports parseA1Range


parseR1C1Range

Re-exports parseR1C1Range


RangeA1

Re-exports RangeA1


RangeR1C1

Re-exports RangeR1C1


ReferenceA1

Re-exports ReferenceA1


ReferenceA1Xlsx

Re-exports ReferenceA1Xlsx


ReferenceIdentifier

Re-exports ReferenceIdentifier


ReferenceName

Re-exports ReferenceName


ReferenceNameXlsx

Re-exports ReferenceNameXlsx


ReferenceR1C1

Re-exports ReferenceR1C1


ReferenceR1C1Xlsx

Re-exports ReferenceR1C1Xlsx


ReferenceStruct

Re-exports ReferenceStruct


ReferenceStructXlsx

Re-exports ReferenceStructXlsx


SourceLocation

Re-exports SourceLocation


stringifyTokens

Re-exports stringifyTokens


toCol

Re-exports toCol


Token

Re-exports Token


TokenEnhanced

Re-exports TokenEnhanced


tokenTypes

Re-exports tokenTypes


translateFormulaToA1

Re-exports translateFormulaToA1


translateFormulaToR1C1

Re-exports translateFormulaToR1C1


translateTokensToA1

Re-exports translateTokensToA1


translateTokensToR1C1

Re-exports translateTokensToR1C1


UnaryExpression

Re-exports UnaryExpression


UnaryOperator

Re-exports UnaryOperator

addTokenMeta()

functionaddTokenMeta(tokenlist: Token[],context?: {sheetName?: string;workbookName?: string;}): TokenEnhanced[];

Runs through a list of tokens and adds extra attributes such as matching parens and ranges.

The context parameter defines default reference attributes: { workbookName: 'report.xlsx', sheetName: 'Sheet1' }. If supplied, these are used to match A1 to Sheet1!A1.

All tokens will be tagged with a .depth number value to indicating the level of nesting in parentheses as well as an .index number indicating their zero based position in the list.

The returned output will be the same array of tokens but the following properties will added to tokens (as applicable):

Parentheses ( )

Matching parens will be tagged with .groupId string identifier as well as a .depth number value (indicating the level of nesting).

Closing parens without a counterpart will be tagged with .error (boolean true).

Curly brackets { }

Matching curly brackets will be tagged with .groupId string identifier. These may not be nested in Excel.

Closing curly brackets without a counterpart will be tagged with .error (boolean true).

Ranges (REF_RANGE or REF_BEAM type tokens)

All ranges will be tagged with .groupId string identifier regardless of the number of times they occur.

Tokens of type UNKNOWN

All will be tagged with .error (boolean true).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens (from tokenize())
context?{ sheetName?: string; workbookName?: string; }A context used to match A1 to Sheet1!A1.
context.sheetName?stringAn implied sheet name ('Sheet1')
context.workbookName?stringAn implied workbook name ('report.xlsx')

Returns

TokenEnhanced[]

The input array with the enchanced tokens

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens and returns a new array of tokens with values and position-data updated.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Unlike Excel, fx does not normalize sheet or workbook names of references.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1Xlsx|ReferenceNameXlsx;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// workbookName: '',// sheetName: 'Sheet1',// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1Xlsx | ReferenceNameXlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceNameXlsx|ReferenceR1C1Xlsx;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceNameXlsx | ReferenceR1C1Xlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStructXlsx;

Parse a structured reference string into an object representing it.

parseStructRef('[workbook.xlsx]!tableName[[#Data],[Column1]:[Column2]]');// => {// workbookName: 'workbook.xlsx',// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStructXlsx

An object representing a valid reference or null if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1Xlsx|ReferenceNameXlsx): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({sheetName: 'Sheet1',range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1Xlsx | ReferenceNameXlsxA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceNameXlsx|ReferenceR1C1Xlsx): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({sheetName: 'Sheet1',range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceNameXlsx | ReferenceR1C1XlsxA reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStructXlsx,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({workbookName: 'workbook.xlsx',sheetName: '',sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructXlsxA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

History
3323 lines (2177 loc) · 76.1 KB

File metadata and controls

3323 lines (2177 loc) · 76.1 KB

@borgar/fx

Modules

fx

A tokenizer, parser, and other utilities to work with Excel formula code.

The base entry-point methods expect and return the variant of references that uses contexts. If you are using xlsx files or otherwise want to work with the xlsx-file variant of references you should use the fx/xlsx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Type Aliases

Variables

Functions

addA1RangeBounds()

functionaddA1RangeBounds(range: RangeA1): RangeA1;

Fill the any missing bounds in range objects. Top will be set to 0, bottom to 1048575, left to 0, and right to 16383, if they are null or undefined.

addA1RangeBounds({top: 0,left: 0,bottom: 1,$top: true,$left: false,$bottom: false,});// => {// top: 0,// left: 0,// bottom: 1,// right: 16383, // ← Added// $top: true,// $left: false,// $bottom: false,// $right: false // ← Added// }

Parameters

ParameterTypeDescription
rangeRangeA1The range part of a reference object.

Returns

RangeA1

The same range with missing bounds filled in.

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Returns a new array of tokens with values and position data updated.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

fromCol()

functionfromCol(columnString: string): number;

Convert a column string representation to a 0 based offset number ("C" = 2).

The method expects a valid column identifier made up of only A-Z letters, which may be either upper or lower case. Other input will return garbage.

Parameters

ParameterTypeDescription
columnStringstringThe column string identifier

Returns

number

Zero based column index number

isArrayNode()

functionisArrayNode(node?: Node): node is ArrayExpression;

Determines whether the specified node is a ArrayExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ArrayExpression

True if the specified token is a ArrayExpression, False otherwise.

isBinaryNode()

functionisBinaryNode(node?: Node): node is BinaryExpression;

Determines whether the specified node is a BinaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is BinaryExpression

True if the specified token is a BinaryExpression, False otherwise.

isCallNode()

functionisCallNode(node?: Node): node is CallExpression;

Determines whether the specified node is a CallExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is CallExpression

True if the specified token is a CallExpression, False otherwise.

isError()

functionisError(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an error.

Returns true if the input is a token of type ERROR (#VALUE!). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is error, False otherwise.

isErrorNode()

functionisErrorNode(node?: Node): node is ErrorLiteral;

Determines whether the specified node is an ErrorLiteral.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ErrorLiteral

True if the specified token is an ErrorLiteral, False otherwise.

isExpressionNode()

functionisExpressionNode(node?: Node): node is AstExpression;

Determines whether the specified node is a AstExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is AstExpression

True if the specified token is a AstExpression, False otherwise.

isFunction()

functionisFunction(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a function.

Returns true if the input is a token of type FUNCTION. In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is function, False otherwise.

isFxPrefix()

functionisFxPrefix(token?: Pick<Token,"type">): boolean;

Returns true if the input is a token of type FX_PREFIX (leading = in formula). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is effects prefix, False otherwise.

isIdentifierNode()

functionisIdentifierNode(node?: Node): node is Identifier;

Determines whether the specified node is an Identifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Identifier

True if the specified token is an Identifier, False otherwise.

isLambdaNode()

functionisLambdaNode(node?: Node): node is LambdaExpression;

Determines whether the specified node is a LambdaExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LambdaExpression

True if the specified token is a LambdaExpression, False otherwise.

isLetDeclaratorNode()

functionisLetDeclaratorNode(node?: Node): node is LetDeclarator;

Determines whether the specified node is a LetDeclarator.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetDeclarator

True if the specified token is a LetDeclarator, False otherwise.

isLetNode()

functionisLetNode(node?: Node): node is LetExpression;

Determines whether the specified node is a LetExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is LetExpression

True if the specified token is a LetExpression, False otherwise.

isLiteral()

functionisLiteral(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a literal.

Returns true if the input is a token of type BOOLEAN (TRUE or FALSE), ERROR (#VALUE!), NUMBER (123.4), or STRING ("lorem ipsum"). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is literal, False otherwise.

isLiteralNode()

functionisLiteralNode(node?: Node): node is Literal;

Determines whether the specified node is a Literal.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is Literal

True if the specified token is a Literal, False otherwise.

isOperator()

functionisOperator(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is an operator.

Returns true if the input is a token of type OPERATOR (+ or :). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is operator, False otherwise.

isRange()

functionisRange(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a range.

Returns true if the input is a token that has a type of either REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), or REF_BEAM (A:A or 1:1). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">A token

Returns

boolean

True if the specified token is range, False otherwise.

isReference()

functionisReference(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is a reference.

Returns true if the input is a token of type REF_RANGE (A1 or A1:B2), REF_TERNARY (A1:A, A1:1, 1:A1, or A:A1), REF_BEAM (A:A or 1:1), or REF_NAMED (myrange). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is reference, False otherwise.

isReferenceNode()

functionisReferenceNode(node?: Node): node is ReferenceIdentifier;

Determines whether the specified node is a ReferenceIdentifier.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is ReferenceIdentifier

True if the specified token is a ReferenceIdentifier, False otherwise.

isUnaryNode()

functionisUnaryNode(node?: Node): node is UnaryExpression;

Determines whether the specified node is a UnaryExpression.

Parameters

ParameterTypeDescription
node?NodeAn AST node.

Returns

node is UnaryExpression

True if the specified token is a UnaryExpression, False otherwise.

isWhitespace()

functionisWhitespace(token?: Pick<Token,"type">): boolean;

Determines whether the specified token is whitespace.

Returns true if the input is a token of type WHITESPACE () or NEWLINE (\n). In all other cases false is returned.

Parameters

ParameterTypeDescription
token?Pick<Token, "type">The token

Returns

boolean

True if the specified token is whitespace, False otherwise.

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parse()

functionparse(tokenlist: Token[],options?: OptsParse): AstExpression;

Parses a string formula or list of tokens into an AST.

The parser assumes mergeRefs and negativeNumbers were true when the tokens were generated. It does not yet recognize reference context tokens or know how to deal with unary minuses in arrays.

The AST Abstract Syntax Tree's format is documented in AST_format.md.

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.
optionsOptsParseOptions for the parsers behavior.

Returns

AstExpression

An AST of nodes.

See

parseA1Range()

functionparseA1Range(rangeString: string,allowTernary?: boolean): RangeA1;

Parse A1-style range string into a RangeA1 object.

Parameters

ParameterTypeDefault valueDescription
rangeStringstringundefinedA1-style range string.
allowTernary?booleantruePermit ternary ranges like A2:A or B2:2.

Returns

RangeA1

A reference object.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1|ReferenceName;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// context: [ 'Sheet1' ],// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1 | ReferenceName

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Range()

functionparseR1C1Range(rangeString: string): RangeR1C1;

Parse R1C1-style range string into a RangeR1C1 object.

Parameters

ParameterTypeDescription
rangeStringstringR1C1-style range string.

Returns

RangeR1C1

A reference object.

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceName|ReferenceR1C1;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceName | ReferenceR1C1

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStruct;

Parse a structured reference string into an object representing it.

parseStructRef('workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]');// => {// context: [ 'workbook.xlsx' ],// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStruct

An object representing a valid reference or undefined if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1|ReferenceName): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({context: ['Sheet1'],range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1 | ReferenceNameA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceName|ReferenceR1C1): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({context: ['Sheet1'],range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceName | ReferenceR1C1A reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStruct,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({context: ['workbook.xlsx'],sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

See

OptsStringifyStructRef

stringifyTokens()

functionstringifyTokens(tokens: Token[]): string;

Collapses a list of tokens into a formula string.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens.

Returns

string

A formula string.

toCol()

functiontoCol(columnIndex: number): string;

Convert a 0 based offset number to a column string representation (0 = "A", 2 = "C").

The method expects a number between 0 and 16383. Other input will return garbage.

Parameters

ParameterTypeDescription
columnIndexnumberZero based column index number

Returns

string

The column string identifier

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parsers will need to handle this.

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See

translateFormulaToA1()

functiontranslateFormulaToA1(formula: string,anchorCell: string,options?: OptsTranslateFormulaToA1): string;

Translates ranges in a formula from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so you can set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Parameters

ParameterTypeDescription
formulastringAn Excel formula string that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateFormulaToA1Translation options.

Returns

string

A formula string.

See

OptsTranslateFormulaToA1

translateFormulaToR1C1()

functiontranslateFormulaToR1C1(formula: string,anchorCell: string,options?: OptsTranslateToR1C1): string;

Translates ranges in a formula from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
formulastringAn Excel formula that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
options?OptsTranslateToR1C1The options

Returns

string

A formula string.

See

OptsTranslateToR1C1

translateTokensToA1()

functiontranslateTokensToA1(tokens: Token[],anchorCell: string,options?: OptsTranslateTokensToA1): Token[];

Translates ranges in a list of tokens from relative R1C1 syntax to absolute A1 syntax.

translateToA1("=SUM(RC[1],R2C5,Sheet!R3C5)","D10");// => "=SUM(E10,$E$2,Sheet!$E$3)");

If an input range is -1,-1 relative rows/columns and the anchor is A1, the resulting range will (by default) wrap around to the bottom of the sheet resulting in the range XFD1048576. This may not be what you want so may set { wrapEdges } to false which will instead turn the range into a #REF! error.

translateToA1("=R[-1]C[-1]","A1");// => "=XFD1048576");translateToA1("=R[-1]C[-1]","A1",{wrapEdges: false});// => "=#REF!");

Note that if you are passing in a list of tokens that was not created using mergeRefs and you disable edge wrapping (or you simply set both options to false), you can end up with a formula such as =#REF!:B2 or =Sheet3!#REF!:F3. These are valid formulas in the Excel formula language and Excel will accept them, but they are not supported in Google Sheets.

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).
optionsOptsTranslateTokensToA1Translation options.

Returns

Token[]

A token list.

See

OptsTranslateTokensToA1

translateTokensToR1C1()

functiontranslateTokensToR1C1(tokens: Token[],anchorCell: string): Token[];

Translates ranges in a list of tokens from absolute A1 syntax to relative R1C1 syntax.

translateFormulaToR1C1("=SUM(E10,$E$2,Sheet!$E$3)","D10");// => "=SUM(RC[1],R2C5,Sheet!R3C5)");

Parameters

ParameterTypeDescription
tokensToken[]A token list that should be adjusted.
anchorCellstringA simple string reference to an A1 cell ID (AF123 or$C$5).

Returns

Token[]

A token list.

ArrayExpression

typeArrayExpression={elements: (|ReferenceIdentifier|Literal|ErrorLiteral|CallExpression)[][];loc?: SourceLocation;type: "ArrayExpression";}&Node;

An array expression. Excel does not have empty or sparse arrays and restricts array elements to literals. Google Sheets allows ReferenceIdentifiers and CallExpressions as elements of arrays, the fx parser has options for this but they are off by default.

Type Declaration

NameTypeDescription
elements( | ReferenceIdentifier | Literal | ErrorLiteral | CallExpression)[][]The elements of the array.
loc?SourceLocationThe original source position of the node.
type"ArrayExpression"The type of this AST node.

AstExpression

typeAstExpression=|ReferenceIdentifier|Literal|ErrorLiteral|UnaryExpression|BinaryExpression|CallExpression|ArrayExpression|LambdaExpression|LetExpression;

Represents an evaluate-able expression.

BinaryExpression

typeBinaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: BinaryOperator;type: "BinaryExpression";}&Node;

A binary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorBinaryOperatorThe expression's operator.
type"BinaryExpression"The type of this AST node.

BinaryOperator

typeBinaryOperator=|"="|"<"|">"|"<="|">="|"<>"|"-"|"+"|"*"|"/"|"^"|":"|" "|","|"&";

A binary operator token.

Note that Excels union operator is whitespace so a parser must take care to normalize this to a single space.

CallExpression

typeCallExpression={arguments: AstExpression[];callee: Identifier;loc?: SourceLocation;type: "CallExpression";}&Node;

A function call expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the function.
calleeIdentifierThe function being called.
loc?SourceLocationThe original source position of the node.
type"CallExpression"The type of this AST node.

ErrorLiteral

typeErrorLiteral={loc?: SourceLocation;raw: string;type: "ErrorLiteral";value: string;}&Node;

An Error expression.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"ErrorLiteral"The type of this AST node.
valuestringThe value of the error.

Identifier

typeIdentifier={loc?: SourceLocation;name: string;type: "Identifier";}&Node;

An identifier. These appear on CallExpression, LambdaExpression, and LetExpression and will always be a static string representing the name of a function call or parameter.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
namestringThe identifying name.
type"Identifier"The type of this AST node.

LambdaExpression

typeLambdaExpression={body: AstExpression|null;loc?: SourceLocation;params: Identifier[];type: "LambdaExpression";}&Node;

A LAMBDA expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LAMBDA's expression.
loc?SourceLocationThe original source position of the node.
paramsIdentifier[]The LAMBDA's parameters.
type"LambdaExpression"The type of this AST node.

LetDeclarator

typeLetDeclarator={id: Identifier;init: AstExpression|null;loc?: SourceLocation;type: "LetDeclarator";}&Node;

A LET parameter declaration.

Type Declaration

NameTypeDescription
idIdentifierThe name of the variable.
initAstExpression | nullThe variable's initializing expression.
loc?SourceLocationThe original source position of the node.
type"LetDeclarator"The type of this AST node.

LetExpression

typeLetExpression={body: AstExpression|null;declarations: LetDeclarator[];loc?: SourceLocation;type: "LetExpression";}&Node;

A LET expression.

Type Declaration

NameTypeDescription
bodyAstExpression | nullThe LET's scoped expression.
declarationsLetDeclarator[]The LET's variable declarations.
loc?SourceLocationThe original source position of the node.
type"LetExpression"The type of this AST node.

Literal

typeLiteral={loc?: SourceLocation;raw: string;type: "Literal";value: string|number|boolean;}&Node;

A literal token. Captures numbers, strings, and booleans. Literal errors have their own variant type.

Type Declaration

NameTypeDescription
loc?SourceLocationThe original source position of the node.
rawstringThe untouched literal source.
type"Literal"The type of this AST node.
valuestring | number | booleanThe value of the literal.

Node

typeNode={loc?: SourceLocation;type: string;};

All AST nodes are represented by Node objects. They may have any prototype inheritance but implement the same basic interface.

The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements.

Properties

PropertyTypeDescription
loc?SourceLocationThe original source position of the node.
typestringThe type of this AST node.

OptsFixRanges

typeOptsFixRanges={addBounds?: boolean;thisRow?: boolean;};

Options for fixTokenRanges and fixFormulaRanges.

Properties

PropertyTypeDefault valueDescription
addBounds?booleanfalseFill in any undefined bounds of range objects. Top to 0, bottom to 1048575, left to 0, and right to 16383.
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsParse

typeOptsParse={looseRefCalls?: boolean;permitArrayCalls?: boolean;permitArrayRanges?: boolean;};

Options for parse.

Properties

PropertyTypeDefault valueDescription
looseRefCalls?booleanfalsePermits any function call where otherwise only functions that return references would be permitted.
permitArrayCalls?booleanfalseFunction calls are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.
permitArrayRanges?booleanfalseRanges are allowed as elements of arrays. This is a feature in Google Sheets while Excel does not allow it.

OptsParseA1Ref

typeOptsParseA1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseA1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsParseR1C1Ref

typeOptsParseR1C1Ref={allowNamed?: boolean;allowTernary?: boolean;};

Options for parseR1C1Ref.

Properties

PropertyTypeDefault valueDescription
allowNamed?booleantrueEnable parsing names as well as ranges.
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsStringifyStructRef

typeOptsStringifyStructRef={thisRow?: boolean;};

Options for stringifyStructRef

Properties

PropertyTypeDefault valueDescription
thisRow?booleanfalseEnforces using the [#This Row] instead of the @ shorthand when serializing structured ranges.

OptsTokenize

typeOptsTokenize={allowTernary?: boolean;mergeRefs?: boolean;negativeNumbers?: boolean;r1c1?: boolean;withLocation?: boolean;};

Options for tokenize.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleanfalseEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be returned as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2). This is the same as calling mergeRefTokens
negativeNumbers?booleantrueMerges unary minuses with their immediately following number tokens (-,1) => -1 (alternatively these will be unary operations in the tree).
r1c1?booleanfalseRanges are expected to be in the R1C1 style format rather than the more popular A1 style.
withLocation?booleantrueNodes will include source position offsets to the tokens: { loc: [ start, end ] }

OptsTranslateFormulaToA1

typeOptsTranslateFormulaToA1={allowTernary?: boolean;mergeRefs?: boolean;wrapEdges?: boolean;};

Options for translateFormulaToA1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.
mergeRefs?booleantrueShould ranges be treated as whole references (Sheet1!A1:B2) or as separate tokens for each part: (Sheet1,!,A1,:,B2).
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

OptsTranslateToR1C1

typeOptsTranslateToR1C1={allowTernary?: boolean;};

Options for translateFormulaToR1C1.

Properties

PropertyTypeDefault valueDescription
allowTernary?booleantrueEnables the recognition of ternary ranges in the style of A1:A or A1:1. These are supported by Google Sheets but not Excel. See: References.md.

OptsTranslateTokensToA1

typeOptsTranslateTokensToA1={wrapEdges?: boolean;};

Options for translateTokensToA1

Properties

PropertyTypeDefault valueDescription
wrapEdges?booleantrueWrap out-of-bounds ranges around sheet edges rather than turning them to #REF! errors.

RangeA1

typeRangeA1={$bottom?: boolean|null;$left?: boolean|null;$right?: boolean|null;$top?: boolean|null;bottom?: number|null;left: number|null;right?: number|null;top: number|null;trim?: "head"|"tail"|"both"|null;};

A range in A1 style coordinates.

Properties

PropertyTypeDescription
$bottom?boolean | nullSignifies that bottom is a "locked" value
$left?boolean | nullSignifies that left is a "locked" value
$right?boolean | nullSignifies that right is a "locked" value
$top?boolean | nullSignifies that top is a "locked" value
bottom?number | nullBottom row of the range
leftnumber | nullLeft column of the range
right?number | nullRight column of the range
topnumber | nullTop row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

RangeR1C1

typeRangeR1C1={$c0?: boolean|null;$c1?: boolean|null;$r0?: boolean|null;$r1?: boolean|null;c0?: number|null;c1?: number|null;r0?: number|null;r1?: number|null;trim?: "head"|"tail"|"both"|null;};

A range in R1C1 style coordinates.

Properties

PropertyTypeDescription
$c0?boolean | nullSignifies that c0 is an absolute value
$c1?boolean | nullSignifies that c1 is an absolute value
$r0?boolean | nullSignifies that r0 is an absolute value
$r1?boolean | nullSignifies that r1 is an absolute value
c0?number | nullLeft column of the range
c1?number | nullRight column of the range
r0?number | nullTop row of the range
r1?number | nullBottom row of the range
trim?"head" | "tail" | "both" | nullShould empty rows and columns at the top/left or bottom/right be discarded when range is read?

ReferenceA1

typeReferenceA1={context?: string[];range: RangeA1;};

A reference containing an A1 style range. See Prefixes.md for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeA1The reference's range

ReferenceA1Xlsx

typeReferenceA1Xlsx={range: RangeA1;sheetName?: string;workbookName?: string;};

A reference containing an A1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeA1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceIdentifier

typeReferenceIdentifier={kind: "name"|"range"|"beam"|"table";loc?: SourceLocation;type: "ReferenceIdentifier";value: string;}&Node;

An identifier for a range or a name.

Type Declaration

NameTypeDescription
kind"name" | "range" | "beam" | "table"The kind of reference the value holds.
loc?SourceLocationThe original source position of the node.
type"ReferenceIdentifier"The type of this AST node.
valuestringThe untouched reference value.

ReferenceName

typeReferenceName={context?: string[];name: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
namestringThe reference's name

ReferenceNameXlsx

typeReferenceNameXlsx={name: string;sheetName?: string;workbookName?: string;};

A reference containing a name. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
namestringThe reference's name
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceR1C1

typeReferenceR1C1={context?: string[];range: RangeR1C1;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
context?string[]A collection of scopes for the reference
rangeRangeR1C1The reference's range

ReferenceR1C1Xlsx

typeReferenceR1C1Xlsx={range: RangeR1C1;sheetName?: string;workbookName?: string;};

A reference containing a R1C1 style range. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
rangeRangeR1C1The reference's range
sheetName?stringA context sheet scope
workbookName?stringA context workbook scope

ReferenceStruct

typeReferenceStruct={columns?: string[];context?: string[];sections?: string[];table?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
context?string[]A collection of scopes for the reference
sections?string[]The sections this reference targets
table?stringThe table this reference targets

ReferenceStructXlsx

typeReferenceStructXlsx={columns?: string[];sections?: string[];sheetName?: string;table?: string;workbookName?: string;};

A reference containing a table slice definition. See [Prefixes.md] for documentation on how scopes work in Fx.

Properties

PropertyTypeDescription
columns?string[]The sections this reference targets
sections?string[]The sections this reference targets
sheetName?stringA context sheet scope
table?stringThe table this reference targets
workbookName?stringA context workbook scope

SourceLocation

typeSourceLocation=number[];

Represents the source location information of the node. If the node contains no information about the source location, the field is null; otherwise it is an array consisting of a two numbers: A start offset (the position of the first character of the parsed source region) and an end offset (the position of the first character after the parsed source region).

Token

typeToken=Record<string,unknown>&{loc?: number[];type: string;unterminated?: boolean;value: string;};

A formula language token.

Type Declaration

NameTypeDescription
loc?number[]Source position offsets to the token
typestringThe type of the token
unterminated?booleanSignifies an unterminated string token
valuestringThe value of the token

TokenEnhanced

typeTokenEnhanced=Token&{depth?: number;error?: boolean;groupId?: string;index: number;};

A token with extra meta data.

Type Declaration

NameTypeDescription
depth?numberThis token's level of nesting inside parentheses
error?booleanToken is of unknown type or a paren without a match
groupId?stringThe ID of a group which this token belongs (e.g. matching parens)
indexnumberA zero based position in a token list

UnaryExpression

typeUnaryExpression={arguments: AstExpression[];loc?: SourceLocation;operator: UnaryOperator;type: "UnaryExpression";}&Node;

A unary operator expression.

Type Declaration

NameTypeDescription
argumentsAstExpression[]The arguments for the operator.
loc?SourceLocationThe original source position of the node.
operatorUnaryOperatorThe expression's operator.
type"UnaryExpression"The type of this AST node.

UnaryOperator

typeUnaryOperator="+"|"-"|"%"|"#"|"@";

A unary operator token.

MAX_COLS

constMAX_COLS: number;

The maximum number of columns a spreadsheet reference may hold (16383).

MAX_ROWS

constMAX_ROWS: number;

The maximum number of rows a spreadsheet reference may hold (1048575).

nodeTypes

constnodeTypes: Readonly<{ARRAY: "ArrayExpression";BINARY: "BinaryExpression";CALL: "CallExpression";ERROR: "ErrorLiteral";IDENTIFIER: "Identifier";LAMBDA: "LambdaExpression";LET: "LetExpression";LET_DECL: "LetDeclarator";LITERAL: "Literal";REFERENCE: "ReferenceIdentifier";UNARY: "UnaryExpression";}>;

A dictionary of the types used to identify AST node variants.

tokenTypes

consttokenTypes: Readonly<{BOOLEAN: "bool";CONTEXT: "context";CONTEXT_QUOTE: "context_quote";ERROR: "error";FUNCTION: "func";FX_PREFIX: "fx_prefix";NEWLINE: "newline";NUMBER: "number";OPERATOR: "operator";REF_BEAM: "range_beam";REF_NAMED: "range_named";REF_RANGE: "range";REF_STRUCT: "structured";REF_TERNARY: "range_ternary";STRING: "string";UNKNOWN: "unknown";WHITESPACE: "whitespace";}>;

A dictionary of the types used to identify token variants.

fx/xlsx

A tokenizer, parser, and other utilities to work with Excel formula code.

The xslx entry-point methods expect and return the variant of references that uses properties. If you are not using xlsx files you should use the fx variant methods.

See Prefixes.md for documentation on how scopes work in Fx.

Functions

References

addA1RangeBounds

Re-exports addA1RangeBounds


ArrayExpression

Re-exports ArrayExpression


AstExpression

Re-exports AstExpression


BinaryExpression

Re-exports BinaryExpression


BinaryOperator

Re-exports BinaryOperator


CallExpression

Re-exports CallExpression


ErrorLiteral

Re-exports ErrorLiteral


fromCol

Re-exports fromCol


Identifier

Re-exports Identifier


isArrayNode

Re-exports isArrayNode


isBinaryNode

Re-exports isBinaryNode


isCallNode

Re-exports isCallNode


isError

Re-exports isError


isErrorNode

Re-exports isErrorNode


isExpressionNode

Re-exports isExpressionNode


isFunction

Re-exports isFunction


isFxPrefix

Re-exports isFxPrefix


isIdentifierNode

Re-exports isIdentifierNode


isLambdaNode

Re-exports isLambdaNode


isLetDeclaratorNode

Re-exports isLetDeclaratorNode


isLetNode

Re-exports isLetNode


isLiteral

Re-exports isLiteral


isLiteralNode

Re-exports isLiteralNode


isOperator

Re-exports isOperator


isRange

Re-exports isRange


isReference

Re-exports isReference


isReferenceNode

Re-exports isReferenceNode


isUnaryNode

Re-exports isUnaryNode


isWhitespace

Re-exports isWhitespace


LambdaExpression

Re-exports LambdaExpression


LetDeclarator

Re-exports LetDeclarator


LetExpression

Re-exports LetExpression


Literal

Re-exports Literal


MAX_COLS

Re-exports MAX_COLS


MAX_ROWS

Re-exports MAX_ROWS


Node

Re-exports Node


nodeTypes

Re-exports nodeTypes


OptsFixRanges

Re-exports OptsFixRanges


OptsParse

Re-exports OptsParse


OptsParseA1Ref

Re-exports OptsParseA1Ref


OptsParseR1C1Ref

Re-exports OptsParseR1C1Ref


OptsStringifyStructRef

Re-exports OptsStringifyStructRef


OptsTokenize

Re-exports OptsTokenize


OptsTranslateFormulaToA1

Re-exports OptsTranslateFormulaToA1


OptsTranslateTokensToA1

Re-exports OptsTranslateTokensToA1


OptsTranslateToR1C1

Re-exports OptsTranslateToR1C1


parse

Re-exports parse


parseA1Range

Re-exports parseA1Range


parseR1C1Range

Re-exports parseR1C1Range


RangeA1

Re-exports RangeA1


RangeR1C1

Re-exports RangeR1C1


ReferenceA1

Re-exports ReferenceA1


ReferenceA1Xlsx

Re-exports ReferenceA1Xlsx


ReferenceIdentifier

Re-exports ReferenceIdentifier


ReferenceName

Re-exports ReferenceName


ReferenceNameXlsx

Re-exports ReferenceNameXlsx


ReferenceR1C1

Re-exports ReferenceR1C1


ReferenceR1C1Xlsx

Re-exports ReferenceR1C1Xlsx


ReferenceStruct

Re-exports ReferenceStruct


ReferenceStructXlsx

Re-exports ReferenceStructXlsx


SourceLocation

Re-exports SourceLocation


stringifyTokens

Re-exports stringifyTokens


toCol

Re-exports toCol


Token

Re-exports Token


TokenEnhanced

Re-exports TokenEnhanced


tokenTypes

Re-exports tokenTypes


translateFormulaToA1

Re-exports translateFormulaToA1


translateFormulaToR1C1

Re-exports translateFormulaToR1C1


translateTokensToA1

Re-exports translateTokensToA1


translateTokensToR1C1

Re-exports translateTokensToR1C1


UnaryExpression

Re-exports UnaryExpression


UnaryOperator

Re-exports UnaryOperator

addTokenMeta()

functionaddTokenMeta(tokenlist: Token[],context?: {sheetName?: string;workbookName?: string;}): TokenEnhanced[];

Runs through a list of tokens and adds extra attributes such as matching parens and ranges.

The context parameter defines default reference attributes: { workbookName: 'report.xlsx', sheetName: 'Sheet1' }. If supplied, these are used to match A1 to Sheet1!A1.

All tokens will be tagged with a .depth number value to indicating the level of nesting in parentheses as well as an .index number indicating their zero based position in the list.

The returned output will be the same array of tokens but the following properties will added to tokens (as applicable):

Parentheses ( )

Matching parens will be tagged with .groupId string identifier as well as a .depth number value (indicating the level of nesting).

Closing parens without a counterpart will be tagged with .error (boolean true).

Curly brackets { }

Matching curly brackets will be tagged with .groupId string identifier. These may not be nested in Excel.

Closing curly brackets without a counterpart will be tagged with .error (boolean true).

Ranges (REF_RANGE or REF_BEAM type tokens)

All ranges will be tagged with .groupId string identifier regardless of the number of times they occur.

Tokens of type UNKNOWN

All will be tagged with .error (boolean true).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens (from tokenize())
context?{ sheetName?: string; workbookName?: string; }A context used to match A1 to Sheet1!A1.
context.sheetName?stringAn implied sheet name ('Sheet1')
context.workbookName?stringAn implied workbook name ('report.xlsx')

Returns

TokenEnhanced[]

The input array with the enchanced tokens

fixFormulaRanges()

functionfixFormulaRanges(formula: string,options?: OptsFixRanges&OptsTokenize): string;

Normalizes A1 style ranges and structured references in a formula.

Internally it uses fixTokenRanges so see it's documentation for details.

Returns the same formula with the ranges updated. If an array of tokens was supplied, then a new array is returned.

Parameters

ParameterTypeDescription
formulastringA string (an Excel formula) or a token list that should be adjusted.
options?OptsFixRanges & OptsTokenizeOptions

Returns

string

A formula string with ranges adjusted

See

OptsFixRanges & OptsTokenize

fixTokenRanges()

functionfixTokenRanges(tokens: Token[],options?: OptsFixRanges): Token[];

Normalizes A1 style ranges and structured references in a list of tokens and returns a new array of tokens with values and position-data updated.

It ensures that that the top and left coordinates of an A1 range are on the left-hand side of a colon operator:

B2:A1 → A1:B2
1:A1 → A1:1
A:A1 → A1:A
B:A → A:B
2:1 → 1:2
A1:A1 → A1

When { addBounds } option is set to true, the missing bounds are also added. This can be done to ensure Excel compatible ranges. The fixes then additionally include:

1:A1 → A1:1 → 1:1
A:A1 → A1:A → A:A
A1:A → A:A
A1:1 → A:1
B2:B → B2:1048576
B2:2 → B2:XFD2

Structured ranges are normalized to have consistent order and capitalization of sections as well as removing redundant ones.

Unlike Excel, fx does not normalize sheet or workbook names of references.

Parameters

ParameterTypeDescription
tokensToken[]A list of tokens to be adjusted.
options?OptsFixRangesOptions.

Returns

Token[]

A token list with ranges adjusted.

See

OptsFixRanges

mergeRefTokens()

functionmergeRefTokens(tokenlist: Token[]): Token[];

Merges context with reference tokens as possible in a list of tokens.

When given a tokenlist, this function returns a new list with ranges returned as whole references (Sheet1!A1:B2) rather than separate tokens for each part: (Sheet1,!,A1,:,B2).

Parameters

ParameterTypeDescription
tokenlistToken[]An array of tokens.

Returns

Token[]

A new list of tokens with range parts merged.

parseA1Ref()

functionparseA1Ref(refString: string,options?: OptsParseA1Ref): |ReferenceA1Xlsx|ReferenceNameXlsx;

Parse a string reference into an object representing it.

parseA1Ref('Sheet1!A$1:$B2');// => {// workbookName: '',// sheetName: 'Sheet1',// range: {// top: 0,// left: 0,// bottom: 1,// right: 1// $top: true,// $left: false,// $bottom: false,// $right: true// }// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify.

Parameters

ParameterTypeDescription
refStringstringAn A1-style reference string.
optionsOptsParseA1RefOptions.

Returns

| ReferenceA1Xlsx | ReferenceNameXlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseA1Ref

parseR1C1Ref()

functionparseR1C1Ref(refString: string,options?: OptsParseR1C1Ref): |ReferenceNameXlsx|ReferenceR1C1Xlsx;

Parse a string reference into an object representing it.

parseR1C1Ref('Sheet1!R[9]C9:R[9]C9');// => {// context: [ 'Sheet1' ],// range: {// r0: 9,// c0: 8,// r1: 9,// c1: 8,// $c0: true,// $c1: true// $r0: false,// $r1: false// }// }

Parameters

ParameterTypeDescription
refStringstringAn R1C1-style reference string.
options?OptsParseR1C1RefOptions.

Returns

| ReferenceNameXlsx | ReferenceR1C1Xlsx

An object representing a valid reference or undefined if it is invalid.

See

OptsParseR1C1Ref

parseStructRef()

functionparseStructRef(ref: string): ReferenceStructXlsx;

Parse a structured reference string into an object representing it.

parseStructRef('[workbook.xlsx]!tableName[[#Data],[Column1]:[Column2]]');// => {// workbookName: 'workbook.xlsx',// sections: [ 'data' ],// columns: [ 'my column', '@foo' ],// table: 'tableName',// }

For A:A or A1:A style ranges, null will be used for any dimensions that the syntax does not specify:

See References.md.

Parameters

ParameterTypeDescription
refstringA structured reference string

Returns

ReferenceStructXlsx

An object representing a valid reference or null if it is invalid.

stringifyA1Ref()

functionstringifyA1Ref(refObject: |ReferenceA1Xlsx|ReferenceNameXlsx): string;

Get an A1-style string representation of a reference object.

stringifyA1Ref({sheetName: 'Sheet1',range: {top: 0,left: 0,bottom: 1,right: 1,$top: true,$left: false,$bottom: false,$right: true}});// => 'Sheet1!A$1:$B2'

Parameters

ParameterTypeDescription
refObject| ReferenceA1Xlsx | ReferenceNameXlsxA reference object.

Returns

string

The reference in A1-style string format.

stringifyR1C1Ref()

functionstringifyR1C1Ref(refObject: |ReferenceNameXlsx|ReferenceR1C1Xlsx): string;

Get an R1C1-style string representation of a reference object.

stringifyR1C1Ref({sheetName: 'Sheet1',range: {r0: 9,c0: 8,r1: 9,c1: 8,$c0: true,$c1: true$r0: false,$r1: false}});// => 'Sheet1!R[9]C9:R[9]C9'

Parameters

ParameterTypeDescription
refObject| ReferenceNameXlsx | ReferenceR1C1XlsxA reference object.

Returns

string

The reference in R1C1-style string format.

stringifyStructRef()

functionstringifyStructRef(refObject: ReferenceStructXlsx,options?: OptsStringifyStructRef): string;

Returns a string representation of a structured reference object.

stringifyStructRef({workbookName: 'workbook.xlsx',sheetName: '',sections: ['data'],columns: ['my column','@foo'],table: 'tableName',});// => 'workbook.xlsx!tableName[[#Data],[Column1]:[Column2]]'

Parameters

ParameterTypeDescription
refObjectReferenceStructXlsxA structured reference object.
options?OptsStringifyStructRefOptions.

Returns

string

The given structured reference in string format.

tokenize()

functiontokenize(formula: string,options?: OptsTokenize): Token[];

Breaks a string formula into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: FX_PREFIX,value: '='},{type: FUNCTION,value: 'SUM'},{type: OPERATOR,value: '('},{type: REF_RANGE,value: 'A1:B2'},{type: OPERATOR,value: ')'}]

A collection of token types may be found as an object as the tokenTypes export on the package.

Warning: To support syntax highlighting as you type, STRING tokens are allowed to be "unterminated". For example, the incomplete formula ="Hello world would be tokenized as:

[{type: FX_PREFIX,value: '='},{type: STRING,value: '"Hello world',unterminated: true},]

Parameters

ParameterTypeDescription
formulastringAn Excel formula string (an Excel expression).
options?OptsTokenizeOptions

Returns

Token[]

An array of Tokens

See