contextkey

package
v1.7.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package contextkey holds context keys and evaluates when-clause expressions (SPEC §11.2).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EqualWithConstants

func EqualWithConstants(a, b Expr) bool

EqualWithConstants tells whether two expressions, either may be nil, are the same once their constants are replaced.

func Implies

func Implies(p, q Expr) bool

Implies tells whether it can be shown that p implies q (whenever p holds, q holds). A false answer means "not shown", not "does not".

Types

type ChangeEvent

type ChangeEvent struct {
	// Keys are the keys whose value, as the scope sees it, changed.
	Keys []string
}

ChangeEvent tells which keys changed in a scope.

func (ChangeEvent) AffectsSome

func (e ChangeEvent) AffectsSome(keys []string) bool

AffectsSome tells whether one of the keys changed.

func (ChangeEvent) AllKeysContainedIn

func (e ChangeEvent) AllKeysContainedIn(keys []string) bool

AllKeysContainedIn tells whether every changed key is one of keys.

type Context

type Context interface {
	Value(key string) any
}

Context gives the value of a key; a key that is not set has the value nil.

type Diagnostic

type Diagnostic struct {
	Message string
	Offset  int
	Length  int
}

Diagnostic is a problem in a when-clause.

func Validate

func Validate(input string) []Diagnostic

Validate lists the problems of a when-clause, for the editor of keybindings: none when it is valid. It uses the strict parser.

Ported from VS Code: src/vs/platform/contextkey/common/contextkey.ts (validateWhenClauses)

type Expr

type Expr interface {
	// Type tells what kind of expression it is.
	Type() ExprType
	// Cmp orders expressions: negative, zero or positive.
	Cmp(other Expr) int
	// Equals tells whether two expressions are the same in normal form.
	Equals(other Expr) bool
	// SubstituteConstants replaces the keys with a fixed value (isLinux, isMac, …) by true or
	// false.
	SubstituteConstants() Expr
	// Evaluate tells whether the expression holds in a context.
	Evaluate(ctx Context) bool
	// Serialize writes the expression so that Parse reads it back.
	Serialize() string
	// Keys lists the keys the expression depends on, with repeats.
	Keys() []string
	// Negate returns the opposite expression, in normal form.
	Negate() Expr
}

Expr is a when-clause expression in the normal form VS Code keeps: && and || are flat, sorted, without repeated terms, and || is the outermost operator (no parentheses). Build one with Parse or with the functions of this package. An Expr never changes, so it can be shared by goroutines.

Ported from VS Code: src/vs/platform/contextkey/common/contextkey.ts

func And

func And(exprs ...Expr) Expr

And joins expressions with &&, in normal form: nil terms are dropped, true terms are dropped, a false term makes the result false, repeated terms are merged, and a || inside is distributed (a && (b || c) is a && b || a && c). It returns nil when there is no term.

func Equals

func Equals(key string, value any) Expr

Equals is the expression "key == value". A value of true or false gives "key" or "!key".

func False

func False() Expr

False is the expression that never holds.

func Greater

func Greater(key string, value any) Expr

Greater is the expression "key > value". The value is a number, or a string that starts with one; with any other string the expression never holds.

func GreaterEquals

func GreaterEquals(key string, value any) Expr

GreaterEquals is the expression "key >= value".

func Has

func Has(key string) Expr

Has is the expression "key": it holds when the value of the key is truthy.

func In

func In(key, valueKey string) Expr

In is the expression "key in valueKey": the value of key is an element of the array, or a property of the object, that valueKey holds.

func Not

func Not(key string) Expr

Not is the expression "!key".

func NotEquals

func NotEquals(key string, value any) Expr

NotEquals is the expression "key != value".

func NotIn

func NotIn(key, valueKey string) Expr

NotIn is the expression "key not in valueKey".

func Or

func Or(exprs ...Expr) Expr

Or joins expressions with ||, in normal form. It returns nil when there is no term.

func Parse

func Parse(input string) (Expr, error)

Parse reads a when-clause with the strict parser (a regex with unescaped slashes is an error). It fails with the tag WhenClauseInvalid, whose metadata has the message and the offset of the first problem.

Ported from VS Code: src/vs/platform/contextkey/common/contextkey.ts (ContextKeyExpr.deserialize)

func Regex

func Regex(key, source, flags string) (Expr, error)

Regex is the expression "key =~ /source/flags". The pattern is written as in JavaScript; the flags i, m and s are used, g and y are dropped and u is kept but has no effect. It fails when the pattern or the flags are not valid.

func Smaller

func Smaller(key string, value any) Expr

Smaller is the expression "key < value".

func SmallerEquals

func SmallerEquals(key string, value any) Expr

SmallerEquals is the expression "key <= value".

func True

func True() Expr

True is the expression that always holds.

type ExprType

type ExprType int

ExprType tells what an expression is; it also orders expressions of different kinds.

const (
	// TypeFalse is false.
	TypeFalse ExprType = iota
	// TypeTrue is true.
	TypeTrue
	// TypeDefined is a key alone: true when its value is truthy.
	TypeDefined
	// TypeNot is !key.
	TypeNot
	// TypeEquals is key == value.
	TypeEquals
	// TypeNotEquals is key != value.
	TypeNotEquals
	// TypeAnd is a && b.
	TypeAnd
	// TypeRegex is key =~ /regex/.
	TypeRegex
	// TypeNotRegex is the negation of a regex.
	TypeNotRegex
	// TypeOr is a || b.
	TypeOr
	// TypeIn is key in otherKey.
	TypeIn
	// TypeNotIn is key not in otherKey.
	TypeNotIn
	// TypeGreater is key > number.
	TypeGreater
	// TypeGreaterEquals is key >= number.
	TypeGreaterEquals
	// TypeSmaller is key < number.
	TypeSmaller
	// TypeSmallerEquals is key <= number.
	TypeSmallerEquals
)

The kinds of expressions, in the order they sort in.

type LexingError

type LexingError struct {
	Offset int
	Lexeme string
	// AdditionalInfo is a hint, such as "Did you mean == or =~?".
	AdditionalInfo string
}

LexingError is text the scanner could not make a token of.

type MapContext

type MapContext map[string]any

MapContext is a Context of a map, for tests and for evaluating against fixed values.

func (MapContext) Value

func (m MapContext) Value(key string) any

Value implements Context.

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser reads when-clauses. After Parse, LexingErrors and ParsingErrors say what was wrong when it returned nil. A Parser is not safe for concurrent use.

Grammar:

expression ::= or
or         ::= and { '||' and }*
and        ::= term { '&&' term }*
term       ::= '!' (KEY | true | false | parenthesized) | primary
primary    ::= 'true' | 'false' | parenthesized | KEY '=~' REGEX
             | KEY [ ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'not' 'in' | 'in') value ]
parenthesized ::= '(' expression ')'
value      ::= 'true' | 'false' | 'in' | VALUE | SINGLE_QUOTED_STR | (nothing)

Ported from VS Code: src/vs/platform/contextkey/common/contextkey.ts (Parser)

func NewParser

func NewParser(cfg ParserConfig) *Parser

NewParser makes a parser.

func (*Parser) LexingErrors

func (p *Parser) LexingErrors() []LexingError

LexingErrors are the lexing errors of the last Parse.

func (*Parser) Parse

func (p *Parser) Parse(input string) (expr Expr)

Parse reads a when-clause. It returns nil when there are errors.

func (*Parser) ParsingErrors

func (p *Parser) ParsingErrors() []ParsingError

ParsingErrors are the parsing errors of the last Parse.

type ParserConfig

type ParserConfig struct {
	// RegexErrorRecovery lets the parser rebuild a regex that has unescaped slashes
	// (/src//), as VS Code's own keybindings and menus need. Parse and Validate turn it off,
	// to guide users to correct regexes.
	RegexErrorRecovery bool
}

ParserConfig tunes the parser.

type ParsingError

type ParsingError struct {
	Message string
	Offset  int
	Lexeme  string
	// AdditionalInfo is a hint.
	AdditionalInfo string
}

ParsingError is something wrong in the order of the tokens.

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner splits a when-clause into tokens.

Ported from VS Code: src/vs/platform/contextkey/common/scanner.ts

func (*Scanner) Errors

func (s *Scanner) Errors() []LexingError

Errors are the lexing errors of the last Scan.

func (*Scanner) Reset

func (s *Scanner) Reset(input string) *Scanner

Reset sets the input to scan and forgets the last scan.

func (*Scanner) Scan

func (s *Scanner) Scan() []Token

Scan returns the tokens of the input, ending with TokEOF. Text that is no token is a TokError and is listed in Errors.

type Scope

type Scope struct {
	// contains filtered or unexported fields
}

Scope holds context keys for a part of the window (SPEC §11.2). Scopes form a tree: window, part, widget. A widget gets a child of its parent's scope and sets its keys in it; a lookup walks up the tree, so a key set in a scope is seen by its descendants unless they set it themselves. A Scope is safe for concurrent use; its listeners are called in the goroutine that changed a key, with no lock held.

Ported from VS Code: src/vs/platform/contextkey/browser/contextKeyService.ts (ContextKeyService)

func NewRoot

func NewRoot() *Scope

NewRoot makes the root scope of a window.

func (*Scope) Batch

func (s *Scope) Batch(fn func())

Batch runs fn and holds the change events until it returns, so a listener hears of all the keys that fn changed in one event. Batches of the same tree nest.

func (*Scope) Child

func (s *Scope) Child() *Scope

Child makes a scope below this one. A child of a disposed scope is disposed.

func (*Scope) Dispose

func (s *Scope) Dispose()

Dispose removes the scope from its parent, disposes the scopes below it and forgets its keys and listeners. A disposed scope ignores Set and Reset.

func (*Scope) Get

func (s *Scope) Get(key string) any

Get returns the value of a key as this scope sees it: its own, else the closest ancestor's, else nil.

func (*Scope) Matches

func (s *Scope) Matches(expr Expr) bool

Matches tells whether an expression holds in this scope. A nil expression always does.

func (*Scope) OnChange

func (s *Scope) OnChange(fn func(ChangeEvent)) (unsubscribe func())

OnChange registers fn to be called when a key changes in this scope or above it without being hidden by this scope. The returned function removes it.

func (*Scope) Reset

func (s *Scope) Reset(key string)

Reset removes the key from this scope, so the value of an ancestor shows again.

func (*Scope) Set

func (s *Scope) Set(key string, value any)

Set gives a key a value in this scope. The value may be a bool, a number, a string, a slice or a map with string keys (anything else counts as an object). Listeners of this scope and of the descendants that do not set the key themselves are told if the value, as they see it, changed.

func (*Scope) Value

func (s *Scope) Value(key string) any

Value implements Context.

type Token

type Token struct {
	Type   TokenType
	Offset int
	// Lexeme is the text of a TokRegexStr, TokStr, TokQuotedStr and TokError.
	Lexeme string
	// TripleEq is set for === and !==.
	TripleEq bool
}

Token is a piece of a when-clause. Offsets are in bytes.

func (Token) String

func (t Token) String() string

Lexeme returns the text of a token as the parser shows it in messages.

type TokenType

type TokenType int

TokenType is the kind of a token of a when-clause.

const (
	// TokLParen is (.
	TokLParen TokenType = iota
	// TokRParen is ).
	TokRParen
	// TokNeg is !.
	TokNeg
	// TokEq is == or ===.
	TokEq
	// TokNotEq is != or !==.
	TokNotEq
	// TokLt is <.
	TokLt
	// TokLtEq is <=.
	TokLtEq
	// TokGt is >.
	TokGt
	// TokGtEq is >=.
	TokGtEq
	// TokRegexOp is =~.
	TokRegexOp
	// TokRegexStr is /regex/ with its flags.
	TokRegexStr
	// TokTrue is true.
	TokTrue
	// TokFalse is false.
	TokFalse
	// TokIn is in.
	TokIn
	// TokNot is not.
	TokNot
	// TokAnd is &&.
	TokAnd
	// TokOr is ||.
	TokOr
	// TokStr is a word: a key or a value.
	TokStr
	// TokQuotedStr is a 'quoted string', its lexeme without the quotes.
	TokQuotedStr
	// TokError is text that is no token.
	TokError
	// TokEOF is the end of the input.
	TokEOF
)

The kinds of tokens.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL