Debian Codegraph @

extensions/CodeEditor/modules/jquery.codeEditor.js

raw symbols SCIP
1 /* Ace syntax-highlighting code editor extension for wikiEditor */
2 /* global ace */
3 /* eslint-disable no-jquery/no-global-selector */
4 ( function () {
5 $.wikiEditor.modules.codeEditor = {
6 /**
7 * Core Requirements
8 */
9 req: [ 'codeEditor' ],
10 /**
11 * Configuration
12 */
13 cfg: {
14 //
15 },
16 /**
17 * API accessible functions
18 */
19 api: {
20 //
21 },
22 /**
23 * Event handlers
24 */
25 evt: {
26 //
27 },
28 /**
29 * Internally used functions
30 */
31 fn: {
32 }
33
34 };
35
36 $.wikiEditor.extensions.codeEditor = function ( context ) {
37 var saveAndExtend,
38 textSelectionFn,
39 hasErrorsOnSave = false,
40 selectedLine = 0,
41 returnFalse = function () {
42 return false;
43 },
44 api = new mw.Api();
45
46 // Initialize state
47 var cookieEnabled = parseInt( mw.cookie.get( 'codeEditor-' + context.instance + '-showInvisibleChars' ), 10 );
48 context.showInvisibleChars = ( cookieEnabled === 1 );
49 cookieEnabled = parseInt( mw.cookie.get( 'codeEditor-' + context.instance + '-lineWrappingActive' ), 10 );
50 context.lineWrappingActive = ( cookieEnabled === 1 );
51
52 /*
53 * Event Handlers
54 *
55 * WikiEditor inspects the 'evt' object for event names and uses them if present as additional
56 * event handlers that fire before the default handling.
57 * To prevent WikiEditor from running its own handling, handlers should return false.
58 *
59 * This is also where we can attach some extra information to the events.
60 */
61 context.evt = Object.assign( context.evt, {
62 keydown: returnFalse,
63 change: returnFalse,
64 delayedChange: returnFalse,
65 cut: returnFalse,
66 paste: returnFalse,
67 ready: returnFalse,
68 codeEditorSubmit: function () {
69 var form = this;
70 context.evt.codeEditorSync();
71 if ( hasErrorsOnSave ) {
72 hasErrorsOnSave = false;
73 OO.ui.confirm( mw.msg( 'codeeditor-save-with-errors' ) ).done( function ( confirmed ) {
74 if ( confirmed ) {
75 // Programmatic submit doesn't retrigger this event listener
76 form.submit();
77 }
78 } );
79 return false;
80 }
81 return true;
82 },
83 codeEditorSave: function () {
84 if ( context.codeEditor.getSession().getAnnotations().some( function ( ann ) {
85 return ann.type === 'error';
86 } ) ) {
87 hasErrorsOnSave = true;
88 }
89 },
90 codeEditorSync: function () {
91 context.$textarea.val( context.$textarea.textSelection( 'getContents' ) );
92
93 }
94 } );
95
96 // Make sure to cast '0' to false
97 context.codeEditorActive = !!Number( mw.user.options.get( 'usecodeeditor' ) );
98
99 /**
100 * Internally used functions
101 */
102 context.fn = Object.assign( context.fn, {
103 isCodeEditorActive: function () {
104 return context.codeEditorActive;
105 },
106 isShowInvisibleChars: function () {
107 return context.showInvisibleChars;
108 },
109 isLineWrappingActive: function () {
110 return context.lineWrappingActive;
111 },
112 changeCookieValue: function ( cookieName, value ) {
113 mw.cookie.set(
114 'codeEditor-' + context.instance + '-' + cookieName,
115 value
116 );
117 },
118 aceGotoLineColumn: function () {
119 OO.ui.prompt( mw.msg( 'codeeditor-gotoline-prompt' ), {
120 textInput: { placeholder: mw.msg( 'codeeditor-gotoline-placeholder' ) }
121 } ).done( function ( result ) {
122 if ( !result ) {
123 return;
124 }
125
126 var matches = result.split( ':' );
127 var line = 0;
128 var column = 0;
129
130 if ( matches.length > 0 ) {
131 line = +matches[ 0 ];
132 if ( isNaN( line ) ) {
133 return;
134 } else {
135 // Lines are zero-indexed
136 line--;
137 }
138 }
139 if ( matches.length > 1 ) {
140 column = +matches[ 1 ];
141 if ( isNaN( column ) ) {
142 column = 0;
143 }
144 }
145 context.codeEditor.navigateTo( line, column );
146 // Scroll up a bit to give some context
147 context.codeEditor.scrollToRow( line - 4 );
148 } );
149 },
150 setupCodeEditorToolbar: function () {
151 var toggleEditor = function ( ctx ) {
152 ctx.codeEditorActive = !ctx.codeEditorActive;
153
154 ctx.fn.setCodeEditorPreference( ctx.codeEditorActive );
155 ctx.fn.updateCodeEditorToolbarButton();
156
157 if ( ctx.codeEditorActive ) {
158 // set it back up!
159 ctx.fn.setupCodeEditor();
160 } else {
161 ctx.fn.disableCodeEditor();
162 }
163 };
164 var toggleInvisibleChars = function ( ctx ) {
165 ctx.showInvisibleChars = !ctx.showInvisibleChars;
166
167 ctx.fn.changeCookieValue( 'showInvisibleChars', ctx.showInvisibleChars ? 1 : 0 );
168 ctx.fn.updateInvisibleCharsButton();
169
170 ctx.codeEditor.setShowInvisibles( ctx.showInvisibleChars );
171 };
172 var toggleSearchReplace = function ( ctx ) {
173 var searchBox = ctx.codeEditor.searchBox;
174 if ( searchBox && $( searchBox.element ).css( 'display' ) !== 'none' ) {
175 searchBox.hide();
176 } else {
177 ctx.codeEditor.execCommand(
178 ctx.codeEditor.getReadOnly() ? 'find' : 'replace'
179 );
180 }
181 };
182 var toggleLineWrapping = function ( ctx ) {
183 ctx.lineWrappingActive = !ctx.lineWrappingActive;
184
185 ctx.fn.changeCookieValue( 'lineWrappingActive', ctx.lineWrappingActive ? 1 : 0 );
186 ctx.fn.updateLineWrappingButton();
187
188 ctx.codeEditor.getSession().setUseWrapMode( ctx.lineWrappingActive );
189 };
190 var indent = function ( ctx ) {
191 ctx.codeEditor.execCommand( 'indent' );
192 };
193 var outdent = function ( ctx ) {
194 ctx.codeEditor.execCommand( 'outdent' );
195 };
196 var gotoLine = function ( ctx ) {
197 ctx.codeEditor.execCommand( 'gotolinecolumn' );
198 };
199
200 context.api.addToToolbar( context, {
201 section: 'main',
202 groups: {
203 'codeeditor-main': {
204 tools: {
205 codeEditor: {
206 label: mw.msg( 'codeeditor-toolbar-toggle' ),
207 type: 'toggle',
208 oouiIcon: 'markup',
209 action: {
210 type: 'callback',
211 execute: toggleEditor
212 }
213 }
214 }
215 },
216 'codeeditor-format': {
217 tools: {
218 indent: {
219 label: mw.msg( 'codeeditor-indent' ),
220 type: 'button',
221 oouiIcon: 'indent',
222 action: {
223 type: 'callback',
224 execute: indent
225 }
226 },
227 outdent: {
228 label: mw.msg( 'codeeditor-outdent' ),
229 type: 'button',
230 oouiIcon: 'outdent',
231 action: {
232 type: 'callback',
233 execute: outdent
234 }
235 }
236
237 }
238 },
239 'codeeditor-style': {
240 tools: {
241 invisibleChars: {
242 label: mw.msg( 'codeeditor-invisibleChars-toggle' ),
243 type: 'toggle',
244 oouiIcon: 'pilcrow',
245 action: {
246 type: 'callback',
247 execute: toggleInvisibleChars
248 }
249 },
250 lineWrapping: {
251 label: mw.msg( 'codeeditor-lineWrapping-toggle' ),
252 type: 'toggle',
253 oouiIcon: 'wrapping',
254 action: {
255 type: 'callback',
256 execute: toggleLineWrapping
257 }
258 },
259 gotoLine: {
260 label: mw.msg( 'codeeditor-gotoline' ),
261 type: 'button',
262 oouiIcon: 'gotoLine',
263 action: {
264 type: 'callback',
265 execute: gotoLine
266 }
267 },
268 toggleSearchReplace: {
269 label: mw.msg( 'codeeditor-searchReplace-toggle' ),
270 type: 'button',
271 oouiIcon: 'articleSearch',
272 action: {
273 type: 'callback',
274 execute: toggleSearchReplace
275 }
276 }
277 }
278 }
279 }
280 } );
281 context.fn.updateCodeEditorToolbarButton();
282 context.fn.updateInvisibleCharsButton();
283 context.fn.updateLineWrappingButton();
284 $( '.group-codeeditor-style' ).prependTo( '.section-main' );
285 $( '.group-codeeditor-format' ).prependTo( '.section-main' );
286 $( '.group-codeeditor-main' ).prependTo( '.section-main' );
287 },
288 updateButtonIcon: function ( targetName, iconFn ) {
289 var target = '.tool[rel=' + targetName + ']',
290 $button = context.modules.toolbar.$toolbar.find( target );
291
292 $button.data( 'setActive' )( iconFn() );
293 },
294 updateCodeEditorToolbarButton: function () {
295 context.fn.updateButtonIcon( 'codeEditor', context.fn.isCodeEditorActive );
296 },
297 updateInvisibleCharsButton: function () {
298 context.fn.updateButtonIcon( 'invisibleChars', context.fn.isShowInvisibleChars );
299 },
300 updateLineWrappingButton: function () {
301 context.fn.updateButtonIcon( 'lineWrapping', context.fn.isLineWrappingActive );
302 },
303 setCodeEditorPreference: function ( prefValue ) {
304 // Abort any previous request
305 api.abort();
306
307 api.saveOption( 'usecodeeditor', prefValue ? 1 : 0 )
308 .fail( function ( code, result ) {
309 if ( code === 'http' && result.textStatus === 'abort' ) {
310 // Request was aborted. Ignore error
311 return;
312 }
313 if ( code === 'notloggedin' ) {
314 // Expected for non-registered users
315 return;
316 }
317
318 var message = 'Failed to set code editor preference: ' + code;
319 if ( result.error && result.error.info ) {
320 message += '\n' + result.error.info;
321 }
322 mw.log.warn( message );
323 } );
324 },
325 /**
326 * Sets up the iframe in place of the textarea to allow more advanced operations
327 */
328 setupCodeEditor: function () {
329 var $box = context.$textarea;
330 var lang = mw.config.get( 'wgCodeEditorCurrentLanguage' );
331 var basePath = mw.config.get( 'wgExtensionAssetsPath', '' );
332 if ( basePath.slice( 0, 2 ) === '//' ) {
333 // ACE uses web workers, which have importScripts, which don't like relative links.
334 // This is a problem only when the assets are on another server, so this rewrite should suffice
335 // Protocol relative
336 basePath = window.location.protocol + basePath;
337 }
338 ace.config.set( 'basePath', basePath + '/CodeEditor/modules/lib/ace' );
339
340 if ( lang ) {
341 // Ace doesn't like replacing a textarea directly.
342 // We'll stub this out to sit on top of it...
343 // line-height is needed to compensate for oddity in WikiEditor extension, which zeroes the line-height on a parent container
344 // eslint-disable-next-line no-jquery/no-parse-html-literal
345 var container = context.$codeEditorContainer = $( '<div style="position: relative"><div class="editor" style="line-height: 1.5em; top: 0; left: 0; right: 0; bottom: 0; position: absolute;"></div></div>' ).insertAfter( $box );
346 var editdiv = container.find( '.editor' );
347
348 $box.css( 'display', 'none' );
349 container.height( $box.height() );
350
351 // Non-lazy loaded dependencies: Enable code completion
352 ace.require( 'ace/ext/language_tools' );
353
354 // Load the editor now
355 context.codeEditor = ace.edit( editdiv[ 0 ] );
356 context.codeEditor.getSession().setValue( $box.val() );
357 $box.textSelection( 'register', textSelectionFn );
358
359 // Disable some annoying keybindings
360 context.codeEditor.commands.bindKeys( {
361 'Ctrl-T': null,
362 'Ctrl-L': null,
363 'Command-L': null
364 } );
365
366 context.codeEditor.setReadOnly( $box.prop( 'readonly' ) );
367 context.codeEditor.setShowInvisibles( context.showInvisibleChars );
368
369 var htmlClasses = document.documentElement.classList;
370 var inDarkMode = htmlClasses.contains( 'skin-theme-clientpref-night' ) || (
371 htmlClasses.contains( 'skin-theme-clientpref-os' ) &&
372 window.matchMedia && window.matchMedia( '(prefers-color-scheme: dark)' ).matches
373 );
374
375 // The options to enable
376 context.codeEditor.setOptions( {
377 enableBasicAutocompletion: true,
378 enableSnippets: true,
379 theme: inDarkMode ? 'ace/theme/monokai' : 'ace/theme/textmate'
380 } );
381
382 context.codeEditor.commands.addCommand( {
383 name: 'gotolinecolumn',
384 bindKey: { mac: 'Command-Shift-L', windows: 'Ctrl-Alt-L' },
385 exec: context.fn.aceGotoLineColumn,
386 readOnly: true
387 } );
388
389 $box.closest( 'form' )
390 .on( 'submit', context.evt.codeEditorSubmit )
391 .find( '#wpSave' ).on( 'click', context.evt.codeEditorSave );
392
393 var session = context.codeEditor.getSession();
394
395 // Use proper tabs
396 session.setUseSoftTabs( false );
397 session.setUseWrapMode( context.lineWrappingActive );
398
399 // Configure any workers
400 session.on( 'changeMode', function ( e, session2 ) {
401 // eslint-disable-next-line no-jquery/variable-pattern
402 var mode = session2.getMode().$id;
403 if ( mode === 'ace/mode/javascript' ) {
404 session2.$worker.send( 'changeOptions', [ {
405 maxerr: 1000,
406 globals: { mw: true, mediaWiki: true, $: true, jQuery: true, OO: true }
407 } ] );
408 }
409 } );
410
411 mw.hook( 'codeEditor.configure' ).fire( session );
412
413 // Add an Ace change handler to pass changes to Edit Recovery.
414 mw.hook( 'editRecovery.loadEnd' ).add( function ( data ) {
415 session.on( 'change', data.fieldChangeHandler );
416 } );
417
418 ace.config.loadModule( 'ace/ext/modelist', function ( modelist ) {
419 if ( !modelist || !modelist.modesByName[ lang ] ) {
420 lang = 'text';
421 }
422 session.setMode( 'ace/mode/' + lang );
423 } );
424
425 // Use jQuery UI resizable() so that users can make the box taller
426
427 container.resizable( {
428 handles: 's',
429 minHeight: $box.height(),
430 resize: function () {
431
432 context.codeEditor.resize();
433 }
434 } );
435 $( '.wikiEditor-ui-toolbar' ).addClass( 'codeEditor-ui-toolbar' );
436
437 if ( selectedLine > 0 ) {
438 // Line numbers in CodeEditor are zero-based
439 context.codeEditor.navigateTo( selectedLine - 1, 0 );
440 // Scroll up a bit to give some context
441 context.codeEditor.scrollToRow( selectedLine - 4 );
442 }
443
444 context.fn.setupStatusBar();
445
446 document.body.classList.remove( 'codeeditor-loading' );
447
448 // Let modules know we're ready to start working with the content
449 context.fn.trigger( 'ready' );
450 }
451 },
452
453 /**
454 * Turn off the code editor view and return to the plain textarea.
455 * May be needed by some folks with funky browsers, or just to compare.
456 */
457 disableCodeEditor: function () {
458 // Kills it!
459 context.$textarea.closest( 'form' )
460 .off( 'submit', context.evt.codeEditorSubmit )
461 .find( '#wpSave' ).off( 'click', context.evt.codeEditorSave );
462
463 // Save contents
464 context.$textarea.textSelection( 'unregister' );
465 context.$textarea.val( textSelectionFn.getContents() );
466
467 // @todo fetch cursor, scroll position
468
469 // Drop the fancy editor widget...
470 context.fn.removeStatusBar();
471 context.$codeEditorContainer.remove();
472 context.$codeEditorContainer = undefined;
473 context.codeEditor = undefined;
474
475 // Restore textarea
476 context.$textarea.show();
477 // Restore toolbar
478 $( '.wikiEditor-ui-toolbar' ).removeClass( 'codeEditor-ui-toolbar' );
479
480 // @todo restore cursor, scroll position
481 },
482
483 /**
484 * Start monitoring the fragment of the current window for hash change
485 * events. If the hash is already set, handle it as a new event.
486 */
487 codeEditorMonitorFragment: function () {
488 function onHashChange() {
489 var regexp = /#mw-ce-l(\d+)/;
490 var result = regexp.exec( window.location.hash );
491
492 if ( result === null ) {
493 return;
494 }
495
496 selectedLine = parseInt( result[ 1 ], 10 );
497 if ( context.codeEditor && selectedLine > 0 ) {
498 // Line numbers in CodeEditor are zero-based
499 context.codeEditor.navigateTo( selectedLine - 1, 0 );
500 // Scroll up a bit to give some context
501 context.codeEditor.scrollToRow( selectedLine - 4 );
502 }
503 }
504
505 onHashChange();
506 $( window ).on( 'hashchange', onHashChange );
507 },
508 /**
509 * This creates a Statusbar, that allows you to see a count of the
510 * errors, warnings and the warning of the current line, as well as
511 * the position of the cursor.
512 */
513 setupStatusBar: function () {
514 var shouldUpdateAnnotations,
515 shouldUpdateSelection,
516 shouldUpdateLineInfo,
517 nextAnnotation,
518 delayedUpdate,
519 editor = context.codeEditor,
520 lang = ace.require( 'ace/lib/lang' ),
521 $errors = $( '<span>' ).addClass( 'codeEditor-status-worker-cell ace_gutter-cell ace_error' ).text( '0' ),
522 $warnings = $( '<span>' ).addClass( 'codeEditor-status-worker-cell ace_gutter-cell ace_warning' ).text( '0' ),
523 $infos = $( '<span>' ).addClass( 'codeEditor-status-worker-cell ace_gutter-cell ace_info' ).text( '0' ),
524 $message = $( '<div>' ).addClass( 'codeEditor-status-message' ),
525 $lineAndMode = $( '<div>' ).addClass( 'codeEditor-status-line' ),
526 $workerStatus = $( '<div>' )
527 .addClass( 'codeEditor-status-worker' )
528 .attr( 'title', mw.msg( 'codeeditor-next-annotation' ) )
529 .append( $errors )
530 .append( $warnings )
531 .append( $infos );
532
533 context.$statusBar = $( '<div>' )
534 .addClass( 'codeEditor-status' )
535 .append( $workerStatus )
536 .append( $message )
537 .append( $lineAndMode );
538
539 /* Help function to concatenate strings with different separators */
540 function addToStatus( status, str, separator ) {
541 if ( str ) {
542 status.push( str, separator || '|' );
543 }
544 }
545
546 /**
547 * Update all the information in the status bar
548 */
549 function updateStatusBar() {
550 var errors = 0,
551 warnings = 0,
552 infos = 0,
553 distance,
554 shortestDistance = Infinity,
555 closestAnnotation,
556 currentLine = editor.selection.lead.row,
557 annotations = editor.getSession().getAnnotations(),
558 closestType;
559
560 // Reset the next annotation
561 nextAnnotation = null;
562
563 for ( var i = 0; i < annotations.length; i++ ) {
564 var annotation = annotations[ i ];
565 distance = Math.abs( currentLine - annotation.row );
566
567 if ( distance < shortestDistance ) {
568 shortestDistance = distance;
569 closestAnnotation = annotation;
570 }
571 if ( nextAnnotation === null && annotation.row > currentLine ) {
572 nextAnnotation = annotation;
573 }
574
575 switch ( annotations[ i ].type ) {
576 case 'error':
577 errors++;
578 break;
579 case 'warning':
580 warnings++;
581 break;
582 case 'info':
583 infos++;
584 break;
585 }
586 }
587 // Wrap around to the beginning for nextAnnotation
588 if ( nextAnnotation === null && annotations.length > 0 ) {
589 nextAnnotation = annotations[ 0 ];
590 }
591 // Update the annotation counts
592 if ( shouldUpdateAnnotations ) {
593 $errors.text( errors );
594 $warnings.text( warnings );
595 $infos.text( infos );
596 }
597
598 // Show the message of the current line, if we have not already done so
599 if ( closestAnnotation &&
600 currentLine === closestAnnotation.row &&
601 closestAnnotation !== $message.data( 'annotation' ) ) {
602 $message.data( 'annotation', closestAnnotation );
603 closestType =
604 closestAnnotation.type.charAt( 0 ).toUpperCase() +
605 closestAnnotation.type.slice( 1 );
606
607 $message.text( closestType + ': ' + closestAnnotation.text );
608 } else if ( $message.data( 'annotation' ) !== null &&
609 ( !closestAnnotation || currentLine !== closestAnnotation.row ) ) {
610 // If we are on a different line without an annotation, then blank the message
611 $message.data( 'annotation', null );
612 $message.text( '' );
613 }
614
615 // The cursor position has changed
616 if ( shouldUpdateSelection || shouldUpdateLineInfo ) {
617 // Adapted from Ajax.org's ace/ext/statusbar module
618 var status = [];
619
620 if ( editor.$vimModeHandler ) {
621 addToStatus( status, editor.$vimModeHandler.getStatusText() );
622 } else if ( editor.commands.recording ) {
623 addToStatus( status, 'REC' );
624 }
625
626 var c = editor.selection.lead;
627 addToStatus( status, ( c.row + 1 ) + ':' + c.column, '' );
628 if ( !editor.selection.isEmpty() ) {
629 var r = editor.getSelectionRange();
630 addToStatus( status, '(' + ( r.end.row - r.start.row ) + ':' + ( r.end.column - r.start.column ) + ')' );
631 }
632 status.pop();
633 $lineAndMode.text( status.join( '' ) );
634 }
635
636 shouldUpdateLineInfo = shouldUpdateSelection = shouldUpdateAnnotations = false;
637 }
638
639 // Function to delay/debounce updates for the StatusBar
640 delayedUpdate = lang.delayedCall( function () {
641 updateStatusBar( editor );
642 } );
643
644 /**
645 * Click handler that allows you to skip to the next annotation
646 */
647 $workerStatus.on( 'click', function ( e ) {
648 if ( nextAnnotation ) {
649 context.codeEditor.navigateTo( nextAnnotation.row, nextAnnotation.column );
650 // Scroll up a bit to give some context
651 context.codeEditor.scrollToRow( nextAnnotation.row - 3 );
652 e.preventDefault();
653 }
654 } );
655
656 editor.getSession().on( 'changeAnnotation', function () {
657 shouldUpdateAnnotations = true;
658 delayedUpdate.schedule( 100 );
659 } );
660 editor.on( 'changeStatus', function () {
661 shouldUpdateLineInfo = true;
662 delayedUpdate.schedule( 100 );
663 } );
664 editor.on( 'changeSelection', function () {
665 shouldUpdateSelection = true;
666 delayedUpdate.schedule( 100 );
667 } );
668
669 // Force update
670 shouldUpdateLineInfo = shouldUpdateSelection = shouldUpdateAnnotations = true;
671 updateStatusBar( editor );
672
673 context.$statusBar.insertAfter( $( '.wikiEditor-ui-view-wikitext .wikiEditor-ui-bottom' ) );
674 },
675 removeStatusBar: function () {
676 context.codeEditor.getSession().removeListener( 'changeAnnotation' );
677 context.codeEditor.removeListener( 'changeSelection' );
678 context.codeEditor.removeListener( 'changeStatus' );
679 context.nextAnnotation = null;
680 context.$statusBar = null;
681
682 $( '.codeEditor-status' ).remove();
683 }
684
685 } );
686
687 /**
688 * Override the base functions in a way that lets
689 * us fall back to the originals when we turn off.
690 *
691 * @param {Object} base
692 * @param {Object} extended
693 */
694 saveAndExtend = function ( base, extended ) {
695 // eslint-disable-next-line no-jquery/no-map-util
696 $.map( extended, function ( func, name ) {
697 if ( name in base ) {
698 var orig = base[ name ];
699 base[ name ] = function () {
700 if ( context.codeEditorActive ) {
701 return func.apply( this, arguments );
702 }
703 if ( orig ) {
704 return orig.apply( this, arguments );
705 }
706 throw new Error( 'CodeEditor: no original function to call for ' + name );
707 };
708 } else {
709 base[ name ] = func;
710 }
711 } );
712 };
713
714 saveAndExtend( context.fn, {
715 saveSelection: function () {
716 mw.log( 'codeEditor stub function saveSelection called' );
717 },
718 restoreSelection: function () {
719 mw.log( 'codeEditor stub function restoreSelection called' );
720 },
721
722 /**
723 * Scroll an element to the top of the iframe
724 */
725 scrollToTop: function () {
726 mw.log( 'codeEditor stub function scrollToTop called' );
727 }
728 } );
729
730 /**
731 * Compatibility with the $.textSelection jQuery plug-in. When the iframe is in use, these functions provide
732 * equivalant functionality to the otherwise textarea-based functionality.
733 */
734 textSelectionFn = {
735
736 /* Needed for search/replace */
737 getContents: function () {
738 return context.codeEditor.getSession().getValue();
739 },
740
741 setContents: function ( newContents ) {
742 context.codeEditor.getSession().setValue( newContents );
743 },
744
745 /**
746 * Gets the currently selected text in the content
747 * DO NOT CALL THIS DIRECTLY, use $.textSelection( 'functionname', options ) instead
748 *
749 * @return {string}
750 */
751 getSelection: function () {
752 return context.codeEditor.getCopyText();
753 },
754
755 /**
756 * Replace the current selection with the given text.
757 * DO NOT CALL THIS DIRECTLY, use $.textSelection( 'functionname', options ) instead
758 *
759 * @param {string} text
760 */
761 replaceSelection: function ( text ) {
762 context.codeEditor.insert( text );
763 },
764
765 /**
766 * Inserts text at the begining and end of a text selection, optionally inserting text at the caret when
767 * selection is empty.
768 * DO NOT CALL THIS DIRECTLY, use $.textSelection( 'functionname', options ) instead
769 *
770 * @param {Object} options
771 * @return {jQuery}
772 */
773 encapsulateSelection: function ( options ) {
774 // Does not yet handle 'ownline', 'splitlines' option
775 var sel = context.codeEditor.getSelection();
776 var range = sel.getRange();
777 var selText = textSelectionFn.getSelection();
778 var isSample = false;
779
780 if ( !selText ) {
781 selText = options.peri;
782 isSample = true;
783 } else if ( options.replace ) {
784 selText = options.peri;
785 }
786
787 var text = options.pre;
788 text += selText;
789 text += options.post;
790 context.codeEditor.insert( text );
791 if ( isSample && options.selectPeri && !options.splitlines ) {
792 // May esplode if anything has newlines, be warned. :)
793 range.setStart( range.start.row, range.start.column + options.pre.length );
794 range.setEnd( range.start.row, range.start.column + selText.length );
795 sel.setSelectionRange( range );
796 }
797 return context.$textarea;
798 },
799
800 /**
801 * Gets the position (in resolution of bytes not nessecarily characters) in a textarea
802 * DO NOT CALL THIS DIRECTLY, use $.textSelection( 'functionname', options ) instead
803 *
804 * @param {Object} options
805 * @param {Object} [options.startAndEnd=false] Return range of the selection rather than just start
806 * @return {number|number[]} If options.startAndEnd is true, returns an array holding the start and
807 * end of the selection, else returns only the start of the selection as a single number.
808 */
809 getCaretPosition: function ( options ) {
810 var selection = context.codeEditor.getSelection(),
811 range = selection.getRange(),
812 doc = context.codeEditor.getSession().getDocument(),
813 startOffset = doc.positionToIndex( range.start );
814
815 if ( options.startAndEnd ) {
816 var endOffset = doc.positionToIndex( range.end );
817 return [ startOffset, endOffset ];
818 }
819
820 return startOffset;
821 },
822
823 /**
824 * Sets the selection of the content
825 * DO NOT CALL THIS DIRECTLY, use $.textSelection( 'functionname', options ) instead
826 *
827 * @param {Object} options
828 * @return {jQuery}
829 */
830 setSelection: function ( options ) {
831 // Ace stores positions for ranges as row/column pairs.
832 // To convert from character offsets, we'll need to iterate through the document
833 var doc = context.codeEditor.getSession().getDocument();
834 var lines = doc.getAllLines();
835
836 var offsetToPos = function ( offset ) {
837 var row, col, pos;
838
839 row = 0;
840 col = 0;
841 pos = 0;
842
843 while ( row < lines.length && pos + lines[ row ].length < offset ) {
844 pos += lines[ row ].length;
845 pos++; // for the newline
846 row++;
847 }
848 col = offset - pos;
849 return { row: row, column: col };
850 };
851 var start = offsetToPos( options.start );
852 var end = offsetToPos( options.end );
853
854 var sel = context.codeEditor.getSelection();
855 var range = sel.getRange();
856 range.setStart( start.row, start.column );
857 range.setEnd( end.row, end.column );
858 sel.setSelectionRange( range );
859 return context.$textarea;
860 },
861
862 /**
863 * Scroll a textarea to the current cursor position. You can set the cursor position with setSelection()
864 * DO NOT CALL THIS DIRECTLY, use $.textSelection( 'functionname', options ) instead
865 *
866 * @return {jQuery}
867 */
868 scrollToCaretPosition: function () {
869 mw.log( 'codeEditor stub function scrollToCaretPosition called' );
870 return context.$textarea;
871 }
872 };
873
874 /* Setup the editor */
875 context.fn.setupCodeEditorToolbar();
876 if ( context.codeEditorActive ) {
877 context.fn.setupCodeEditor();
878 }
879
880 };
881 }() );