1.3.0 ā€¢ Published 10 days ago

vue-codemirror6 v1.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
10 days ago

vue-codemirror6

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

PropsTypeInformation
model-valuestring | TextText value. (Not value)
basicbooleanUse basicSetup.
minimalbooleanUse miniSetup. If a basic prop is also specified, that setting will take precedence.
darkbooleanToggle Darkmode.
placeholderstringAdd placeholder text (or HTML DOM) when blank
wrapbooleanLine text wrapping. see lineWrapping.
tabbooleanEnables tab indentation.
allow-multiple-selectionsbooleanAllow Multiple Selection. See allowMultipleSelections
tab-sizenumberConfigures the tab size to use in this state.
line-separatorstringSet 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.
readonlybooleanMakes the cursor visible or you can drag the text but not edit the value.
disabledbooleanThis is the reversed value of the CodeMirror editable. Similar to readonly, but setting this value to true disables dragging.
langLanguageSupportThe language you want to have syntax highlighting. see https://codemirror.net/6/#languages
phrasesRecord<string, string>Specify here if you want to make the displayed character string multilingual. see https://codemirror.net/6/examples/translate/
extensionsExtension[]Includes enhancements to extend CodeMirror.
linterLintSourceSet 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.
linterConfigObjectsee https://codemirror.net/docs/ref/#lint.linter^config
forceLintingbooleansee https://codemirror.net/docs/ref/#lint.forceLinting
gutterbooleanDisplay šŸ”“ on the line where there was an error when linter was specified. It will not work if linter is not specified.
gutterConfigObjectsee https://codemirror.net/docs/ref/#lint.lintGutter^config
tagstringHTML tags used in the component. (Default is div tag.)

āš  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-vue2-vuetify-ts-starter.

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

<script lang="ts">
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';

export default defineComponent({
  components: {
    CodeMirror,
  },
  setup() {
    /**
     * Get Vuetify instance
     *
     * @see {@link https://github.com/logue/vite-vue2-vuetify-ts-starter | vite-vue2-vuetify-ts-starter}
     */
    const vuetify = useVuetify();

    /** 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: Ref<Record<string, string>> = ref({
      // @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': 'ć‚Øćƒ©ćƒ¼ćŖ恗',
    });

    /** When dark value changed, sync vuetify's dark mode */
    watch(dark, v => (vuetify.theme.dark = v));

    return {
      dark,
      value,
      lang,
      phrases,
    };
  },
});
</script>

Events

EventDescription
readyWhen CodeMirror loaded.
focusWhen focus changed.
updateWhen CodeMirror state changed. Returns ViewUpdate object.
changeValue 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 / ParameterDescription
viewGet and set EditorView.
selectionGet and set the EditorSelection instance.
cursorGet and set the cursor location.
jsonGet and set state to a JSON-serializable object.
focusGet 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.

FunctionDescription
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: [
            // Split CodeMirror code.
            'vue-codemirror6'
            'codemirror',
            '@codemirror/autocomplete',
            '@codemirror/commands',
            '@codemirror/language',
            '@codemirror/lint',
            '@codemirror/search',
            '@codemirror/state',
            '@codemirror/view',
          ],
          'codemirror-lang': [
            // Add the following as needed.
            '@codemirror/lang-html',
            '@codemirror/lang-javascript',
            '@codemirror/lang-markdown',
          ],
          // ...
        },
      },
    },
  },
  // ...
};

LICENSE

Ā©2022-2023 by Logue. Licensed under the MIT License.

1.3.0

10 days ago

1.2.5

3 months ago

1.2.3

4 months ago

1.2.2

4 months ago

1.2.0

5 months ago

1.1.32

5 months ago

1.1.28

6 months ago

1.1.30

6 months ago

1.1.31

5 months ago

1.1.23

9 months ago

1.1.22

11 months ago

1.1.27

8 months ago

1.1.26

8 months ago

1.1.24

9 months ago

1.1.9

1 year ago

1.1.8

1 year ago

1.1.6

1 year ago

1.1.12

1 year ago

1.1.11

1 year ago

1.1.10

1 year ago

1.1.16

1 year ago

1.1.15

1 year ago

1.1.14

1 year ago

1.1.13

1 year ago

1.1.19

1 year ago

1.1.18

1 year ago

1.1.17

1 year ago

1.1.21

12 months ago

1.1.20

1 year ago

1.1.1

1 year ago

1.1.0

2 years ago

1.1.4

1 year ago

1.1.3

1 year ago

1.1.2

1 year ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.6.7

2 years ago

0.6.6

2 years ago

0.6.8

2 years ago

0.6.3

2 years ago

0.5.4

2 years ago

0.3.6

2 years ago

0.6.2

2 years ago

0.5.3

2 years ago

0.1.7

2 years ago

0.6.5

2 years ago

0.6.4

2 years ago

0.5.5

2 years ago

0.3.7

2 years ago

0.5.0

2 years ago

0.6.1

2 years ago

0.5.2

2 years ago

0.1.6

2 years ago

0.6.0

2 years ago

0.5.1

2 years ago

0.3.5

2 years ago

0.1.4

2 years ago

0.3.3

2 years ago

0.1.0

2 years ago

0.1.2

2 years ago

0.3.0

2 years ago

0.3.2

2 years ago

0.0.5

2 years ago

0.1.3

2 years ago

0.3.1

2 years ago

0.0.6

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago