@codemirror/state#Extension TypeScript Examples
The following examples show how to use
@codemirror/state#Extension.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PumlView.ts From obsidian-plantuml with MIT License | 7 votes |
extensions: Extension[] = [
highlightActiveLine(),
highlightActiveLineGutter(),
highlightSelectionMatches(),
drawSelection(),
keymap.of([...defaultKeymap, indentWithTab]),
history(),
search(),
EditorView.updateListener.of(v => {
if(v.docChanged) {
this.requestSave();
this.renderPreview();
}
})
]
Example #2
Source File: languages.ts From starboard-notebook with Mozilla Public License 2.0 | 6 votes |
export function getCodemirrorLanguageExtension(language?: string): Extension | undefined {
let lang = language || "";
lang = lang.toLowerCase();
// TODO: maybe this should be a switch
if (["javascript", "js"].indexOf(lang) !== -1) return javascript();
else if (["typescript", "ts"].indexOf(lang) !== -1) return javascript({ typescript: true });
else if (["jsx"].indexOf(lang) !== -1) return javascript({ jsx: true });
else if (["tsx"].indexOf(lang) !== -1) return javascript({ typescript: true, jsx: true });
else if (["python", "py"].indexOf(lang) !== -1) return python();
else if (lang === "css") return css();
else if (lang === "html") return html();
else if (["markdown", "md"].indexOf(lang) !== -1) return markdown();
else if (lang === "xml") return xml();
else if (lang === "json") return json();
// TODO specify the SQL dialects individually?
else if (lang === "sql") return sql();
else if (lang === "rust") return rust();
// Legacy languages
else if (["go", "golang"].indexOf(lang) !== -1) return StreamLanguage.define(go);
else if (lang === "r") return StreamLanguage.define(r as any);
else if (lang === "yaml") return StreamLanguage.define(yaml as any);
else if (lang === "toml") return StreamLanguage.define(toml as any);
else if (["shader", "glsl", "opengl"].indexOf(lang) !== -1) return StreamLanguage.define(shader);
// There is actually a modern cpp and java extension, but it is much larger in bundle size
// given the rarity of cpp or java in a notebook we use the clike one instead to save ~50kb gzipped(!)
else if (lang === "cpp") return StreamLanguage.define(cpp);
else if (lang === "java") return StreamLanguage.define(java);
else if (lang === "kotlin") return StreamLanguage.define(kotlin);
else if (lang === "c") return StreamLanguage.define(c);
else if (lang === "dart") return StreamLanguage.define(dart);
}
Example #3
Source File: main.ts From obsidian-banners with MIT License | 5 votes |
extensions: Extension[];
Example #4
Source File: index.tsx From pintora with MIT License | 4 votes |
Editor = (props: Props) => {
const { code, onCodeChange, editorOptions, errorInfo } = props
const wrapperRef = useRef<HTMLDivElement>()
const viewRef = useRef<EditorView>()
const stateRef = useRef<EditorState>()
useEffect(() => {
if (!wrapperRef.current) return
let editor = viewRef.current
let state = stateRef.current
if (viewRef.current) viewRef.current.destroy()
if (!state) {
const onUpdateExtension = EditorView.updateListener.of(update => {
if (update.docChanged && state) {
const newCode = update.view.state.doc.toJSON().join('\n')
onCodeChange(newCode)
}
})
const extensions: Extension[] = [
keymap.of(standardKeymap),
history(),
keymap.of(historyKeymap),
onUpdateExtension,
keymap.of(searchKeymap),
lineNumbers(),
search({ top: true }),
highlightActiveLine(),
oneDark,
keymap.of(tabKeymaps),
]
if (editorOptions.language === 'json') {
extensions.push(json())
}
state = EditorState.create({
doc: code,
extensions,
})
stateRef.current = state
}
editor = new EditorView({
parent: wrapperRef.current,
state: state,
})
viewRef.current = editor
return () => {
if (viewRef.current) {
viewRef.current.destroy()
}
}
}, [])
useEffect(() => {
const view = viewRef.current
if (view && view.state) {
const state = view.state
const currentCode = state.doc.toJSON().join('\n')
// console.log('currentCode == code', currentCode == code)
if (currentCode !== code) {
view.dispatch(state.update({ changes: { from: 0, to: currentCode.length, insert: code } }))
}
}
}, [code])
useEffect(() => {
const view = viewRef.current
if (view) {
if (errorInfo) {
const spec = setDiagnostics(view.state, [
{
severity: 'error',
message: errorInfo.message,
from: errorInfo.offset,
to: errorInfo.offset,
},
])
view.dispatch(spec)
} else {
view.dispatch(setDiagnostics(view.state, []))
}
}
}, [errorInfo])
// TOOD: highlight error
// useEffect(() => {
// }, [errorInfo])
return <div className="CMEditor" ref={wrapperRef as any}></div>
}
Example #5
Source File: main.ts From quick_latex_obsidian with MIT License | 4 votes |
private readonly makeExtensionThing = ():Extension => Prec.high(keymap.of([
{
key: '$',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (editor.getSelection().length > 0) {
// enclose selected text
if (this.settings.encloseSelection_toggle) {
const anchor = editor.getCursor("anchor")
const head = editor.getCursor("head")
editor.replaceSelection(`$${editor.getSelection()}$`)
if (anchor.line > head.line) {
editor.setSelection({line:anchor.line,ch:anchor.ch},{line:head.line,ch:head.ch+1})
} else if (anchor.line < head.line) {
editor.setSelection({line:anchor.line,ch:anchor.ch+1},{line:head.line,ch:head.ch})
} else {
editor.setSelection({line:anchor.line,ch:anchor.ch+1},{line:head.line,ch:head.ch+1})
}
return true
}
return false
} else {
// close math symbol
const position = editor.getCursor()
const prev_char = editor.getRange(
{line:position.line,ch:position.ch-1},
{line:position.line,ch:position.ch})
const next_char = editor.getRange(
{line:position.line,ch:position.ch},
{line:position.line,ch:position.ch+1})
const next2_char = editor.getRange(
{line:position.line,ch:position.ch},
{line:position.line,ch:position.ch+2})
if (prev_char != "$" && next_char == "$"){
if (next2_char == "$$") {
editor.setCursor({line:position.line,ch:position.ch+2})
return true
} else {
editor.setCursor({line:position.line,ch:position.ch+1})
return true
}
}
// auto close math
if (this.settings.autoCloseMath_toggle && this.vimAllow_autoCloseMath) {
editor.replaceSelection("$");
}
// move into math
if (this.settings.moveIntoMath_toggle) {
const position = editor.getCursor();
const t = editor.getRange(
{ line: position.line, ch: position.ch - 1 },
{ line: position.line, ch: position.ch })
const t2 = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch + 1 })
const t_2 = editor.getRange(
{ line: position.line, ch: position.ch - 2 },
{ line: position.line, ch: position.ch })
if (t == '$' && t2 != '$') {
editor.setCursor({ line: position.line, ch: position.ch - 1 })
} else if (t_2 == '$$') {
editor.setCursor({ line: position.line, ch: position.ch - 1 })
};
}
return false
}
},
},
{
key: 'Tab',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
// Tab shortcut for matrix block
if (this.settings.addMatrixBlock_toggle) {
if (this.withinAnyBrackets_document(editor,
'\\begin{' + this.settings.addMatrixBlock_parameter,
'\\end{' + this.settings.addMatrixBlock_parameter,
)) {
editor.replaceSelection(' & ')
return true
};
}
// Tab shortcut for cases block
if (this.settings.addCasesBlock_toggle) {
if (this.withinAnyBrackets_document(editor,
'\\begin{cases}',
'\\end{cases}'
)) {
editor.replaceSelection(' & ')
return true
};
}
// Tab to go to next #tab
const position = editor.getCursor();
const current_line = editor.getLine(position.line);
const tab_position = current_line.indexOf("#tab");
if (tab_position!=-1){
editor.replaceRange("",
{line:position.line, ch:tab_position},
{line:position.line, ch:tab_position+4})
editor.setCursor({line:position.line, ch:tab_position})
return true
}
return false
},
},
{
key: 'Space',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (!this.settings.autoFraction_toggle &&
!this.settings.autoLargeBracket_toggle &&
!this.settings.autoEncloseSup_toggle &&
!this.settings.autoEncloseSub_toggle &&
!this.settings.customShorthand_toggle) return false;
if (this.withinMath(editor)) {
const position = editor.getCursor();
const current_line = editor.getLine(position.line);
const last_dollar = current_line.lastIndexOf('$', position.ch - 1);
// check for custom shorthand
if (this.settings.customShorthand_toggle && !this.withinText(editor, position.ch)) {
let keyword:string = "";
let keyword_length:number = 0;
for (let i = 0 ; i < this.shorthand_array.length ; i++) {
keyword_length = this.shorthand_array[i][0].length;
if ( keyword_length > position.ch) {
continue;
} else if ( keyword_length == position.ch ) {
keyword = "@" + editor.getRange(
{ line: position.line, ch: position.ch - keyword_length },
{ line: position.line, ch: position.ch });
} else {
keyword = editor.getRange(
{ line: position.line, ch: position.ch - keyword_length - 1 },
{ line: position.line, ch: position.ch });
}
if (keyword[0].toLowerCase() == keyword[0].toUpperCase() ||
keyword[0] == "@" ) {
if (this.shorthand_array[i][0] == keyword.slice(- keyword_length) &&
this.shorthand_array[i][1] != keyword) {
const replace_slash = (keyword[0]=="\\" && this.shorthand_array[i][1][0]=="\\") ? 1 : 0;
const set_cursor_position = this.shorthand_array[i][1].indexOf("#cursor");
editor.replaceRange(this.shorthand_array[i][1],
{ line: position.line, ch: position.ch - keyword_length - replace_slash },
{ line: position.line, ch: position.ch });
if (set_cursor_position != -1) {
editor.replaceRange("",
{line:position.line, ch:position.ch - keyword_length + set_cursor_position},
{line:position.line, ch:position.ch - keyword_length + set_cursor_position+7});
editor.setCursor({line:position.line, ch:position.ch - keyword_length + set_cursor_position})
} else if (this.shorthand_array[i][1].slice(-2) == "{}") {
editor.setCursor(
{ line: position.line,
ch: position.ch + this.shorthand_array[i][1].length - keyword_length - 1 - replace_slash}
);
} else {
}
return true;
};
};
}
};
// find last unbracketed subscript within last 10 characters and perform autoEncloseSub
// ignore expression that contain + - * / ^
const last_math = current_line.lastIndexOf('$', position.ch - 1);
if (this.settings.autoEncloseSub_toggle) {
let last_subscript = current_line.lastIndexOf('_', position.ch);
if (last_subscript != -1 && last_subscript > last_math) {
const letter_after_subscript = editor.getRange(
{ line: position.line, ch: last_subscript + 1 },
{ line: position.line, ch: last_subscript + 2 });
if (letter_after_subscript != "{" &&
(position.ch - last_subscript) <= 10 ) {
editor.replaceSelection("}");
editor.replaceRange("{", {line:position.line, ch:last_subscript+1});
return true;
};
};
};
// retrieve the last unbracketed superscript
let last_superscript = current_line.lastIndexOf('^', position.ch);
while (last_superscript != -1) {
const two_letters_after_superscript = editor.getRange(
{ line: position.line, ch: last_superscript + 1 },
{ line: position.line, ch: last_superscript + 3 });
if (two_letters_after_superscript[0] == '{' || two_letters_after_superscript == ' {') {
last_superscript = current_line.lastIndexOf('^', last_superscript - 1);
} else if (last_superscript < last_math) {
last_superscript = -1
break;
} else {
break;
}
}
// retrieve the last divide symbol
let last_divide = current_line.lastIndexOf('/', position.ch - 1);
// perform autoEncloseSup
if (this.settings.autoEncloseSup_toggle) {
if (last_superscript > last_divide) {
return this.autoEncloseSup(editor, event, last_superscript);
};
};
// perform autoFraction
if (this.settings.autoFraction_toggle && !this.withinText(editor, last_divide)) {
if (last_divide > last_dollar) {
const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
// if any brackets in denominator still unclosed, dont do autoFraction yet
if (!brackets.some(e => this.unclosed_bracket(editor, e[0], e[1], position.ch, last_divide)[0])) {
return this.autoFractionCM6(editor, last_superscript);
};
};
};
// perform autoLargeBracket
if (this.settings.autoLargeBracket_toggle) {
let symbol_before = editor.getRange(
{ line: position.line, ch: position.ch - 1 },
{ line: position.line, ch: position.ch })
if (symbol_before == ')' || symbol_before == ']') {
return this.autoLargeBracket(editor, event);
};
}
}
},
},
{
key: 'Enter',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.settings.addAlignBlock_toggle) {
if (this.withinAnyBrackets_document(
editor,
'\\begin{' + this.settings.addAlignBlock_parameter,
'\\end{' + this.settings.addAlignBlock_parameter)
) {
editor.replaceSelection('\\\\\n&')
return true;
}
}
if (this.settings.addMatrixBlock_toggle) {
if (this.withinAnyBrackets_document(
editor,
'\\begin{' + this.settings.addMatrixBlock_parameter,
'\\end{' + this.settings.addMatrixBlock_parameter
)) {
editor.replaceSelection(' \\\\ ')
return true;
}
}
if (this.settings.addCasesBlock_toggle) {
if (this.withinAnyBrackets_document(
editor,
'\\begin{cases}',
'\\end{cases}'
)) {
editor.replaceSelection(' \\\\\n')
return true;
}
}
// double enter for $$
if (this.withinMath(editor)) {
const position = editor.getCursor();
const prev2_Char = editor.getRange(
{ line: position.line, ch: position.ch - 2 },
{ line: position.line, ch: position.ch })
const next2_Char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch + 2 })
if (prev2_Char=="$$"&&next2_Char=="$$") {
editor.replaceSelection('\n')
editor.setCursor(position)
return false
}
}
return false
},
},
{
key: '{',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseCurly_toggle) {
const position = editor.getCursor();
const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
const next_char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+1 });
const next_2char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+2 });
const followed_by_$spacetabnonedoubleslash = (['$',' ',' ',''].contains(next_char) || next_2char == '\\\\');
if (!this.withinAnyBrackets_inline(editor, brackets) && followed_by_$spacetabnonedoubleslash) {
editor.replaceSelection('{}');
editor.setCursor({line:position.line, ch:position.ch+1});
return true;
};
};
};
return false
},
},
{
key: '[',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseSquare_toggle) {
const position = editor.getCursor();
const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
const next_char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+1 });
const next_2char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+2 });
const followed_by_$spacetabnonedoubleslash = (['$',' ',' ',''].contains(next_char) || next_2char == '\\\\');
if (!this.withinAnyBrackets_inline(editor, brackets) && followed_by_$spacetabnonedoubleslash) {
editor.replaceSelection('[]');
editor.setCursor({line:position.line, ch:position.ch+1});
return true;
};
};
};
return false
},
},
{
key: '(',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseRound_toggle) {
const position = editor.getCursor();
const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
const next_char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+1 });
const next_2char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+2 });
const followed_by_$spacetabnonedoubleslash = (['$',' ',' ',''].contains(next_char) || next_2char == '\\\\');
if (!this.withinAnyBrackets_inline(editor, brackets) && followed_by_$spacetabnonedoubleslash) {
editor.replaceSelection('()');
editor.setCursor({line:position.line, ch:position.ch+1});
return true;
};
};
};
return false
},
},
{
key: '}',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseRound_toggle) {
const position = editor.getCursor();
const end = editor.getLine(position.line).length
const next_sym = editor.getRange({line:position.line,ch:position.ch},{line:position.line,ch:position.ch+1})
if (!this.unclosed_bracket(editor, "{", "}", end, 0)[0] &&
!this.unclosed_bracket(editor, "{", "}", end, 0, false)[0] &&
next_sym == "}") {
editor.setCursor({line:position.line,ch:position.ch+1})
return true;
} else {
return false;
};
};
};
return false
},
},
{
key: ']',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseRound_toggle) {
const position = editor.getCursor();
const end = editor.getLine(position.line).length
const next_sym = editor.getRange({line:position.line,ch:position.ch},{line:position.line,ch:position.ch+1})
if (!this.unclosed_bracket(editor, "[", "]", end, 0)[0] &&
!this.unclosed_bracket(editor, "[", "]", end, 0, false)[0] &&
next_sym == "]") {
editor.setCursor({line:position.line,ch:position.ch+1})
return true;
} else {
return false;
};
};
};
return false
},
},
{
key: ')',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseRound_toggle) {
const position = editor.getCursor();
const end = editor.getLine(position.line).length
const next_sym = editor.getRange({line:position.line,ch:position.ch},{line:position.line,ch:position.ch+1})
if (!this.unclosed_bracket(editor, "(", ")", end, 0)[0] &&
!this.unclosed_bracket(editor, "(", ")", end, 0, false)[0] &&
next_sym == ")") {
editor.setCursor({line:position.line,ch:position.ch+1})
return true;
} else {
return false;
};
};
};
return false
},
},
{
key: 'm',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (!this.withinMath(editor)) return false
const position = editor.getCursor();
if (!this.settings.autoSumLimit_toggle) return;
if (this.withinMath(editor)) {
if (editor.getRange(
{ line: position.line, ch: position.ch - 3 },
{ line: position.line, ch: position.ch }) == '\\su') {
editor.replaceSelection('m\\limits')
return true;
};
};
return false
},
},
]));