Bug 16424: Add framework support to advanced MARC 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
139     var _editorKeys = {
140         'Alt-C': function( cm ) {
141             cm.replaceRange( '©', cm.getCursor() );
142         },
143
144         'Alt-P': function( cm ) {
145             cm.replaceRange( '℗', cm.getCursor() );
146         },
147
148         Enter: 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         'Shift-Enter': function( cm ) {
155             var cur = cm.getCursor();
156
157             cm.replaceRange( "\n", cur, null );
158         },
159
160         'Ctrl-X': function( cm ) {
161             // Delete line (or cut)
162             if ( cm.somethingSelected() ) return true;
163
164             cm.execCommand('deleteLine');
165         },
166
167         'Shift-Ctrl-L': 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         'Shift-Ctrl-X': 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         Tab: 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         'Shift-Tab': 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         'Ctrl-D': function( cm ) {
239             // Insert subfield delimiter
240             var cur = cm.getCursor();
241
242             cm.replaceRange( "‡", cur, null );
243         },
244     };
245
246     // The objects below are part of a field/subfield manipulation API, accessed through the base
247     // editor object.
248     //
249     // Each one is tied to a particular line; this means that using a field or subfield object after
250     // any other changes to the record will cause entertaining explosions. The objects are meant to
251     // be temporary, and should only be reused with great care. The macro code does this only
252     // because it is careful to dispose of the object after any other updates.
253     //
254     // Note, however, tha you can continue to use a field object after changing subfields. It's just
255     // the subfield objects that become invalid.
256
257     // This is an exception raised by the EditorSubfield and EditorField when an invalid change is
258     // attempted.
259     function FieldError(line, message) {
260         this.line = line;
261         this.message = message;
262     };
263
264     FieldError.prototype.toString = function() {
265         return 'FieldError(' + this.line + ', "' + this.message + '")';
266     };
267
268     // This is the temporary object for a particular subfield in a field. Any change to any other
269     // subfields will invalidate this subfield object.
270     function EditorSubfield( field, index, start, end ) {
271         this.field = field;
272         this.index = index;
273         this.start = start;
274         this.end = end;
275
276         if ( this.field.isControlField ) {
277             this.contentsStart = start;
278             this.code = '@';
279         } else {
280             this.contentsStart = start + 2;
281             this.code =  this.field.contents.substr( this.start + 1, 1 );
282         }
283
284         this.cm = field.cm;
285
286         var marks = this.cm.findMarksAt( { line: field.line, ch: this.contentsStart } );
287         if ( marks[0] && marks[0].widget ) {
288             this.widget = marks[0].widget;
289
290             this.text = this.widget.text;
291             this.setText = this.widget.setText;
292             this.getFixed = this.widget.getFixed;
293             this.setFixed = this.widget.setFixed;
294         } else {
295             this.widget = null;
296             this.text = this.field.contents.substr( this.contentsStart, end - this.contentsStart );
297         }
298     };
299
300     $.extend( EditorSubfield.prototype, {
301         _invalid: function() {
302             return this.field._subfieldsInvalid();
303         },
304
305         delete: function() {
306             this.cm.replaceRange( "", { line: this.field.line, ch: this.start }, { line: this.field.line, ch: this.end }, 'marcAware' );
307         },
308         focus: function() {
309             this.cm.setCursor( { line: this.field.line, ch: this.contentsStart } );
310         },
311         focusEnd: function() {
312             this.cm.setCursor( { line: this.field.line, ch: this.end } );
313         },
314         getText: function() {
315             return this.text;
316         },
317         setText: function( text ) {
318             if ( !this._invalid() ) throw new FieldError( this.field.line, 'subfield invalid' );
319             this.cm.replaceRange( text, { line: this.field.line, ch: this.contentsStart }, { line: this.field.line, ch: this.end }, 'marcAware' );
320             this.field._invalidateSubfields();
321         },
322     } );
323
324     function EditorField( editor, line ) {
325         this.editor = editor;
326         this.line = line;
327
328         this.cm = editor.cm;
329
330         this._updateInfo();
331         this.tag = this.contents.substr( 0, 3 );
332         this.isControlField = ( this.tag < '010' );
333
334         if ( this.isControlField ) {
335             this._ind1 = this.contents.substr( 4, 1 );
336             this._ind2 = this.contents.substr( 6, 1 );
337         } else {
338             this._ind1 = null;
339             this._ind2 = null;
340         }
341
342         this.subfields = null;
343     }
344
345     $.extend( EditorField.prototype, {
346         _subfieldsInvalid: function() {
347             return !this.subfields;
348         },
349         _invalidateSubfields: function() {
350             this._subfields = null;
351         },
352
353         _updateInfo: function() {
354             this.info = this.editor.getLineInfo( { line: this.line, ch: 0 } );
355             if ( this.info == null ) throw new FieldError( 'Invalid field' );
356             this.contents = this.info.contents;
357         },
358         _scanSubfields: function() {
359             this._updateInfo();
360
361             if ( this.isControlField ) {
362                 this._subfields = [ new EditorSubfield( this, 0, 4, this.contents.length ) ];
363             } else {
364                 var field = this;
365                 var subfields = this.info.subfields;
366                 this._subfields = [];
367
368                 for (var i = 0; i < this.info.subfields.length; i++) {
369                     var end = i == subfields.length - 1 ? this.contents.length : subfields[i+1].ch;
370
371                     this._subfields.push( new EditorSubfield( this, i, subfields[i].ch, end ) );
372                 }
373             }
374         },
375
376         delete: function() {
377             this.cm.replaceRange( "", { line: this.line, ch: 0 }, { line: this.line + 1, ch: 0 }, 'marcAware' );
378         },
379         focus: function() {
380             this.cm.setCursor( { line: this.line, ch: 0 } );
381
382             return this;
383         },
384
385         getText: function() {
386             var result = '';
387
388             $.each( this.getSubfields(), function() {
389                 if ( this.code != '@' ) result += '‡' + this.code;
390
391                 result += this.getText();
392             } );
393
394             return result;
395         },
396         setText: function( text ) {
397             var indicator_match = /^([_ 0-9])([_ 0-9])\‡/.exec( text );
398             if ( indicator_match ) {
399                 text = text.substr(2);
400                 this.setIndicator1( indicator_match[1] );
401                 this.setIndicator2( indicator_match[2] );
402             }
403
404             this.cm.replaceRange( text, { line: this.line, ch: this.isControlField ? 4 : 8 }, { line: this.line }, 'marcAware' );
405             this._invalidateSubfields();
406
407             return this;
408         },
409
410         getIndicator1: function() {
411             return this._ind1;
412         },
413         getIndicator2: function() {
414             return this._ind2;
415         },
416         setIndicator1: function(val) {
417             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
418
419             this._ind1 = ( !val || val == ' ' ) ? '_' : val;
420             this.cm.replaceRange( this._ind1, { line: this.line, ch: 4 }, { line: this.line, ch: 5 }, 'marcAware' );
421
422             return this;
423         },
424         setIndicator2: function(val) {
425             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
426
427             this._ind2 = ( !val || val == ' ' ) ? '_' : val;
428             this.cm.replaceRange( this._ind2, { line: this.line, ch: 6 }, { line: this.line, ch: 7 }, 'marcAware' );
429
430             return this;
431         },
432
433         appendSubfield: function( code ) {
434             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
435
436             this._invalidateSubfields();
437             this.cm.replaceRange( '‡' + code, { line: this.line }, null, 'marcAware' );
438             var subfields = this.getSubfields();
439
440             return subfields[ subfields.length - 1 ];
441         },
442         insertSubfield: function( code, position ) {
443             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
444
445             position = position || 0;
446
447             var subfields = this.getSubfields();
448             this._invalidateSubfields();
449             this.cm.replaceRange( '‡' + code, { line: this.line, ch: subfields[position] ? subfields[position].start : null }, null, 'marcAware' );
450             subfields = this.getSubfields();
451
452             return subfields[ position ];
453         },
454         getSubfields: function( code ) {
455             if ( !this._subfields ) this._scanSubfields();
456             if ( code == null ) return this._subfields;
457
458             var result = [];
459
460             $.each( this._subfields, function() {
461                 if ( code == null || this.code == code ) result.push(this);
462             } );
463
464             return result;
465         },
466         getFirstSubfield: function( code ) {
467             var result = this.getSubfields( code );
468
469             return ( result && result.length ) ? result[0] : null;
470         },
471         getSubfieldAt: function( ch ) {
472             var subfields = this.getSubfields();
473
474             for (var i = 0; i < subfields.length; i++) {
475                 if ( subfields[i].start < ch && subfields[i].end >= ch ) return subfields[i];
476             }
477         },
478     } );
479
480     function MARCEditor( options ) {
481         this.frameworkcode = '';
482
483         this.cm = CodeMirror(
484             options.position,
485             {
486                 extraKeys: _editorKeys,
487                 gutters: [
488                     'modified-line-gutter',
489                 ],
490                 lineWrapping: true,
491                 mode: {
492                     name: 'marc',
493                     nonRepeatableTags: KohaBackend.GetTagsBy( '', 'repeatable', '0' ),
494                     nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' )
495                 }
496             }
497         );
498         this.cm.marceditor = this;
499
500         this.cm.on( 'beforeChange', editorBeforeChange );
501         this.cm.on( 'changes', editorChanges );
502         this.cm.on( 'cursorActivity', editorCursorActivity );
503         this.cm.on( 'overwriteToggle', editorSetOverwriteMode );
504
505         this.onCursorActivity = options.onCursorActivity;
506
507         this.subscribers = [];
508         this.subscribe( function( marceditor ) {
509             Widget.Notify( marceditor );
510         } );
511     }
512
513     MARCEditor.FieldError = FieldError;
514
515     $.extend( MARCEditor.prototype, {
516         setUseWidgets: function( val ) {
517             if ( val ) {
518                 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
519                     Widget.UpdateLine( this, line );
520                 }
521             } else {
522                 $.each( this.cm.getAllMarks(), function( undef, mark ) {
523                     if ( mark.widget ) mark.widget.clearToText();
524                 } );
525             }
526         },
527
528         focus: function() {
529             this.cm.focus();
530         },
531
532         getCursor: function() {
533             return this.cm.getCursor();
534         },
535
536         refresh: function() {
537             this.cm.refresh();
538         },
539
540         setFrameworkCode: function( code, callback ) {
541             this.frameworkcode = code;
542             $( 'a.change-framework i.selected' ).addClass( 'hidden' );
543             $( 'a.change-framework i.unselected' ).removeClass( 'hidden' );
544             $( 'a.change-framework[data-frameworkcode="' + code + '"] i.unselected' ).addClass( 'hidden' );
545             $( 'a.change-framework[data-frameworkcode="' + code + '"] i.selected' ).removeClass( 'hidden ');
546             KohaBackend.InitFramework( code, callback );
547         },
548
549         displayRecord: function( record ) {
550             this.cm.setValue( TextMARC.RecordToText(record) );
551             this.modified = false;
552             var cm = this.cm;
553             this.setFrameworkCode(
554                 typeof record.frameworkcode !== 'undefined' ? record.frameworkcode : '',
555                 function ( error ) {
556                     if ( typeof error !== 'undefined' ) {
557                         humanMsg.displayAlert( _(error), { className: 'humanError' } );
558                     }
559                     cm.setOption( 'mode', {
560                         name: 'marc',
561                         nonRepeatableTags: KohaBackend.GetTagsBy( this.frameworkcode, 'repeatable', '0' ),
562                         nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( this.frameworkcode, 'repeatable', '0' )
563                     });
564                 }
565             );
566         },
567
568         getRecord: function() {
569             this.textMode = true;
570
571             $.each( this.cm.getAllMarks(), function( undef, mark ) {
572                 if ( mark.widget ) mark.widget.clearToText();
573             } );
574             var record = TextMARC.TextToRecord( this.cm.getValue() );
575             for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
576                 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( this, line );
577             }
578
579             this.textMode = false;
580
581             record.frameworkcode = this.frameworkcode;
582             return record;
583         },
584
585         getLineInfo: function( pos ) {
586             var contents = this.cm.getLine( pos.line );
587             if ( contents == null ) return {};
588
589             var tagNumber = contents.match( /^([A-Za-z0-9]{3})/ );
590
591             if ( !tagNumber ) return null; // No tag at all on this line
592             tagNumber = tagNumber[1];
593
594             if ( tagNumber < '010' ) return { tagNumber: tagNumber, contents: contents }; // No current subfield
595
596             var matcher = /‡([a-z0-9%])/g;
597             var match;
598
599             var subfields = [];
600             var currentSubfield;
601
602             while ( ( match = matcher.exec(contents) ) ) {
603                 subfields.push( { code: match[1], ch: match.index } );
604                 if ( match.index < pos.ch ) currentSubfield = match[1];
605             }
606
607             return { tagNumber: tagNumber, subfields: subfields, currentSubfield: currentSubfield, contents: contents };
608         },
609
610         addError: function( line, error ) {
611             var found = false;
612             var options = {};
613
614             if ( line == null ) {
615                 line = 0;
616                 options.above = true;
617             }
618
619             $.each( this.cm.getLineHandle(line).widgets || [], function( undef, widget ) {
620                 if ( !widget.isErrorMarker ) return;
621
622                 found = true;
623
624                 $( widget.node ).append( '; ' + error );
625                 widget.changed();
626
627                 return false;
628             } );
629
630             if ( found ) return;
631
632             var node = $( '<div class="structure-error"><i class="fa fa-remove"></i> ' + error + '</div>' )[0];
633             var widget = this.cm.addLineWidget( line, node, options );
634
635             widget.node = node;
636             widget.isErrorMarker = true;
637         },
638
639         removeErrors: function() {
640             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
641                 $.each( this.cm.getLineHandle( line ).widgets || [], function( undef, lineWidget ) {
642                     if ( lineWidget.isErrorMarker ) lineWidget.clear();
643                 } );
644             }
645         },
646
647         startNotify: function() {
648             if ( this.notifyTimeout ) clearTimeout( this.notifyTimeout );
649             this.notifyTimeout = setTimeout( $.proxy( function() {
650                 this.notifyAll();
651
652                 this.notifyTimeout = null;
653             }, this ), NOTIFY_TIMEOUT );
654         },
655
656         notifyAll: function() {
657             $.each( this.subscribers, $.proxy( function( undef, subscriber ) {
658                 subscriber(this);
659             }, this ) );
660         },
661
662         subscribe: function( subscriber ) {
663             this.subscribers.push( subscriber );
664         },
665
666         createField: function( tag, line ) {
667             var contents = tag + ( tag < '010' ? ' ' : ' _ _ ' );
668
669             if ( line > this.cm.lastLine() ) {
670                 contents = '\n' + contents;
671             } else {
672                 contents = contents + '\n';
673             }
674
675             this.cm.replaceRange( contents, { line: line, ch: 0 }, null, 'marcAware' );
676
677             return new EditorField( this, line );
678         },
679
680         createFieldOrdered: function( tag ) {
681             var line, contents;
682
683             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
684                 if ( contents && contents.substr(0, 3) > tag ) break;
685             }
686
687             return this.createField( tag, line );
688         },
689
690         createFieldGrouped: function( tag ) {
691             // Control fields should be inserted in actual order, whereas other fields should be
692             // inserted grouped
693             if ( tag < '010' ) return this.createFieldOrdered( tag );
694
695             var line, contents;
696
697             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
698                 if ( contents && contents[0] > tag[0] ) break;
699             }
700
701             return this.createField( tag, line );
702         },
703
704         getFieldAt: function( line ) {
705             try {
706                 return new EditorField( this, line );
707             } catch (e) {
708                 return null;
709             }
710         },
711
712         getCurrentField: function() {
713             return this.getFieldAt( this.cm.getCursor().line );
714         },
715
716         getFields: function( tag ) {
717             var result = [];
718
719             if ( tag != null ) tag += ' ';
720
721             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
722                 if ( tag && this.cm.getLine(line).substr( 0, 4 ) != tag ) continue;
723
724                 // If this throws a FieldError, pretend it doesn't exist
725                 try {
726                     result.push( new EditorField( this, line ) );
727                 } catch (e) {
728                     if ( !( e instanceof FieldError ) ) throw e;
729                 }
730             }
731
732             return result;
733         },
734
735         getFirstField: function( tag ) {
736             var result = this.getFields( tag );
737
738             return ( result && result.length ) ? result[0] : null;
739         },
740
741         getAllFields: function( tag ) {
742             return this.getFields( null );
743         },
744     } );
745
746     return MARCEditor;
747 } );