パッケージの詳細

vue-codemirror6

logue59.1kMIT1.3.20

CodeMirror6 Component for vue2 and vue3.

vuejs, vue, vue-components, vue-codemirror

readme

vue-codemirror6

logo

jsdelivr CDN NPM Downloads Open in unpkg npm version Open in Gitpod Twitter Follow

A component for using CodeMirror6 with Vue. This component works in both Vue2 and Vue3.

Usage

yarn add vue-codemirror6 codemirror

For Vue 2.7 or below, @vue/composition-api is required separately.

yarn add vue-codemirror6 @vue/composition-api

This component can handle bidirectional binding by v-model like a general Vue component.

Props

Props Type Information
model-value string \ Text Text value. (Not value)
basic boolean Use basicSetup.
minimal boolean Use miniSetup. If a basic prop is also specified, that setting will take precedence.
dark boolean Toggle Darkmode.
placeholder string Add placeholder text (or HTML DOM) when blank
wrap boolean Line text wrapping. see lineWrapping.
tab boolean Enables tab indentation.
allow-multiple-selections boolean Allow Multiple Selection. See allowMultipleSelections
tab-size number Configures the tab size to use in this state.
line-separator string Set line break (separetor) char. (Default is \n.)
theme { [selector: string]: StyleSpec } Specify the theme. For example, if you use @codemirror/theme-one-dark, import oneDark and put it in this prop.
readonly boolean Makes the cursor visible or you can drag the text but not edit the value.
disabled boolean This is the reversed value of the CodeMirror editable. Similar to readonly, but setting this value to true disables dragging.
lang LanguageSupport The language you want to have syntax highlighting. see https://codemirror.net/6/#languages
phrases Record<string, string> Specify here if you want to make the displayed character string multilingual. see https://codemirror.net/6/examples/translate/
extensions Extension[] Includes enhancements to extend CodeMirror.
linter LintSource Set Linter. Enter a linter (eg esLint([arbitrary rule]) function for @codemirror/lang-javascript, jsonParseLinter()function for@codemirror/json). See the sources for various language libraries for more information.
linterConfig Object see https://codemirror.net/docs/ref/#lint.linter^config
forceLinting boolean see https://codemirror.net/docs/ref/#lint.forceLinting
gutter boolean Display 🔴 on the line where there was an error when linter was specified. It will not work if linter is not specified.
gutterConfig Object see https://codemirror.net/docs/ref/#lint.lintGutter^config
tag string HTML tags used in the component. (Default is div tag.)
scrollIntoView boolean Allows an external update to scroll the form. (Default is true)
keymap KeyBinding[] Key bindings associate key names with command-style functions. See https://codemirror.net/docs/ref/#view.KeyBinding

⚠ Notice: lang and linter can also be set together in extensions. These are separated for compatibility with previous versions of CodeMirror settings and for typing props.

Supported Languages

Official

Unofficial

Supported Themes

Example

Mark up as follows to make it work at a minimum.

<template>
  <code-mirror v-model="value" />
</template>

<script>
import { ref, defineComponent } from 'vue';

import CodeMirror from 'vue-codemirror6';

export default defineComponent({
  components: {
    CodeMirror,
  },
  setup() {
    const value = ref('Cozy lummox gives smart squid who asks for job pen.');

    return { value };
  },
});
</script>

Example using Slots

The contents of the slot will overwrite the existing v-model. For this reason, it is recommended to use it when simply displaying with a readonly prop without using v-model.

Also, insert a <pre> tag to prevent the text in the slot from being automatically formatted.

<template>
  <code-mirror :lang="lang" :linter="linter">
    <pre>
{
  "key": "value"
}</pre
    >
  </code-mirror>
</template>

<script>
import { ref, defineComponent } from 'vue';

import { json, jsonParseLinter } from '@codemirror/lang-json';

import CodeMirror from 'vue-codemirror6';

export default defineComponent({
  components: {
    CodeMirror,
  },
  setup() {
    const lang = json();
    const linter = jsonParseLinter();
    return { lang, linter };
  },
});
</script>

Full Example

When using as a Markdown editor on vite-vue3-ts-starter.

<script lang="ts" setup>
import { ref, defineComponent, type Ref } from 'vue';

// Load component
import CodeMirror from 'vue-codemirror6';

// CodeMirror extensions
import { markdown as md } from '@codemirror/lang-markdown';
import type { LanguageSupport } from '@codemirror/language';
import type { Extension } from '@codemirror/state';
import type { ViewUpdate } from '@codemirror/view';

/** text */
const value: Ref<string> = ref('');

/** Dark mode **/
const dark: Ref<boolean> = ref(
  window.matchMedia('(prefers-color-scheme: dark)').matches
);

/**
 * CodeMirror Language
 *
 * @see {@link https://codemirror.net/6/docs/ref/#language | @codemirror/language}
 */
const lang: LanguageSupport = md();

/**
 * Internationalization Config.
 * In this example, the display language to Japanese.
 * Must be reactive when used in combination with vue-i18n.
 *
 * @see {@link https://codemirror.net/6/examples/translate/ | Example: Internationalization}
 */
const phrases: Record<string, string> = {
  // @codemirror/view
  'Control character': '制御文字',
  // @codemirror/commands
  'Selection deleted': '選択を削除',
  // @codemirror/language
  'Folded lines': '折り畳まれた行',
  'Unfolded lines': '折り畳める行',
  to: '行き先',
  'folded code': '折り畳まれたコード',
  unfold: '折り畳みを解除',
  'Fold line': '行を折り畳む',
  'Unfold line': '行の折り畳む解除',
  // @codemirror/search
  'Go to line': '行き先の行',
  go: 'OK',
  Find: '検索',
  Replace: '置き換え',
  next: '▼',
  previous: '▲',
  all: 'すべて',
  'match case': '一致条件',
  'by word': '全文検索',
  regexp: '正規表現',
  replace: '置き換え',
  'replace all': 'すべてを置き換え',
  close: '閉じる',
  'current match': '現在の一致',
  'replaced $ matches': '$ 件の一致を置き換え',
  'replaced match on line $': '$ 行の一致を置き換え',
  'on line': 'した行',
  // @codemirror/autocomplete
  Completions: '自動補完',
  // @codemirror/lint
  Diagnostics: 'エラー',
  'No diagnostics': 'エラーなし',
};
</script>

<template>
  <code-mirror
    v-model="value"
    basic
    :dark="dark"
    :lang="lang"
    :phrases="phrases"
  />
</template>

Events

Event Description
ready When CodeMirror loaded.
focus When focus changed.
update When CodeMirror state changed. Returns ViewUpdate object.
change Value changed. Returns EditorState

Parameter / Function

<script setup lang="ts">
import { ref, onMounted, type Ref, type PropType } from 'vue';
import CodeMirror from 'vue-codemirror6';

const cm: Ref<InstanceType<typeof CodeMirror> | undefined> = ref();

onMounted(() => {
  console.log(cm.value?.json);
});
</script>
<template>
  <code-mirror ref="cm" />
</template>
Function / Parameter Description
view Get and set EditorView.
selection Get and set the EditorSelection instance.
cursor Get and set the cursor location.
json Get and set state to a JSON-serializable object.
focus Get and set focus.
lint() Force run linter (Only if linter prop is specified)
forceReconfigure() Re register all extensions.

CodeMirror5 backward compatible functions

The instructions below are compatible methods for those familiar with codemirror5. Since the above method is usually sufficient, its active use is not recommended.

Function Description
getRange(from?: number, to?: number) Get the text between the given points in the editor.
getLine(number: number) Get the content of line.
lineCount() Get the number of lines in the editor.
getCursor() Retrieve one end of the primary selection.
listSelections() Retrieves a list of all current selections.
getSelection() Get the currently selected code.
getSelections() The length of the given array should be the same as the number of active selections.
somethingSelected() Return true if any text is selected.
replaceRange(replacement: string \ Text, from: number, to: number) Replace the part of the document between from and to with the given string.
replaceSelection(replacement: string \ Text) Replace the selection(s) with the given string.
setCursor(position: number) Set the cursor position.
setSelection(anchor: number, head?: number) Set a single selection range.
setSelections(ranges: readonly SelectionRange[], primary?: number) Sets a new set of selections.
extendSelectionsBy(f: Function) Applies the given function to all existing selections, and calls extendSelections on the result.

Recommendations

Since CodeMirror has a relatively large capacity, when using vite, it is recommended to set it to output as a separate file using the manualChunks option at build time as shown below.

const config: UserConfig = {
  // ...
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          // ...
          codemirror: ['vue-codemirror6'],
          'codemirror-lang': [
            // Add the following as needed.
            '@codemirror/lang-html',
            '@codemirror/lang-javascript',
            '@codemirror/lang-markdown',
          ],
          // ...
        },
      },
    },
  },
  // ...
};

LICENSE

©2022-2025 by Logue. Licensed under the MIT License.

更新履歴

Changelog

All notable changes to this project will be documented in this file. Dates are displayed in UTC.

Generated by auto-changelog.

1.3.20

  • fix: full example link #58
  • Update dependencies. 985f36f
  • Update vue, codemirror. bfbd153
  • Removed unnecessary comment. 8d624a4

1.3.13

31 March 2025

  • Rewrite to eslint.config.ts 841f686
  • Fixed types path. 2b86b2c
  • Update @codemirror/language, @codemirror/lint, @codemirror/state, @codemirror/view. 916fa98

1.3.8

22 November 2024

  • Fix sample code syntax error #47
  • chore: demo docs #43
  • fix: editor not update content when modelValue change and selection is out of range #44
  • chore: props and readme doc #31
  • Reduce unnecessary updates #22
  • fix: coalescing-operator #20
  • Migrate to pnpm. 6d83aec
  • Update dependencies. 992f209
  • Update dependencies. b839a33

1.1.16

18 March 2023

  • Expose view. #16 daf3e6b
  • Fixed Maximum call stack size exceeded error. f10eaae
  • Partially fixed the problem that the values defined in props disappeared under certain conditions. 1cc4468

1.1.13

13 March 2023

  • Changed minimum Vue version requirement to 2.7.14. 5b8b255
  • Add allow-multiple-selections prop. ced91ed
  • Update CHANGELOG.md 51d30e2

1.1.12

10 March 2023

  • chore(CODEOWNERS): CODEOWNERS.com Bot, at your service! #14
  • Update demo code. (Replaced @codemirror/html to @codemirror/vue.) 8da1a8a
  • Changed implementation to generate *.d.ts with vite-plugin-dts. 1caaa20
  • Update README.md. f8dd493

1.1.11

4 February 2023

  • [SECURITY FIX] CWE-1333: Inefficient Regular Expression Complexity #13 fc63a9f
  • Fix for #11 c634b55
  • Add forceReconfigure() function. bbfa8ad

1.1.3

9 January 2023

  • Bump json5 from 1.0.1 to 1.0.2 #10
  • Consolidated demo code generation settings into a single vite.config.ts 7fe3ad2
  • Update dependencies. 75b984e

1.1.2

24 December 2022

1.1.1

7 November 2022

  • Fixed Markdown demo. 399f32c
  • Fix cross-binding not works. 137765b
  • Fixed taking URL class from other than node when building docs. fbf1d56

1.1.0

31 October 2022

  • Rewrite the demo code with Vue3 setup. fdc7e3c
  • Fixed wrong typing of computed value. 9b5a572
  • Add CHANGELOG.md. 1de388f

1.0.3

12 October 2022

1.0.2

15 September 2022

  • Enabled to specify HTML tags used in components. 9b9eecd

1.0.1

8 September 2022

1.0.0

20 August 2022

0.6.8

1 August 2022

  • Unify props monitoring process. 15b8a17
  • Fixed an error around linter. b2fe3db
  • Fixed dispatch may be executed multiple times when the value of prop is changed. 2e19316

0.6.5

4 July 2022

  • Remove banner from source code. 043e0ed
  • Delete unnecessary cursor movement processing and assignment processing. c89fd00

0.6.4

28 June 2022

  • Fixed a bug that the cursor may move to a strange place when inputting. 9977976
  • Changed the logic when assigning text values to CodeMirror. 313e701
  • Fixed the problem that the definition file was omitted because the binary output by analyze was given to npm. 503a52e

0.6.0

9 June 2022

0.5.5

8 June 2022

0.5.4

31 May 2022

  • Fixed a bug that the cursor goes to a strange place when inputting. 81af5b2

0.5.3

31 May 2022

  • Fixed an issue where parent-to-child binding did not work properly. d355f2c
  • Changed the implementation to call the extension directly with a function. 98d338f
  • The initial value of linter is set to simple undefined. 6cec8b0

0.5.2

30 May 2022

  • Simplify extension processing. cd875ff
  • Since lintGutter is displayed even for components for which linter is not specified, lintGutter is made an option. ab16cbb
  • Fixed innerText is undefined error. 6466784

0.5.1

28 May 2022

0.5.0

27 May 2022

  • The output program is compatible with both Vue2 and Vue3.☺ 7571423

0.3.7

26 May 2022

0.3.6

19 May 2022

  • Rename serve.vue to DemoPage.vue. 3ba582b
  • Fixed an issue where CodeMirror may not work properly during initial display. 8092b64
  • Add basic and tab props. 54eace6

0.3.2

6 April 2022

  • When building with vue3, it doesn't work with vue2, so build with vue2. 87be702
  • Rewrite the wrapper part. 1e77661
  • Update sample. f7ed0a5

0.3.0

29 March 2022

0.1.7

26 May 2022

0.1.6

19 May 2022

  • Follow changes in the master branch d7a9e3f
  • Follow Vue3 version. 1867c6c
  • Since past values may be included, nextTick processing was added to onMouted. dac2bdd

0.1.2

6 April 2022

  • Squashed commit of the following: db4abdd
  • When building with vue3, it doesn't work with vue2, so build with vue2. 87be702
  • Rewrite the wrapper part. 1e77661

0.1.0

18 March 2022

  • Update Samples. (run yarn run dev) f658c65
  • Fixed IME probrem. 7a42e63

0.0.6

17 March 2022

  • Fixed d.ts file destination. 2cd9cdf

0.0.5

17 March 2022

  • Fixed a bug that the cursor position may be at the top when entering a key. e7f5407

0.0.4

16 February 2022

  • Update demo code. 599fa5f
  • Removed code that depends on other libraries from the output code. 7d9e383
  • Add demo code. 3e06ef7

0.0.2

14 February 2022

  • Update package.json. Fixed typing settings. 12ead23

0.0.1

10 February 2022