How about: "Adding code to a specific location in Monaco editor using programming methods"

I have encountered a two-part issue. The first part involves retrieving the editor content using getValue(), which provides the raw text from the Monaco editor. If I need to append new code after a specific code block, how can this be achieved?

Although I can obtain the current cursor location with currentPosition(), I am unsure of how to pinpoint the location for a particular code block and insert new code thereafter. Here is an example of extracting code from the editor:

<body>
    <div>Big brown fox jumps at lazy dog.</div>

    <!-- I WANT TO ADD CODE HERE PROGRAMMATICALLY -->

    <p>we have all the details for singleton methods.</p>
    <div>new data comes here.</div>
</body>

How can I insert code between two code blocks? One potential solution that comes to mind is if I could retrieve position/line locations along with the code using getValue, and subsequently utilize these pointers to add new blocks within the code. However, I have yet to find a viable solution.

Answer №1

Below are two custom functions that can be used to insert HTML content into the editor:

  • computeInsertRange – Determines the range in the editor to replace a specified placeholder
  • insertContent – Inserts content at a specific line within the editor based on a pattern

In the following example, after 1 second, the HTML content inside the editor will be updated.

require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs' }});
window.MonacoEnvironment = { getWorkerUrl: () => proxy };

let proxy = URL.createObjectURL(new Blob([`
    self.MonacoEnvironment = {
        baseUrl: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min'
    };
    importScripts('https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs/base/worker/workerMain.min.js');
`], { type: 'text/javascript' }));

const
  container = document.querySelector('#container'),
  htmlContent = `
<body>
  <div>Big brown fox jumps at lazy dog.</div>

  <!-- I WANT TO ADD CODE HERE PROGRAMMATICALLY -->

  <p>we have all the details for singleton methods.</p>
  <div>new data comes here.</div>
</body>
`.trim(),
  additionalHtmlContent = `
  <div>
    <strong>Hello World!</strong>
  </div>
`.trim();

const computeInsertRange = (editor, pattern) => {
  const lines = editor.getValue().split('\n');
  for (let index = 0; index < lines.length; index++) {
    if (lines[index].match(pattern)) {
      const indent = /^\s*/.exec(lines[index])?.[0].length ?? 0;
      return new monaco.Range(index + 1, indent + 1, index + 1, lines[index].length + 1);
    }
  }
  return null;
};

// Adapted from: https://stackoverflow.com/a/48764277/1762224
const insertContent = (editor, pattern, content) => {
  editor.executeEdits('my-source', [{
    identifier: { major: 1, minor: 1 },
    range: computeInsertRange(editor, pattern),
    text: content,
    forceMoveMarkers: true
  }]);
};

require(['vs/editor/editor.main'], function () {
  const editor = monaco.editor.create(container, {
    value: htmlContent,
    language: 'html',
    theme: 'vs-dark'
    });

setTimeout(() => {
insertContent(editor, /<!-- .+ -->/, additionalHtmlContent);
}, 1000);
});
html, body, #container {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f9fbfaf5f7fbb9f1f0fde0fbe6d4a4baacbaa7">[email protected]</a>/min/vs/loader.js"></script>
<div id="container"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Applying hover effect to material-ui IconButton component

As stated in the React Material-UI documentation, I have access to a prop called hoveredStyle: http://www.material-ui.com/#/components/icon-button I intend to utilize the IconButton for two specific purposes: Make use of its tooltip prop for improved ac ...

What is the best way to obtain a list of all the modules that are currently accessible in AngularJS

When declaring an Angular module, I specify its dependencies as follows: const myModule = angular.module("MyModuleName", ["Dep1", "Dep2", "Dep3"]); Each dependency comes with its own set of dependencies, directives, controllers, etc. Is there a way to qu ...

What is the reason for using a callback as a condition in the ternary operator for the Material UI Dialog component?

I am in the process of reconstructing the Material UI Customized Dialog component based on the instructions provided in this particular section of the documentation. However, I am unable to grasp the purpose behind using a callback function onClose conditi ...

Component fails to re-render after token refresh on subsequent requests

Here is my axios-hoook.js file, utilizing the axios-hooks package. import useAxios from 'axios-hooks'; import axios from 'axios'; import LocalStorageService from './services/local-storage.service'; import refreshToken from &ap ...

What is the correct process for authenticating requests from SSR to the Feathers JS API?

There are some examples available on how to access FeathersJS API from SSR, but the important aspect of authorizing such requests is missing. Is it feasible to create a feathers-client app for each request? Wouldn't that put too much load on the syste ...

Is there a way to upload a file using express/multer without triggering a redirect?

Note: Despite coming across this post, I couldn't find it helpful. Other related posts were focused on angular/react, which are not relevant to my current project. I have implemented a file upload feature that should provide a response indicating whe ...

Registration window restriction

I have implemented a sign-up modal on a Bootstrap website and am looking to restrict the number of times visitors see it to twice per session instead of on every page, as well as hiding it once a visitor has subscribed. The modal will appear after 5 second ...

Issue: [$injector:unpr] encountered while configuring routing

Looking to implement a basic authentication system for my angularjs application. The problem arises when I try to debug the app.js on line 20, and an error is displayed: Error: [$injector:unpr] http://errors.angularjs.org/1.2.16/$injector/unpr?p0=configPr ...

Error: The ngModelProvider provider is not recognized

Attempting to incorporate ngModel into an Angular directive results in the following error: Error: [$injector:unpr] Unknown provider: ngModelProvider <- ngModel http://errors.angularjs.org/1.2.18/$injector/unpr?p0=ngModelProvider%20%3C-%20ngModel a ...

Review all the information in the Excel spreadsheet

I aim to extract data from the initial row, execute an operation on it, record the outcome, then proceed to the subsequent rows until all the data in the Excel file has been processed. Here are some queries I have: Why are the iterators not functioning ...

Displaying content in Bootstrap 5 modal with jQuery may cause a delay in the appearance of a centered spinner before the content loads

In my Bootstrap 5 modal, I have implemented specific functionality in jQuery where a centered spinner is supposed to show up in the modal before loading the content. You can see a live example of this here. The issue I am facing is that the spinner takes ...

Issue with inconsistent error handling in Mui DateTimePicker and react-hook-form

I am currently facing an issue with a DateTimePicker component that I am trying to integrate into a form controlled by react-hook-form. The validation is straightforward - I am using the disablePast prop on the DateTimePicker to ensure that the selected da ...

The integration of query, URL, and body parameters is not working as expected in Seneca when using Seneca

I'm facing some difficulties with Seneca and seneca-web as a beginner. This is the current state of my code: "use strict"; var express = require('express'); var Web = require("seneca-web"); var bodyParser = require('body-parser' ...

Is there a way to confirm the presence of multiple attributes in a JSON format using JavaScript?

Currently, I am developing a module that processes multiple complex JSON files and requires a method to notify users if certain elements are missing. Although the current approach works, I can't shake the feeling that there must be a more efficient a ...

Send a Dictionary<String, List<String>> object to JavaScript

I am looking to send a Dictionary> from the server to the client using JavaScript. Although I came across this post, I am still unsure about the steps to follow. To clarify my objective, the dictionary comprises the 'name' key of all workshee ...

Trouble with Bootstrap/CSS division not aligning left or right

I'm struggling to make my divs float left for the first one and then float right for the second one, and so on. I've attempted using float and also tried Bootstrap 5 float options, but neither seems to work. I've searched online for solution ...

Customizing error styles in a table using Jquery validation

My form is using JQuery .validation(). Here is the structure of my form: <form....> <table cellspacing="0" cellpadding="0"> <tr> <td>Name: </td> <td><input type='text' name='Name'/></td> ...

Update the table that includes a php script

I have a piece of PHP code embedded within a table tag that displays text from a database. I am looking for a way to automatically refresh this table every minute with updated content from the database, without refreshing the entire page. While I have co ...

Testing React Component State Updates

I've been dedicated to achieving close to 100% unit test coverage with my React application, focusing particularly on the useAsync hook. I came across a code snippet from react hooks: import { useState, useEffect, useCallback } from 'react'; ...

Having trouble with an Ajax request in jQuery

Need some help with the code below - I can't seem to get the success or error event to fire. Even though the server returns a 200 OK response with the required data. Any assistance would be greatly appreciated! $('body').on('click&apos ...