CodeMirror 6 auto select and indent

The HTML source code is received from the database without any indentation. Is there any possible way of selecting all of the code and applying the auto indent, so the HTML code is displayed accordingly?

LE: So far I’ve managed to only select the text, but I can’t figure out how to use the IndentContext or something that can help on indenting

            state: EditorState.create({
                doc: getContent(editor),
                extensions: [
                    basicSetup,
                    html(),
                    keymap.of([indentWithTab]),
                    defaultHighlightStyle,
                    drawSelection(),
                    EditorView.lineWrapping,
                ]
            })
        })

        let update = view.state.update({
            selection: {
                anchor: 0,
                head: view.state.doc.length
            }
        })
        view.update([update])

Well, I’ve managed to solve my issue, after breaking my head against the “documentation”, this happend:

import {EditorState, EditorView, basicSetup} from '@codemirror/basic-setup'
import {keymap, drawSelection} from '@codemirror/view'
import {defaultHighlightStyle} from '@codemirror/highlight'
import {html} from '@codemirror/lang-html'
import {indentWithTab, indentSelection} from '@codemirror/commands'

let view = new EditorView({
    state: EditorState.create({
        doc: getContent(editor),
        extensions: [
            basicSetup,
            html(),
            keymap.of([indentWithTab]),
            defaultHighlightStyle,
            drawSelection(),
            EditorView.lineWrapping,
        ],
    })
})

view.dispatch({
    selection: {
        anchor: 0,
        head: view.state.doc.length
    }
})

indentSelection({
    state: view.state,
    dispatch: transaction => (
        view.update([transaction])
    )
})

The issue with what I have so far, is that for some reason there is a line limit or something to witch the code is indented. My original code is has no identation and it seems that after line 32 the code has wrong indentation… If I try to apply the identation command shortcut (CTRL + ALT + \), the code will indeed be indented correct.

1 Like

As to answer to my own existential questions, I found out that indenting isn’t finished due to the fact that my code is not executed when the whole document was loaded.

In order to test this out, I used a timeout (not a solution though):

setTimeout(() => {
    indentSelection({
        state: view.state,
        dispatch: transaction => {
            view.update([transaction])
        }
    })
}, 2000);

Anyway, hope that this findings help someone else with similar issues. :slight_smile:

Hi, thank you for putting down your answer. I tried to follow it, I am able to select the text, but indentSelection doesn’t indent for json format.