Formatting the code

Hello,
I’m developping a javascript code editor in a web app with React.
I would like to format the code (indentations, brackets etc…) when I click on a specific button.
I Used the autoFormatRange function, but when i click on the button, it only format one line, and i have to press the button again to format another line of the selection. Very strange…
Could you help me to fix this please?

CodeMirror doesn’t come with a formatting feature. You can reindent, but that’s it.

I suggest using the Prettier API

Is there an example of prettier (or other formatters) integration?

While what you’re asking is more help on using Prettier than CodeMirror, I’ve done this in my own code editor (ICEcoder) and it prettifies code (JS, JSON, TS, CSS, SCSS, Less, HTML, XML, YAML, MD or PHP) on save, so thought I’d share some code.

Grab the Prettier JS files for the languages you want. You can grab from my zip if you wish:
http://icecoder.net/plugin-zips/prettier.zip

Basic usage could be something like:

let parser = "babel"; // for JS. Other values: json, typescript, css, scss, less, html (also for xml), yaml or php

prettierVersion = prettier.formatWithCursor(
    editor.getValue(),
    {
        parser: parser,
        plugins: prettierPlugins,
        tabWidth: 4
        useTabs: false,
        cursorOffset: editor.indexFromPos(editor.getCursor())
    }
);

editor.setValue(prettierVersion);

if (false === editor.somethingSelected()) {
    editor.setCursor(editor.posFromIndex(prettierVersion.cursorOffset));
}

The last section there moves the cursor for you (if something isn’t selected), to a similar place after prettifying.

Note that the above is a simple example and not very elegant as it replaces the entire doc contents, so not efficient at all. ie, if you have a 1000 line doc, prettify the contents and only 2 lines change, it’s still replacing the 1000 lines with new content. A more efficient approach would be to diff compare the changes between what it was and what it is after prettifying and using replaceRange for added, replaced or deleted sections.

If you wish to get things more efficient by using replaceRange, you may want to check out this section of my code:

Hope this helps.

1 Like

@mattpass this is perfect! Thanks you!

I was mostly looking for an example how to preserve cursor and selection. Your snippets are a perfect place to start. Thank you so much!!! <3

1 Like

do you mind if you explained this method. I mean, how can i use this to format my code