1. chainWebpack: (config) => {
  2. config.plugin("monaco-editor").use(MonacoWebpackPlugin, [
  3. {
  4. // Languages are loaded on demand at runtime
  5. languages: ["json", "javascript", "html", "xml"],
  6. },
  7. ]);
  8. },

monaco 静态方法

export namespace editor

editor 相关 ts
image.png

monaco.editor.create

  1. export function create(domElement: HTMLElement, options?: IStandaloneEditorConstructionOptions, override?: IEditorOverrideServices): IStandaloneCodeEditor;
  2. export interface IStandaloneEditorConstructionOptions extends IEditorConstructionOptions, IGlobalEditorOptions {
  3. model?: ITextModel | null;
  4. value?: string;
  5. language?: string;
  6. theme?: string;
  7. autoDetectHighContrast?: boolean;
  8. accessibilityHelpUrl?: string;
  9. ariaContainerElement?: HTMLElement;
  10. acceptSuggestionOnCommitCharacter: true, // 接受关于提交字符的建议
  11. acceptSuggestionOnEnter: 'on', // 接受输入建议 "on" | "off" | "smart"
  12. accessibilityPageSize: 10, // 辅助功能页面大小 Number 说明:控制编辑器中可由屏幕阅读器读出的行数。警告:这对大于默认值的数字具有性能含义。
  13. accessibilitySupport: 'on', // 辅助功能支持 控制编辑器是否应在为屏幕阅读器优化的模式下运行。
  14. autoClosingBrackets: 'always', // 是否自动添加结束括号(包括中括号) "always" | "languageDefined" | "beforeWhitespace" | "never"
  15. autoClosingDelete: 'always', // 是否自动删除结束括号(包括中括号) "always" | "never" | "auto"
  16. autoClosingOvertype: 'always', // 是否关闭改写 即使用insert模式时是覆盖后面的文字还是不覆盖后面的文字 "always" | "never" | "auto"
  17. autoClosingQuotes: 'always', // 是否自动添加结束的单引号 双引号 "always" | "languageDefined" | "beforeWhitespace" | "never"
  18. autoIndent: 'None', // 控制编辑器在用户键入、粘贴、移动或缩进行时是否应自动调整缩进
  19. automaticLayout: true, // 自动布局
  20. codeLens: false, // 是否显示codeLens 通过 CodeLens,你可以在专注于工作的同时了解代码所发生的情况 – 而无需离开编辑器。 可以查找代码引用、代码更改、关联的 Bug、工作项、代码评审和单元测试。
  21. codeLensFontFamily: '', // codeLens的字体样式
  22. codeLensFontSize: 14, // codeLens的字体大小
  23. colorDecorators: false, // 呈现内联色彩装饰器和颜色选择器
  24. comments: {
  25. ignoreEmptyLines: true, // 插入行注释时忽略空行。默认为真。
  26. insertSpace: true // 在行注释标记之后和块注释标记内插入一个空格。默认为真。
  27. }, // 注释配置
  28. contextmenu?: true, // 启用右键菜单
  29. columnSelection: false, // 启用列编辑 按下shift键位然后按↑↓键位可以实现列选择 然后实现列编辑
  30. autoSurround: 'never', // 是否应自动环绕选择
  31. copyWithSyntaxHighlighting: true, // 是否应将语法突出显示复制到剪贴板中 即 当你复制到word中是否保持文字高亮颜色
  32. cursorBlinking: 'Solid', // 光标动画样式
  33. cursorSmoothCaretAnimation: true, // 是否启用光标平滑插入动画 当你在快速输入文字的时候 光标是直接平滑的移动还是直接"闪现"到当前文字所处位置
  34. cursorStyle: 'UnderlineThin', // "Block"|"BlockOutline"|"Line"|"LineThin"|"Underline"|"UnderlineThin" 光标样式
  35. cursorSurroundingLines: 0, // 光标环绕行数 当文字输入超过屏幕时 可以看见右侧滚动条中光标所处位置是在滚动条中间还是顶部还是底部 即光标环绕行数 环绕行数越大 光标在滚动条中位置越居中
  36. cursorSurroundingLinesStyle: 'all', // "default" | "all" 光标环绕样式
  37. cursorWidth: 2, // <=25 光标宽度
  38. minimap: {
  39. enabled: false // 是否启用预览图
  40. }, // 预览图设置
  41. folding: true, // 是否启用代码折叠
  42. links: true, // 是否点击链接
  43. overviewRulerBorder: false, // 是否应围绕概览标尺绘制边框
  44. renderLineHighlight: 'gutter', // 当前行突出显示方式
  45. roundedSelection: false, // 选区是否有圆角
  46. scrollBeyondLastLine: false, // 设置编辑器是否可以滚动到最后一行之后
  47. readOnly: false, // 是否为只读模式
  48. theme: 'vs'// vs, hc-black, or vs-dark
  49. }

monaco.editor.createModel

Model是一个保存编辑状态的对象,里面含有语言信息,当前的编辑文本信息,标注信息等。所以我们可以缓存一下Model对象,在需要的时候直接调用setModel即可随时切换到之前的状态。或者也可以在初始化实例的时候设置一个Model。

  1. /**
  2. * Create a new editor model.
  3. * You can specify the language that should be set for this model or let the language be inferred from the `uri`.
  4. */
  5. export function createModel(value: string, language?: string, uri?: Uri): ITextModel;
  1. const model=monaco.editor.createModel("hahahaha","javascript");
  2. monacoInstance = monaco.editor.create(this.monacoDom.current, {
  3. model:model
  4. })

TextModel的ts定义

  1. export interface ITextModel {
  2. /**
  3. * Gets the resource associated with this editor model.
  4. */
  5. readonly uri: Uri;
  6. /**
  7. * A unique identifier associated with this model.
  8. */
  9. readonly id: string;
  10. /**
  11. * Get the resolved options for this model.
  12. */
  13. getOptions(): TextModelResolvedOptions;
  14. /**
  15. * Get the current version id of the model.
  16. * Anytime a change happens to the model (even undo/redo),
  17. * the version id is incremented.
  18. */
  19. getVersionId(): number;
  20. /**
  21. * Get the alternative version id of the model.
  22. * This alternative version id is not always incremented,
  23. * it will return the same values in the case of undo-redo.
  24. */
  25. getAlternativeVersionId(): number;
  26. /**
  27. * Replace the entire text buffer value contained in this model.
  28. */
  29. setValue(newValue: string): void;
  30. /**
  31. * Get the text stored in this model.
  32. * @param eol The end of line character preference. Defaults to `EndOfLinePreference.TextDefined`.
  33. * @param preserverBOM Preserve a BOM character if it was detected when the model was constructed.
  34. * @return The text.
  35. */
  36. getValue(eol?: EndOfLinePreference, preserveBOM?: boolean): string;
  37. /**
  38. * Get the length of the text stored in this model.
  39. */
  40. getValueLength(eol?: EndOfLinePreference, preserveBOM?: boolean): number;
  41. /**
  42. * Get the text in a certain range.
  43. * @param range The range describing what text to get.
  44. * @param eol The end of line character preference. This will only be used for multiline ranges. Defaults to `EndOfLinePreference.TextDefined`.
  45. * @return The text.
  46. */
  47. getValueInRange(range: IRange, eol?: EndOfLinePreference): string;
  48. /**
  49. * Get the length of text in a certain range.
  50. * @param range The range describing what text length to get.
  51. * @return The text length.
  52. */
  53. getValueLengthInRange(range: IRange): number;
  54. /**
  55. * Get the character count of text in a certain range.
  56. * @param range The range describing what text length to get.
  57. */
  58. getCharacterCountInRange(range: IRange): number;
  59. /**
  60. * Get the number of lines in the model.
  61. */
  62. getLineCount(): number;
  63. /**
  64. * Get the text for a certain line.
  65. */
  66. getLineContent(lineNumber: number): string;
  67. /**
  68. * Get the text length for a certain line.
  69. */
  70. getLineLength(lineNumber: number): number;
  71. /**
  72. * Get the text for all lines.
  73. */
  74. getLinesContent(): string[];
  75. /**
  76. * Get the end of line sequence predominantly used in the text buffer.
  77. * @return EOL char sequence (e.g.: '\n' or '\r\n').
  78. */
  79. getEOL(): string;
  80. /**
  81. * Get the end of line sequence predominantly used in the text buffer.
  82. */
  83. getEndOfLineSequence(): EndOfLineSequence;
  84. /**
  85. * Get the minimum legal column for line at `lineNumber`
  86. */
  87. getLineMinColumn(lineNumber: number): number;
  88. /**
  89. * Get the maximum legal column for line at `lineNumber`
  90. */
  91. getLineMaxColumn(lineNumber: number): number;
  92. /**
  93. * Returns the column before the first non whitespace character for line at `lineNumber`.
  94. * Returns 0 if line is empty or contains only whitespace.
  95. */
  96. getLineFirstNonWhitespaceColumn(lineNumber: number): number;
  97. /**
  98. * Returns the column after the last non whitespace character for line at `lineNumber`.
  99. * Returns 0 if line is empty or contains only whitespace.
  100. */
  101. getLineLastNonWhitespaceColumn(lineNumber: number): number;
  102. /**
  103. * Create a valid position,
  104. */
  105. validatePosition(position: IPosition): Position;
  106. /**
  107. * Advances the given position by the given offset (negative offsets are also accepted)
  108. * and returns it as a new valid position.
  109. *
  110. * If the offset and position are such that their combination goes beyond the beginning or
  111. * end of the model, throws an exception.
  112. *
  113. * If the offset is such that the new position would be in the middle of a multi-byte
  114. * line terminator, throws an exception.
  115. */
  116. modifyPosition(position: IPosition, offset: number): Position;
  117. /**
  118. * Create a valid range.
  119. */
  120. validateRange(range: IRange): Range;
  121. /**
  122. * Converts the position to a zero-based offset.
  123. *
  124. * The position will be [adjusted](#TextDocument.validatePosition).
  125. *
  126. * @param position A position.
  127. * @return A valid zero-based offset.
  128. */
  129. getOffsetAt(position: IPosition): number;
  130. /**
  131. * Converts a zero-based offset to a position.
  132. *
  133. * @param offset A zero-based offset.
  134. * @return A valid [position](#Position).
  135. */
  136. getPositionAt(offset: number): Position;
  137. /**
  138. * Get a range covering the entire model
  139. */
  140. getFullModelRange(): Range;
  141. /**
  142. * Returns if the model was disposed or not.
  143. */
  144. isDisposed(): boolean;
  145. /**
  146. * Search the model.
  147. * @param searchString The string used to search. If it is a regular expression, set `isRegex` to true.
  148. * @param searchOnlyEditableRange Limit the searching to only search inside the editable range of the model.
  149. * @param isRegex Used to indicate that `searchString` is a regular expression.
  150. * @param matchCase Force the matching to match lower/upper case exactly.
  151. * @param wordSeparators Force the matching to match entire words only. Pass null otherwise.
  152. * @param captureMatches The result will contain the captured groups.
  153. * @param limitResultCount Limit the number of results
  154. * @return The ranges where the matches are. It is empty if not matches have been found.
  155. */
  156. findMatches(
  157. searchString: string,
  158. searchOnlyEditableRange: boolean,
  159. isRegex: boolean,
  160. matchCase: boolean,
  161. wordSeparators: string | null,
  162. captureMatches: boolean,
  163. limitResultCount?: number
  164. ): FindMatch[];
  165. /**
  166. * Search the model.
  167. * @param searchString The string used to search. If it is a regular expression, set `isRegex` to true.
  168. * @param searchScope Limit the searching to only search inside these ranges.
  169. * @param isRegex Used to indicate that `searchString` is a regular expression.
  170. * @param matchCase Force the matching to match lower/upper case exactly.
  171. * @param wordSeparators Force the matching to match entire words only. Pass null otherwise.
  172. * @param captureMatches The result will contain the captured groups.
  173. * @param limitResultCount Limit the number of results
  174. * @return The ranges where the matches are. It is empty if no matches have been found.
  175. */
  176. findMatches(
  177. searchString: string,
  178. searchScope: IRange | IRange[],
  179. isRegex: boolean,
  180. matchCase: boolean,
  181. wordSeparators: string | null,
  182. captureMatches: boolean,
  183. limitResultCount?: number
  184. ): FindMatch[];
  185. /**
  186. * Search the model for the next match. Loops to the beginning of the model if needed.
  187. * @param searchString The string used to search. If it is a regular expression, set `isRegex` to true.
  188. * @param searchStart Start the searching at the specified position.
  189. * @param isRegex Used to indicate that `searchString` is a regular expression.
  190. * @param matchCase Force the matching to match lower/upper case exactly.
  191. * @param wordSeparators Force the matching to match entire words only. Pass null otherwise.
  192. * @param captureMatches The result will contain the captured groups.
  193. * @return The range where the next match is. It is null if no next match has been found.
  194. */
  195. findNextMatch(
  196. searchString: string,
  197. searchStart: IPosition,
  198. isRegex: boolean,
  199. matchCase: boolean,
  200. wordSeparators: string | null,
  201. captureMatches: boolean
  202. ): FindMatch | null;
  203. /**
  204. * Search the model for the previous match. Loops to the end of the model if needed.
  205. * @param searchString The string used to search. If it is a regular expression, set `isRegex` to true.
  206. * @param searchStart Start the searching at the specified position.
  207. * @param isRegex Used to indicate that `searchString` is a regular expression.
  208. * @param matchCase Force the matching to match lower/upper case exactly.
  209. * @param wordSeparators Force the matching to match entire words only. Pass null otherwise.
  210. * @param captureMatches The result will contain the captured groups.
  211. * @return The range where the previous match is. It is null if no previous match has been found.
  212. */
  213. findPreviousMatch(
  214. searchString: string,
  215. searchStart: IPosition,
  216. isRegex: boolean,
  217. matchCase: boolean,
  218. wordSeparators: string | null,
  219. captureMatches: boolean
  220. ): FindMatch | null;
  221. /**
  222. * Get the language associated with this model.
  223. */
  224. getModeId(): string;
  225. /**
  226. * Get the word under or besides `position`.
  227. * @param position The position to look for a word.
  228. * @return The word under or besides `position`. Might be null.
  229. */
  230. getWordAtPosition(position: IPosition): IWordAtPosition | null;
  231. /**
  232. * Get the word under or besides `position` trimmed to `position`.column
  233. * @param position The position to look for a word.
  234. * @return The word under or besides `position`. Will never be null.
  235. */
  236. getWordUntilPosition(position: IPosition): IWordAtPosition;
  237. /**
  238. * Perform a minimum amount of operations, in order to transform the decorations
  239. * identified by `oldDecorations` to the decorations described by `newDecorations`
  240. * and returns the new identifiers associated with the resulting decorations.
  241. *
  242. * @param oldDecorations Array containing previous decorations identifiers.
  243. * @param newDecorations Array describing what decorations should result after the call.
  244. * @param ownerId Identifies the editor id in which these decorations should appear. If no `ownerId` is provided, the decorations will appear in all editors that attach this model.
  245. * @return An array containing the new decorations identifiers.
  246. */
  247. deltaDecorations(
  248. oldDecorations: string[],
  249. newDecorations: IModelDeltaDecoration[],
  250. ownerId?: number
  251. ): string[];
  252. /**
  253. * Get the options associated with a decoration.
  254. * @param id The decoration id.
  255. * @return The decoration options or null if the decoration was not found.
  256. */
  257. getDecorationOptions(id: string): IModelDecorationOptions | null;
  258. /**
  259. * Get the range associated with a decoration.
  260. * @param id The decoration id.
  261. * @return The decoration range or null if the decoration was not found.
  262. */
  263. getDecorationRange(id: string): Range | null;
  264. /**
  265. * Gets all the decorations for the line `lineNumber` as an array.
  266. * @param lineNumber The line number
  267. * @param ownerId If set, it will ignore decorations belonging to other owners.
  268. * @param filterOutValidation If set, it will ignore decorations specific to validation (i.e. warnings, errors).
  269. * @return An array with the decorations
  270. */
  271. getLineDecorations(
  272. lineNumber: number,
  273. ownerId?: number,
  274. filterOutValidation?: boolean
  275. ): IModelDecoration[];
  276. /**
  277. * Gets all the decorations for the lines between `startLineNumber` and `endLineNumber` as an array.
  278. * @param startLineNumber The start line number
  279. * @param endLineNumber The end line number
  280. * @param ownerId If set, it will ignore decorations belonging to other owners.
  281. * @param filterOutValidation If set, it will ignore decorations specific to validation (i.e. warnings, errors).
  282. * @return An array with the decorations
  283. */
  284. getLinesDecorations(
  285. startLineNumber: number,
  286. endLineNumber: number,
  287. ownerId?: number,
  288. filterOutValidation?: boolean
  289. ): IModelDecoration[];
  290. /**
  291. * Gets all the decorations in a range as an array. Only `startLineNumber` and `endLineNumber` from `range` are used for filtering.
  292. * So for now it returns all the decorations on the same line as `range`.
  293. * @param range The range to search in
  294. * @param ownerId If set, it will ignore decorations belonging to other owners.
  295. * @param filterOutValidation If set, it will ignore decorations specific to validation (i.e. warnings, errors).
  296. * @return An array with the decorations
  297. */
  298. getDecorationsInRange(
  299. range: IRange,
  300. ownerId?: number,
  301. filterOutValidation?: boolean
  302. ): IModelDecoration[];
  303. /**
  304. * Gets all the decorations as an array.
  305. * @param ownerId If set, it will ignore decorations belonging to other owners.
  306. * @param filterOutValidation If set, it will ignore decorations specific to validation (i.e. warnings, errors).
  307. */
  308. getAllDecorations(
  309. ownerId?: number,
  310. filterOutValidation?: boolean
  311. ): IModelDecoration[];
  312. /**
  313. * Gets all the decorations that should be rendered in the overview ruler as an array.
  314. * @param ownerId If set, it will ignore decorations belonging to other owners.
  315. * @param filterOutValidation If set, it will ignore decorations specific to validation (i.e. warnings, errors).
  316. */
  317. getOverviewRulerDecorations(
  318. ownerId?: number,
  319. filterOutValidation?: boolean
  320. ): IModelDecoration[];
  321. /**
  322. * Gets all the decorations that contain injected text.
  323. * @param ownerId If set, it will ignore decorations belonging to other owners.
  324. */
  325. getInjectedTextDecorations(ownerId?: number): IModelDecoration[];
  326. /**
  327. * Normalize a string containing whitespace according to indentation rules (converts to spaces or to tabs).
  328. */
  329. normalizeIndentation(str: string): string;
  330. /**
  331. * Change the options of this model.
  332. */
  333. updateOptions(newOpts: ITextModelUpdateOptions): void;
  334. /**
  335. * Detect the indentation options for this model from its content.
  336. */
  337. detectIndentation(defaultInsertSpaces: boolean, defaultTabSize: number): void;
  338. /**
  339. * Close the current undo-redo element.
  340. * This offers a way to create an undo/redo stop point.
  341. */
  342. pushStackElement(): void;
  343. /**
  344. * Open the current undo-redo element.
  345. * This offers a way to remove the current undo/redo stop point.
  346. */
  347. popStackElement(): void;
  348. /**
  349. * Push edit operations, basically editing the model. This is the preferred way
  350. * of editing the model. The edit operations will land on the undo stack.
  351. * @param beforeCursorState The cursor state before the edit operations. This cursor state will be returned when `undo` or `redo` are invoked.
  352. * @param editOperations The edit operations.
  353. * @param cursorStateComputer A callback that can compute the resulting cursors state after the edit operations have been executed.
  354. * @return The cursor state returned by the `cursorStateComputer`.
  355. */
  356. pushEditOperations(
  357. beforeCursorState: Selection[] | null,
  358. editOperations: IIdentifiedSingleEditOperation[],
  359. cursorStateComputer: ICursorStateComputer
  360. ): Selection[] | null;
  361. /**
  362. * Change the end of line sequence. This is the preferred way of
  363. * changing the eol sequence. This will land on the undo stack.
  364. */
  365. pushEOL(eol: EndOfLineSequence): void;
  366. /**
  367. * Edit the model without adding the edits to the undo stack.
  368. * This can have dire consequences on the undo stack! See @pushEditOperations for the preferred way.
  369. * @param operations The edit operations.
  370. * @return If desired, the inverse edit operations, that, when applied, will bring the model back to the previous state.
  371. */
  372. applyEdits(operations: IIdentifiedSingleEditOperation[]): void;
  373. applyEdits(
  374. operations: IIdentifiedSingleEditOperation[],
  375. computeUndoEdits: false
  376. ): void;
  377. applyEdits(
  378. operations: IIdentifiedSingleEditOperation[],
  379. computeUndoEdits: true
  380. ): IValidEditOperation[];
  381. /**
  382. * Change the end of line sequence without recording in the undo stack.
  383. * This can have dire consequences on the undo stack! See @pushEOL for the preferred way.
  384. */
  385. setEOL(eol: EndOfLineSequence): void;
  386. /**
  387. * An event emitted when the contents of the model have changed.
  388. * @event
  389. */
  390. onDidChangeContent(
  391. listener: (e: IModelContentChangedEvent) => void
  392. ): IDisposable;
  393. /**
  394. * An event emitted when decorations of the model have changed.
  395. * @event
  396. */
  397. onDidChangeDecorations(
  398. listener: (e: IModelDecorationsChangedEvent) => void
  399. ): IDisposable;
  400. /**
  401. * An event emitted when the model options have changed.
  402. * @event
  403. */
  404. onDidChangeOptions(
  405. listener: (e: IModelOptionsChangedEvent) => void
  406. ): IDisposable;
  407. /**
  408. * An event emitted when the language associated with the model has changed.
  409. * @event
  410. */
  411. onDidChangeLanguage(
  412. listener: (e: IModelLanguageChangedEvent) => void
  413. ): IDisposable;
  414. /**
  415. * An event emitted when the language configuration associated with the model has changed.
  416. * @event
  417. */
  418. onDidChangeLanguageConfiguration(
  419. listener: (e: IModelLanguageConfigurationChangedEvent) => void
  420. ): IDisposable;
  421. /**
  422. * An event emitted when the model has been attached to the first editor or detached from the last editor.
  423. * @event
  424. */
  425. onDidChangeAttached(listener: () => void): IDisposable;
  426. /**
  427. * An event emitted right before disposing the model.
  428. * @event
  429. */
  430. onWillDispose(listener: () => void): IDisposable;
  431. /**
  432. * Destroy this model. This will unbind the model from the mode
  433. * and make all necessary clean-up to release this object to the GC.
  434. */
  435. dispose(): void;
  436. /**
  437. * Returns if this model is attached to an editor or not.
  438. */
  439. isAttachedToEditor(): boolean;
  440. }

image.png

可以直接在model上绑定事件

  1. model.onDidChangeContent((event)=>{
  2. ...
  3. })
  4. // 相当于
  5. editor.onDidChangeModelContent(() => {
  6. const value = editor.getValue()
  7. })

Model最后也需要我们销毁,这里分两种情况,假如是通过createModel创建的Model,那么我们需要手动销毁,但是如果是monaco默认创建的,则不需要,在调用实例的销毁方法时,会顺带销毁默认创建的Model。

  1. model.dispose();

在简单的场景下,Model的存在可能使得我们使用起来比较繁琐,但是,在复杂场景下,model可以极大的简化代码复杂性。

设想一下我们有5个tab,每个tab都是一个编辑器,每个编辑器都有各自的语言,内容和标注信息,如果没有Model,我们需要保存每个tab的语言,内容等信息,在切换到对应tab时再将这些信息初始化到编辑器上,但是利用Model,我们不需要额外去保存每个tab的编辑信息,只需要保存每个tab的Model,然后将Model传给编辑器进行初始化即可。

setModelLanguage

monaco.editor.setModelMarkers()

在编辑器中用波浪线标出错误提示。

  1. monaco.editor.setModelMarkers(editor.getModel(), 'owner', [
  2. {
  3. startLineNumber,
  4. startColumn,
  5. endLineNumber,
  6. endColumn,
  7. message, // 提示文案
  8. severity: monaco.MarkerSeverity.Error, // marker 底部波浪线的信息等级 Hint,Info,Warning,Error
  9. },
  10. ])

export namespace languages

monaco.languages.registerCompletionItemProvider

配置代码自动补全

  1. monaco.languages.registerCompletionItemProvider('javascript', {
  2. provideCompletionItems:function(model, position){
  3. .......
  4. return {
  5. suggestions: [{
  6. label: '$:', // 显示的提示内容
  7. kind: monaco.languages.CompletionItemKind['Function'], // 用来显示提示内容后的不同的图标
  8. insertText: '$:', // 选择后粘贴到编辑器中的文字
  9. detail: '', // 提示内容后的说明
  10. range: range
  11. }]
  12. }
  13. }
  14. })
  1. monacoCompletionProvide = monaco.languages.registerCompletionItemProvider(
  2. 'lua',
  3. {
  4. provideCompletionItems: function (model, position): any {
  5. // 获取当前行数
  6. const line = position.lineNumber
  7. // 获取当前列数
  8. const column = position.column
  9. // 获取当前输入行的内容
  10. const content = model.getLineContent(line)
  11. console.log('🚀 ~ 当前行 content', content)
  12. // 获取起始位置到当前位置的文本内容
  13. let textUntilPosition = model.getValueInRange({
  14. startLineNumber: 1, // position.lineNumber
  15. startColumn: 1,
  16. endLineNumber: position.lineNumber,
  17. endColumn: position.column
  18. })
  19. console.log('🚀 ~ line 94 textUntilPosition', textUntilPosition)
  20. // 通过下标来获取当前光标后一个内容,即为刚输入的内容
  21. const sym = content[column - 2]
  22. // console.log('🚀 ~ file: Index.vue ~ line 84 ~ init ~ sym', sym)
  23. // 获取当前位置的 单词
  24. let word = model.getWordUntilPosition(position)
  25. // console.log('🚀 ~ file: Index.vue ~ line 88 ~ init ~ word', word)
  26. // 插入内容覆盖当前位置的单词
  27. let range = {
  28. startLineNumber: position.lineNumber,
  29. endLineNumber: position.lineNumber,
  30. startColumn: word.startColumn,
  31. endColumn: word.endColumn
  32. }
  33. // console.log('🚀 ~ file: Index.vue ~ line 112 ~ init ~ range', range)
  34. let suggestions = createCompleters(range, sym)
  35. // console.log('🚀 ~ suggestions', suggestions)
  36. return {
  37. suggestions: suggestions
  38. }
  39. },
  40. triggerCharacters: ['.']
  41. }
  42. )

monaco 实例方法

export interface IEditor 编辑器实例方法

image.png

editor.dispose() 销毁实例

editor.getValue()

获取编辑器中的所有文本,并生成一个字符串返回,会保留所有信息(换行、缩进、注释等等)。

editor.setValue()

editor.updateOptions()

editor.getSelection()

获取编辑器中被选中文案的 range ,返回一个对象,如下:

  1. {
  2. startLineNumber: 0,
  3. startColumnNumber: 0,
  4. endLineNumber: 0,
  5. endColumnNumber: 0,
  6. }

editor.getModel()

获取编辑器当前的 textmodel,一般不会直接使用,通过 textmodel 可以对文本各种操作。

editor.executeEdits()

在指定位置插入代码,跟 editor.setValue() 不同的地方是,可以用 “⌘ + Z” 撤销输入。

  1. /**
  2. * Execute edits on the editor.
  3. * The edits will land on the undo-redo stack, but no "undo stop" will be pushed.
  4. * @param source The source of the call.
  5. * @param edits The edits to execute.
  6. * @param endCursorState Cursor state after the edits were applied.
  7. */
  8. executeEdits(source: string | null | undefined, edits: IIdentifiedSingleEditOperation[], endCursorState?: ICursorStateComputer | Selection[]): boolean;
  9. /**
  10. * A single edit operation, that has an identifier.
  11. */
  12. export interface IIdentifiedSingleEditOperation {
  13. /**
  14. * The range to replace. This can be empty to emulate a simple insert.
  15. */
  16. range: IRange;
  17. /**
  18. * The text to replace with. This can be null to emulate a simple delete.
  19. */
  20. text: string | null;
  21. /**
  22. * This indicates that this operation has "insert" semantics.
  23. * i.e. forceMoveMarkers = true => if `range` is collapsed, all markers at the position will be moved.
  24. */
  25. forceMoveMarkers?: boolean;
  26. }
  1. editor.executeEdits('insert-code', [
  2. {
  3. range: {
  4. startLineNumber: 1,
  5. startColumn: 1,
  6. endLineNumber: 1,
  7. endColumn: 1,
  8. },
  9. text: 'text',
  10. },
  11. ])

editor.addAction()

在右键菜单里增加一栏自定义的操作。

  1. editor.addAction({
  2. id: '', // 菜单项 id
  3. label: '', // 菜单项名称
  4. keybindings: [this.monaco.KeyMod.CtrlCmd | this.monaco.KeyCode.KEY_J], // 绑定快捷键
  5. contextMenuGroupId: '9_cutcopypaste', // 所属菜单的分组
  6. run: () => {}, // 点击后执行的操作
  7. })

editor.getAction(‘actions.xxx’).run()

手动调用monaco方法。

  1. //实现查找效果
  2. const model = editor.getModel();
  3. const range = model.findMatches('匹配的字符串或者正则表达式')[0].range;
  4. editor.setSelection(range);
  5. editor.getAction('actions.find').run();
  6. //实现拷贝效果
  7. editor.getAction('editor.action.clipboardCopyAction').run();
  8. //实现复制效果
  9. var selection = editor.getSelection();
  10. var content = localStorage.getItem('your-content');
  11. editor.executeEdits("", [
  12. {
  13. range: new monaco.Range(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn),
  14. text: content
  15. }
  16. ])