View | Details | Raw Unified | Return to bug 32613
Collapse All | Expand All

(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/highlight.css (+6 lines)
Line 0 Link Here
1
.cm-style1 {
2
  color: maroon !important;
3
}
4
.cm-style2 {
5
  color: limegreen !important;
6
}
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/highlight.js (+24 lines)
Line 0 Link Here
1
(function(mod) {
2
  if (typeof exports == "object" && typeof module == "object") // CommonJS
3
    mod(require("../../lib/codemirror"));
4
  else if (typeof define == "function" && define.amd) // AMD
5
    define(["../../lib/codemirror"], mod);
6
  else // Plain browser env
7
    mod(CodeMirror);
8
})(function(CodeMirror) {
9
  CodeMirror.defineOption("keyword", {}, function(cm, val, prev) {
10
    if (prev == CodeMirror.Init) prev = false;
11
    if (prev && !val)
12
      cm.removeOverlay("keyword");
13
    else if (!prev && val)
14
      cm.addOverlay({
15
        token: function(stream) {
16
          for (var key in cm.options.keyword) {
17
            if (stream.match(new RegExp(key))) return cm.options.keyword[key];
18
          }
19
          stream.next();
20
        },
21
        name: "keyword"
22
      });
23
  });
24
});
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/show-hint.css (+36 lines)
Line 0 Link Here
1
.CodeMirror-hints {
2
  position: absolute;
3
  z-index: 10;
4
  overflow: hidden;
5
  list-style: none;
6
7
  margin: 0;
8
  padding: 2px;
9
10
  -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
11
  -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
12
  box-shadow: 2px 3px 5px rgba(0,0,0,.2);
13
  border-radius: 3px;
14
  border: 1px solid silver;
15
16
  background: white;
17
  font-size: 90%;
18
  font-family: monospace;
19
20
  max-height: 20em;
21
  overflow-y: auto;
22
}
23
24
.CodeMirror-hint {
25
  margin: 0;
26
  padding: 0 4px;
27
  border-radius: 2px;
28
  white-space: pre;
29
  color: black;
30
  cursor: pointer;
31
}
32
33
li.CodeMirror-hint-active {
34
  background: #08f;
35
  color: white;
36
}
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/show-hint.js (+479 lines)
Line 0 Link Here
1
// CodeMirror, copyright (c) by Marijn Haverbeke and others
2
// Distributed under an MIT license: https://codemirror.net/LICENSE
3
4
(function(mod) {
5
  if (typeof exports == "object" && typeof module == "object") // CommonJS
6
    mod(require("../../lib/codemirror"));
7
  else if (typeof define == "function" && define.amd) // AMD
8
    define(["../../lib/codemirror"], mod);
9
  else // Plain browser env
10
    mod(CodeMirror);
11
})(function(CodeMirror) {
12
  "use strict";
13
14
  var HINT_ELEMENT_CLASS        = "CodeMirror-hint";
15
  var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
16
17
  // This is the old interface, kept around for now to stay
18
  // backwards-compatible.
19
  CodeMirror.showHint = function(cm, getHints, options) {
20
    if (!getHints) return cm.showHint(options);
21
    if (options && options.async) getHints.async = true;
22
    var newOpts = {hint: getHints};
23
    if (options) for (var prop in options) newOpts[prop] = options[prop];
24
    return cm.showHint(newOpts);
25
  };
26
27
  CodeMirror.defineExtension("showHint", function(options) {
28
    options = parseOptions(this, this.getCursor("start"), options);
29
    var selections = this.listSelections()
30
    if (selections.length > 1) return;
31
    // By default, don't allow completion when something is selected.
32
    // A hint function can have a `supportsSelection` property to
33
    // indicate that it can handle selections.
34
    if (this.somethingSelected()) {
35
      if (!options.hint.supportsSelection) return;
36
      // Don't try with cross-line selections
37
      for (var i = 0; i < selections.length; i++)
38
        if (selections[i].head.line != selections[i].anchor.line) return;
39
    }
40
41
    if (this.state.completionActive) this.state.completionActive.close();
42
    var completion = this.state.completionActive = new Completion(this, options);
43
    if (!completion.options.hint) return;
44
45
    CodeMirror.signal(this, "startCompletion", this);
46
    completion.update(true);
47
  });
48
49
  CodeMirror.defineExtension("closeHint", function() {
50
    if (this.state.completionActive) this.state.completionActive.close()
51
  })
52
53
  function Completion(cm, options) {
54
    this.cm = cm;
55
    this.options = options;
56
    this.widget = null;
57
    this.debounce = 0;
58
    this.tick = 0;
59
    this.startPos = this.cm.getCursor("start");
60
    this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;
61
62
    var self = this;
63
    cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
64
  }
65
66
  var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
67
    return setTimeout(fn, 1000/60);
68
  };
69
  var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
70
71
  Completion.prototype = {
72
    close: function() {
73
      if (!this.active()) return;
74
      this.cm.state.completionActive = null;
75
      this.tick = null;
76
      this.cm.off("cursorActivity", this.activityFunc);
77
78
      if (this.widget && this.data) CodeMirror.signal(this.data, "close");
79
      if (this.widget) this.widget.close();
80
      CodeMirror.signal(this.cm, "endCompletion", this.cm);
81
    },
82
83
    active: function() {
84
      return this.cm.state.completionActive == this;
85
    },
86
87
    pick: function(data, i) {
88
      var completion = data.list[i], self = this;
89
      this.cm.operation(function() {
90
        if (completion.hint)
91
          completion.hint(self.cm, data, completion);
92
        else
93
          self.cm.replaceRange(getText(completion), completion.from || data.from,
94
                               completion.to || data.to, "complete");
95
        CodeMirror.signal(data, "pick", completion);
96
        self.cm.scrollIntoView();
97
      })
98
      this.close();
99
    },
100
101
    cursorActivity: function() {
102
      if (this.debounce) {
103
        cancelAnimationFrame(this.debounce);
104
        this.debounce = 0;
105
      }
106
107
      var identStart = this.startPos;
108
      if(this.data) {
109
        identStart = this.data.from;
110
      }
111
112
      var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
113
      if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
114
          pos.ch < identStart.ch || this.cm.somethingSelected() ||
115
          (!pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
116
        this.close();
117
      } else {
118
        var self = this;
119
        this.debounce = requestAnimationFrame(function() {self.update();});
120
        if (this.widget) this.widget.disable();
121
      }
122
    },
123
124
    update: function(first) {
125
      if (this.tick == null) return
126
      var self = this, myTick = ++this.tick
127
      fetchHints(this.options.hint, this.cm, this.options, function(data) {
128
        if (self.tick == myTick) self.finishUpdate(data, first)
129
      })
130
    },
131
132
    finishUpdate: function(data, first) {
133
      if (this.data) CodeMirror.signal(this.data, "update");
134
135
      var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
136
      if (this.widget) this.widget.close();
137
138
      this.data = data;
139
140
      if (data && data.list.length) {
141
        if (picked && data.list.length == 1) {
142
          this.pick(data, 0);
143
        } else {
144
          this.widget = new Widget(this, data);
145
          CodeMirror.signal(data, "shown");
146
        }
147
      }
148
    }
149
  };
150
151
  function parseOptions(cm, pos, options) {
152
    var editor = cm.options.hintOptions;
153
    var out = {};
154
    for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
155
    if (editor) for (var prop in editor)
156
      if (editor[prop] !== undefined) out[prop] = editor[prop];
157
    if (options) for (var prop in options)
158
      if (options[prop] !== undefined) out[prop] = options[prop];
159
    if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
160
    return out;
161
  }
162
163
  function getText(completion) {
164
    if (typeof completion == "string") return completion;
165
    else return completion.text;
166
  }
167
168
  function buildKeyMap(completion, handle) {
169
    var baseMap = {
170
      Up: function() {handle.moveFocus(-1);},
171
      Down: function() {handle.moveFocus(1);},
172
      PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
173
      PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
174
      Home: function() {handle.setFocus(0);},
175
      End: function() {handle.setFocus(handle.length - 1);},
176
      Enter: handle.pick,
177
      Tab: handle.pick,
178
      Esc: handle.close
179
    };
180
181
    var mac = /Mac/.test(navigator.platform);
182
183
    if (mac) {
184
      baseMap["Ctrl-P"] = function() {handle.moveFocus(-1);};
185
      baseMap["Ctrl-N"] = function() {handle.moveFocus(1);};
186
    }
187
188
    var custom = completion.options.customKeys;
189
    var ourMap = custom ? {} : baseMap;
190
    function addBinding(key, val) {
191
      var bound;
192
      if (typeof val != "string")
193
        bound = function(cm) { return val(cm, handle); };
194
      // This mechanism is deprecated
195
      else if (baseMap.hasOwnProperty(val))
196
        bound = baseMap[val];
197
      else
198
        bound = val;
199
      ourMap[key] = bound;
200
    }
201
    if (custom)
202
      for (var key in custom) if (custom.hasOwnProperty(key))
203
        addBinding(key, custom[key]);
204
    var extra = completion.options.extraKeys;
205
    if (extra)
206
      for (var key in extra) if (extra.hasOwnProperty(key))
207
        addBinding(key, extra[key]);
208
    return ourMap;
209
  }
210
211
  function getHintElement(hintsElement, el) {
212
    while (el && el != hintsElement) {
213
      if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
214
      el = el.parentNode;
215
    }
216
  }
217
218
  function Widget(completion, data) {
219
    this.completion = completion;
220
    this.data = data;
221
    this.picked = false;
222
    var widget = this, cm = completion.cm;
223
    var ownerDocument = cm.getInputField().ownerDocument;
224
    var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow;
225
226
    var hints = this.hints = ownerDocument.createElement("ul");
227
    var theme = completion.cm.options.theme;
228
    hints.className = "CodeMirror-hints " + theme;
229
    this.selectedHint = data.selectedHint || 0;
230
231
    var completions = data.list;
232
    for (var i = 0; i < completions.length; ++i) {
233
      var elt = hints.appendChild(ownerDocument.createElement("li")), cur = completions[i];
234
      var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
235
      if (cur.className != null) className = cur.className + " " + className;
236
      elt.className = className;
237
      if (cur.render) cur.render(elt, data, cur);
238
      else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur)));
239
      elt.hintId = i;
240
    }
241
242
    var container = completion.options.container || ownerDocument.body;
243
    var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
244
    var left = pos.left, top = pos.bottom, below = true;
245
    var offsetLeft = 0, offsetTop = 0;
246
    if (container !== ownerDocument.body) {
247
      // We offset the cursor position because left and top are relative to the offsetParent's top left corner.
248
      var isContainerPositioned = ['absolute', 'relative', 'fixed'].indexOf(parentWindow.getComputedStyle(container).position) !== -1;
249
      var offsetParent = isContainerPositioned ? container : container.offsetParent;
250
      var offsetParentPosition = offsetParent.getBoundingClientRect();
251
      var bodyPosition = ownerDocument.body.getBoundingClientRect();
252
      offsetLeft = (offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft);
253
      offsetTop = (offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop);
254
    }
255
    hints.style.left = (left - offsetLeft) + "px";
256
    hints.style.top = (top - offsetTop) + "px";
257
258
    // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
259
    var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth);
260
    var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight);
261
    container.appendChild(hints);
262
    var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
263
    var scrolls = hints.scrollHeight > hints.clientHeight + 1
264
    var startScroll = cm.getScrollInfo();
265
266
    if (overlapY > 0) {
267
      var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
268
      if (curTop - height > 0) { // Fits above cursor
269
        hints.style.top = (top = pos.top - height - offsetTop) + "px";
270
        below = false;
271
      } else if (height > winH) {
272
        hints.style.height = (winH - 5) + "px";
273
        hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px";
274
        var cursor = cm.getCursor();
275
        if (data.from.ch != cursor.ch) {
276
          pos = cm.cursorCoords(cursor);
277
          hints.style.left = (left = pos.left - offsetLeft) + "px";
278
          box = hints.getBoundingClientRect();
279
        }
280
      }
281
    }
282
    var overlapX = box.right - winW;
283
    if (overlapX > 0) {
284
      if (box.right - box.left > winW) {
285
        hints.style.width = (winW - 5) + "px";
286
        overlapX -= (box.right - box.left) - winW;
287
      }
288
      hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px";
289
    }
290
    if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
291
      node.style.paddingRight = cm.display.nativeBarWidth + "px"
292
293
    cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
294
      moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
295
      setFocus: function(n) { widget.changeActive(n); },
296
      menuSize: function() { return widget.screenAmount(); },
297
      length: completions.length,
298
      close: function() { completion.close(); },
299
      pick: function() { widget.pick(); },
300
      data: data
301
    }));
302
303
    if (completion.options.closeOnUnfocus) {
304
      var closingOnBlur;
305
      cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
306
      cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
307
    }
308
309
    cm.on("scroll", this.onScroll = function() {
310
      var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
311
      var newTop = top + startScroll.top - curScroll.top;
312
      var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop);
313
      if (!below) point += hints.offsetHeight;
314
      if (point <= editor.top || point >= editor.bottom) return completion.close();
315
      hints.style.top = newTop + "px";
316
      hints.style.left = (left + startScroll.left - curScroll.left) + "px";
317
    });
318
319
    CodeMirror.on(hints, "dblclick", function(e) {
320
      var t = getHintElement(hints, e.target || e.srcElement);
321
      if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
322
    });
323
324
    CodeMirror.on(hints, "click", function(e) {
325
      var t = getHintElement(hints, e.target || e.srcElement);
326
      if (t && t.hintId != null) {
327
        widget.changeActive(t.hintId);
328
        if (completion.options.completeOnSingleClick) widget.pick();
329
      }
330
    });
331
332
    CodeMirror.on(hints, "mousedown", function() {
333
      setTimeout(function(){cm.focus();}, 20);
334
    });
335
    this.scrollToActive()
336
337
    CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]);
338
    return true;
339
  }
340
341
  Widget.prototype = {
342
    close: function() {
343
      if (this.completion.widget != this) return;
344
      this.completion.widget = null;
345
      this.hints.parentNode.removeChild(this.hints);
346
      this.completion.cm.removeKeyMap(this.keyMap);
347
348
      var cm = this.completion.cm;
349
      if (this.completion.options.closeOnUnfocus) {
350
        cm.off("blur", this.onBlur);
351
        cm.off("focus", this.onFocus);
352
      }
353
      cm.off("scroll", this.onScroll);
354
    },
355
356
    disable: function() {
357
      this.completion.cm.removeKeyMap(this.keyMap);
358
      var widget = this;
359
      this.keyMap = {Enter: function() { widget.picked = true; }};
360
      this.completion.cm.addKeyMap(this.keyMap);
361
    },
362
363
    pick: function() {
364
      this.completion.pick(this.data, this.selectedHint);
365
    },
366
367
    changeActive: function(i, avoidWrap) {
368
      if (i >= this.data.list.length)
369
        i = avoidWrap ? this.data.list.length - 1 : 0;
370
      else if (i < 0)
371
        i = avoidWrap ? 0  : this.data.list.length - 1;
372
      if (this.selectedHint == i) return;
373
      var node = this.hints.childNodes[this.selectedHint];
374
      if (node) node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
375
      node = this.hints.childNodes[this.selectedHint = i];
376
      node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
377
      this.scrollToActive()
378
      CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
379
    },
380
381
    scrollToActive: function() {
382
      var margin = this.completion.options.scrollMargin || 0;
383
      var node1 = this.hints.childNodes[Math.max(0, this.selectedHint - margin)];
384
      var node2 = this.hints.childNodes[Math.min(this.data.list.length - 1, this.selectedHint + margin)];
385
      var firstNode = this.hints.firstChild;
386
      if (node1.offsetTop < this.hints.scrollTop)
387
        this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;
388
      else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
389
        this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop;
390
    },
391
392
    screenAmount: function() {
393
      return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
394
    }
395
  };
396
397
  function applicableHelpers(cm, helpers) {
398
    if (!cm.somethingSelected()) return helpers
399
    var result = []
400
    for (var i = 0; i < helpers.length; i++)
401
      if (helpers[i].supportsSelection) result.push(helpers[i])
402
    return result
403
  }
404
405
  function fetchHints(hint, cm, options, callback) {
406
    if (hint.async) {
407
      hint(cm, callback, options)
408
    } else {
409
      var result = hint(cm, options)
410
      if (result && result.then) result.then(callback)
411
      else callback(result)
412
    }
413
  }
414
415
  function resolveAutoHints(cm, pos) {
416
    var helpers = cm.getHelpers(pos, "hint"), words
417
    if (helpers.length) {
418
      var resolved = function(cm, callback, options) {
419
        var app = applicableHelpers(cm, helpers);
420
        function run(i) {
421
          if (i == app.length) return callback(null)
422
          fetchHints(app[i], cm, options, function(result) {
423
            if (result && result.list.length > 0) callback(result)
424
            else run(i + 1)
425
          })
426
        }
427
        run(0)
428
      }
429
      resolved.async = true
430
      resolved.supportsSelection = true
431
      return resolved
432
    } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
433
      return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
434
    } else if (CodeMirror.hint.anyword) {
435
      return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
436
    } else {
437
      return function() {}
438
    }
439
  }
440
441
  CodeMirror.registerHelper("hint", "auto", {
442
    resolve: resolveAutoHints
443
  });
444
445
  CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
446
    var cur = cm.getCursor(), token = cm.getTokenAt(cur)
447
    var term, from = CodeMirror.Pos(cur.line, token.start), to = cur
448
    if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
449
      term = token.string.substr(0, cur.ch - token.start)
450
    } else {
451
      term = ""
452
      from = cur
453
    }
454
    var found = [];
455
    for (var i = 0; i < options.words.length; i++) {
456
      var word = options.words[i];
457
      if (word.slice(0, term.length) == term)
458
        found.push(word);
459
    }
460
461
    if (found.length) return {list: found, from: from, to: to};
462
  });
463
464
  CodeMirror.commands.autocomplete = CodeMirror.showHint;
465
466
  var defaultOptions = {
467
    hint: CodeMirror.hint.auto,
468
    completeSingle: true,
469
    alignWithWord: true,
470
    closeCharacters: /[\s()\[\]{};:>,]/,
471
    closeOnUnfocus: true,
472
    completeOnSingleClick: true,
473
    container: null,
474
    customKeys: null,
475
    extraKeys: null
476
  };
477
478
  CodeMirror.defineOption("hintOptions", null);
479
});
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/sql-hint.js (+304 lines)
Line 0 Link Here
1
// CodeMirror, copyright (c) by Marijn Haverbeke and others
2
// Distributed under an MIT license: https://codemirror.net/LICENSE
3
4
(function(mod) {
5
  if (typeof exports == "object" && typeof module == "object") // CommonJS
6
    mod(require("../../lib/codemirror"), require("../../mode/sql/sql"));
7
  else if (typeof define == "function" && define.amd) // AMD
8
    define(["../../lib/codemirror", "../../mode/sql/sql"], mod);
9
  else // Plain browser env
10
    mod(CodeMirror);
11
})(function(CodeMirror) {
12
  "use strict";
13
14
  var tables;
15
  var defaultTable;
16
  var keywords;
17
  var identifierQuote;
18
  var CONS = {
19
    QUERY_DIV: ";",
20
    ALIAS_KEYWORD: "AS"
21
  };
22
  var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos;
23
24
  function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" }
25
26
  function getKeywords(editor) {
27
    var mode = editor.doc.modeOption;
28
    if (mode === "sql") mode = "text/x-sql";
29
    return CodeMirror.resolveMode(mode).keywords;
30
  }
31
32
  function getIdentifierQuote(editor) {
33
    var mode = editor.doc.modeOption;
34
    if (mode === "sql") mode = "text/x-sql";
35
    return CodeMirror.resolveMode(mode).identifierQuote || "`";
36
  }
37
38
  function getText(item) {
39
    return typeof item == "string" ? item : item.text;
40
  }
41
42
  function wrapTable(name, value) {
43
    if (isArray(value)) value = {columns: value}
44
    if (!value.text) value.text = name
45
    return value
46
  }
47
48
  function parseTables(input) {
49
    var result = {}
50
    if (isArray(input)) {
51
      for (var i = input.length - 1; i >= 0; i--) {
52
        var item = input[i]
53
        result[getText(item).toUpperCase()] = wrapTable(getText(item), item)
54
      }
55
    } else if (input) {
56
      for (var name in input)
57
        result[name.toUpperCase()] = wrapTable(name, input[name])
58
    }
59
    return result
60
  }
61
62
  function getTable(name) {
63
    return tables[name.toUpperCase()]
64
  }
65
66
  function shallowClone(object) {
67
    var result = {};
68
    for (var key in object) if (object.hasOwnProperty(key))
69
      result[key] = object[key];
70
    return result;
71
  }
72
73
  function match(string, word) {
74
    var len = string.length;
75
    var sub = getText(word).substr(0, len);
76
    return string.toUpperCase() === sub.toUpperCase();
77
  }
78
79
  function addMatches(result, search, wordlist, formatter) {
80
    if (isArray(wordlist)) {
81
      for (var i = 0; i < wordlist.length; i++)
82
        if (match(search, wordlist[i])) result.push(formatter(wordlist[i]))
83
    } else {
84
      for (var word in wordlist) if (wordlist.hasOwnProperty(word)) {
85
        var val = wordlist[word]
86
        if (!val || val === true)
87
          val = word
88
        else
89
          val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text
90
        if (match(search, val)) result.push(formatter(val))
91
      }
92
    }
93
  }
94
95
  function cleanName(name) {
96
    // Get rid name from identifierQuote and preceding dot(.)
97
    if (name.charAt(0) == ".") {
98
      name = name.substr(1);
99
    }
100
    // replace doublicated identifierQuotes with single identifierQuotes
101
    // and remove single identifierQuotes
102
    var nameParts = name.split(identifierQuote+identifierQuote);
103
    for (var i = 0; i < nameParts.length; i++)
104
      nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote,"g"), "");
105
    return nameParts.join(identifierQuote);
106
  }
107
108
  function insertIdentifierQuotes(name) {
109
    var nameParts = getText(name).split(".");
110
    for (var i = 0; i < nameParts.length; i++)
111
      nameParts[i] = identifierQuote +
112
        // doublicate identifierQuotes
113
        nameParts[i].replace(new RegExp(identifierQuote,"g"), identifierQuote+identifierQuote) +
114
        identifierQuote;
115
    var escaped = nameParts.join(".");
116
    if (typeof name == "string") return escaped;
117
    name = shallowClone(name);
118
    name.text = escaped;
119
    return name;
120
  }
121
122
  function nameCompletion(cur, token, result, editor) {
123
    // Try to complete table, column names and return start position of completion
124
    var useIdentifierQuotes = false;
125
    var nameParts = [];
126
    var start = token.start;
127
    var cont = true;
128
    while (cont) {
129
      cont = (token.string.charAt(0) == ".");
130
      useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote);
131
132
      start = token.start;
133
      nameParts.unshift(cleanName(token.string));
134
135
      token = editor.getTokenAt(Pos(cur.line, token.start));
136
      if (token.string == ".") {
137
        cont = true;
138
        token = editor.getTokenAt(Pos(cur.line, token.start));
139
      }
140
    }
141
142
    // Try to complete table names
143
    var string = nameParts.join(".");
144
    addMatches(result, string, tables, function(w) {
145
      return useIdentifierQuotes ? insertIdentifierQuotes(w) : w;
146
    });
147
148
    // Try to complete columns from defaultTable
149
    addMatches(result, string, defaultTable, function(w) {
150
      return useIdentifierQuotes ? insertIdentifierQuotes(w) : w;
151
    });
152
153
    // Try to complete columns
154
    string = nameParts.pop();
155
    var table = nameParts.join(".");
156
157
    var alias = false;
158
    var aliasTable = table;
159
    // Check if table is available. If not, find table by Alias
160
    if (!getTable(table)) {
161
      var oldTable = table;
162
      table = findTableByAlias(table, editor);
163
      if (table !== oldTable) alias = true;
164
    }
165
166
    var columns = getTable(table);
167
    if (columns && columns.columns)
168
      columns = columns.columns;
169
170
    if (columns) {
171
      addMatches(result, string, columns, function(w) {
172
        var tableInsert = table;
173
        if (alias == true) tableInsert = aliasTable;
174
        if (typeof w == "string") {
175
          w = tableInsert + "." + w;
176
        } else {
177
          w = shallowClone(w);
178
          w.text = tableInsert + "." + w.text;
179
        }
180
        return useIdentifierQuotes ? insertIdentifierQuotes(w) : w;
181
      });
182
    }
183
184
    return start;
185
  }
186
187
  function eachWord(lineText, f) {
188
    var words = lineText.split(/\s+/)
189
    for (var i = 0; i < words.length; i++)
190
      if (words[i]) f(words[i].replace(/[,;]/g, ''))
191
  }
192
193
  function findTableByAlias(alias, editor) {
194
    var doc = editor.doc;
195
    var fullQuery = doc.getValue();
196
    var aliasUpperCase = alias.toUpperCase();
197
    var previousWord = "";
198
    var table = "";
199
    var separator = [];
200
    var validRange = {
201
      start: Pos(0, 0),
202
      end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length)
203
    };
204
205
    //add separator
206
    var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV);
207
    while(indexOfSeparator != -1) {
208
      separator.push(doc.posFromIndex(indexOfSeparator));
209
      indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1);
210
    }
211
    separator.unshift(Pos(0, 0));
212
    separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));
213
214
    //find valid range
215
    var prevItem = null;
216
    var current = editor.getCursor()
217
    for (var i = 0; i < separator.length; i++) {
218
      if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) {
219
        validRange = {start: prevItem, end: separator[i]};
220
        break;
221
      }
222
      prevItem = separator[i];
223
    }
224
225
    if (validRange.start) {
226
      var query = doc.getRange(validRange.start, validRange.end, false);
227
228
      for (var i = 0; i < query.length; i++) {
229
        var lineText = query[i];
230
        eachWord(lineText, function(word) {
231
          var wordUpperCase = word.toUpperCase();
232
          if (wordUpperCase === aliasUpperCase && getTable(previousWord))
233
            table = previousWord;
234
          if (wordUpperCase !== CONS.ALIAS_KEYWORD)
235
            previousWord = word;
236
        });
237
        if (table) break;
238
      }
239
    }
240
    return table;
241
  }
242
243
  CodeMirror.registerHelper("hint", "sql", function(editor, options) {
244
    tables = parseTables(options && options.tables)
245
    var defaultTableName = options && options.defaultTable;
246
    var disableKeywords = options && options.disableKeywords;
247
    defaultTable = defaultTableName && getTable(defaultTableName);
248
    keywords = getKeywords(editor);
249
    identifierQuote = getIdentifierQuote(editor);
250
251
    if (defaultTableName && !defaultTable)
252
      defaultTable = findTableByAlias(defaultTableName, editor);
253
254
    defaultTable = defaultTable || [];
255
256
    if (defaultTable.columns)
257
      defaultTable = defaultTable.columns;
258
259
    var cur = editor.getCursor();
260
    var result = [];
261
    var token = editor.getTokenAt(cur), start, end, search;
262
    if (token.end > cur.ch) {
263
      token.end = cur.ch;
264
      token.string = token.string.slice(0, cur.ch - token.start);
265
    }
266
267
    if (token.string.match(/^[.`"'\w@][\w$#]*$/g)) {
268
      search = token.string;
269
      start = token.start;
270
      end = token.end;
271
    } else {
272
      start = end = cur.ch;
273
      search = "";
274
    }
275
    if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) {
276
      start = nameCompletion(cur, token, result, editor);
277
    } else {
278
      var objectOrClass = function(w, className) {
279
        if (typeof w === "object") {
280
          w.className = className;
281
        } else {
282
          w = { text: w, className: className };
283
        }
284
        return w;
285
      };
286
    addMatches(result, search, defaultTable, function(w) {
287
        return objectOrClass(w, "CodeMirror-hint-table CodeMirror-hint-default-table");
288
    });
289
    addMatches(
290
        result,
291
        search,
292
        tables, function(w) {
293
          return objectOrClass(w, "CodeMirror-hint-table");
294
        }
295
    );
296
    if (!disableKeywords)
297
      addMatches(result, search, keywords, function(w) {
298
          return objectOrClass(w.toUpperCase(), "CodeMirror-hint-keyword");
299
      });
300
  }
301
302
    return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};
303
  });
304
});
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/sql.js (-136 / +3 lines)
Lines 275-281 CodeMirror.defineMode("sql", function(config, parserConfig) { Link Here
275
  }
275
  }
276
276
277
  // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
277
  // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
278
  var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit ";
278
  var sqlKeywords = "alter and as asc between by count desc distinct from group having in into is join like not on or order select set table union values where limit ";
279
279
280
  // turn a space-separated list into an array
280
  // turn a space-separated list into an array
281
  function set(str) {
281
  function set(str) {
Lines 314-453 CodeMirror.defineMode("sql", function(config, parserConfig) { Link Here
314
  CodeMirror.defineMIME("text/x-mysql", {
314
  CodeMirror.defineMIME("text/x-mysql", {
315
    name: "sql",
315
    name: "sql",
316
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
316
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
317
    keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
317
    keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with"),
318
    builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
319
    atoms: set("false true null unknown"),
320
    operatorChars: /^[*+\-%<>!=&|^]/,
321
    dateSQL: set("date time timestamp"),
322
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
323
    hooks: {
324
      "@":   hookVar,
325
      "`":   hookIdentifier,
326
      "\\":  hookClient
327
    }
328
  });
329
330
  CodeMirror.defineMIME("text/x-mariadb", {
331
    name: "sql",
332
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
333
    keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
334
    builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
335
    atoms: set("false true null unknown"),
336
    operatorChars: /^[*+\-%<>!=&|^]/,
337
    dateSQL: set("date time timestamp"),
338
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
339
    hooks: {
340
      "@":   hookVar,
341
      "`":   hookIdentifier,
342
      "\\":  hookClient
343
    }
344
  });
345
346
  // provided by the phpLiteAdmin project - phpliteadmin.org
347
  CodeMirror.defineMIME("text/x-sqlite", {
348
    name: "sql",
349
    // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd
350
    client: set("auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width"),
351
    // ref: http://sqlite.org/lang_keywords.html
352
    keywords: set(sqlKeywords + "abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without"),
353
    // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
354
    builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real"),
355
    // ref: http://sqlite.org/syntax/literal-value.html
356
    atoms: set("null current_date current_time current_timestamp"),
357
    // ref: http://sqlite.org/lang_expr.html#binaryops
358
    operatorChars: /^[*+\-%<>!=&|/~]/,
359
    // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
360
    dateSQL: set("date time timestamp datetime"),
361
    support: set("decimallessFloat zerolessFloat"),
362
    identifierQuote: "\"",  //ref: http://sqlite.org/lang_keywords.html
363
    hooks: {
364
      // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam
365
      "@":   hookVar,
366
      ":":   hookVar,
367
      "?":   hookVar,
368
      "$":   hookVar,
369
      // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html
370
      "\"":   hookIdentifierDoublequote,
371
      // there is also support for backtics, ref: http://sqlite.org/lang_keywords.html
372
      "`":   hookIdentifier
373
    }
374
  });
375
376
  // the query language used by Apache Cassandra is called CQL, but this mime type
377
  // is called Cassandra to avoid confusion with Contextual Query Language
378
  CodeMirror.defineMIME("text/x-cassandra", {
379
    name: "sql",
380
    client: { },
381
    keywords: set("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"),
382
    builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),
383
    atoms: set("false true infinity NaN"),
384
    operatorChars: /^[<>=]/,
385
    dateSQL: { },
386
    support: set("commentSlashSlash decimallessFloat"),
387
    hooks: { }
388
  });
389
390
  // this is based on Peter Raganitsch's 'plsql' mode
391
  CodeMirror.defineMIME("text/x-plsql", {
392
    name:       "sql",
393
    client:     set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),
394
    keywords:   set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),
395
    builtin:    set("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"),
396
    operatorChars: /^[*+\-%<>!=~]/,
397
    dateSQL:    set("date time timestamp"),
398
    support:    set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
399
  });
400
401
  // Created to support specific hive keywords
402
  CodeMirror.defineMIME("text/x-hive", {
403
    name: "sql",
404
    keywords: set("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external false fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger true unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with"),
405
    builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"),
406
    atoms: set("false true null unknown"),
407
    operatorChars: /^[*+\-%<>!=]/,
408
    dateSQL: set("date timestamp"),
409
    support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
410
  });
411
412
  CodeMirror.defineMIME("text/x-pgsql", {
413
    name: "sql",
414
    client: set("source"),
415
    // https://www.postgresql.org/docs/10/static/sql-keywords-appendix.html
416
    keywords: set(sqlKeywords + "a abort abs absent absolute access according action ada add admin after aggregate all allocate also always analyse analyze any are array array_agg array_max_cardinality asensitive assertion assignment asymmetric at atomic attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli binary bit_length blob blocked bom both breadth c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain characteristics characters character_length character_set_catalog character_set_name character_set_schema char_length check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column columns column_name command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constraint constraints constraint_catalog constraint_name constraint_schema constructor contains content continue control conversion convert copy corr corresponding cost covar_pop covar_samp cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datetime_interval_code datetime_interval_precision day db deallocate dec declare default defaults deferrable deferred defined definer degree delimiter delimiters dense_rank depth deref derived describe descriptor deterministic diagnostics dictionary disable discard disconnect dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain dynamic dynamic_function dynamic_function_code each element else empty enable encoding encrypted end end-exec end_frame end_partition enforced enum equals escape event every except exception exclude excluding exclusive exec execute exists exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreign fortran forward found frame_row free freeze fs full function functions fusion g general generated get global go goto grant granted greatest grouping groups handler header hex hierarchy hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import including increment indent index indexes indicator inherit inherits initially inline inner inout input insensitive instance instantiable instead integrity intersect intersection invoker isnull isolation k key key_member key_type label lag language large last last_value lateral lc_collate lc_ctype lead leading leakproof least left length level library like_regex link listen ln load local localtime localtimestamp location locator lock locked logged lower m map mapping match matched materialized max maxvalue max_cardinality member merge message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized nothing notify notnull nowait nth_value ntile null nullable nullif nulls number object occurrences_regex octets octet_length of off offset oids old only open operator option options ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parallel parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password percent percentile_cont percentile_disc percent_rank period permission placing plans pli policy portion position position_regex power precedes preceding prepare prepared preserve primary prior privileges procedural procedure program public quote range rank read reads reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict restricted result return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns revoke right role rollback rollup routine routine_catalog routine_name routine_schema row rows row_count row_number rule savepoint scale schema schema_name scope scope_catalog scope_name scope_schema scroll search second section security selective self sensitive sequence sequences serializable server server_name session session_user setof sets share show similar simple size skip snapshot some source space specific specifictype specific_name sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset substring substring_regex succeeds sum symmetric sysid system system_time system_user t tables tablesample tablespace table_name temp template temporary then ties timezone_hour timezone_minute to token top_level_count trailing transaction transactions_committed transactions_rolled_back transaction_active transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted unique unknown unlink unlisten unlogged unnamed unnest until untyped upper uri usage user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of varbinary variadic var_pop var_samp verbose version versioning view views volatile when whenever whitespace width_bucket window within work wrapper write xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes loop repeat attach path depends detach zone"),
417
    // https://www.postgresql.org/docs/10/static/datatype.html
418
    builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),
419
    atoms: set("false true null unknown"),
420
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
421
    dateSQL: set("date time timestamp"),
422
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")
423
  });
424
425
  // Google's SQL-like query language, GQL
426
  CodeMirror.defineMIME("text/x-gql", {
427
    name: "sql",
428
    keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),
429
    atoms: set("false true"),
430
    builtin: set("blob datetime first key __key__ string integer double boolean null"),
431
    operatorChars: /^[*+\-%<>!=]/
432
  });
433
434
  // Greenplum
435
  CodeMirror.defineMIME("text/x-gpsql", {
436
    name: "sql",
437
    client: set("source"),
438
    //https://github.com/greenplum-db/gpdb/blob/master/src/include/parser/kwlist.h
439
    keywords: set("abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone"),
440
    builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),
441
    atoms: set("false true null unknown"),
442
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
443
    dateSQL: set("date time timestamp"),
444
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")
445
  });
446
447
  // Spark SQL
448
  CodeMirror.defineMIME("text/x-sparksql", {
449
    name: "sql",
450
    keywords: set("add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases datata dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with"),
451
    builtin: set("tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"),
318
    builtin: set("tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"),
452
    atoms: set("false true null"),
319
    atoms: set("false true null"),
453
    operatorChars: /^[*+\-%<>!=~&|^]/,
320
    operatorChars: /^[*+\-%<>!=~&|^]/,
Lines 460-466 CodeMirror.defineMode("sql", function(config, parserConfig) { Link Here
460
    name: "sql",
327
    name: "sql",
461
    client: set("source"),
328
    client: set("source"),
462
    // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html
329
    // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html
463
    keywords: set("alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until update variable weekday when where window"),
330
    keywords: set("alter and as asc between by count desc distinct from group having in into is join like not on or order select set table union values where limit after all and as at asc avedev avg between by case cast coalesce count current_timestamp day days define desc distinct else end escape events every exists false first from full group having hour hours in inner instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until variable weekday when where window"),
464
    builtin: {},
331
    builtin: {},
465
    atoms: set("false true null"),
332
    atoms: set("false true null"),
466
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
333
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
(-)a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/guided_reports_start.tt (-40 / +90 lines)
Lines 7-12 Link Here
7
[% USE JSON.Escape %]
7
[% USE JSON.Escape %]
8
[% PROCESS 'i18n.inc' %]
8
[% PROCESS 'i18n.inc' %]
9
[% SET footerjs = 1 %]
9
[% SET footerjs = 1 %]
10
[% USE To %]
10
11
11
[%- BLOCK area_name -%]
12
[%- BLOCK area_name -%]
12
    [%- SWITCH area -%]
13
    [%- SWITCH area -%]
Lines 1259-1265 Link Here
1259
                            <legend>SQL:</legend>
1260
                            <legend>SQL:</legend>
1260
                            <div style="margin:1em;">
1261
                            <div style="margin:1em;">
1261
                                [% PROCESS insert_runtime_parameter  %]
1262
                                [% PROCESS insert_runtime_parameter  %]
1262
                                <textarea id="sql" name="sql" class="required" required="required" cols="50" rows="10">[% sql | html %]</textarea>
1263
                                <textarea id="sql" name="sql" class="required" required="required" cols="50" rows="10" >[% sql | html %]</textarea>
1264
                                <span style='color:#383838; font-style:italic'>* In order to achieve auto-complete for columns, please prepend the column name with the table name, followed by a period. For example: 'borrowers.surname'</span>
1265
                                <br/>
1263
                                <span class="required">Required</span>
1266
                                <span class="required">Required</span>
1264
                            </div>
1267
                            </div>
1265
                        </fieldset>
1268
                        </fieldset>
Lines 1269-1274 Link Here
1269
                            <input type="submit" name="submit" class="btn btn-primary" value="Save report" />
1272
                            <input type="submit" name="submit" class="btn btn-primary" value="Save report" />
1270
                            <a href="/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved" class="cancel">Cancel</a>
1273
                            <a href="/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved" class="cancel">Cancel</a>
1271
                        </fieldset>
1274
                        </fieldset>
1275
1272
                    </form>
1276
                    </form>
1273
                [% END #/IF ( create ) %]
1277
                [% END #/IF ( create ) %]
1274
1278
Lines 1371-1376 Link Here
1371
                            <legend>SQL:</legend>
1375
                            <legend>SQL:</legend>
1372
                                [% PROCESS insert_runtime_parameter  %]
1376
                                [% PROCESS insert_runtime_parameter  %]
1373
                                <textarea id="sql" name="sql" class="required" required="required" cols="50" rows="10">[% sql | html %]</textarea>
1377
                                <textarea id="sql" name="sql" class="required" required="required" cols="50" rows="10">[% sql | html %]</textarea>
1378
                                <span style='color:#383838; font-style:italic'>* In order to achieve auto-complete for columns, please prepend the column name with the table name, followed by a period. For example: 'borrowers.surname'</span>
1379
                                <br/>
1374
                                <span class="required" style="margin-left:30px;">Required</span>
1380
                                <span class="required" style="margin-left:30px;">Required</span>
1375
                        </fieldset>
1381
                        </fieldset>
1376
1382
Lines 1494-1501 Link Here
1494
    [% END %]
1500
    [% END %]
1495
    [% Asset.js( "lib/codemirror/codemirror.min.js" ) | $raw %]
1501
    [% Asset.js( "lib/codemirror/codemirror.min.js" ) | $raw %]
1496
    [% Asset.js( "lib/codemirror/overlay.min.js" ) | $raw %]
1502
    [% Asset.js( "lib/codemirror/overlay.min.js" ) | $raw %]
1497
    [% Asset.js( "lib/codemirror/sql.min.js" ) | $raw %]
1503
    [% Asset.js( "lib/codemirror/sql.js" ) | $raw %]
1504
    [% Asset.js( "lib/codemirror/show-hint.js" ) | $raw %]
1505
    [% Asset.css("lib/codemirror/show-hint.css") | $raw %]
1506
    [% Asset.js( "lib/codemirror/sql-hint.js" ) | $raw %]
1507
    [% Asset.js( "lib/codemirror/highlight.js" ) | $raw %]
1508
    [% Asset.css("lib/codemirror/highlight.css") | $raw %]
1498
    [% Asset.js( "js/mana.js" ) | $raw %]
1509
    [% Asset.js( "js/mana.js" ) | $raw %]
1510
1499
    <script>
1511
    <script>
1500
1512
1501
        function hide_bar_element() {
1513
        function hide_bar_element() {
Lines 1526-1563 Link Here
1526
            }
1538
            }
1527
        }
1539
        }
1528
1540
1529
        /* overlay a syntax-highlighting definition on top of the existing sql one */
1530
        CodeMirror.defineMode("sqlPlaceholders", function(config, parserConfig) {
1531
            var sqlPlaceholdersOverlay = {
1532
                token: function(stream, state) {
1533
                    var ch;
1534
1535
                    if (stream.match("<<")) {
1536
                        while ((ch = stream.next()) != null) {
1537
                            if (ch == ">" && stream.next() == ">") {
1538
                                stream.eat(">");
1539
                                return "sqlParams";
1540
                            }
1541
                        }
1542
                    }
1543
1544
                    if (stream.match("[[")) {
1545
                        while ((ch = stream.next()) != null) {
1546
                            if (ch == "]" && stream.next() == "]") {
1547
                                stream.eat("]");
1548
                                return "columnPlaceholder";
1549
                            }
1550
                        }
1551
                    }
1552
1553
                    else if (stream.next() != null) {
1554
                        return null;
1555
                    }
1556
                }
1557
            };
1558
            return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "text/x-sql"), sqlPlaceholdersOverlay);
1559
        });
1560
1561
        var MSG_CONFIRM_DELETE = _("Are you sure you want to delete this report? This cannot be undone.");
1541
        var MSG_CONFIRM_DELETE = _("Are you sure you want to delete this report? This cannot be undone.");
1562
        var group_subgroups = {};
1542
        var group_subgroups = {};
1563
        [% FOREACH group IN groups_with_subgroups %]
1543
        [% FOREACH group IN groups_with_subgroups %]
Lines 1574-1585 Link Here
1574
1554
1575
            var editor = CodeMirror.fromTextArea(sql, {
1555
            var editor = CodeMirror.fromTextArea(sql, {
1576
                lineNumbers: true,
1556
                lineNumbers: true,
1577
                mode: "sqlPlaceholders", /* text/x-sql plus custom sqlPlaceholders configuration */
1557
                mode: "text/x-sql",
1578
                lineWrapping: true,
1558
                lineWrapping: true,
1579
                smartIndent: false
1559
                smartIndent: false,
1560
                keyword: { // Custom highlighting for items bounded in [[ ]] or << >>.
1561
                    "\\[\\[(.*?)\\]\\]":"style1",
1562
                    "<<(.*?)>>":"style1"
1563
                },
1564
                extraKeys: {"Tab": "autocomplete"}, //enable tab to accept auto-complete
1565
                hint: CodeMirror.hint.sql,
1580
            });
1566
            });
1567
            var ExcludedTriggerKeys = { //key-code combinations of keys that will not fire the auto-complete script
1568
                "8": "backspace",
1569
                "9": "tab",
1570
                "13": "enter",
1571
                "16": "shift",
1572
                "17": "ctrl",
1573
                "18": "alt",
1574
                "19": "pause",
1575
                "20": "capslock",
1576
                "27": "escape",
1577
                "33": "pageup",
1578
                "32": "spacebar",
1579
                "34": "pagedown",
1580
                "35": "end",
1581
                "36": "home",
1582
                "37": "left",
1583
                "38": "up",
1584
                "39": "right",
1585
                "40": "down",
1586
                "45": "insert",
1587
                "46": "delete",
1588
                "56": "asterisk",
1589
                "59": "semicolon",
1590
                "91": "left window key",
1591
                "92": "right window key",
1592
                "93": "select",
1593
                "106": "asterisk",
1594
                "107": "add",
1595
                "109": "subtract",
1596
                "110": "decimal point",
1597
                "111": "divide",
1598
                "112": "f1",
1599
                "113": "f2",
1600
                "114": "f3",
1601
                "115": "f4",
1602
                "116": "f5",
1603
                "117": "f6",
1604
                "118": "f7",
1605
                "119": "f8",
1606
                "120": "f9",
1607
                "121": "f10",
1608
                "122": "f11",
1609
                "123": "f12",
1610
                "144": "numlock",
1611
                "145": "scrolllock",
1612
                "186": "semicolon",
1613
                "187": "equalsign",
1614
                "188": "comma",
1615
                "189": "dash",
1616
                "191": "slash",
1617
                "192": "graveaccent",
1618
                "220": "backslash",
1619
                "222": "quote"
1620
            }
1621
            //Trigger auto-complete on all keys not in dictionary of exclusions above.
1622
            editor.on("keyup", function(cm, e) {
1623
                if (ExcludedTriggerKeys[e.keyCode] == undefined) {
1624
                         CodeMirror.commands.autocomplete(editor, null, { completeSingle: false });
1625
                }
1626
            })
1581
1627
1582
            // https://stackoverflow.com/questions/2086287/how-to-clear-jquery-validation-error-messages#answer-16025232
1628
           // https://stackoverflow.com/questions/2086287/how-to-clear-jquery-validation-error-messages#answer-16025232
1583
            function clearValidation( formElement ){
1629
            function clearValidation( formElement ){
1584
                // formElement should be a jQuery object
1630
                // formElement should be a jQuery object
1585
                var validator = formElement.validate();
1631
                var validator = formElement.validate();
Lines 1594-1604 Link Here
1594
        [% END %]
1640
        [% END %]
1595
1641
1596
        [% IF ( showsql ) %]
1642
        [% IF ( showsql ) %]
1643
1597
            var editor = CodeMirror.fromTextArea(sql, {
1644
            var editor = CodeMirror.fromTextArea(sql, {
1598
                lineNumbers: false,
1645
                lineNumbers: false,
1599
                mode: "sqlPlaceholders", /* text/x-sql plus custom sqlPlaceholders configuration */
1646
                mode: "text/x-sql",
1600
                lineWrapping: true,
1647
                lineWrapping: true,
1601
                readOnly: true
1648
                readOnly: true,
1649
                keyword: { // Custom highlighting for items bounded in [[ ]] or << >>.
1650
                    "\\[\\[(.*?)\\]\\]":"style2",
1651
                    "<<(.*?)>>":"style1"
1652
               },
1602
            });
1653
            });
1603
        [% END %]
1654
        [% END %]
1604
1655
1605
- 

Return to bug 32613