Use an ONLYOFFICE macro to convert selected text into a LaTeX equation

Originally published at: Use an ONLYOFFICE macro to convert selected text into a LaTeX equation | ONLYOFFICE Blog


LaTeX is a widely-used format for creating high-quality, structured documents, especially in academic and scientific fields. Its popularity stems from its ability to handle complex formatting like mathematical equations with precision. In this article, we’ll show how to create an ONLYOFFICE macro that converts selected text into LaTeX format, streamlining your document workflow.

Use an ONLYOFFICE macro to convert selected text into a LaTeX equation

About the AddMathEquation method

ONLYOFFICE Docs 8.2 introduces a wide range of new features, including the AddMathEquation method, which enables the insertion of LaTeX equations into documents:

 Api.GetDocument().AddMathEquation( text, "latex")

Building the macro

First, we retrieve the current document:

const oDocument = Api.GetDocument();

Then we capture the range of the selected text by using the GetRangeBySelect method:

const oRange = oDocument.GetRangeBySelect();

We extract the actual text content from the selected range:

const text = oRange.GetText();

Finally, we implement the AddMathEquation method to insert a LaTeX equation directly into the document:

Api.GetDocument().AddMathEquation( text, "latex")

The entire macro code is the following:

(function()
{
const oDocument = Api.GetDocument();
const oRange = oDocument.GetRangeBySelect();
const text = oRange.GetText();
 Api.GetDocument().AddMathEquation( text, "latex")
})();

Now, let’s run our macro and see how it works!

We hope this macro proves useful in helping you seamlessly convert your equations into LaTeX format within the ONLYOFFICE editors. At ONLYOFFICE, we are committed to providing the best user experience by continuously adding features that cater to your specific needs. We encourage you to explore our extensive API library and create your own macros to enhance your workflow.

If you have any ideas, suggestions, or macros you’d like to share, please don’t hesitate to contact us. We’re always open to discussion and collaboration.

A fully functional plugin is also in development, which will allow users to convert handwritten formulas into LaTeX format and insert them directly into documents. Stay tuned for more updates! And best of luck in your exploratory endeavors!

Useful links

ONLYOFFICE on GitHub

Get free office desktop suite

Text document API

Macros in ONLYOFFICE Docs [FREE COURSE]