How to use line wrapping in CodeMirror 6

I am using CodeMirror 6, and in the CSS, I have styled the content element (.cm-content) with white-space: pre-wrap;, but it didn’t work. I tried inserting lineWrapping: true in here:

var editor = new EditorView({
    lineWrapping: true,
    state,
    parent: document.getElementById("editor")
});

But the line wrapping still didn’t work. Has anyone faced this issue, and if so, how do I fix it? What am I missing?

Your style is probably being overridden by the built-in styles. Try including EditorView.lineWrapping in your set of extensions.

2 Likes

I tried including it in my set of extensions, and it worked! Thank you so much!

How can line wrapping and font-size be changed dynamically (based on the user’s preferences)?

1 Like

I’m also wondering how to remove line wrapping. I have a Compartment set up to add the EditorView.lineWrapping extension, but when I remove that from the Compartment, the cm-lineWrapping class still remains.

There doesn’t seem to be a way to update the lineWrapping contentAttribute Facet to remove the class when it’s removed. Is this a bug or is this how contentAttribute is supposed to work?

Nevermind. It seems that updating a compartment from EditorView.lineWrapping to an empty array [] works as expected. I was replacing with null before, but that doesn’t have the same effect.

https://codemirror.net/try/?c=aW1wb3J0IHtiYXNpY1NldHVwLCBFZGl0b3JWaWV3IH0gZnJvbSAiY29kZW1pcnJvciIKaW1wb3J0IHsgQ29tcGFydG1lbnQgfSBmcm9tICdAY29kZW1pcnJvci9zdGF0ZScKaW1wb3J0IHtqYXZhc2NyaXB0fSBmcm9tICJAY29kZW1pcnJvci9sYW5nLWphdmFzY3JpcHQiCgpjb25zdCBjb21wYXJ0bWVudCA9IG5ldyBDb21wYXJ0bWVudCgpOwpjb25zdCB2aWV3ID0gbmV3IEVkaXRvclZpZXcoewogIGRvYzogYGNvbnNvbGUubG9nKCJ0aGlzIGlzIHJlYWxseSBsb25nIHRleHQgdGhhdCBzaG91bGQgd3JhcCBhcm91bmQgaWYgbGluZSB3cmFwcGluZyBpcyBvbiwgYnV0IGlmIGl0XCdzIG9mZiBpdFwnbGwgZXh0ZW5kIHRoZSB3aG9sZSBhcmVhIilcbmAsCiAgZXh0ZW5zaW9uczogW2Jhc2ljU2V0dXAsIGNvbXBhcnRtZW50Lm9mKFtdKSwgamF2YXNjcmlwdCgpXSwKICBwYXJlbnQ6IGRvY3VtZW50LmJvZHkKfSkKCmNvbnN0IGJ1dHRvbiA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2J1dHRvbicpOwpidXR0b24uaW5uZXJUZXh0ID0gIkxpbmUgV3JhcHBpbmc6IE9mZiI7CmRvY3VtZW50LmJvZHkuaW5zZXJ0QWRqYWNlbnRFbGVtZW50KCdhZnRlcmJlZ2luJywgYnV0dG9uKTsKCmxldCB3cmFwcGluZyA9IGZhbHNlOwpidXR0b24uYWRkRXZlbnRMaXN0ZW5lcignY2xpY2snLCAoKSA9PiB7CiAgd3JhcHBpbmcgPSAhd3JhcHBpbmc7CiAgYnV0dG9uLmlubmVyVGV4dCA9IGBMaW5lIFdyYXBwaW5nOiAke3dyYXBwaW5nID8gJ09uJyA6ICdPZmYnfWA7CiAgCiAgdmlldy5kaXNwYXRjaCh7CiAgICBlZmZlY3RzOiBbY29tcGFydG1lbnQucmVjb25maWd1cmUoCiAgICAgIHdyYXBwaW5nID8gRWRpdG9yVmlldy5saW5lV3JhcHBpbmcgOiBbXQogICAgKV0KICB9KTsKfSk=

Note that you can do this to remove the line wrapping, but that feels really sloppy.

view.contentDOM.classList.remove(EditorView.lineWrapping.value.class);

It would make sense for a contentAttribute extension to remove any added attributes when it’s removed from the Editor. :man_shrugging: