!function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror"),require("../../mode/sql/sql")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../../mode/sql/sql"],t):t(CodeMirror)}(function(t){"use strict";function r(r){var n=r.doc.modeOption;return"sql"===n&&(n="text/x-sql"),t.resolveMode(n).keywords}function n(t){return"string"==typeof t?t:t.text}function e(t,r){if(!t.slice)return t[r];for(var e=t.length-1;e>=0;e--)if(n(t[e])==r)return t[e]}function o(t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]=t[n]);return r}function i(t,r){var e=t.length,o=n(r).substr(0,e);return t.toUpperCase()===o.toUpperCase()}function s(t,r,n,e){for(var o in n)n.hasOwnProperty(o)&&(Array.isArray(n)&&(o=n[o]),i(r,o)&&t.push(e(o)))}function a(t){return"."==t.charAt(0)&&(t=t.substr(1)),t.replace(/`/g,"")}function u(t){for(var r=n(t).split("."),e=0;e<r.length;e++)r[e]="`"+r[e]+"`";var i=r.join(".");return"string"==typeof t?i:(t=o(t),t.text=i,t)}function f(t,r,n,i){for(var f=!1,c=[],l=r.start,p=!0;p;)p="."==r.string.charAt(0),f=f||"`"==r.string.charAt(0),l=r.start,c.unshift(a(r.string)),r=i.getTokenAt(y(t.line,r.start)),"."==r.string&&(p=!0,r=i.getTokenAt(y(t.line,r.start)));var v=c.join(".");s(n,v,h,function(t){return f?u(t):t}),s(n,v,d,function(t){return f?u(t):t}),v=c.pop();var A=c.join(".");e(h,A)||(A=g(A,i));var m=e(h,A);return m&&Array.isArray(h)&&m.columns&&(m=m.columns),m&&s(n,v,m,function(t){return"string"==typeof t?t=A+"."+t:(t=o(t),t.text=A+"."+t.text),f?u(t):t}),l}function c(t,r){if(t)for(var n=/[,;]/g,e=t.split(" "),o=0;o<e.length;o++)r(e[o]?e[o].replace(n,""):"")}function l(t){return t.line+t.ch/Math.pow(10,6)}function p(t){return y(Math.floor(t),+t.toString().split(".").pop())}function g(t,r){for(var n=r.doc,o=n.getValue(),i=t.toUpperCase(),s="",a="",u=[],f={start:y(0,0),end:y(r.lastLine(),r.getLineHandle(r.lastLine()).length)},g=o.indexOf(A.QUERY_DIV);-1!=g;)u.push(n.posFromIndex(g)),g=o.indexOf(A.QUERY_DIV,g+1);u.unshift(y(0,0)),u.push(y(r.lastLine(),r.getLineHandle(r.lastLine()).text.length));for(var d=0,v=l(r.getCursor()),m=0;m<u.length;m++){var x=l(u[m]);if(v>d&&v<=x){f={start:p(d),end:p(x)};break}d=x}for(var b=n.getRange(f.start,f.end,!1),m=0;m<b.length;m++){if(c(b[m],function(t){var r=t.toUpperCase();r===i&&e(h,s)&&(a=s),r!==A.ALIAS_KEYWORD&&(s=t)}),a)break}return a}var h,d,v,A={QUERY_DIV:";",ALIAS_KEYWORD:"AS"},y=t.Pos;t.registerHelper("hint","sql",function(t,n){h=n&&n.tables||{};var o=n&&n.defaultTable;d=o&&e(h,o)||[],v=v||r(t);var i,a,u,c=t.getCursor(),l=[],p=t.getTokenAt(c);return p.end>c.ch&&(p.end=c.ch,p.string=p.string.slice(0,c.ch-p.start)),p.string.match(/^[.`\w@]\w*$/)?(u=p.string,i=p.start,a=p.end):(i=a=c.ch,u=""),"."==u.charAt(0)||"`"==u.charAt(0)?i=f(c,p,l,t):(s(l,u,h,function(t){return t}),s(l,u,d,function(t){return t}),s(l,u,v,function(t){return t.toUpperCase()})),{list:l,from:y(c.line,i),to:y(c.line,a)}})});