Text Editor - Code Highlight Plugin
Syntax highlight selected code using Shiki with configurable themes and languages.
#Usage
import { TextEditor } from '@primeui/vue-texteditor';
import { codeHighlightPlugin } from './code-highlight-plugin';<TextEditor.Root v-model="value" :plugins="[[codeHighlightPlugin, { theme: 'github-dark', langs: ['javascript', 'html'] }]]">
<TextEditor.Toolbar>
<HighlightButton />
</TextEditor.Toolbar>
<TextEditor.Content />
</TextEditor.Root>The Code Highlight plugin adds a highlight command that syntax-highlights the selected text and replaces it with the rendered HTML. Pass the plugin as a [plugin, options] tuple to set the theme and languages, then call pluginCommands.codeHighlight?.highlight(lang) from a widget. The plugin owns the highlighter; the editor owns the selection it replaces.
#Overview
The plugin wraps Shiki. Themes and supported languages are passed as plugin options; the highlighter is created lazily on first use and disposed when the plugin unmounts.
#Plugin Definition
import { defineTextEditorPlugin } from '@primeui/vue-texteditor';
import { createHighlighter, type Highlighter } from 'shiki';
export interface CodeHighlightOptions {
theme?: string;
langs?: string[];
}
export const codeHighlightPlugin = defineTextEditorPlugin<CodeHighlightOptions>('codeHighlight', ({ getSelectedText, replaceSelection, options, onUnmounted }) => {
let highlighter: Highlighter | null = null;
const theme = options?.theme ?? 'github-dark';
const langs = options?.langs ?? ['javascript', 'html', 'css'];
const getOrCreateHighlighter = async () => {
if (!highlighter) {
highlighter = await createHighlighter({ themes: [theme], langs });
}
return highlighter;
};
onUnmounted(() => {
highlighter?.dispose();
highlighter = null;
});
return {
commands: {
highlight: async (lang: string) => {
if (!langs.includes(lang)) return;
const text = getSelectedText();
if (!text) return;
const h = await getOrCreateHighlighter();
const html = h.codeToHtml(text, { lang, theme });
replaceSelection(html, true);
},
getSupportedLangs: () => langs
}
};
});#Options
| Option | Type | Default | Description |
|---|---|---|---|
theme | string | 'github-dark' | Shiki theme for syntax highlighting |
langs | string[] | ['javascript', 'html', 'css'] | Supported languages for highlighting |
#Commands
| Command | Signature | Description |
|---|---|---|
highlight | (lang: string) => Promise<void> | Highlights selected text with the given language |
getSupportedLangs | () => string[] | Returns the list of supported languages |
#Example
Select text in the editor, pick a language, and click Highlight.
Loading Demo...