Bug 17178: Add virtual keyboard to advanced cataloguing editor
[koha.git] / koha-tmpl / intranet-tmpl / lib / koha / cateditor / marc-editor.js
1 /**
2  * Copyright 2015 ByWater Solutions
3  *
4  * This file is part of Koha.
5  *
6  * Koha is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Koha is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Koha; if not, see <http://www.gnu.org/licenses>.
18  */
19
20 define( [ 'marc-record', 'koha-backend', 'preferences', 'text-marc', 'widget' ], function( MARC, KohaBackend, Preferences, TextMARC, Widget ) {
21
22     var NOTIFY_TIMEOUT = 250;
23
24     function editorCursorActivity( cm ) {
25         var editor = cm.marceditor;
26         var field = editor.getCurrentField();
27         if ( !field ) return;
28
29         // Set overwrite mode for tag numbers/indicators and contents of fixed fields
30         if ( field.isControlField || cm.getCursor().ch < 8 ) {
31             cm.toggleOverwrite(true);
32         } else {
33             cm.toggleOverwrite(false);
34         }
35
36         editor.onCursorActivity();
37     }
38
39     // This function exists to prevent inserting or partially deleting text that belongs to a
40     // widget. The 'marcAware' change source exists for other parts of the editor code to bypass
41     // this check.
42     function editorBeforeChange( cm, change ) {
43         var editor = cm.marceditor;
44         if ( editor.textMode || change.origin == 'marcAware' || change.origin == 'widget.clearToText' ) return;
45
46         // FIXME: Should only cancel changes if this is a control field/subfield widget
47         if ( change.from.line !== change.to.line || Math.abs( change.from.ch - change.to.ch ) > 1 || change.text.length != 1 || change.text[0].length != 0 ) return; // Not single-char change
48
49         if ( change.from.ch == change.to.ch - 1 && cm.findMarksAt( { line: change.from.line, ch: change.from.ch + 1 } ).length ) {
50             change.cancel();
51         } else if ( change.from.ch == change.to.ch && cm.findMarksAt(change.from).length && !change.text[0] == '‡' ) {
52             change.cancel();
53         }
54     }
55
56     function editorChanges( cm, changes ) {
57         var editor = cm.marceditor;
58         if ( editor.textMode ) return;
59
60         for (var i = 0; i < changes.length; i++) {
61             var change = changes[i];
62
63             var origin = change.from.line;
64             var newTo = CodeMirror.changeEnd(change);
65
66             for (var delLine = origin; delLine <= change.to.line; delLine++) {
67                 // Line deleted; currently nothing to do
68             }
69
70             for (var line = origin; line <= newTo.line; line++) {
71                 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( cm.marceditor, line );
72                 if ( change.origin != 'setValue' && change.origin != 'marcWidgetPrefill' && change.origin != 'widget.clearToText' ) {
73                     cm.addLineClass( line, 'wrapper', 'modified-line' );
74                     editor.modified = true;
75                 }
76             }
77         }
78
79         Widget.ActivateAt( cm, cm.getCursor() );
80         cm.marceditor.startNotify();
81     }
82
83     function editorSetOverwriteMode( cm, newState ) {
84         var editor = cm.marceditor;
85
86         editor.overwriteMode = newState;
87     }
88
89     // Editor helper functions
90     function activateTabPosition( cm, pos, idx ) {
91         // Allow tabbing to as-yet-nonexistent positions
92         var lenDiff = pos.ch - cm.getLine( pos.line ).length;
93         if ( lenDiff > 0 ) {
94             var extra = '';
95             while ( lenDiff-- > 0 ) extra += ' ';
96             if ( pos.prefill ) extra += pos.prefill;
97             cm.replaceRange( extra, { line: pos.line } );
98         }
99
100         cm.setCursor( pos );
101         Widget.ActivateAt( cm, pos, idx );
102     }
103
104     function getTabPositions( editor, cur ) {
105         cur = cur || editor.cm.getCursor();
106         var field = editor.getFieldAt( cur.line );
107
108         if ( field ) {
109             if ( field.isControlField ) {
110                 var positions = [ { ch: 0 }, { ch: 4 } ];
111
112                 $.each( positions, function( undef, pos ) {
113                     pos.line = cur.line;
114                 } );
115
116                 return positions;
117             } else {
118                 var positions = [ { ch: 0 }, { ch: 4, prefill: '_' }, { ch: 6, prefill: '_' } ];
119
120                 $.each( positions, function( undef, pos ) {
121                     pos.line = cur.line;
122                 } );
123                 $.each( field.getSubfields(), function( undef, subfield ) {
124                     positions.push( { line: cur.line, ch: subfield.contentsStart } );
125                 } );
126
127                 // Allow to tab to start of empty field
128                 if ( field.getSubfields().length == 0 ) {
129                     positions.push( { line: cur.line, ch: 8 } );
130                 }
131
132                 return positions;
133             }
134         } else {
135             return [];
136         }
137     }
138     var _editorKeys = {};
139
140     _editorKeys[insert_copyright] =  function( cm ) {
141             cm.replaceRange( '©', cm.getCursor() );
142         }
143
144     _editorKeys[insert_copyright_sound] = function( cm ) {
145             cm.replaceRange( '℗', cm.getCursor() );
146         }
147
148     _editorKeys[new_line] = function( cm ) {
149             var cursor = cm.getCursor();
150             cm.replaceRange( '\n', { line: cursor.line }, null, 'marcAware' );
151             cm.setCursor( { line: cursor.line + 1, ch: 0 } );
152         }
153
154     _editorKeys[line_break] =  function( cm ) {
155             var cur = cm.getCursor();
156
157             cm.replaceRange( "\n", cur, null );
158         }
159
160     _editorKeys[delete_field] =  function( cm ) {
161             // Delete line (or cut)
162             if ( cm.somethingSelected() ) return true;
163
164             cm.execCommand('deleteLine');
165         }
166
167     _editorKeys[link_authorities] =  function( cm ) {
168             // Launch the auth search popup
169             var field = cm.marceditor.getCurrentField();
170
171             if ( !field ) return;
172             if ( authInfo[field.tag] == undefined ) return;
173             authtype = authInfo[field.tag].authtypecode;
174             index = 'tag_'+field.tag+'_rancor';
175             var mainmainstring = '';
176             if( field.getSubfields( authInfo[field.tag].subfield ).length != 0 ){
177                 mainmainstring += field.getSubfields( authInfo[field.tag].subfield )[0].text;
178             }
179
180             var subfields = field.getSubfields();
181             var mainstring= '';
182             for(i=0;i < subfields.length ;i++){
183                 if ( authInfo[field.tag].subfield == subfields[i].code ) continue;
184                 if( subfields[i].code == '9' ) continue;
185                 mainstring += subfields[i].text+' ';
186             }
187             newin=window.open("../authorities/auth_finder.pl?source=biblio&authtypecode="+authtype+"&index="+index+"&value_mainstr="+encodeURI(mainmainstring)+"&value_main="+encodeURI(mainstring), "_blank",'width=700,height=550,toolbar=false,scrollbars=yes');
188
189         }
190
191     _editorKeys[delete_subfield] = function( cm ) {
192             // Delete subfield
193             var field = cm.marceditor.getCurrentField();
194             if ( !field ) return;
195
196             var subfield = field.getSubfieldAt( cm.getCursor().ch );
197             if ( subfield ) subfield.delete();
198         }
199
200      _editorKeys[next_position] =  function( cm ) {
201             // Move through parts of tag/fixed fields
202             var positions = getTabPositions( cm.marceditor );
203             var cur = cm.getCursor();
204
205             for ( var i = 0; i < positions.length; i++ ) {
206                 if ( positions[i].ch > cur.ch ) {
207                     activateTabPosition( cm, positions[i] );
208                     return false;
209                 }
210             }
211
212             cm.setCursor( { line: cur.line + 1, ch: 0 } );
213         }
214
215     _editorKeys[prev_position] = function( cm ) {
216             // Move backwards through parts of tag/fixed fields
217             var positions = getTabPositions( cm.marceditor );
218             var cur = cm.getCursor();
219
220             for ( var i = positions.length - 1; i >= 0; i-- ) {
221                 if ( positions[i].ch < cur.ch ) {
222                     activateTabPosition( cm, positions[i], -1 );
223                     return false;
224                 }
225             }
226
227             if ( cur.line == 0 ) return;
228
229             var prevPositions = getTabPositions( cm.marceditor, { line: cur.line - 1, ch: cm.getLine( cur.line - 1 ).length } );
230
231             if ( prevPositions.length ) {
232                 activateTabPosition( cm, prevPositions[ prevPositions.length - 1 ], -1 );
233             } else {
234                 cm.setCursor( { line: cur.line - 1, ch: 0 } );
235             }
236         }
237
238     _editorKeys[insert_delimiter] = function(cm){
239         var cur = cm.getCursor();
240
241         cm.replaceRange( "‡", cur, null );
242     }
243
244     _editorKeys[toggle_keyboard] = function( cm ) {
245        let keyboard = $(cm.getInputField()).getkeyboard();
246        keyboard.isVisible()?keyboard.close():keyboard.reveal();
247     }
248
249     // The objects below are part of a field/subfield manipulation API, accessed through the base
250     // editor object.
251     //
252     // Each one is tied to a particular line; this means that using a field or subfield object after
253     // any other changes to the record will cause entertaining explosions. The objects are meant to
254     // be temporary, and should only be reused with great care. The macro code does this only
255     // because it is careful to dispose of the object after any other updates.
256     //
257     // Note, however, tha you can continue to use a field object after changing subfields. It's just
258     // the subfield objects that become invalid.
259
260     // This is an exception raised by the EditorSubfield and EditorField when an invalid change is
261     // attempted.
262     function FieldError(line, message) {
263         this.line = line;
264         this.message = message;
265     };
266
267     FieldError.prototype.toString = function() {
268         return 'FieldError(' + this.line + ', "' + this.message + '")';
269     };
270
271     // This is the temporary object for a particular subfield in a field. Any change to any other
272     // subfields will invalidate this subfield object.
273     function EditorSubfield( field, index, start, end ) {
274         this.field = field;
275         this.index = index;
276         this.start = start;
277         this.end = end;
278
279         if ( this.field.isControlField ) {
280             this.contentsStart = start;
281             this.code = '@';
282         } else {
283             this.contentsStart = start + 2;
284             this.code =  this.field.contents.substr( this.start + 1, 1 );
285         }
286
287         this.cm = field.cm;
288
289         var marks = this.cm.findMarksAt( { line: field.line, ch: this.contentsStart } );
290         if ( marks[0] && marks[0].widget ) {
291             this.widget = marks[0].widget;
292
293             this.text = this.widget.text;
294             this.setText = this.widget.setText;
295             this.getFixed = this.widget.getFixed;
296             this.setFixed = this.widget.setFixed;
297         } else {
298             this.widget = null;
299             this.text = this.field.contents.substr( this.contentsStart, end - this.contentsStart );
300         }
301     };
302
303     $.extend( EditorSubfield.prototype, {
304         _invalid: function() {
305             return this.field._subfieldsInvalid();
306         },
307
308         delete: function() {
309             this.cm.replaceRange( "", { line: this.field.line, ch: this.start }, { line: this.field.line, ch: this.end }, 'marcAware' );
310         },
311         focus: function() {
312             this.cm.setCursor( { line: this.field.line, ch: this.contentsStart } );
313         },
314         focusEnd: function() {
315             this.cm.setCursor( { line: this.field.line, ch: this.end } );
316         },
317         getText: function() {
318             return this.text;
319         },
320         setText: function( text ) {
321             if ( !this._invalid() ) throw new FieldError( this.field.line, 'subfield invalid' );
322             this.cm.replaceRange( text, { line: this.field.line, ch: this.contentsStart }, { line: this.field.line, ch: this.end }, 'marcAware' );
323             this.field._invalidateSubfields();
324         },
325     } );
326
327     function EditorField( editor, line ) {
328         this.editor = editor;
329         this.line = line;
330
331         this.cm = editor.cm;
332
333         this._updateInfo();
334         this.tag = this.contents.substr( 0, 3 );
335         this.isControlField = ( this.tag < '010' );
336
337         if ( this.isControlField ) {
338             this._ind1 = this.contents.substr( 4, 1 );
339             this._ind2 = this.contents.substr( 6, 1 );
340         } else {
341             this._ind1 = null;
342             this._ind2 = null;
343         }
344
345         this.subfields = null;
346     }
347
348     $.extend( EditorField.prototype, {
349         _subfieldsInvalid: function() {
350             return !this.subfields;
351         },
352         _invalidateSubfields: function() {
353             this._subfields = null;
354         },
355
356         _updateInfo: function() {
357             this.info = this.editor.getLineInfo( { line: this.line, ch: 0 } );
358             if ( this.info == null ) throw new FieldError( 'Invalid field' );
359             this.contents = this.info.contents;
360         },
361         _scanSubfields: function() {
362             this._updateInfo();
363
364             if ( this.isControlField ) {
365                 this._subfields = [ new EditorSubfield( this, 0, 4, this.contents.length ) ];
366             } else {
367                 var field = this;
368                 var subfields = this.info.subfields;
369                 this._subfields = [];
370
371                 for (var i = 0; i < this.info.subfields.length; i++) {
372                     var end = i == subfields.length - 1 ? this.contents.length : subfields[i+1].ch;
373
374                     this._subfields.push( new EditorSubfield( this, i, subfields[i].ch, end ) );
375                 }
376             }
377         },
378
379         delete: function() {
380             this.cm.replaceRange( "", { line: this.line, ch: 0 }, { line: this.line + 1, ch: 0 }, 'marcAware' );
381         },
382         focus: function() {
383             this.cm.setCursor( { line: this.line, ch: 0 } );
384
385             return this;
386         },
387
388         getText: function() {
389             var result = '';
390
391             $.each( this.getSubfields(), function() {
392                 if ( this.code != '@' ) result += '‡' + this.code;
393
394                 result += this.getText();
395             } );
396
397             return result;
398         },
399         setText: function( text ) {
400             var indicator_match = /^([_ 0-9])([_ 0-9])\‡/.exec( text );
401             if ( indicator_match ) {
402                 text = text.substr(2);
403                 this.setIndicator1( indicator_match[1] );
404                 this.setIndicator2( indicator_match[2] );
405             }
406
407             this.cm.replaceRange( text, { line: this.line, ch: this.isControlField ? 4 : 8 }, { line: this.line }, 'marcAware' );
408             this._invalidateSubfields();
409
410             return this;
411         },
412
413         getIndicator1: function() {
414             return this._ind1;
415         },
416         getIndicator2: function() {
417             return this._ind2;
418         },
419         setIndicator1: function(val) {
420             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
421
422             this._ind1 = ( !val || val == ' ' ) ? '_' : val;
423             this.cm.replaceRange( this._ind1, { line: this.line, ch: 4 }, { line: this.line, ch: 5 }, 'marcAware' );
424
425             return this;
426         },
427         setIndicator2: function(val) {
428             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
429
430             this._ind2 = ( !val || val == ' ' ) ? '_' : val;
431             this.cm.replaceRange( this._ind2, { line: this.line, ch: 6 }, { line: this.line, ch: 7 }, 'marcAware' );
432
433             return this;
434         },
435
436         appendSubfield: function( code ) {
437             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
438
439             this._invalidateSubfields();
440             this.cm.replaceRange( '‡' + code, { line: this.line }, null, 'marcAware' );
441             var subfields = this.getSubfields();
442
443             return subfields[ subfields.length - 1 ];
444         },
445         insertSubfield: function( code, position ) {
446             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
447
448             position = position || 0;
449
450             var subfields = this.getSubfields();
451             this._invalidateSubfields();
452             this.cm.replaceRange( '‡' + code, { line: this.line, ch: subfields[position] ? subfields[position].start : null }, null, 'marcAware' );
453             subfields = this.getSubfields();
454
455             return subfields[ position ];
456         },
457         getSubfields: function( code ) {
458             if ( !this._subfields ) this._scanSubfields();
459             if ( code == null ) return this._subfields;
460
461             var result = [];
462
463             $.each( this._subfields, function() {
464                 if ( code == null || this.code == code ) result.push(this);
465             } );
466
467             return result;
468         },
469         getFirstSubfield: function( code ) {
470             var result = this.getSubfields( code );
471
472             return ( result && result.length ) ? result[0] : null;
473         },
474         getSubfieldAt: function( ch ) {
475             var subfields = this.getSubfields();
476
477             for (var i = 0; i < subfields.length; i++) {
478                 if ( subfields[i].start < ch && subfields[i].end >= ch ) return subfields[i];
479             }
480         },
481     } );
482
483     function MARCEditor( options ) {
484         this.frameworkcode = '';
485
486         this.cm = CodeMirror(
487             options.position,
488             {
489                 extraKeys: _editorKeys,
490                 gutters: [
491                     'modified-line-gutter',
492                 ],
493                 lineWrapping: true,
494                 mode: {
495                     name: 'marc',
496                     nonRepeatableTags: KohaBackend.GetTagsBy( '', 'repeatable', '0' ),
497                     nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' )
498                 }
499             }
500         );
501         var inf = this.cm.getInputField();
502         var self = this;
503         var kb = $(inf).keyboard({
504             //keyBinding: "mousedown touchstart",
505             usePreview: false,
506             lockInput: false,
507             autoAccept: true,
508             autoAcceptOnEsc: true,
509             userClosed: true,
510             //alwaysOpen: true,
511             openOn : '',
512             position: {
513               of: $("#statusbar"), // optional - null (attach to input/textarea) or a jQuery object (attach elsewhere)
514               my: 'center top',
515               at: 'center bottom',
516               at2: 'center bottom' // used when "usePreview" is false (centers keyboard at bottom of the input/textarea)
517             },
518             beforeInsert: function(evnt, keyboard, elem, txt) {
519               var position = self.cm.getCursor();
520               if (txt === "\b") {
521                 self.cm.execCommand("delCharBefore");
522               }
523               if (txt === "\b" && position.ch === 0 && position.line !== 0) {
524                 elem.value = self.cm.getLine(position.line) || "";
525                 txt = "";
526               }
527               return txt;
528             },
529             visible: function() {
530                 $('#set-keyboard-layout').removeClass('hide');
531             },
532             hidden: function(e, keyboard, el, accepted) {
533                 inf.focus();
534                 $('#set-keyboard-layout').addClass('hide');
535             }
536           }).getkeyboard();
537
538
539         Object.keys($.keyboard.layouts).forEach(function(layout) {
540             var div = $('#keyboard-layout .layouts').append('<div class="layout" data-layout="'+layout+'" data-name="'+($.keyboard.layouts[layout].name||layout)+'" >'+($.keyboard.layouts[layout].name||layout)+'</div>')
541             if(kb.layout == layout) {
542                 div.addClass('active');
543             }
544         });
545         $('#keyboard-layout')
546             .on('show.bs.modal', function() {
547                 kb.close();
548                 $('#keyboard-layout .filter').focus();
549                 $('#set-keyboard-layout').removeClass('hide');
550             })
551             .on('hide.bs.modal', function() {
552                 !kb.isVisible() && kb.reveal();
553             });
554         $('#keyboard-layout .layout').click(function(event) {
555             $('#keyboard-layout .layout').removeClass('active');
556             $(this).addClass('active');
557             var layout = $(this).data().layout;
558             kb.redraw(layout);
559             $('#keyboard-layout').modal('hide');
560             $('#keyboard-layout .filter').val('');
561             $('#keyboard-layout .layout').show();
562         });
563         $('#keyboard-layout .filter').keyup(function() {
564             var val = $(this).val();
565             if(!val||!val.length) return $('#keyboard-layout .layout').show();
566             var filter = new RegExp(val, 'i');
567             $('#keyboard-layout .layout').hide();
568             $('#keyboard-layout .layout').each(function() {
569                 var name = $(this).data().name;
570                 if(filter.test(name)) $(this).show();
571             })
572         });
573
574         this.cm.marceditor = this;
575
576         this.cm.on( 'beforeChange', editorBeforeChange );
577         this.cm.on( 'changes', editorChanges );
578         this.cm.on( 'cursorActivity', editorCursorActivity );
579         this.cm.on( 'overwriteToggle', editorSetOverwriteMode );
580
581         this.onCursorActivity = options.onCursorActivity;
582
583         this.subscribers = [];
584         this.subscribe( function( marceditor ) {
585             Widget.Notify( marceditor );
586         } );
587     }
588
589     MARCEditor.FieldError = FieldError;
590
591     $.extend( MARCEditor.prototype, {
592         setUseWidgets: function( val ) {
593             if ( val ) {
594                 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
595                     Widget.UpdateLine( this, line );
596                 }
597             } else {
598                 $.each( this.cm.getAllMarks(), function( undef, mark ) {
599                     if ( mark.widget ) mark.widget.clearToText();
600                 } );
601             }
602         },
603
604         focus: function() {
605             this.cm.focus();
606         },
607
608         getCursor: function() {
609             return this.cm.getCursor();
610         },
611
612         refresh: function() {
613             this.cm.refresh();
614         },
615
616         setFrameworkCode: function( code, updateFields, callback ) {
617             this.frameworkcode = code;
618             $( 'a.change-framework i.selected' ).addClass( 'hidden' );
619             $( 'a.change-framework i.unselected' ).removeClass( 'hidden' );
620             $( 'a.change-framework[data-frameworkcode="' + code + '"] i.unselected' ).addClass( 'hidden' );
621             $( 'a.change-framework[data-frameworkcode="' + code + '"] i.selected' ).removeClass( 'hidden ');
622             var cm = this.cm;
623             KohaBackend.InitFramework( code, function ( error ) {
624                 cm.setOption( 'mode', {
625                     name: 'marc',
626                     nonRepeatableTags: KohaBackend.GetTagsBy( code, 'repeatable', '0' ),
627                     nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( code, 'repeatable', '0' )
628                 });
629                 if ( updateFields ) {
630                     var record = TextMARC.TextToRecord( cm.getValue() );
631                     KohaBackend.FillRecord( code, record );
632                     cm.setValue( TextMARC.RecordToText(record) );
633                 }
634                 callback( error );
635             } );
636         },
637
638         displayRecord: function( record ) {
639             this.cm.setValue( TextMARC.RecordToText(record) );
640             this.modified = false;
641             this.setFrameworkCode(
642                 typeof record.frameworkcode !== 'undefined' ? record.frameworkcode : '',
643                 false,
644                 function ( error ) {
645                     if ( typeof error !== 'undefined' ) {
646                         humanMsg.displayAlert( _(error), { className: 'humanError' } );
647                     }
648                 }
649             );
650         },
651
652         getRecord: function() {
653             this.textMode = true;
654
655             $.each( this.cm.getAllMarks(), function( undef, mark ) {
656                 if ( mark.widget ) mark.widget.clearToText();
657             } );
658             var record = TextMARC.TextToRecord( this.cm.getValue() );
659             for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
660                 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( this, line );
661             }
662
663             this.textMode = false;
664
665             record.frameworkcode = this.frameworkcode;
666             return record;
667         },
668
669         getLineInfo: function( pos ) {
670             var contents = this.cm.getLine( pos.line );
671             if ( contents == null ) return {};
672
673             var tagNumber = contents.match( /^([A-Za-z0-9]{3})/ );
674
675             if ( !tagNumber ) return null; // No tag at all on this line
676             tagNumber = tagNumber[1];
677
678             if ( tagNumber < '010' ) return { tagNumber: tagNumber, contents: contents }; // No current subfield
679
680             var matcher = /‡([a-z0-9%])/g;
681             var match;
682
683             var subfields = [];
684             var currentSubfield;
685
686             while ( ( match = matcher.exec(contents) ) ) {
687                 subfields.push( { code: match[1], ch: match.index } );
688                 if ( match.index < pos.ch ) currentSubfield = match[1];
689             }
690
691             return { tagNumber: tagNumber, subfields: subfields, currentSubfield: currentSubfield, contents: contents };
692         },
693
694         addError: function( line, error ) {
695             var found = false;
696             var options = {};
697
698             if ( line == null ) {
699                 line = 0;
700                 options.above = true;
701             }
702
703             $.each( this.cm.getLineHandle(line).widgets || [], function( undef, widget ) {
704                 if ( !widget.isErrorMarker ) return;
705
706                 found = true;
707
708                 $( widget.node ).append( '; ' + error );
709                 widget.changed();
710
711                 return false;
712             } );
713
714             if ( found ) return;
715
716             var node = $( '<div class="structure-error"><i class="fa fa-remove"></i> ' + error + '</div>' )[0];
717             var widget = this.cm.addLineWidget( line, node, options );
718
719             widget.node = node;
720             widget.isErrorMarker = true;
721         },
722
723         removeErrors: function() {
724             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
725                 $.each( this.cm.getLineHandle( line ).widgets || [], function( undef, lineWidget ) {
726                     if ( lineWidget.isErrorMarker ) lineWidget.clear();
727                 } );
728             }
729         },
730
731         startNotify: function() {
732             if ( this.notifyTimeout ) clearTimeout( this.notifyTimeout );
733             this.notifyTimeout = setTimeout( $.proxy( function() {
734                 this.notifyAll();
735
736                 this.notifyTimeout = null;
737             }, this ), NOTIFY_TIMEOUT );
738         },
739
740         notifyAll: function() {
741             $.each( this.subscribers, $.proxy( function( undef, subscriber ) {
742                 subscriber(this);
743             }, this ) );
744         },
745
746         subscribe: function( subscriber ) {
747             this.subscribers.push( subscriber );
748         },
749
750         createField: function( tag, line ) {
751             var contents = tag + ( tag < '010' ? ' ' : ' _ _ ' );
752
753             if ( line > this.cm.lastLine() ) {
754                 contents = '\n' + contents;
755             } else {
756                 contents = contents + '\n';
757             }
758
759             this.cm.replaceRange( contents, { line: line, ch: 0 }, null, 'marcAware' );
760
761             return new EditorField( this, line );
762         },
763
764         createFieldOrdered: function( tag ) {
765             var line, contents;
766
767             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
768                 if ( contents && contents.substr(0, 3) > tag ) break;
769             }
770
771             return this.createField( tag, line );
772         },
773
774         createFieldGrouped: function( tag ) {
775             // Control fields should be inserted in actual order, whereas other fields should be
776             // inserted grouped
777             if ( tag < '010' ) return this.createFieldOrdered( tag );
778
779             var line, contents;
780
781             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
782                 if ( contents && contents[0] > tag[0] ) break;
783             }
784
785             return this.createField( tag, line );
786         },
787
788         getFieldAt: function( line ) {
789             try {
790                 return new EditorField( this, line );
791             } catch (e) {
792                 return null;
793             }
794         },
795
796         getCurrentField: function() {
797             return this.getFieldAt( this.cm.getCursor().line );
798         },
799
800         getFields: function( tag ) {
801             var result = [];
802
803             if ( tag != null ) tag += ' ';
804
805             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
806                 if ( tag && this.cm.getLine(line).substr( 0, 4 ) != tag ) continue;
807
808                 // If this throws a FieldError, pretend it doesn't exist
809                 try {
810                     result.push( new EditorField( this, line ) );
811                 } catch (e) {
812                     if ( !( e instanceof FieldError ) ) throw e;
813                 }
814             }
815
816             return result;
817         },
818
819         getFirstField: function( tag ) {
820             var result = this.getFields( tag );
821
822             return ( result && result.length ) ? result[0] : null;
823         },
824
825         getAllFields: function( tag ) {
826             return this.getFields( null );
827         },
828     } );
829
830     return MARCEditor;
831 } );