|
| 1 | +import extractAbbreviation from '@emmetio/extract-abbreviation'; |
| 2 | +import { expand } from '@emmetio/expand-abbreviation'; |
| 3 | + |
| 4 | +const field = () => ''; |
| 5 | + |
| 6 | +const expandAbbreviation = (source, language) => |
| 7 | + expand(source.abbreviation, { |
| 8 | + field, |
| 9 | + syntax: language, |
| 10 | + addons: { |
| 11 | + jsx: true, |
| 12 | + }, |
| 13 | + }); |
| 14 | + |
| 15 | +const enableEmmet = (editor, monaco) => { |
| 16 | + if (!editor) { |
| 17 | + throw new Error('Must provide monaco-editor instance.'); |
| 18 | + } |
| 19 | + |
| 20 | + editor.addAction({ |
| 21 | + // An unique identifier of the contributed action. |
| 22 | + id: 'emmet-abbr', |
| 23 | + |
| 24 | + // A label of the action that will be presented to the user. |
| 25 | + label: 'Emmet: Expand abbreviation', |
| 26 | + |
| 27 | + // An optional array of keybindings for the action. |
| 28 | + keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_E], // eslint-disable-line no-bitwise |
| 29 | + |
| 30 | + // A precondition for this action. |
| 31 | + precondition: null, |
| 32 | + |
| 33 | + // A rule to evaluate on top of the precondition in order to dispatch the keybindings. |
| 34 | + keybindingContext: null, |
| 35 | + |
| 36 | + contextMenuGroupId: 'navigation', |
| 37 | + |
| 38 | + contextMenuOrder: 1.5, |
| 39 | + |
| 40 | + // Method that will be executed when the action is triggered. |
| 41 | + // @param editor The editor instance is passed in as a convenience |
| 42 | + run: () => { |
| 43 | + let word = editor.model.getValueInRange(editor.getSelection()); |
| 44 | + const pos = editor.getPosition(); |
| 45 | + if (!word) { |
| 46 | + const lineContent = editor.model.getLineContent(pos.lineNumber); |
| 47 | + word = extractAbbreviation(lineContent.substring(0, pos.column)); |
| 48 | + } |
| 49 | + if (word) { |
| 50 | + // Get expand text |
| 51 | + const expandText = expandAbbreviation(word, 'html'); |
| 52 | + if (expandText) { |
| 53 | + // replace range content: pos.column , pos.column -word.length; |
| 54 | + const range = new monaco.Range( |
| 55 | + pos.lineNumber, |
| 56 | + pos.column - word.abbreviation.length, |
| 57 | + pos.lineNumber, |
| 58 | + pos.column |
| 59 | + ); |
| 60 | + const id = { major: 1, minor: 1 }; |
| 61 | + const op = { |
| 62 | + identifier: id, |
| 63 | + range, |
| 64 | + text: expandText, |
| 65 | + forceMoveMarkers: true, |
| 66 | + }; |
| 67 | + editor.executeEdits('', [op]); |
| 68 | + return null; |
| 69 | + } |
| 70 | + return false; |
| 71 | + } |
| 72 | + return false; |
| 73 | + }, |
| 74 | + }); |
| 75 | +}; |
| 76 | + |
| 77 | +export default enableEmmet; |
0 commit comments