forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
1 lines (1 loc) · 10 KB
/
Copy pathmain.js
File metadata and controls
1 lines (1 loc) · 10 KB
1
define(function(require,exports,module){const AppInit=brackets.getModule("utils/AppInit"),CodeHintManager=brackets.getModule("editor/CodeHintManager"),EditorManager=brackets.getModule("editor/EditorManager"),TabstopManager=brackets.getModule("editor/TabstopManager"),Strings=brackets.getModule("strings"),PROVIDER_PRIORITY=100,STYLE_JSDOC="jsdoc",STYLE_TSDOC="tsdoc",STYLE_PHPDOC="phpdoc",STYLE_TAGDOC="tagdoc",STYLE_PYDOC="pydoc",LANGUAGES={javascript:{style:"jsdoc",params:"first",opener:"block",label:"DOC_COMMENT_ADD_JSDOC"},typescript:{style:STYLE_TSDOC,params:"first",opener:"block",label:"DOC_COMMENT_ADD_JSDOC"},jsx:{style:"jsdoc",params:"first",opener:"block",label:"DOC_COMMENT_ADD_JSDOC"},tsx:{style:STYLE_TSDOC,params:"first",opener:"block",label:"DOC_COMMENT_ADD_JSDOC"},php:{style:STYLE_PHPDOC,params:"first",opener:"block",label:"DOC_COMMENT_ADD_PHPDOC"},java:{style:STYLE_TAGDOC,params:"last",opener:"block",label:"DOC_COMMENT_ADD_JAVADOC"},c:{style:STYLE_TAGDOC,params:"last",opener:"block",label:"DOC_COMMENT_ADD_DOXYGEN"},cpp:{style:STYLE_TAGDOC,params:"last",opener:"block",label:"DOC_COMMENT_ADD_DOXYGEN"},python:{style:STYLE_PYDOC,params:"first",opener:"pydoc",label:"DOC_COMMENT_ADD_DOCSTRING"}},OPENERS={block:{full:/^\s*\/\*\*$/,partial:/^\s*\/\*{0,2}$/,chars:"/*",dir:"below",fullLine:!1,alwaysGate:!1,replaceLine:!1},pydoc:{full:/^\s*"{3,6}$/,partial:/^\s*"{1,6}$/,chars:'"',dir:"above",fullLine:!0,alwaysGate:!0,replaceLine:!0}};function _configFor(editor){return LANGUAGES[editor.getLanguageForSelection().getId()]||null}function _eachTopLevel(s,visit){let depth=0,quote=null;for(let i=0;i<s.length;i++){const c=s[i];if(quote){"\\"===c?i++:c===quote&&(quote=null);continue}if('"'===c||"'"===c||"`"===c){quote=c;continue}const open="("===c||"["===c||"{"===c||"<"===c,close=")"===c||"]"===c||"}"===c||">"===c&&"="!==s[i-1];open||close||visit(c,i,0===depth),open?depth++:close&&depth--}}function _splitTopLevel(s,sep){const out=[];let start=0;return _eachTopLevel(s,function(c,i,top){top&&c===sep&&(out.push(s.slice(start,i)),start=i+1)}),out.push(s.slice(start)),out}function _indexOfTopLevel(s,pred){let found=-1;return _eachTopLevel(s,function(c,i,top){-1===found&&top&&pred(c,i)&&(found=i)}),found}function _validType(t){if(!(t=t.trim()))return!1;let depth=0,quote=null;for(let i=0;i<t.length;i++){const c=t[i];if(quote)"\\"===c?i++:c===quote&&(quote=null);else if('"'!==c&&"'"!==c&&"`"!==c){if("("===c||"["===c||"{"===c||"<"===c?depth++:(")"===c||"]"===c||"}"===c||">"===c&&"="!==t[i-1])&&depth--,depth<0)return!1}else quote=c}return 0===depth&&null===quote}function _declarationFor(editor,openerLine,dir){const lastLine=editor.lineCount()-1,step="above"===dir?-1:1;let l=openerLine+step;for(;l>=0&&l<=lastLine&&""===editor.document.getLine(l).trim();)l+=step;if(l<0||l>lastLine)return null;let text=editor.document.getLine(l),guard=0;for(;0!==_parenDepth(text)&&l>0&&l<lastLine&&guard<30;)l+=step,text=step>0?text+" "+editor.document.getLine(l):editor.document.getLine(l)+" "+text,guard++;return text}function _parenDepth(text){let depth=0;for(let i=0;i<text.length;i++)"("===text[i]?depth++:")"===text[i]&&depth--;return depth}function _splitParams(s){return _splitTopLevel(s,",").filter(function(t){return""!==t.trim()})}const IDENT=/[A-Za-z_][\w]*/g,PARAMS_TO_SKIP={self:!0,cls:!0,this:!0,void:!0};function _isDefaultEq(t){return function(c,i){return"="===c&&">"!==t[i+1]&&"="!==t[i+1]&&"="!==t[i-1]&&"<"!==t[i-1]&&">"!==t[i-1]&&"!"!==t[i-1]}}function _parseParam(token,convention){let t=token.trim();if(!t)return null;const eq=_indexOfTopLevel(t=t.replace(/^\.\.\.\s*/,""),_isDefaultEq(t));-1!==eq&&(t=t.slice(0,eq));const colon=_indexOfTopLevel(t,function(c){return":"===c});let namePart=(-1===colon?t:t.slice(0,colon)).trim(),typePart=-1===colon?null:t.slice(colon+1).trim(),optional=!1,name;if(namePart.endsWith("?")&&(optional=!0,namePart=namePart.slice(0,-1).trim()),"first"===convention){const m=namePart.match(/^[*&\s]*(\$?[A-Za-z_][\w]*)/);name=m?m[1]:null}else{const ids=namePart.match(IDENT);name=ids&&ids.length?ids[ids.length-1]:null,typePart=null}return name?{name:name,type:typePart&&_validType(typePart)?typePart.trim():null,optional:optional}:null}function _returnType(after){const m=after.match(/^\s*(?::|->)\s*/);if(!m)return null;const s=after.slice(m[0].length);let depth=0,quote=null,end=s.length;for(let i=0;i<s.length;i++){const c=s[i];if(quote)"\\"===c?i++:c===quote&&(quote=null);else if('"'!==c&&"'"!==c&&"`"!==c){if(0===depth&&("{"===c||";"===c||"="===c&&">"===s[i+1])){end=i;break}"("===c||"["===c||"{"===c||"<"===c?depth++:(")"===c||"]"===c||"}"===c||">"===c&&"="!==s[i-1])&&depth--}else quote=c}const type=s.slice(0,end).trim();return _validType(type)?type:null}function _parseSignature(declText,convention){if(!declText)return null;const open=declText.indexOf("("),classMatch=/\b(class|interface|struct|enum|trait)\b/.exec(declText);if(classMatch&&(-1===open||classMatch.index<open))return{params:[],returnType:null,isClass:!0,hasReturn:!1,hasReturnType:!1,isDeclaration:!0};if(-1===open)return{params:[],returnType:null,isClass:!1,hasReturn:!1,hasReturnType:!1,isDeclaration:!1};let depth=0,close=-1;for(let i=open;i<declText.length;i++)if("("===declText[i])depth++;else if(")"===declText[i]&&0===--depth){close=i;break}const inner=-1===close?declText.slice(open+1):declText.slice(open+1,close),params=[];_splitParams(inner).forEach(function(tok){const p=_parseParam(tok,convention);p&&!PARAMS_TO_SKIP[p.name]&¶ms.push(p)});const after=-1===close?"":declText.slice(close+1),isCtor=/\b(constructor|__init__)\b/.test(declText)||/\bvoid\s+\w+\s*\(/.test(declText),isVoid=/:\s*void\b/.test(after)||/->\s*(None|\(\s*\))/.test(after)||isCtor,hasReturnType=/->\s*(?!None\b)[A-Za-z_]/.test(after);return{params:params,returnType:_returnType(after),isClass:!1,hasReturn:!isVoid,hasReturnType:hasReturnType,isDeclaration:!0}}function _esc(text){return String(text).replace(/[\\$}]/g,"\\$&")}function _buildJsDoc(sig,indent){const star=indent+" * ",out=["/**",star+"${1:"+_escDesc(Strings.DOC_COMMENT_SUMMARY)+"}"];let stop=2;if(sig&&!sig.isClass&&(sig.params.forEach(function(p){const type=p.type?_esc(p.type):"*",nameOut=p.optional?"["+_esc(p.name)+"]":_esc(p.name);out.push(star+"@param {${"+stop+++":"+type+"}} "+nameOut)}),sig.hasReturn)){const rtype=sig.returnType?_esc(sig.returnType):"*";out.push(star+"@returns {${"+stop+++":"+rtype+"}}")}return out.push(indent+" */"),out.join("\n")}function _buildPhpDoc(sig,indent){const star=indent+" * ",out=["/**",star+"${1:"+_escDesc(Strings.DOC_COMMENT_SUMMARY)+"}"];let stop=2;return sig&&!sig.isClass&&(sig.params.forEach(function(p){out.push(star+"@param ${"+stop+++":mixed} "+_esc(p.name))}),sig.hasReturn&&out.push(star+"@return ${"+stop+++":mixed}")),out.push(indent+" */"),out.join("\n")}function _buildTagDoc(returnTag){return function(sig,indent){const star=indent+" * ",out=["/**",star+"${1:"+_escDesc(Strings.DOC_COMMENT_SUMMARY)+"}"];return sig&&!sig.isClass&&(sig.params.forEach(function(p){out.push(star+"@param "+_esc(p.name))}),sig.hasReturn&&out.push(star+returnTag)),out.push(indent+" */"),out.join("\n")}}function _buildPyDoc(sig,indent){const out=['"""${1:'+_escDesc(Strings.DOC_COMMENT_SUMMARY)+"}"];let stop=2;const desc=_escDesc(Strings.DOC_COMMENT_DESC);return sig&&sig.params.length&&(out.push(""),out.push(indent+"Args:"),sig.params.forEach(function(p){out.push(indent+" "+_esc(p.name)+": ${"+stop+++":"+desc+"}")})),sig&&sig.hasReturnType&&(out.push(""),out.push(indent+"Returns:"),out.push(indent+" ${"+stop+++":"+desc+"}")),out.push(indent+'"""'),out.join("\n")}function _escDesc(text){return String(text).replace(/[\\}]/g,"\\$&")}function _buildSnippet(style,sig,indent){switch(style){case STYLE_PYDOC:return _buildPyDoc(sig,indent);case STYLE_PHPDOC:return _buildPhpDoc(sig,indent);case STYLE_TAGDOC:return _buildTagDoc("@return")(sig,indent);case STYLE_TSDOC:return _buildTagDoc("@returns")(sig,indent);default:return _buildJsDoc(sig,indent)}}function _openerContext(editor,implicitChar){const cfg=_configFor(editor);if(!cfg)return null;const opener=OPENERS[cfg.opener];if(implicitChar&&-1===opener.chars.indexOf(implicitChar))return null;const cursor=editor.getCursorPos(),lineText=editor.document.getLine(cursor.line),text=opener.fullLine?lineText.trim():lineText.slice(0,cursor.ch);if(!opener.partial.test(text))return null;if(opener.full.test(text)&&!opener.alwaysGate)return{cfg:cfg};const sig=_parseSignature(_declarationFor(editor,cursor.line,opener.dir),cfg.params);return sig&&sig.isDeclaration?{cfg:cfg}:null}function DocCommentHintProvider(){}DocCommentHintProvider.prototype.hasHints=function(editor,implicitChar){this.editor=editor;const ctx=_openerContext(editor,implicitChar);return this._cfg=ctx&&ctx.cfg,!!ctx},DocCommentHintProvider.prototype.getHints=function(){if(!this.editor||!_openerContext(this.editor,null))return null;const cfg=this._cfg,marker="above"===OPENERS[cfg.opener].dir?'"""':"/**",$hint=$("<span>").addClass("doc-comment-hint").data("docComment",!0).append($("<span>").addClass("doc-comment-hint-marker").text(marker)).append($("<span>").addClass("doc-comment-hint-label").text(" "+Strings[cfg.label]));return{hints:[$hint],match:null,selectInitial:!0,handleWideResults:!0}},DocCommentHintProvider.prototype.insertHint=function(){const editor=this.editor||EditorManager.getActiveEditor(),cfg=editor&&_configFor(editor);if(!editor||!cfg)return!1;const cursor=editor.getCursorPos(),line=editor.document.getLine(cursor.line),indent=(line.match(/^\s*/)||[""])[0],opener=OPENERS[cfg.opener],decl=_declarationFor(editor,cursor.line,opener.dir),sig=_parseSignature(decl,cfg.params),snippet=_buildSnippet(cfg.style,sig,indent),startPos={line:cursor.line,ch:indent.length},endPos={line:cursor.line,ch:opener.replaceLine?line.length:cursor.ch};return TabstopManager.insertSnippet(editor,snippet,startPos,endPos),!1},AppInit.appReady(function(){const provider=new DocCommentHintProvider;CodeHintManager.registerHintProvider(provider,Object.keys(LANGUAGES),100)}),exports._parseSignature=_parseSignature,exports._buildSnippet=_buildSnippet,exports._splitParams=_splitParams,exports._parseParam=_parseParam,exports._validType=_validType,exports._Provider=DocCommentHintProvider,exports._LANGUAGES=LANGUAGES});