Extension talk:CodeMirror

About this board

Thanks for your feedback about the Extension:CodeMirror used to provide wikitext syntax highlight to pages on MediaWiki-based projects.

Report a new bug in Phabricator

Plantaest (talkcontribs)

How to use this syntax highlighter's API on some userscript or out of MediaWiki?

Thiemo Kreuz (WMDE) (talkcontribs)

There is not really an official API, as far as I'm aware of. What you can do is to re-use the original CodeMirror library the same way the extension does. In a user script this would probably be done via mw.loader.using( [ 'ext.CodeMirror.lib' ] ).then( … ) and then something like CodeMirror.fromTextArea( … ). See ResourceLoader/Developing with ResourceLoader as well as ext.CodeMirror.js for more information.

Plantaest (talkcontribs)

Thanks. I understood.

This syntax highlighter for wikitext is really good. It should be added into CodeMirror docs: https://codemirror.net/5/mode/index.html for other uses out of MediaWiki scope.

I didn't find much syntax highlighter for wikitext on Internet.

Reply to "API"
Megajoule (talkcontribs)

MW 1.35.6 / PHP 7.4.27 / CodeMirror 4.0.0

Despite the option being enabled, line numbering does not work.

$wgCodeMirrorLineNumberingNamespaces = [ NS_TEMPLATE ];

Thiemo Kreuz (WMDE) (talkcontribs)

The feature didn't exist before MediaWiki 1.37.

Megajoule (talkcontribs)

MW 1.37.2 / PHP 7.4.27 / CodeMirror 4.0.0

The line numbering still does not work.

Try with $wgCodeMirrorLineNumberingNamespaces = null; → no more success.

Thiemo Kreuz (WMDE) (talkcontribs)

The CodeMirror version number is not very meaningful, unfortunately. Are you sure you updated the extension? You can check if CodeMirror/extension.json contains "CodeMirrorLineNumberingNamespaces".

Reply to "No line numbering"

Highlighter does not work in pageforms free text area

1
Plegault3397 (talkcontribs)
Reply to "Highlighter does not work in pageforms free text area"

Option selectionPointer (from selection-pointer CM addon)

3
MarMi wiki (talkcontribs)

You can't change mouse cursor through option selectionPointer (from CM selection-pointer addon).

It works if you load mediawiki mode manually (topic Collapsed range (markText) hides cursor just before the range).

mw.loader.load("//codemirror.net/addon/selection/selection-pointer.js")
editor.setOption("selectionPointer","grab")

pl.wikipedia.org

MarMi wiki (talkcontribs)

Oh, that because cm.display.selectionDiv doesn't have any children.

Also it doesn't use class CodeMirror-selected to mark the selection.

MarMi wiki (talkcontribs)

Correction/update: cm.display.selectionDiv eventually will have children, if you make more than one selection (with Ctrl). It stores all the selection boxes EXCEPT the current/last/active one (so if you only use one, it will be most likely always empty).

Reply to "Option selectionPointer (from selection-pointer CM addon)"

Wrapped lines: spaces on wraps and End

4
MarMi wiki (talkcontribs)

If wrapped lines ends by spaces (so nearly always), End puts the cursor at the beginning of the next wrapped line - so it basically behaves like Home (except it puts the cursor in the wrapped line below).

You can't put the cursor behind the last space (in the same horizontal line), you can either put cursor before the last space, or "after" it (which puts cursor at the beginning of the wrapped line below).

Can it be set so it would behave like thread editor here: End puts the cursor after last space (in the same horizontal line). Cursor right places cursor at the beginning of wrapped line below)?


Example of a long wrapped line:

Góry Zielone (ang. Green Mountains, fr. Montagnes Vertes) – pasmo górskie w stanach Vermont i Massachusetts (Stany Zjednoczone) oraz prowincji Quebec (Kanada), wchodzące w skład Appalachów. Góry Zielone (ang. Green Mountains, fr. Montagnes Vertes) – pasmo górskie w stanach Vermont i Massachusetts (Stany Zjednoczone) oraz prowincji Quebec (Kanada), wchodzące w skład Appalachów.

Thiemo Kreuz (WMDE) (talkcontribs)
MarMi wiki (talkcontribs)

TL: read the summary in my next post.


Not quite, because current version of CM wraps lines similar to what I proposed - except cursor right at the end of wrap (End) places the cursor after first char of the wrapped line below.

So this is either the question of CM implementation used by the extension (ie. this could be introduced in later version than 5.53.x), or some settings (or maybe mode/style influence the cursor?).

Edit: 5.53.3 can set the cursor at the end of line wrap, because it does so if the mode is loaded manually:

editor.setOption("lineWrapping",true);
var ek=editor.getOption("extraKeys");
if (!ek) ek={}
ek.End='goLineRight'
editor.setOption("extraKeys",ek);

So it's a matter of extension changes in implementation, its settings or mode (including styles).

I think that placing the cursor at the end of line by End is more natural than its current behavior in mediawiki mode.

(Does mediawiki mode is also covered by Extension:CodeMirror?).

Even later edit: I've pinpointed the setting that influences cursor behavior: it's inputStyle: 'contenteditable' (in ex.CodeMirror.js)

Full test code for clarity:

mw.loader.load("ext.CodeMirror")    //execute separately

mw.loader.load("ext.CodeMirror.mode.mediawiki") //execute separately

var cmOptions={mode:"text/mediawiki",mwConfig:mw.config.get('extCodeMirrorConfig'),lineWrapping: true,inputStyle: 'contenteditable'}
var editor = CodeMirror.fromTextArea(document.getElementById("wpTextbox1"),cmOptions)
var ek=editor.getOption("extraKeys");
if (!ek) ek={}
ek.End='goLineRight'
editor.setOption("extraKeys",ek);
MarMi wiki (talkcontribs)

Summary of the above (sorry for multiple edits):

I guess it's a CM thing after all.

Since you can't change inputStyle at runtime (yet, according to comment in CM code), maybe there is a way to change it on Wikipedia on the browser client side (without the need of changing code in the extension)?

Edit: Also, on contenteditable in 2020: What are the pitfalls of using inputStyle ‘contenteditable’ in 2020?.

And in 2021: CM5: No cursor before bookmark.

As to the cursor at the end of wrapped lines (in contenteditable): it's probably possible, but would require implementing a custom cursor (CM5: inputStyle contenteditable, cursor display after goLineRight (wrapped line)).

Reply to "Wrapped lines: spaces on wraps and End"

Collapsed range (markText) hides cursor just before the range

4
MarMi wiki (talkcontribs)

If you do markText with option collapsed=true (with replacedWith), and place the cursor just before the arrows marking collapsed range, the cursor won't be showing.

Example code (part above the empty line run once, markText to test range, clear to remove mark):

var text = document.createTextNode('\u2194');
widget = document.createElement("span");
widget.appendChild(text);
widget.className = "CodeMirror-foldmarker";
var editor = $(".CodeMirror")

editor[0].CodeMirror.doc.markText({line:0,ch:1},{line:1,ch:10},{collapsed:true,replacedWith:widget})
editor[0].CodeMirror.getAllMarks()[0].clear()

pl.wikipedia.org

Thiemo Kreuz (WMDE) (talkcontribs)
MarMi wiki (talkcontribs)

I don't think it's entirely the CM fault, it could be something either in the changed CM library code, mediawiki mode, or in mediawiki css (or it's just a matter of config option?).

Because if you load mode manually, the cursor in front of the range is shown.

This works (in code editor without CodeMirror present - disable highlighting and refresh the editor by F5; use editor. in place of editor[0].CodeMirror. with markText line above):

mw.loader.load("ext.CodeMirror")
mw.loader.load("ext.CodeMirror.lib.mode.htmlmixed")
var editor = CodeMirror.fromTextArea(document.getElementById("wpTextbox1"),{mode:"htmlmixed"})

mw.loader.load("ext.CodeMirror")
mw.loader.load("ext.CodeMirror.mode.mediawiki")
var editor = CodeMirror.fromTextArea(document.getElementById("wpTextbox1"),{mode:"mediawiki",mwConfig:mw.config.get( 'extCodeMirrorConfig' )})

But if you switch normally to CM editor by the button, the cursor in front of the range won't be shown (move cursor by cursor keys, mouse isn't very reliable).

MarMi wiki (talkcontribs)
Reply to "Collapsed range (markText) hides cursor just before the range"

Selected text isn't shown in CodeMirror after switching to it

1
Summary last edited by MarMi wiki 20:11, 7 February 2022 7 months ago
MarMi wiki (talkcontribs)

If you select text before switching to CodeMirror (CM) editor, the selection won't be visible - unless you click on the right scrollbar and press the Tab key.

pl.wikipedia.org, old code editor (with syntax highlighting/CM switch).


Edit: Now it seems that it also doesn't select the text if you turn off the CM. It did so couple days ago (at the time of writing topics below).

Reply to "Selected text isn't shown in CodeMirror after switching to it"

Stability of cm.getTokenAt(pos)

4
Summary by Thiemo Kreuz (WMDE)

Please report at codemirror.net.

MarMi wiki (talkcontribs)

Does the value returned by cm.getTokenAt(pos) (specifically string) shouldn't be stable (the string value shouldn't change its value on every call)?

Example from pl.wikipedia.org:

  • Article Francisco Echevarría (link to edit in old code ditor [if not logged in] and in safemode), enable CodeMirror (pen[?] button between puzzle piece and Zaawansowane [Advanced]).
  • In dev console (F12) paste and execute var editor = $(".CodeMirror")
  • Paste and execute a few (3 or more) times: editor[0].CodeMirror.getTokenAt({line:26,ch:5}), notice that the string property adds a new token every time
  • Add new line before the 26 line (before the quotes of the black name Francisco Echevarria), notice that the color of highlighting changes.
  • Again execute a few times getTokenAt (with updated line to 27!), notice that the string property is stable (doesn't add new tokens)
  • To restore the previous state, delete the new line (also probably backspace would be needed, to place the name line after the closing brackets of template above it)
Thiemo Kreuz (WMDE) (talkcontribs)
MarMi wiki (talkcontribs)

It can cause problems (), since calling getTokenAt also influences what getLineTokens returns: normally it returns an array for entire line, but if you run getLineTokens after getTokenAt, on its first call the returned array will have less elements than normal.

getTokenAt cycles through all the tokens in the line - first it's the token at pos, then what's before it, and then adds the tokens after it (one by one), until the end of line, where it resets and starts the cycle again.

I don't know if it matters in wiki context, but it could cause problems with some CodeMirror addons.

MarMi wiki (talkcontribs)

I'm familiarizing myself with CodeMirror on pl.wiki, to eventually add user script with ref folding (using the CodeMirror fold addons) in old code editor. Text/mediawiki mode doesn't set the html/xml (sub)mode for tags, so the xml-fold helper doesn't work automatically.

Variable surroundingBrackets should be configurable (findSurroundingBrackets in matchbrackets-wmde addon)

2
Summary by Thiemo Kreuz (WMDE)

Out of scope.

MarMi wiki (talkcontribs)

matchbrackets-wmde addon, in function findSurroundingBrackets:

Variable surroundingBrackets should either check config.bracketRegex to see if given bracket is present there, or also be configurable (like bracketRegex).

Because if you want to, for example, match only curly brackets in {[something]}, then if the position is inside the [] block, then this block will be matched (instead of curly brackets).

Edit: Hmm, I think that it might be possible to bypass surroundingBrackets by manually scanning bracket in scanForBracket, and then calling findMatchingBracket with found position (not tested).

Thiemo Kreuz (WMDE) (talkcontribs)

Thanks for bringing this up. That's indeed a limitation of the code we added. However. While the Technical Wishes team tries to have non-Wikimedia users in mind, we have limited resources only and can't provide active support for features that aren't used on Wikimedia wikis. The addon is open source. You are free to modify it as you like.

Maksim E. Otstavnov (talkcontribs)
wfLoadExtension( 'CodeMirror' );
$wgDefaultUserOptions['usecodemirror'] = 1;
# Enable bracket matching in CodeMirror
$wgCodeMirrorEnableBracketMatching = true;
# Enable accessible colors in CodeMirror
$wgCodeMirrorAccessibilityColors = true;
#Enable line numbering in CodeMirror
#defaults to the template namespace `[ NS_TEMPLATE ]`
#`null` enables it for all namespace
#[] for disabling everywhere
$wgCodeMirrorLineNumberingNamespaces = [];

seems to have no effect on editing templates, I still see the line numbers. (Unfortunately, this forum prevents me from attaching screenshots.)

MediaWiki 1.36.1, PHP 7.4.15 (cgi-fcgi), MySQL 5.7.28-log, ICU 60.2, Apache 2.4.29-1ubuntu4.16 Extensions: Echo – (1a15ef8), VisualEditor 0.1.2, MyVariables 3.5.1, NoTitle 0.4.0 (780dbb6), DynamicSidebar 1.1 (b2f3feb), Lockdown – (2409546), MassMessage0.4.0 (c9b6e87), CodeMirror4.0.0 (508b9f6) 15:59, 22 July 2021.

Thiemo Kreuz (WMDE) (talkcontribs)

Using [] is correct and should do the job. Maybe it's a caching thing and you need to shift+reload the page?

Maksim E. Otstavnov (talkcontribs)

I see no effect even for newly created pages.

I believe something went wrong with my local settings. Just encountered the same problem with $wgNamespacesWithSubpages.

Christoph Jauera (WMDE) (talkcontribs)

Hej @Maksim E. Otstavnov, thanks for the report.

We just took another look at this and it seems that there is a bug that disallows disabling the default namespace. The bug is tracked in task T290226 now and will be taken care of. :-)

Adamw (talkcontribs)

The bug should be fixed, if you check out the newest version of CodeMirror it will disable line numbering given the OP's config.

Shall I download the newest version from Git? --previous unsigned comment by Maksim E. Otstavnov

Adamw (talkcontribs)

Yes, take the newest code from Git. Let us know how it goes!

Maksim E. Otstavnov (talkcontribs)
Reply to "Disabling line numbering?"