### minimalEditor Setup Source: https://prism-code-editor.netlify.app/api-reference/setups/f-minimaleditor Initializes the Prism Code Editor within a specified container element. It allows for custom options and provides a callback for when the editor is ready. ```APIDOC ## minimalEditor ### Description Adds an editor inside a shadow root to the given element and asynchronously loads the styles. ### Method `minimalEditor(container, options, onLoad?)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### container (string | HTMLElement) - Required - Must be an element you can attach a shadow root to. #### options (SetupOptions) - Required - Options to create the editor as well as the theme to use. #### onLoad? (() => any) - Optional - Function called when the styles are loaded and the editor is appended to the DOM. ### Request Example ```javascript minimalEditor('#editor-container', { theme: 'prism-dark' }, () => { console.log('Editor loaded'); }); ``` ### Response #### Success Response (200) `PrismEditor`<{ `theme`: `EditorTheme`; }> Object to interact with the editor. #### Response Example ```json { "theme": "prism-dark" } ``` ``` -------------------------------- ### getIndentGuides Function Source: https://prism-code-editor.netlify.app/api-reference/guides/f-getindentguides Calculates the position and height of indentation guides for a given string of code and tab size. ```APIDOC ## getIndentGuides Function ### Description Calculates the position and height of indentation guides for a string of code. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript getIndentGuides(codeString, tabSizeNumber) ``` ### Response #### Success Response (200) - **indentGuides** (`number[][]`) - An array of indentation guides. Each guide is a tuple containing 3 numbers: the starting line, the offset in tabs, and the height in lines. ``` -------------------------------- ### readonlyEditor Setup Source: https://prism-code-editor.netlify.app/api-reference/setups/f-readonlyeditor Initializes a read-only Prism code editor instance with pre-configured extensions. This setup is ideal for displaying code without allowing user modifications. ```APIDOC ## readonlyEditor Setup ### Description Initializes a read-only Prism code editor instance with several helpful extensions, including copyButton, matchBrackets, highlightBracketPairs, matchTags, indentGuides, highlightSelectionMatches, and readOnlyCodeFolding. This setup is best used with the `readOnly` option set to true as no commands are added. ### Method Constructor ### Endpoint N/A (This is a JavaScript function setup) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### container - **container** (string | HTMLElement) - Required - The DOM element or its ID where the editor will be mounted. #### options - **options** (SetupOptions) - Required - Configuration options for the editor setup. #### onLoad? - **onLoad?** (() => any) - Optional - A callback function that is executed when the editor has finished loading. ### Request Example ```javascript const editor = readonlyEditor('#my-editor', { language: 'javascript', theme: 'prism-theme-dark' }); ``` ### Response #### Success Response (200) - **PrismEditor** (PrismEditor<{ theme: EditorTheme; }>) - The initialized PrismEditor instance with theme information. #### Response Example ```json { "editorInstance": "[object PrismEditor]", "theme": "prism-theme-dark" } ``` ``` -------------------------------- ### Custom Tokenizer Example with tokenize Source: https://prism-code-editor.netlify.app/api-reference/prism/v-tokenize Demonstrates the typical structure of a custom tokenizer using the 'tokenize' symbol. It first tokenizes the code with the existing grammar and then applies custom logic. The example highlights the importance of using 'withoutTokenizer' to avoid recursive calls. ```javascript const myGrammar = { // some tokens ... [tokenize](code, grammar) { const tokens = withoutTokenizer(code, grammar); // Do something with the tokens return tokens; } }; ``` -------------------------------- ### Cursor Methods Source: https://prism-code-editor.netlify.app/api-reference/cursor/i-cursor API documentation for the methods of the Cursor extension, including getting the cursor position and scrolling it into view. ```APIDOC ## Cursor Methods ### Description Methods available on a Cursor instance. ### Methods #### getPosition() ##### Description Gets the cursor position relative to the editor overlays. ##### Method `getPosition(): CursorPosition` ##### Parameters None ##### Returns * **CursorPosition** - The current cursor position. #### scrollIntoView() ##### Description Scrolls the cursor into view. ##### Method `scrollIntoView(): void` ##### Parameters None ##### Returns * **void** - This method does not return a value. ``` -------------------------------- ### getLines Function Source: https://prism-code-editor.netlify.app/api-reference/utils/f-getlines Retrieves lines from a given text that fall within a specified start and end range. It returns the matching lines along with their start and end positions. ```APIDOC ## getLines ### Description Gets all lines that are at least partially between `start` and `end`. ### Method `FUNCTION` ### Endpoint N/A (This is a function, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **text** (string) - Required - Text to search in. - **start** (number) - Required - Start of the selection. - **end** (number) - Optional - End of the selection. Defaults to `start`. ### Request Example ```json { "text": "This is line 1\nThis is line 2\nThis is line 3", "start": 10, "end": 30 } ``` ### Response #### Success Response (200) - **lines** (string[]) - An array of lines that are at least partially between start and end. - **startPosition** (number) - The starting position of the first line. - **endPosition** (number) - The ending position of the last line. #### Response Example ```json { "lines": ["This is line 2"], "startPosition": 15, "endPosition": 29 } ``` ``` -------------------------------- ### Overwriting Tokens with insertBefore (JavaScript) Source: https://prism-code-editor.netlify.app/api-reference/prism/utils/v-insertbefore Illustrates a special case of using insertBefore where a token with the same name as an existing one is inserted. This effectively overwrites the original token and allows for inserting new tokens after the 'before' token. This example shows how to insert a new 'comment' token and subsequent tokens after an existing 'comment' token in the 'markup' grammar. ```javascript insertBefore(markup, 'comment', { 'comment': markup.comment, // tokens after 'comment' }); ``` -------------------------------- ### SearchWidget Constructor Source: https://prism-code-editor.netlify.app/api-reference/search/i-searchwidget Initializes the SearchWidget. It extends BasicExtension and takes the editor instance and options as parameters. ```APIDOC ## SearchWidget Constructor ### Description Initializes the SearchWidget. It extends `BasicExtension` and takes the editor instance and options as parameters. ### Method `new SearchWidget(editor, options)` ### Parameters #### editor - **editor** (`PrismEditor<{}>`) - The Prism editor instance. #### options - **options** (`EditorOptions`) - Configuration options for the editor. ### Returns - `any` - The initialized SearchWidget instance. ``` -------------------------------- ### WordHighlighter Constructor Source: https://prism-code-editor.netlify.app/api-reference/search/i-wordhighlighter Initializes a new instance of WordHighlighter. It requires an editor instance and optional configuration options. ```APIDOC ## WordHighlighter Constructor ### Description Initializes a new instance of WordHighlighter. It requires an editor instance and optional configuration options. ### Method Constructor ### Parameters #### editor - **editor** (PrismEditor) - The PrismEditor instance to attach the highlighter to. #### options - **options** (EditorOptions) - Optional configuration options for the editor. ### Returns - **any** - Returns the WordHighlighter instance or related type. ### Request Example ```javascript // Assuming 'editor' is an instance of PrismEditor and 'options' is an EditorOptions object const highlighter = new WordHighlighter(editor, options); ``` ### Response #### Success Response (200) - **any** - Typically returns the initialized highlighter instance. ``` -------------------------------- ### EditHistory Constructor Source: https://prism-code-editor.netlify.app/api-reference/commands/i-edithistory Initializes a new instance of the EditHistory extension for a Prism editor. ```APIDOC ## EditHistory Constructor ### Description Initializes a new instance of the EditHistory extension for a Prism editor. ### Method `new EditHistory(editor, options)` ### Parameters #### editor - **editor** (PrismEditor) - The Prism editor instance to attach the history to. #### options - **options** (EditorOptions) - Configuration options for the history extension. ### Returns - **any** - Returns the initialized EditHistory instance. ### Request Example ```javascript const editor = new PrismEditor(...); const history = new EditHistory(editor, {...options}); ``` ### Response #### Success Response (200) - **any** - The initialized EditHistory instance. #### Response Example ```json { "message": "EditHistory initialized successfully" } ``` ``` -------------------------------- ### Token Class API Source: https://prism-code-editor.netlify.app/api-reference/prism/c-token Documentation for the Token class, covering its constructor and properties. ```APIDOC ## Token Class ### Description Represents a token in the Prism code highlighting process. It holds information about the token's type, content, matched string, and aliases. ### Constructor #### `new Token(type: TokenName, content: string | TokenStream, matchedStr: string, alias?: TokenName)` Creates a new token. ##### Parameters * **type** (`TokenName`) - The type of the token. * **content** (`string` | `TokenStream`) - The strings or tokens contained by this token. * **matchedStr** (`string`) - A copy of the full string this token was created from. * **alias?** (`TokenName`) - The alias(es) of the token. ### Properties #### `alias?` : `optional TokenName` The alias(es) of the token. Multiple aliases are separated by spaces. #### `content` : `string` | `TokenStream` The strings or tokens contained by this token. This will be a token stream if the pattern matched also defined an `inside` grammar. #### `length` : `number` Length of the full string this token was created from. #### `type` : `TokenName` The type of the token. This is usually the key of a pattern in a Grammar. ``` -------------------------------- ### SelectionMatchHighlighter Constructor Source: https://prism-code-editor.netlify.app/api-reference/search/i-selectionmatchhighlighter Details about the SelectionMatchHighlighter constructor, including its parameters and return type. ```APIDOC ## SelectionMatchHighlighter Constructor ### Description Initializes the SelectionMatchHighlighter extension. ### Method `new SelectionMatchHighlighter(editor, options)` ### Parameters #### editor - **editor** (`PrismEditor`) - The Prism editor instance. #### options - **options** (`EditorOptions`) - Configuration options for the editor. ### Returns - `any` - The result of the constructor. ### Properties #### api? (optional) - **api** (`SearchAPI`) - The Search API used by the extension. This property is only present after the extension is added to an editor. It can be used to get the position of matches, for example. ``` -------------------------------- ### addCopyButton Source: https://prism-code-editor.netlify.app/api-reference/code-blocks/f-addcopybutton Adds a copy button to a given code block element. This function requires associated CSS for the copy button to be styled correctly. It also accepts an optional function to customize the code that gets copied. ```APIDOC ## addCopyButton ### Description Adds a copy button to a code block. Requires styles from `prism-code-editor/copy-button.css`. ### Method `addCopyButton(codeBlock, getCode?): void` ### Endpoint N/A (This is a client-side function) ### Parameters #### Arguments - **codeBlock** (`PrismCodeBlock`) - Required - The code block element to which the copy button will be added. - **getCode?** (`(codeBlock) => string`) - Optional - A function used to retrieve the code to be copied. This can be used to modify the copied content, for example, by omitting deleted lines. ### Request Example ```javascript import { addCopyButton } from 'prism-code-editor'; const myCodeBlock = document.querySelector('.my-code-block'); // Basic usage addCopyButton(myCodeBlock); // With custom getCode function addCopyButton(myCodeBlock, (block) => { // custom logic to get code return block.textContent.replace('// ignore this line', ''); }); ``` ### Response #### Success Response `void` - This function does not return any value. #### Response Example N/A ``` -------------------------------- ### Cursor Extension Constructor Source: https://prism-code-editor.netlify.app/api-reference/cursor/i-cursor Initializes the Cursor extension for the Prism Code Editor. It extends the BasicExtension and requires an editor instance and options. ```APIDOC ## Cursor Constructor ### Description Initializes the Cursor extension for the Prism Code Editor. ### Method `new Cursor(editor, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **editor** (PrismEditor) - Required - The Prism editor instance. * **options** (EditorOptions) - Required - The editor options. ### Request Example ```json { "editor": "PrismEditorInstance", "options": "EditorOptionsObject" } ``` ### Response #### Success Response (200) * **any** - Returns the initialized cursor instance. #### Response Example ```json { "instance": "CursorInstance" } ``` ``` -------------------------------- ### Tokenize Code with tokenizeText (JavaScript) Source: https://prism-code-editor.netlify.app/api-reference/prism/v-tokenizetext The tokenizeText function takes raw code and a language grammar to produce a token stream. It's useful for highlighting and parsing code. The example demonstrates iterating through tokens to find numeric literals in JavaScript. ```javascript let code = `var foo = 0;`; let tokens = tokenizeText(code, languages.javascript); tokens.forEach(token => { if (token instanceof Token && token.type == 'number') { console.log(`Found numeric literal: ${token.content}`); } }); ``` -------------------------------- ### BracketMatcher Constructor Source: https://prism-code-editor.netlify.app/api-reference/match-brackets/i-bracketmatcher Initializes the BracketMatcher extension for the Prism Code Editor. ```APIDOC ## BracketMatcher Constructor ### Description Initializes the BracketMatcher extension, enabling bracket matching functionality within the Prism Code Editor. ### Method `constructor` ### Parameters #### editor - **editor** (`PrismEditor`) - The Prism editor instance to which the BracketMatcher will be attached. #### options - **options** (`EditorOptions`) - Configuration options for the BracketMatcher. ### Returns - `any` - Typically returns the instance of the BracketMatcher itself or an initializer. ### Request Example ```javascript // Assuming 'editor' is an instance of PrismEditor const bracketMatcher = new BracketMatcher(editor, { // ... options }); ``` ### Response #### Success Response (200) - **Instance** (`BracketMatcher`) - The initialized BracketMatcher instance. #### Response Example ```json { "message": "BracketMatcher initialized successfully" } ``` ``` -------------------------------- ### Get Closest Token in Prism Editor (JavaScript) Source: https://prism-code-editor.netlify.app/api-reference/utils/f-getclosesttoken Searches for a token matching a CSS selector within specified margins around a position in the Prism editor. It traverses tokens in reverse document order. Returns an HTMLSpanElement if found, otherwise undefined. ```javascript getClosestToken(editor, '.string', -1) ``` -------------------------------- ### findWords Utility Function Source: https://prism-code-editor.netlify.app/api-reference/autocomplete/f-findwords The findWords utility searches the editor's TokenStream for strings. It filters tokens based on language, type, and starting position, and uses a regular expression pattern to find matching words. It can also initialize with a set of words to complete and optionally only search token content that is a string. ```APIDOC ## findWords ### Description Utility that searches the editor’s TokenStream for strings. This utility will only search parts of the document whose language has the same completion definition registered. ### Method FUNCTION ### Endpoint N/A (Utility Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters (Function Arguments) - **context** (`CompletionContext`) - Required - Current completion context. - **editor** (`PrismEditor`) - Required - Editor to search in. - **filter** (`(type, start) => boolean`) - Required - Function used to filter tokens you want to search in. Is called with the type of the token and its starting position. If the filter returns true, the token will be searched. - **pattern** (`RegExp`) - Required - Pattern used to search for words. Must have the `g` flag. - **init?** (`Iterable`) - Optional - Words that should be completed even if they’re not found in the document. - **tokensOnly?** (`boolean`) - Optional - If `true` only the text of tokens whose `content` is a string will be searched. If `false`, any string inside the TokenStream can be searched. ### Request Example ```javascript const foundWords = findWords( currentContext, editorInstance, (type, start) => type !== 'comment', /\b\w+\b/g, ['initialWord'], true ); ``` ### Response #### Success Response - **Return Value** (`Set`) - A set with found identifiers/words. #### Response Example ```json { "example": ["word1", "word2", "initialWord"] } ``` ``` -------------------------------- ### SearchWidget Methods Source: https://prism-code-editor.netlify.app/api-reference/search/i-searchwidget Provides details on the methods available for the SearchWidget, including `close()` and `open()`. ```APIDOC ## SearchWidget Methods ### close() #### Description Hides the search widget and removes most event listeners. #### Method `close(focusTextarea?: boolean): void` #### Parameters ##### focusTextarea? - **focusTextarea** (`boolean`) - Optional. Whether the editor's `textarea` should gain focus. Defaults to true. #### Returns - `void` ### open() #### Description Opens the search widget. #### Method `open(focusInput?: boolean): void` #### Parameters ##### focusInput? - **focusInput** (`boolean`) - Optional. Whether the widget's search input should gain focus. Defaults to true. #### Returns - `void` ``` -------------------------------- ### PrismEditor Methods Source: https://prism-code-editor.netlify.app/api-reference/index/i-prismeditor This section describes the methods available on a PrismEditor instance, including functionalities for managing extensions, selections, events, options, and editor removal. ```APIDOC ## PrismEditor Methods ### addExtensions() - **Description**: Adds extensions to the editor and calls their update methods. - **Method**: `void` - **Parameters**: - `this`: `void` - `...extensions`: `EditorExtension[]` ### getSelection() - **Description**: Gets `selectionStart`, `selectionEnd` and `selectionDirection` for the `textarea`. - **Method**: `InputSelection` - **Parameters**: - `this`: `void` ### on() - **Description**: Adds a listener for events with the specified name. - **Method**: `() => void` - **Type Parameters**: - `U` extends `keyof EditorEventMap<{}>` - **Parameters**: - `this`: `void` - `name`: `U` - `listener`: `EditorEventMap[U]` - **Returns**: `() => void` ### remove() - **Description**: Removes the editor from the DOM. - **Method**: `void` - **Parameters**: - `this`: `void` ### setOptions() - **Description**: Set new options for the editor. Omitted properties will use their old value. - **Method**: `void` - **Parameters**: - `this`: `void` - `options`: `EditorOptions` ``` -------------------------------- ### EditorOptions Configuration Source: https://prism-code-editor.netlify.app/api-reference/index/t-editoroptions Defines the structure and properties for configuring the Prism Code Editor instance. ```APIDOC ## EditorOptions ### Description Represents the configuration object for a Prism Code Editor instance. ### Properties - **class?** (string) - Optional - Additional classes for the root container. Useful to style individual editors. The `.prism-code-editor` selector can be used to style all editors. - **insertSpaces?** (boolean) - Optional - Whether the editor should insert spaces for indentation. Defaults to `true`. - **language** (string) - Required - Language used for syntax highlighting. If the language doesn’t have a registered Prism grammar, syntax highlighting will be disabled. Defaults to `"text"`. - **lineNumbers?** (boolean) - Optional - Whether line numbers should be shown. Defaults to `true`. - **onSelectionChange?** (EditorEventMap[`"selectionChange"`] | null) - Optional - Function called when the selection changes in the editor. - **onTokenize?** (EditorEventMap[`"tokenize"`] | null) - Optional - Function called before the tokens are stringified to HTML. - **onUpdate?** (EditorEventMap[`"update"`] | null) - Optional - Function called when the code of the editor changes. - **readOnly?** (boolean) - Optional - Whether the editor should be read only. Defaults to `false`. - **rtl?** (boolean) - Optional - Whether the editor uses right to left directionality. Requires styles from `prism-code-editor/rtl-layout.css` to work unless the setups are used. Defaults to `false`. - **tabSize?** (number) - Optional - Tabsize for the editor. Defaults to `2`. - **value** (string) - Required - Code to display in the editor. - **wordWrap?** (boolean) - Optional - Whether the editor should have word wrap. Defaults to `false`. ``` -------------------------------- ### Create Prism Editor Instance (TypeScript) Source: https://prism-code-editor.netlify.app/api-reference/index/f-createeditor Creates a Prism Code Editor instance. Accepts a container element (or selector), optional initialization options, and an array of editor extensions. If no container is provided, the editor's DOM element must be manually appended. Extensions can also be added after initialization. ```typescript import { createEditor, EditorExtension } from "prism-code-editor"; // Example usage: const container = document.getElementById("editor-container"); const options = { language: "javascript", theme: "github-dark" }; const extensions: EditorExtension[] = [ // Add extensions here, e.g.,: // import { highlight } from "prismjs/components/prism-core"; // highlight(Prism) ]; const editor = createEditor(container, options, ...extensions); // If container was omitted: // document.body.appendChild(editor.container); ``` -------------------------------- ### mountEditorsUnder Source: https://prism-code-editor.netlify.app/api-reference/client/f-mounteditorsunder Mounts all editors rendered by renderEditor under the specified root. Editors are mounted in document order, and editors that have already been mounted are skipped. ```APIDOC ## mountEditorsUnder ### Description Mounts all editors rendered by renderEditor under the specified root. Editors are mounted in document order, and editors that have already been mounted are skipped. ### Method `mountEditorsUnder(root: Element | Document, getExtensions?: (options: object) => undefined | null | EditorExtension[]): PrismEditor[]` ### Endpoint N/A (This is a function call, not an HTTP endpoint) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript // Example usage: const rootElement = document.getElementById('editor-container'); const editors = mountEditorsUnder(rootElement, (options) => { // Optionally provide extensions based on options return options.customExtension ? [new CustomExtension(options.customExtension)] : []; }); ``` ### Response #### Success Response `PrismEditor[]` - Array of the mounted editors. These editors are in document order. #### Response Example ```json [ { // PrismEditor object structure }, { // PrismEditor object structure } ] ``` ``` -------------------------------- ### cssCompletion Source: https://prism-code-editor.netlify.app/api-reference/autocomplete/css/f-csscompletion Completion source for CSS that adds completion for HTML tags, pseudo-elements, pseudo-classes, classes, CSS variables, at-rules, CSS properties and property values. Requires the `css-extras` grammar and bracket matching extension to work correctly. ```APIDOC ## cssCompletion ### Description Completion source for CSS that adds completion for HTML tags, pseudo-elements, pseudo-classes, classes, CSS variables, at-rules, CSS properties and property values. Requires the `css-extras` grammar and bracket matching extension to work correctly. ### Method Not Applicable (Function definition) ### Endpoint Not Applicable (Function definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Example usage (assuming cssCompletion is imported) cssCompletion(classes, variables); ``` ### Response #### Success Response (200) Returns a `CompletionSource` object. #### Response Example ```json { "type": "CompletionSource" } ``` ## Parameters ### classes? (Iterable) Optional. List of class names that should be completed even if they’re not found in the editor. Each string must be prefixed with `.`. ### variables? (Iterable) Optional. List of CSS variables that should be completed even if they’re not found in the editor. Each string must be prefixed with `--`. ``` -------------------------------- ### BasicExtension API Source: https://prism-code-editor.netlify.app/api-reference/index/i-basicextension Details of the BasicExtension API, including its definition, how it's extended, and its parameters and return types. ```APIDOC ## BasicExtension API ### Description Provides the definition and usage details for the `BasicExtension` in the Prism Editor. This includes information on what it extends, its type parameters, and the parameters it accepts. ### Method N/A (This describes a type/class definition, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Type Parameters - **T** (object) - Optional - Extends `object`, defaults to `{}`. #### Parameters - **editor** (`PrismEditor`<`T`>) - Required - The Prism Editor instance. - **options** (`EditorOptions` & `T`) - Required - The editor options combined with extension-specific options. ### Extended by This section lists the components that extend `BasicExtension`: - `EditHistory` - `Cursor` - `BracketMatcher` - `SearchWidget` - `SelectionMatchHighlighter` ### Returns `any` - The return type of the `BasicExtension` function. ``` -------------------------------- ### renderEditor Source: https://prism-code-editor.netlify.app/api-reference/ssr/f-rendereditor Renders an editor as an HTML string, suitable for SSR or SSG. The rendered editor can be later mounted and made interactive on the client. ```APIDOC ## renderEditor ### Description Renders an editor as an HTML string. This is intended to be used with server-side rendering (SSR) or static-site generation (SSG). The editor can later be made interactive on the client with the `mountEditorsUnder` function. ### Method (This is a function, not an HTTP endpoint) ### Parameters #### options - **options** (Omit & object & Omit) - Required - Options used for the editor. Any properties you define are stringified to JSON, which will later be parsed by `mountEditorsUnder`. This is very useful if you want to add extra configuration options used to customize how the editor is mounted. ### Returns - **string** - The HTML string representation of the rendered editor. ### Type Parameters - **T** (`object` = { }) - A generic type parameter that can extend `object`. ``` -------------------------------- ### WordHighlighter Properties Source: https://prism-code-editor.netlify.app/api-reference/search/i-wordhighlighter Details the properties available on a WordHighlighter instance, including the optional SearchAPI. ```APIDOC ## WordHighlighter Properties ### Description Details the properties available on a WordHighlighter instance, including the optional SearchAPI. ### Properties #### api (optional) - **api** (SearchAPI) - An optional SearchAPI instance. This property is available after the extension is added to an editor and can be used to get match positions. - **Inherited from**: `SelectionMatchHighlighter.api` ``` -------------------------------- ### forEachCodeBlock Function Source: https://prism-code-editor.netlify.app/api-reference/code-blocks/f-foreachcodeblock Runs a callback function for each code block under a specified root element. Skips blocks that have already been processed. The callback receives the code block and any associated options. ```APIDOC ## forEachCodeBlock ### Description Runs a callback function for each code block under the root in document order. If a callback has previously been run for a code block, it’s skipped. The callback function takes the code block as the first argument. The second parameter is any additional properties passed when the code block was created. These options were stringified to JSON and parsed. ### Method `function` ### Endpoint `N/A` ### Parameters #### Type Parameters - **T** (`object`) - Type parameter for options, constrained to be an object. #### Parameters - **root** (`Element` | `Document`) - Required - The root element or document to search for code blocks under. - **callback** (`(codeBlock, options) => void`) - Required - The function to run for each code block. It receives the `codeBlock` and parsed `options` as arguments. ### Returns - **PrismCodeBlock[]** - An array with all visited code blocks in document order. ``` -------------------------------- ### ReplaceAPI Methods Source: https://prism-code-editor.netlify.app/api-reference/search/api/i-replaceapi This section details the methods available in the ReplaceAPI for managing search and replace operations. ```APIDOC ## ReplaceAPI Methods ### closest() * **Description**: Returns the index of the closest match to the current cursor position. * **Method**: N/A (This is a method of the ReplaceAPI object) * **Endpoint**: N/A * **Returns**: `number` - The index of the closest match. ### destroy() * **Description**: Removes the highlight container from the DOM and cleans up any associated event listeners. * **Method**: N/A (This is a method of the ReplaceAPI object) * **Endpoint**: N/A * **Returns**: `void` ### next() * **Description**: Returns the index of the next match ahead of the cursor. * **Method**: N/A (This is a method of the ReplaceAPI object) * **Endpoint**: N/A * **Returns**: `number` - The index of the next match. ### prev() * **Description**: Returns the index of the match behind the cursor. * **Method**: N/A (This is a method of the ReplaceAPI object) * **Endpoint**: N/A * **Returns**: `number` - The index of the previous match. ### replace(replacement) * **Description**: Replaces the currently selected match with the provided replacement string. If a match is selected and differs from the replacement, it's replaced. Otherwise, it returns the index of the closest match. If no match is selected, the index of the closest match is returned. * **Method**: N/A (This is a method of the ReplaceAPI object) * **Endpoint**: N/A * **Parameters**: * **replacement** (string) - Required - The string to replace the selected match with. * **Returns**: `undefined` | `number` - `undefined` if replacement was successful, or the index of the closest match if no match was selected or if the selected match was not different from the replacement. ### replaceAll(replacement, selection?) * **Description**: Replaces all occurrences of the search matches with the specified replacement string. * **Method**: N/A (This is a method of the ReplaceAPI object) * **Endpoint**: N/A * **Parameters**: * **replacement** (string) - Required - The string to replace all matches with. * **selection?** ([number, number]) - Optional - Bounds to perform the replacement within. Kept for backward compatibility, currently does nothing. * **Returns**: `void` ### selectMatch(index, scrollPadding?) * **Description**: Selects the match at the specified index and scrolls it into view. Allows for optional scroll padding. * **Method**: N/A (This is a method of the ReplaceAPI object) * **Endpoint**: N/A * **Parameters**: * **index** (number) - Required - The index of the match to select. * **scrollPadding?** (number) - Optional - Padding to apply when scrolling the match into view. * **Returns**: `void` ``` -------------------------------- ### BracketMatcher Properties Source: https://prism-code-editor.netlify.app/api-reference/match-brackets/i-bracketmatcher Details about the properties exposed by the BracketMatcher extension. ```APIDOC ## BracketMatcher Properties ### Description Provides access to the internal data structures managed by the BracketMatcher, such as detected brackets and their pairings. ### Properties #### brackets - **brackets** (`readonly Bracket[]`) - An array containing information about each detected bracket. Each element is a tuple with the following structure: - `Token`: The bracket's token. - `number`: The starting position of the bracket. - `number`: The ending position of the bracket. - `number`: The nesting level of the bracket. - `string`: The text content of the bracket. - `boolean`: Indicates if it's an opening bracket. #### pairs - **pairs** (`readonly (undefined | number)[]`) - An array that maps the index of a bracket in the `brackets` array to the index of its corresponding matching bracket. `undefined` indicates no match found for that bracket. ``` -------------------------------- ### PrismCodeEditorElement Methods Source: https://prism-code-editor.netlify.app/api-reference/web-component/i-prismeditorelement This section outlines the methods available on the PrismCodeEditorElement for interacting with the editor, such as adding and removing event listeners. ```APIDOC ## PrismCodeEditorElement Methods This section describes the methods available on the `PrismCodeEditorElement`. ### addEventListener() Adds an event listener to the element. **Call Signature:** `addEventListener(type: "ready", listener: (this: PrismEditorElement, ev: Event) => any, options?: boolean | AddEventListenerOptions): void` `addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void` `addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void` **Parameters:** * `type` (`string` | `"ready"` | `K`): The event type to listen for. * `listener` (`EventListenerOrEventListenerObject` | `(this: PrismEditorElement, ev: Event) => any` | `(this: HTMLElement, ev: HTMLElementEventMap[K]) => any`): The function to call when the event is triggered. * `options?` (`boolean` | `AddEventListenerOptions`): Optional options for the event listener. **Returns:** `void` **Overrides:** `HTMLElement.addEventListener` ### removeEventListener() Removes an event listener from the element. **Call Signature:** `removeEventListener(type: "ready", listener: (this: PrismEditorElement, ev: Event) => any, options?: boolean | EventListenerOptions): void` `removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void` `removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void` **Parameters:** * `type` (`string` | `"ready"` | `K`): The event type to remove. * `listener` (`EventListenerOrEventListenerObject` | `(this: PrismEditorElement, ev: Event) => any` | `(this: HTMLElement, ev: HTMLElementEventMap[K]) => any`): The event listener to remove. * `options?` (`boolean` | `EventListenerOptions`): Optional options for the event listener. **Returns:** `void` **Overrides:** `HTMLElement.removeEventListener` ``` -------------------------------- ### editorFromPlaceholder Source: https://prism-code-editor.netlify.app/api-reference/index/f-editorfromplaceholder Creates a Prism editor that replaces a given placeholder element. It's similar to createEditor but modifies the existing element. ```APIDOC ## editorFromPlaceholder ### Description Almost identical to createEditor, but instead of appending the editor to your element, the editor replaces it. The `textContent` of the placeholder will be the code in the editor unless `options.value` is defined. ### Method ``` createEditor(placeholder: string | ChildNode, options?: Partial & Omit, ...extensions: EditorExtension[]): PrismEditor ``` ### Parameters #### placeholder - **placeholder** (string | ChildNode) - Required - Node or selector which will be replaced by the editor. #### options - **options** (Partial & Omit) - Optional - Options the editor is initialized with. #### extensions - **...extensions** (EditorExtension[]) - Optional - Extensions added before the first render. You can still add extensions later. ### Returns #### Success Response - **PrismEditor** - Object to interact with the created editor. ### Type Parameters #### T - **T** (`object` = { }) - Extends object type. ``` -------------------------------- ### addTooltip Utility Source: https://prism-code-editor.netlify.app/api-reference/tooltips/f-addtooltip Provides a utility function to easily add tooltips positioned at the editor's cursor. Requires a cursorPosition extension to be added to the editor before use. ```APIDOC ## addTooltip ### Description Utility making it easy to add tooltips positioned on the editor’s cursor. Before you can show the tooltip, a cursorPosition extension must be added to the editor. This works by appending your tooltip to a flex container. You can style this container with the selector `.pce-tooltip` if needed. This container is then added to the editor’s overlays. It also has `overflow-x: clip` to prevent your tooltip from overflowing in browsers that support it. If you want your tooltip to always be visible when scrolling horizontally, you can add `position: sticky` along with the `right` and `left` CSS properties to it. ### Method [Not explicitly defined, likely a function call] ### Endpoint [Not applicable, this is a utility function] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### editor - **editor** (`PrismEditor`) - Required - Editor you want to add the tooltip to. #### element - **element** (`HTMLElement`) - Required - Element for the tooltip. #### fixedWidth - **fixedWidth** (`boolean`) - Optional - If false, the tooltip will shrink instead of getting offset to the left if there’s not enough space to the right of the cursor. Defaults to `true`. ### Request Example ```javascript const [show, hide] = addTooltip(editor, element) ``` ### Response #### Success Response (200) - **ShowTooltip** (`function`) - Function to show the tooltip. - **HideTooltip** (`function`) - Function to hide the tooltip. #### Response Example ```json { "show": "function", "hide": "function" } ``` ``` -------------------------------- ### registerCompletions API Source: https://prism-code-editor.netlify.app/api-reference/autocomplete/f-registercompletions Registers completion sources for a set of languages. If any of the languages already have completion sources, they are overridden. ```APIDOC ## registerCompletions ### Description Registers completion sources for a set of languages. If any of the languages already have completion sources, they are overridden. ### Method N/A (This is a function definition, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Type Parameters #### T - `T` (object) - Constraint: extends `object` - Type parameter for the completion definition. ### Parameters #### langs - **langs** (string[]) - Required - Array of languages you want the completions to apply for. #### definition - **definition** (CompletionDefinition<`T`>) - Required - Defines the completion sources for the languages along with additional properties on the context passed to the completion sources. ### Request Example ```javascript // Example usage (conceptual, actual implementation depends on context) registerCompletions(['javascript', 'typescript'], { getCompletions: (context) => { // Logic to provide completions return [{ label: 'myCompletion', type: 'keyword', insertText: 'myCompletion' }]; } }); ``` ### Response #### Success Response (void) - Returns `void`. #### Response Example N/A (void return type) ``` -------------------------------- ### renderCodeBlock Function Source: https://prism-code-editor.netlify.app/api-reference/ssr/f-rendercodeblock Renders a static code block as HTML. Styles from prism-code-editor/code-block.css are required in addition to the normal layout. ```APIDOC ## renderCodeBlock ### Description Renders a static code block as HTML. Styles from `prism-code-editor/code-block.css` are required in addition to the normal layout. ### Method Function Call ### Parameters #### Type Parameters - **T** (`object`) - Type parameter that extends object. #### Options - **options** (`CodeBlockOptions` & `Omit`) - Required - Options controlling how to render the code block. Any extra properties not in CodeBlockOptions will be stringified as JSON and later parsed by forEachCodeBlock. ### Returns `string` - String of HTML for the static code block. ``` -------------------------------- ### CompletionSource Type Definition Source: https://prism-code-editor.netlify.app/api-reference/autocomplete/t-completionsource Defines the structure and usage of the CompletionSource type, which is a function that provides code completion suggestions based on context and editor state. ```APIDOC ## CompletionSource Type ### Description The `CompletionSource` type represents a function that can provide code completion suggestions. It takes the current completion context and the editor instance as input and returns a `CompletionResult`, `undefined`, or `null`. ### Type `CompletionSource` where `T` extends `object` ### Parameters #### context - **context** (`CompletionContext` & `T`) - Required - The context in which completion is being requested, including editor state and potential user input. #### editor - **editor** (`PrismEditor`) - Required - The Prism editor instance, providing access to the editor's API and state. ### Returns - **CompletionResult** | `undefined` | `null` - A `CompletionResult` object containing suggestions, or `undefined`/`null` if no suggestions are available for the given context. ``` -------------------------------- ### Modifying Grammar with insertBefore (JavaScript) Source: https://prism-code-editor.netlify.app/api-reference/prism/utils/v-insertbefore Demonstrates how to use the insertBefore utility to add a 'style' token to the 'markup' grammar before the 'cdata' token. This is useful for extending Prism.js to highlight embedded languages like CSS within HTML `