Bug 17179: Add keyboard shortcuts to repeat (duplicate) a field, and cut text
[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             var curLine = cm.getLine( cm.getCursor().line );
164
165             $("#clipboard").prepend('<option>'+curLine+'</option>');
166
167             cm.execCommand('deleteLine');
168         }
169
170     _editorKeys[link_authorities] =  function( cm ) {
171             // Launch the auth search popup
172             var field = cm.marceditor.getCurrentField();
173
174             if ( !field ) return;
175             if ( authInfo[field.tag] == undefined ) return;
176             authtype = authInfo[field.tag].authtypecode;
177             index = 'tag_'+field.tag+'_rancor';
178             var mainmainstring = '';
179             if( field.getSubfields( authInfo[field.tag].subfield ).length != 0 ){
180                 mainmainstring += field.getSubfields( authInfo[field.tag].subfield )[0].text;
181             }
182
183             var subfields = field.getSubfields();
184             var mainstring= '';
185             for(i=0;i < subfields.length ;i++){
186                 if ( authInfo[field.tag].subfield == subfields[i].code ) continue;
187                 if( subfields[i].code == '9' ) continue;
188                 mainstring += subfields[i].text+' ';
189             }
190             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');
191
192         }
193
194     _editorKeys[delete_subfield] = function( cm ) {
195             // Delete subfield
196             var field = cm.marceditor.getCurrentField();
197             if ( !field ) return;
198
199             var curCursor = cm.getCursor();
200             var subfield = field.getSubfieldAt( curCursor().ch );
201             var subfieldText= cm.getRange({line:curCursor.line,ch:subfield.start},{line:curCursor.line,ch:subfield.end});
202             if ( subfield ) {
203                 $("#clipboard").prepend('<option>'+subfieldText+'</option>');
204                 subfield.delete();
205             }
206         }
207
208     _editorKeys[copy_line] = function( cm ) {
209             // Copy line
210             if ( cm.somethingSelected() ) return true;
211             var curLine = cm.getLine( cm.getCursor().line );
212             $("#clipboard").prepend('<option>'+curLine+'</option>');
213         }
214
215     _editorKeys[copy_subfield] = function( cm ) {
216             // Copy subfield
217             var field = cm.marceditor.getCurrentField();
218             if ( !field ) return;
219
220             var curCursor = cm.getCursor();
221             var subfield = field.getSubfieldAt( curCursor().ch );
222             var subfieldText= cm.getRange({line:curCursor.line,ch:subfield.start},{line:curCursor.line,ch:subfield.end});
223             if ( subfield ) {
224                 $("#clipboard").prepend('<option>'+subfieldText+'</option>');
225             }
226         }
227
228     _editorKeys[paste_line] = function( cm ) {
229             // Paste line from "clipboard"
230             if ( cm.somethingSelected() ) return true;
231             var cBoard = document.getElementById("clipboard");
232             var strUser = cBoard.options[cBoard.selectedIndex].text;
233             cm.replaceRange( strUser, cm.getCursor(), null );
234         }
235
236     _editorKeys[insert_line] = function( cm ) {
237             // Copy line and insert below
238             if ( cm.somethingSelected() ) return true;
239             var curLine = cm.getLine( cm.getCursor().line );
240             cm.execCommand('newlineAndIndent');
241             cm.replaceRange( curLine, cm.getCursor(), null );
242         }
243
244      _editorKeys[next_position] =  function( cm ) {
245             // Move through parts of tag/fixed fields
246             var positions = getTabPositions( cm.marceditor );
247             var cur = cm.getCursor();
248
249             for ( var i = 0; i < positions.length; i++ ) {
250                 if ( positions[i].ch > cur.ch ) {
251                     activateTabPosition( cm, positions[i] );
252                     return false;
253                 }
254             }
255
256             cm.setCursor( { line: cur.line + 1, ch: 0 } );
257         }
258
259     _editorKeys[prev_position] = function( cm ) {
260             // Move backwards through parts of tag/fixed fields
261             var positions = getTabPositions( cm.marceditor );
262             var cur = cm.getCursor();
263
264             for ( var i = positions.length - 1; i >= 0; i-- ) {
265                 if ( positions[i].ch < cur.ch ) {
266                     activateTabPosition( cm, positions[i], -1 );
267                     return false;
268                 }
269             }
270
271             if ( cur.line == 0 ) return;
272
273             var prevPositions = getTabPositions( cm.marceditor, { line: cur.line - 1, ch: cm.getLine( cur.line - 1 ).length } );
274
275             if ( prevPositions.length ) {
276                 activateTabPosition( cm, prevPositions[ prevPositions.length - 1 ], -1 );
277             } else {
278                 cm.setCursor( { line: cur.line - 1, ch: 0 } );
279             }
280         }
281
282     _editorKeys[insert_delimiter] = function(cm){
283         var cur = cm.getCursor();
284
285         cm.replaceRange( "‡", cur, null );
286     }
287
288     _editorKeys[toggle_keyboard] = function( cm ) {
289        let keyboard = $(cm.getInputField()).getkeyboard();
290        keyboard.isVisible()?keyboard.close():keyboard.reveal();
291     }
292
293     // The objects below are part of a field/subfield manipulation API, accessed through the base
294     // editor object.
295     //
296     // Each one is tied to a particular line; this means that using a field or subfield object after
297     // any other changes to the record will cause entertaining explosions. The objects are meant to
298     // be temporary, and should only be reused with great care. The macro code does this only
299     // because it is careful to dispose of the object after any other updates.
300     //
301     // Note, however, tha you can continue to use a field object after changing subfields. It's just
302     // the subfield objects that become invalid.
303
304     // This is an exception raised by the EditorSubfield and EditorField when an invalid change is
305     // attempted.
306     function FieldError(line, message) {
307         this.line = line;
308         this.message = message;
309     };
310
311     FieldError.prototype.toString = function() {
312         return 'FieldError(' + this.line + ', "' + this.message + '")';
313     };
314
315     // This is the temporary object for a particular subfield in a field. Any change to any other
316     // subfields will invalidate this subfield object.
317     function EditorSubfield( field, index, start, end ) {
318         this.field = field;
319         this.index = index;
320         this.start = start;
321         this.end = end;
322
323         if ( this.field.isControlField ) {
324             this.contentsStart = start;
325             this.code = '@';
326         } else {
327             this.contentsStart = start + 2;
328             this.code =  this.field.contents.substr( this.start + 1, 1 );
329         }
330
331         this.cm = field.cm;
332
333         var marks = this.cm.findMarksAt( { line: field.line, ch: this.contentsStart } );
334         if ( marks[0] && marks[0].widget ) {
335             this.widget = marks[0].widget;
336
337             this.text = this.widget.text;
338             this.setText = this.widget.setText;
339             this.getFixed = this.widget.getFixed;
340             this.setFixed = this.widget.setFixed;
341         } else {
342             this.widget = null;
343             this.text = this.field.contents.substr( this.contentsStart, end - this.contentsStart );
344         }
345     };
346
347     $.extend( EditorSubfield.prototype, {
348         _invalid: function() {
349             return this.field._subfieldsInvalid();
350         },
351
352         delete: function() {
353             this.cm.replaceRange( "", { line: this.field.line, ch: this.start }, { line: this.field.line, ch: this.end }, 'marcAware' );
354         },
355         focus: function() {
356             this.cm.setCursor( { line: this.field.line, ch: this.contentsStart } );
357         },
358         focusEnd: function() {
359             this.cm.setCursor( { line: this.field.line, ch: this.end } );
360         },
361         getText: function() {
362             return this.text;
363         },
364         setText: function( text ) {
365             if ( !this._invalid() ) throw new FieldError( this.field.line, 'subfield invalid' );
366             this.cm.replaceRange( text, { line: this.field.line, ch: this.contentsStart }, { line: this.field.line, ch: this.end }, 'marcAware' );
367             this.field._invalidateSubfields();
368         },
369     } );
370
371     function EditorField( editor, line ) {
372         this.editor = editor;
373         this.line = line;
374
375         this.cm = editor.cm;
376
377         this._updateInfo();
378         this.tag = this.contents.substr( 0, 3 );
379         this.isControlField = ( this.tag < '010' );
380
381         if ( this.isControlField ) {
382             this._ind1 = this.contents.substr( 4, 1 );
383             this._ind2 = this.contents.substr( 6, 1 );
384         } else {
385             this._ind1 = null;
386             this._ind2 = null;
387         }
388
389         this.subfields = null;
390     }
391
392     $.extend( EditorField.prototype, {
393         _subfieldsInvalid: function() {
394             return !this.subfields;
395         },
396         _invalidateSubfields: function() {
397             this._subfields = null;
398         },
399
400         _updateInfo: function() {
401             this.info = this.editor.getLineInfo( { line: this.line, ch: 0 } );
402             if ( this.info == null ) throw new FieldError( 'Invalid field' );
403             this.contents = this.info.contents;
404         },
405         _scanSubfields: function() {
406             this._updateInfo();
407
408             if ( this.isControlField ) {
409                 this._subfields = [ new EditorSubfield( this, 0, 4, this.contents.length ) ];
410             } else {
411                 var field = this;
412                 var subfields = this.info.subfields;
413                 this._subfields = [];
414
415                 for (var i = 0; i < this.info.subfields.length; i++) {
416                     var end = i == subfields.length - 1 ? this.contents.length : subfields[i+1].ch;
417
418                     this._subfields.push( new EditorSubfield( this, i, subfields[i].ch, end ) );
419                 }
420             }
421         },
422
423         delete: function() {
424             this.cm.replaceRange( "", { line: this.line, ch: 0 }, { line: this.line + 1, ch: 0 }, 'marcAware' );
425         },
426         focus: function() {
427             this.cm.setCursor( { line: this.line, ch: 0 } );
428
429             return this;
430         },
431
432         getText: function() {
433             var result = '';
434
435             $.each( this.getSubfields(), function() {
436                 if ( this.code != '@' ) result += '‡' + this.code;
437
438                 result += this.getText();
439             } );
440
441             return result;
442         },
443         setText: function( text ) {
444             var indicator_match = /^([_ 0-9])([_ 0-9])\‡/.exec( text );
445             if ( indicator_match ) {
446                 text = text.substr(2);
447                 this.setIndicator1( indicator_match[1] );
448                 this.setIndicator2( indicator_match[2] );
449             }
450
451             this.cm.replaceRange( text, { line: this.line, ch: this.isControlField ? 4 : 8 }, { line: this.line }, 'marcAware' );
452             this._invalidateSubfields();
453
454             return this;
455         },
456
457         getIndicator1: function() {
458             return this._ind1;
459         },
460         getIndicator2: function() {
461             return this._ind2;
462         },
463         setIndicator1: function(val) {
464             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
465
466             this._ind1 = ( !val || val == ' ' ) ? '_' : val;
467             this.cm.replaceRange( this._ind1, { line: this.line, ch: 4 }, { line: this.line, ch: 5 }, 'marcAware' );
468
469             return this;
470         },
471         setIndicator2: function(val) {
472             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
473
474             this._ind2 = ( !val || val == ' ' ) ? '_' : val;
475             this.cm.replaceRange( this._ind2, { line: this.line, ch: 6 }, { line: this.line, ch: 7 }, 'marcAware' );
476
477             return this;
478         },
479
480         appendSubfield: function( code ) {
481             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
482
483             this._invalidateSubfields();
484             this.cm.replaceRange( '‡' + code, { line: this.line }, null, 'marcAware' );
485             var subfields = this.getSubfields();
486
487             return subfields[ subfields.length - 1 ];
488         },
489         insertSubfield: function( code, position ) {
490             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
491
492             position = position || 0;
493
494             var subfields = this.getSubfields();
495             this._invalidateSubfields();
496             this.cm.replaceRange( '‡' + code, { line: this.line, ch: subfields[position] ? subfields[position].start : null }, null, 'marcAware' );
497             subfields = this.getSubfields();
498
499             return subfields[ position ];
500         },
501         getSubfields: function( code ) {
502             if ( !this._subfields ) this._scanSubfields();
503             if ( code == null ) return this._subfields;
504
505             var result = [];
506
507             $.each( this._subfields, function() {
508                 if ( code == null || this.code == code ) result.push(this);
509             } );
510
511             return result;
512         },
513         getFirstSubfield: function( code ) {
514             var result = this.getSubfields( code );
515
516             return ( result && result.length ) ? result[0] : null;
517         },
518         getSubfieldAt: function( ch ) {
519             var subfields = this.getSubfields();
520
521             for (var i = 0; i < subfields.length; i++) {
522                 if ( subfields[i].start < ch && subfields[i].end >= ch ) return subfields[i];
523             }
524         },
525     } );
526
527     function MARCEditor( options ) {
528         this.frameworkcode = '';
529
530         this.cm = CodeMirror(
531             options.position,
532             {
533                 extraKeys: _editorKeys,
534                 gutters: [
535                     'modified-line-gutter',
536                 ],
537                 lineWrapping: true,
538                 mode: {
539                     name: 'marc',
540                     nonRepeatableTags: KohaBackend.GetTagsBy( '', 'repeatable', '0' ),
541                     nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' )
542                 }
543             }
544         );
545         var inf = this.cm.getInputField();
546         var self = this;
547         var kb = $(inf).keyboard({
548             //keyBinding: "mousedown touchstart",
549             usePreview: false,
550             lockInput: false,
551             autoAccept: true,
552             autoAcceptOnEsc: true,
553             userClosed: true,
554             //alwaysOpen: true,
555             openOn : '',
556             position: {
557               of: $("#statusbar"), // optional - null (attach to input/textarea) or a jQuery object (attach elsewhere)
558               my: 'center top',
559               at: 'center bottom',
560               at2: 'center bottom' // used when "usePreview" is false (centers keyboard at bottom of the input/textarea)
561             },
562             beforeInsert: function(evnt, keyboard, elem, txt) {
563               var position = self.cm.getCursor();
564               if (txt === "\b") {
565                 self.cm.execCommand("delCharBefore");
566               }
567               if (txt === "\b" && position.ch === 0 && position.line !== 0) {
568                 elem.value = self.cm.getLine(position.line) || "";
569                 txt = "";
570               }
571               return txt;
572             },
573             visible: function() {
574                 $('#set-keyboard-layout').removeClass('hide');
575             },
576             hidden: function(e, keyboard, el, accepted) {
577                 inf.focus();
578                 $('#set-keyboard-layout').addClass('hide');
579             }
580           }).getkeyboard();
581
582
583         Object.keys($.keyboard.layouts).forEach(function(layout) {
584             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>')
585             if(kb.layout == layout) {
586                 div.addClass('active');
587             }
588         });
589         $('#keyboard-layout')
590             .on('show.bs.modal', function() {
591                 kb.close();
592                 $('#keyboard-layout .filter').focus();
593                 $('#set-keyboard-layout').removeClass('hide');
594             })
595             .on('hide.bs.modal', function() {
596                 !kb.isVisible() && kb.reveal();
597             });
598         $('#keyboard-layout .layout').click(function(event) {
599             $('#keyboard-layout .layout').removeClass('active');
600             $(this).addClass('active');
601             var layout = $(this).data().layout;
602             kb.redraw(layout);
603             $('#keyboard-layout').modal('hide');
604             $('#keyboard-layout .filter').val('');
605             $('#keyboard-layout .layout').show();
606         });
607         $('#keyboard-layout .filter').keyup(function() {
608             var val = $(this).val();
609             if(!val||!val.length) return $('#keyboard-layout .layout').show();
610             var filter = new RegExp(val, 'i');
611             $('#keyboard-layout .layout').hide();
612             $('#keyboard-layout .layout').each(function() {
613                 var name = $(this).data().name;
614                 if(filter.test(name)) $(this).show();
615             })
616         });
617
618         this.cm.marceditor = this;
619
620         this.cm.on( 'beforeChange', editorBeforeChange );
621         this.cm.on( 'changes', editorChanges );
622         this.cm.on( 'cursorActivity', editorCursorActivity );
623         this.cm.on( 'overwriteToggle', editorSetOverwriteMode );
624
625         this.onCursorActivity = options.onCursorActivity;
626
627         this.subscribers = [];
628         this.subscribe( function( marceditor ) {
629             Widget.Notify( marceditor );
630         } );
631     }
632
633     MARCEditor.FieldError = FieldError;
634
635     $.extend( MARCEditor.prototype, {
636         setUseWidgets: function( val ) {
637             if ( val ) {
638                 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
639                     Widget.UpdateLine( this, line );
640                 }
641             } else {
642                 $.each( this.cm.getAllMarks(), function( undef, mark ) {
643                     if ( mark.widget ) mark.widget.clearToText();
644                 } );
645             }
646         },
647
648         focus: function() {
649             this.cm.focus();
650         },
651
652         getCursor: function() {
653             return this.cm.getCursor();
654         },
655
656         refresh: function() {
657             this.cm.refresh();
658         },
659
660         setFrameworkCode: function( code, updateFields, callback ) {
661             this.frameworkcode = code;
662             $( 'a.change-framework i.selected' ).addClass( 'hidden' );
663             $( 'a.change-framework i.unselected' ).removeClass( 'hidden' );
664             $( 'a.change-framework[data-frameworkcode="' + code + '"] i.unselected' ).addClass( 'hidden' );
665             $( 'a.change-framework[data-frameworkcode="' + code + '"] i.selected' ).removeClass( 'hidden ');
666             var cm = this.cm;
667             KohaBackend.InitFramework( code, function ( error ) {
668                 cm.setOption( 'mode', {
669                     name: 'marc',
670                     nonRepeatableTags: KohaBackend.GetTagsBy( code, 'repeatable', '0' ),
671                     nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( code, 'repeatable', '0' )
672                 });
673                 if ( updateFields ) {
674                     var record = TextMARC.TextToRecord( cm.getValue() );
675                     KohaBackend.FillRecord( code, record );
676                     cm.setValue( TextMARC.RecordToText(record) );
677                 }
678                 callback( error );
679             } );
680         },
681
682         displayRecord: function( record ) {
683             this.cm.setValue( TextMARC.RecordToText(record) );
684             this.modified = false;
685             this.setFrameworkCode(
686                 typeof record.frameworkcode !== 'undefined' ? record.frameworkcode : '',
687                 false,
688                 function ( error ) {
689                     if ( typeof error !== 'undefined' ) {
690                         humanMsg.displayAlert( _(error), { className: 'humanError' } );
691                     }
692                 }
693             );
694         },
695
696         getRecord: function() {
697             this.textMode = true;
698
699             $.each( this.cm.getAllMarks(), function( undef, mark ) {
700                 if ( mark.widget ) mark.widget.clearToText();
701             } );
702             var record = TextMARC.TextToRecord( this.cm.getValue() );
703             for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
704                 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( this, line );
705             }
706
707             this.textMode = false;
708
709             record.frameworkcode = this.frameworkcode;
710             return record;
711         },
712
713         getLineInfo: function( pos ) {
714             var contents = this.cm.getLine( pos.line );
715             if ( contents == null ) return {};
716
717             var tagNumber = contents.match( /^([A-Za-z0-9]{3})/ );
718
719             if ( !tagNumber ) return null; // No tag at all on this line
720             tagNumber = tagNumber[1];
721
722             if ( tagNumber < '010' ) return { tagNumber: tagNumber, contents: contents }; // No current subfield
723
724             var matcher = /‡([a-z0-9%])/g;
725             var match;
726
727             var subfields = [];
728             var currentSubfield;
729
730             while ( ( match = matcher.exec(contents) ) ) {
731                 subfields.push( { code: match[1], ch: match.index } );
732                 if ( match.index < pos.ch ) currentSubfield = match[1];
733             }
734
735             return { tagNumber: tagNumber, subfields: subfields, currentSubfield: currentSubfield, contents: contents };
736         },
737
738         addError: function( line, error ) {
739             var found = false;
740             var options = {};
741
742             if ( line == null ) {
743                 line = 0;
744                 options.above = true;
745             }
746
747             $.each( this.cm.getLineHandle(line).widgets || [], function( undef, widget ) {
748                 if ( !widget.isErrorMarker ) return;
749
750                 found = true;
751
752                 $( widget.node ).append( '; ' + error );
753                 widget.changed();
754
755                 return false;
756             } );
757
758             if ( found ) return;
759
760             var node = $( '<div class="structure-error"><i class="fa fa-remove"></i> ' + error + '</div>' )[0];
761             var widget = this.cm.addLineWidget( line, node, options );
762
763             widget.node = node;
764             widget.isErrorMarker = true;
765         },
766
767         removeErrors: function() {
768             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
769                 $.each( this.cm.getLineHandle( line ).widgets || [], function( undef, lineWidget ) {
770                     if ( lineWidget.isErrorMarker ) lineWidget.clear();
771                 } );
772             }
773         },
774
775         startNotify: function() {
776             if ( this.notifyTimeout ) clearTimeout( this.notifyTimeout );
777             this.notifyTimeout = setTimeout( $.proxy( function() {
778                 this.notifyAll();
779
780                 this.notifyTimeout = null;
781             }, this ), NOTIFY_TIMEOUT );
782         },
783
784         notifyAll: function() {
785             $.each( this.subscribers, $.proxy( function( undef, subscriber ) {
786                 subscriber(this);
787             }, this ) );
788         },
789
790         subscribe: function( subscriber ) {
791             this.subscribers.push( subscriber );
792         },
793
794         createField: function( tag, line ) {
795             var contents = tag + ( tag < '010' ? ' ' : ' _ _ ' );
796
797             if ( line > this.cm.lastLine() ) {
798                 contents = '\n' + contents;
799             } else {
800                 contents = contents + '\n';
801             }
802
803             this.cm.replaceRange( contents, { line: line, ch: 0 }, null, 'marcAware' );
804
805             return new EditorField( this, line );
806         },
807
808         createFieldOrdered: function( tag ) {
809             var line, contents;
810
811             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
812                 if ( contents && contents.substr(0, 3) > tag ) break;
813             }
814
815             return this.createField( tag, line );
816         },
817
818         createFieldGrouped: function( tag ) {
819             // Control fields should be inserted in actual order, whereas other fields should be
820             // inserted grouped
821             if ( tag < '010' ) return this.createFieldOrdered( tag );
822
823             var line, contents;
824
825             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
826                 if ( contents && contents[0] > tag[0] ) break;
827             }
828
829             return this.createField( tag, line );
830         },
831
832         getFieldAt: function( line ) {
833             try {
834                 return new EditorField( this, line );
835             } catch (e) {
836                 return null;
837             }
838         },
839
840         getCurrentField: function() {
841             return this.getFieldAt( this.cm.getCursor().line );
842         },
843
844         getFields: function( tag ) {
845             var result = [];
846
847             if ( tag != null ) tag += ' ';
848
849             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
850                 if ( tag && this.cm.getLine(line).substr( 0, 4 ) != tag ) continue;
851
852                 // If this throws a FieldError, pretend it doesn't exist
853                 try {
854                     result.push( new EditorField( this, line ) );
855                 } catch (e) {
856                     if ( !( e instanceof FieldError ) ) throw e;
857                 }
858             }
859
860             return result;
861         },
862
863         getFirstField: function( tag ) {
864             var result = this.getFields( tag );
865
866             return ( result && result.length ) ? result[0] : null;
867         },
868
869         getAllFields: function( tag ) {
870             return this.getFields( null );
871         },
872     } );
873
874     return MARCEditor;
875 } );