define(function(require,exports,module){var Commands=require("command/Commands"),Strings=require("strings"),Editor=require("editor/Editor").Editor,CommandManager=require("command/CommandManager"),EditorManager=require("editor/EditorManager"),WorkspaceManager=require("view/WorkspaceManager"),StringUtils=require("utils/StringUtils"),TokenUtils=require("utils/TokenUtils"),CodeMirror=require("thirdparty/CodeMirror/lib/codemirror"),_=require("thirdparty/lodash"),ChangeHelper=require("editor/EditorHelper/ChangeHelper"),LanguageManager=require("language/LanguageManager"),ImageUploadManager=require("features/ImageUploadManager"),Metrics=require("utils/Metrics"),Dialogs=require("widgets/Dialogs"),AppInit=require("utils/AppInit"),DIRECTION_UP=-1,DIRECTION_DOWN=1;function _createSpecialLineExp(lineSyntax,blockSyntax){var i,character,escapedCharacter,subExps=[],prevChars="";for(i=lineSyntax.length;i0||prefixPos&&CodeMirror.cmpPos(sel.end,prefixPos)<0)&&(canComment=!0)}else endLine=sel.end.line,0===sel.end.ch&&editor.hasSelection()&&endLine--,_containsNotLineComment(editor,sel.start.line,endLine,lineExp)?canComment=!0:lineUncomment=!0;else canComment=!0;if(invalidComment)edit={edit:[],selection:selectionsToTrack};else if(lineUncomment)edit=null;else{if(canComment){var completeLineSel=0===sel.start.ch&&0===sel.end.ch&&sel.start.line0&&(completeLineSel?pos.line++:pos.line===sel.end.line&&(pos.ch+=suffix.length)),CodeMirror.cmpPos(pos,sel.start)>=0&&(completeLineSel?pos.line++:pos.line!==sel.start.line||isIndentLineCommand()&&pos.cheditor.getFirstVisibleLine()&&(from.line-=1,from.ch=doc.getLine(from.line).length),to.line-=1,to.ch=doc.getLine(to.line).length),edits.push({edit:{text:"",start:from,end:to}})}),doc.doMultipleEdits(edits)}}function moveLine(editor,direction){if(editor=editor||EditorManager.getFocusedEditor()){var doc=editor.document,lineSelections=editor.convertToLineSelections(editor.getSelections()),isInlineWidget=!!EditorManager.getFocusedInlineWidget(),firstLine=editor.getFirstVisibleLine(),lastLine=editor.getLastVisibleLine(),totalLines=editor.lineCount(),lineLength=0,edits=[],newSels=[],pos={};_.each(lineSelections,function(lineSel){var sel=lineSel.selectionForEdit,editGroup=[];switch(direction){case DIRECTION_UP:if(sel.start.line!==firstLine){var prevText=doc.getRange({line:sel.start.line-1,ch:0},sel.start);sel.end.line===lastLine+1&&(isInlineWidget?(prevText=prevText.substring(0,prevText.length-1),lineLength=doc.getLine(sel.end.line-1).length,editGroup.push({text:"\n",start:{line:sel.end.line-1,ch:lineLength}})):prevText="\n"+prevText.substring(0,prevText.length-1)),editGroup.push({text:"",start:{line:sel.start.line-1,ch:0},end:sel.start}),editGroup.push({text:prevText,start:{line:sel.end.line-1,ch:0}}),_.each(lineSel.selectionsToTrack,function(originalSel){originalSel.start.line--,originalSel.end.line--}),edits.push({edit:editGroup,selection:lineSel.selectionsToTrack})}break;case DIRECTION_DOWN:if(sel.end.line<=lastLine){var nextText=doc.getRange(sel.end,{line:sel.end.line+1,ch:0}),deletionStart=sel.end;sel.end.line===lastLine&&(isInlineWidget?(sel.end.line===totalLines-1&&(nextText+="\n"),lineLength=doc.getLine(sel.end.line-1).length,editGroup.push({text:"\n",start:{line:sel.end.line,ch:doc.getLine(sel.end.line).length}})):(nextText+="\n",deletionStart={line:sel.end.line-1,ch:doc.getLine(sel.end.line-1).length})),editGroup.push({text:"",start:deletionStart,end:{line:sel.end.line+1,ch:0}}),lineLength&&editGroup.push({text:"",start:{line:sel.end.line-1,ch:lineLength},end:{line:sel.end.line,ch:0}}),editGroup.push({text:nextText,start:{line:sel.start.line,ch:0}}),edits.push({edit:editGroup})}}}),edits.length&&(newSels=doc.doMultipleEdits(edits),pos.ch=0,direction===DIRECTION_UP?(editor.setSelections(newSels),pos.line=editor.getSelection().start.line):direction===DIRECTION_DOWN?pos.line=editor.getSelection().end.line:(console.error("EditorCommandHandler.moveLine() called with invalid argument 'direction' = %d",direction),pos=null),editor._codeMirror.scrollIntoView(pos))}}function moveLineUp(editor){moveLine(editor,DIRECTION_UP)}function moveLineDown(editor){moveLine(editor,DIRECTION_DOWN)}function openLine(editor,direction){if(editor=editor||EditorManager.getFocusedEditor()){var selections=editor.getSelections(),isInlineWidget=!!EditorManager.getFocusedInlineWidget(),lastLine=editor.getLastVisibleLine(),doc=editor.document,edits=[],newSelections,line;doc.batchOperation(function(){_.each(selections,function(sel,index){if(0===index||direction===DIRECTION_UP&&sel.start.line>selections[index-1].start.line||direction===DIRECTION_DOWN&&sel.end.line>selections[index-1].end.line){switch(direction){case DIRECTION_UP:line=sel.start.line;break;case DIRECTION_DOWN:line=sel.end.line,0!==CodeMirror.cmpPos(sel.start,sel.end)&&0===sel.end.ch||line++}var insertPos;insertPos=line>lastLine&&isInlineWidget?{line:line-1,ch:doc.getLine(line-1).length}:{line:line,ch:0},edits.push({edit:{text:"\n",start:insertPos},selection:{start:insertPos,end:insertPos,primary:sel.primary}})}else sel.primary&&(edits[edits.length-1].selections[0].primary=!0)}),newSelections=doc.doMultipleEdits(edits,"+input"),_.each(newSelections,function(sel){doc._masterEditor._codeMirror.indentLine(sel.start.line,"smart",!0),sel.start.ch=null,sel.end=sel.start})}),editor.setSelections(newSelections)}}function openLineAbove(editor){openLine(editor,DIRECTION_UP)}function openLineBelow(editor){openLine(editor,DIRECTION_DOWN)}function indentText(){var editor=EditorManager.getFocusedEditor();editor&&editor._codeMirror.execCommand("indentMore")}function unindentText(){var editor=EditorManager.getFocusedEditor();editor&&editor._codeMirror.execCommand("indentLess")}function selectLine(editor){(editor=editor||EditorManager.getFocusedEditor())&&editor.setSelections(_.pluck(editor.convertToLineSelections(editor.getSelections(),{expandEndAtStartOfLine:!0}),"selectionForEdit"))}function splitSelIntoLines(editor){(editor=editor||EditorManager.getFocusedEditor())&&editor._codeMirror.execCommand("splitSelectionByLine")}function addCursorToSelection(editor,dir){if(editor=editor||EditorManager.getFocusedEditor()){var origSels=editor.getSelections(),newSels=[];_.each(origSels,function(sel){var pos,colOffset;(-1===dir&&sel.start.line>editor.getFirstVisibleLine()||1===dir&&sel.end.line{console.error(err),_execCommand("paste")}).finally(()=>{result.resolve()}),result.promise()}const ALLOWED_IMAGE_TYPES=["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"];function _handleImagePaste(editor,cm,event){const items=event.clipboardData&&event.clipboardData.items;if(!items)return!1;let imageItem=null;for(let i=0;i0)return!1;const doc=editor.document;if(!doc||!doc.file)return!1;const lang=LanguageManager.getLanguageForPath(doc.file.fullPath),langId=lang?lang.getId():"";if("markdown"!==langId&&"gfm"!==langId)return!1;if(!ImageUploadManager.isImageUploadAvailable())return!1;event.preventDefault(),Metrics.countEvent(Metrics.EVENT_TYPE.MD,"image","pasteCM");const blob=imageItem.getAsFile(),fileName=blob.name||"image."+blob.type.split("/")[1],provider=ImageUploadManager.getImageUploadProvider(),cmDoc=cm.getDoc();let marker=null;function _clearPlaceholder(){if(marker){const range=marker.find();marker.clear(),range&&cmDoc.replaceRange("",range.from,range.to),marker=null}}return provider.uploadImage(blob,fileName,function onUploadStart(){const cursor=cmDoc.getCursor(),placeholder=`![${Strings.IMAGE_UPLOADING} ${fileName}](https://user-cdn.phcode.site/images/uploading.svg)`;cmDoc.replaceRange(placeholder,cursor);const from=cursor,to={line:cursor.line,ch:cursor.ch+placeholder.length};marker=cmDoc.markText(from,to,{className:"image-uploading",clearWhenEmpty:!1})}).then(function(result){if(result.embedURL){if(marker){const range=marker.find();marker.clear(),marker=null,range&&cmDoc.replaceRange(`![${fileName}](${result.embedURL})`,range.from,range.to)}}else if("cancelled"===result.error);else if("login_required"===result.error){_clearPlaceholder();const previewURL=URL.createObjectURL(blob),loginHTML=`
\n

${Strings.IMAGE_UPLOAD_LOGIN_REQUIRED_MSG}

\n
\n \n
\n
`,dialog=Dialogs.showModalDialog("",Strings.IMAGE_UPLOAD_LOGIN_REQUIRED_TITLE,loginHTML,[{className:Dialogs.DIALOG_BTN_CLASS_NORMAL,id:Dialogs.DIALOG_BTN_CANCEL,text:Strings.CANCEL},{className:Dialogs.DIALOG_BTN_CLASS_PRIMARY,id:"login",text:Strings.IMAGE_UPLOAD_LOGIN_BTN}]);dialog.done(function(id){if(URL.revokeObjectURL(previewURL),"login"===id){const profileBtn=document.getElementById("user-profile-button");profileBtn&&profileBtn.click()}})}else if("UPGRADE_TO_PRO"===result.errorCode){_clearPlaceholder();const ProDialogs=brackets.getModule("extensionsIntegrated/phoenix-pro/services/pro-dialogs");ProDialogs&&ProDialogs.showUpsellDialog&&ProDialogs.showUpsellDialog(Strings.IMAGE_UPLOAD_LIMIT_TITLE,result.errorLoc,"imgUpload")}else _clearPlaceholder(),console.error("Image upload failed:",result.error,result.errorLoc),Dialogs.showModalDialog("",Strings.IMAGE_UPLOAD_FAILED,result.errorLoc||Strings.IMAGE_UPLOAD_FAILED)}).catch(function(err){_clearPlaceholder(),console.error("Image upload error:",err)}),!0}AppInit.appReady(function(){const editorHolder=document.getElementById("editor-holder");editorHolder&&editorHolder.addEventListener("paste",function(e){const editor=EditorManager.getFocusedEditor();editor&&_handleImagePaste(editor,editor._codeMirror,e)},!0)}),CommandManager.register(Strings.CMD_INDENT,Commands.EDIT_INDENT,indentText),CommandManager.register(Strings.CMD_UNINDENT,Commands.EDIT_UNINDENT,unindentText),CommandManager.register(Strings.CMD_COMMENT,Commands.EDIT_LINE_COMMENT,lineComment),CommandManager.register(Strings.CMD_BLOCK_COMMENT,Commands.EDIT_BLOCK_COMMENT,blockComment),CommandManager.register(Strings.CMD_DUPLICATE,Commands.EDIT_DUPLICATE,duplicateText),CommandManager.register(Strings.CMD_DELETE_LINES,Commands.EDIT_DELETE_LINES,deleteCurrentLines),CommandManager.register(Strings.CMD_LINE_UP,Commands.EDIT_LINE_UP,moveLineUp),CommandManager.register(Strings.CMD_LINE_DOWN,Commands.EDIT_LINE_DOWN,moveLineDown),CommandManager.register(Strings.CMD_OPEN_LINE_ABOVE,Commands.EDIT_OPEN_LINE_ABOVE,openLineAbove),CommandManager.register(Strings.CMD_OPEN_LINE_BELOW,Commands.EDIT_OPEN_LINE_BELOW,openLineBelow),CommandManager.register(Strings.CMD_SELECT_LINE,Commands.EDIT_SELECT_LINE,selectLine),CommandManager.register(Strings.CMD_SPLIT_SEL_INTO_LINES,Commands.EDIT_SPLIT_SEL_INTO_LINES,splitSelIntoLines),CommandManager.register(Strings.CMD_ADD_CUR_TO_NEXT_LINE,Commands.EDIT_ADD_CUR_TO_NEXT_LINE,addCursorToNextLine),CommandManager.register(Strings.CMD_ADD_CUR_TO_PREV_LINE,Commands.EDIT_ADD_CUR_TO_PREV_LINE,addCursorToPrevLine),CommandManager.register(Strings.CMD_UNDO,Commands.EDIT_UNDO,handleUndo),CommandManager.register(Strings.CMD_REDO,Commands.EDIT_REDO,handleRedo),CommandManager.register(Strings.CMD_CUT,Commands.EDIT_CUT,_execCommandCut),CommandManager.register(Strings.CMD_COPY,Commands.EDIT_COPY,_execCommandCopy),CommandManager.register(Strings.CMD_PASTE,Commands.EDIT_PASTE,_execCommandPaste),CommandManager.register(Strings.CMD_SELECT_ALL,Commands.EDIT_SELECT_ALL,_handleSelectAll)});