define(function(require,exports,module){var EditorManager=require("editor/EditorManager"),EventDispatcher=require("utils/EventDispatcher"),FileUtils=require("file/FileUtils"),InMemoryFile=require("document/InMemoryFile"),PerfUtils=require("utils/PerfUtils"),LanguageManager=require("language/LanguageManager"),CodeMirror=require("thirdparty/CodeMirror/lib/codemirror"),_=require("thirdparty/lodash");function Document(file,initialTimestamp,rawText){this.file=file,this.editable=!file.readOnly,this._updateLanguage(),this.refreshText(rawText,initialTimestamp,!0),this._associatedFullEditors=[]}function oneOrEach(itemOrArr,cb){Array.isArray(itemOrArr)?_.each(itemOrArr,cb):cb(itemOrArr,0)}EventDispatcher.makeEventDispatcher(Document.prototype),Document.prototype._refCount=0,Document.prototype.file=null,Document.prototype.language=null,Document.prototype.isDirty=!1,Document.prototype.isSaving=!1,Document.prototype.diskTimestamp=null,Document.prototype.lastChangeTimestamp=null,Document.prototype.keepChangesTime=null,Document.prototype._refreshInProgress=!1,Document.prototype._text=null,Document.prototype._masterEditor=null,Document.prototype._lineEndings=null,Document.prototype.addRef=function(){0===this._refCount&&exports.trigger("_afterDocumentCreate",this)||this._refCount++},Document.prototype.releaseRef=function(){this._refCount--,this._refCount<0?console.error("Document ref count has fallen below zero!"):0!==this._refCount||exports.trigger("_beforeDocumentDelete",this)},Document.prototype._makeEditable=function(masterEditor){this._text=null,this._masterEditor=masterEditor,masterEditor.on("change",this._handleEditorChange.bind(this))},Document.prototype._makeNonEditable=function(){this._masterEditor?(this._text=this.getText(!0),this._associatedFullEditors.splice(this._associatedFullEditors.indexOf(this._masterEditor),1),this._associatedFullEditors.length>0?this._masterEditor=this._associatedFullEditors[this._associatedFullEditors.length-1]:this._masterEditor=null):console.error("Document is already non-editable")},Document.prototype._toggleMasterEditor=function(masterEditor){this.file===masterEditor.document.file&&this._associatedFullEditors.indexOf(masterEditor)>=0&&(this._masterEditor=masterEditor)},Document.prototype._checkAssociatedEditorForPane=function(paneId){var editorCount,editorForPane;for(editorCount=0;editorCount=0&&this._associatedFullEditors.splice(this._associatedFullEditors.indexOf(editor),1)},Document.prototype._associateEditor=function(editor){-1===this._associatedFullEditors.indexOf(editor)&&this._associatedFullEditors.push(editor)},Document.prototype._ensureMasterEditor=function(){this._masterEditor||EditorManager._createUnattachedMasterEditor(this)},Document.prototype.getText=function(useOriginalLineEndings){if(this._masterEditor){var codeMirrorText=this._masterEditor._codeMirror.getValue();return useOriginalLineEndings&&this._lineEndings===FileUtils.LINE_ENDINGS_CRLF?codeMirrorText.replace(/\n/g,"\r\n"):codeMirrorText}return useOriginalLineEndings?this._text:Document.normalizeText(this._text)},Document.prototype.getSelectedText=function(useOriginalLineEndings,allSelections){if(this._masterEditor){let codeMirrorText=this._masterEditor.getSelectedText(allSelections);return useOriginalLineEndings&&this._lineEndings===FileUtils.LINE_ENDINGS_CRLF?codeMirrorText.replace(/\n/g,"\r\n"):codeMirrorText}return null},Document.normalizeText=function(text){return text.replace(/\r\n/g,"\n")},Document.prototype.setText=function(text){this._ensureMasterEditor(),this._masterEditor._codeMirror.setValue(text)},Document.prototype._notifyDocumentChange=function(changeList){this.lastChangeTimestamp=Date.now(),this.trigger("change",this,changeList),exports.trigger("documentChange",this,changeList)},Document.prototype.refreshText=function(text,newTimestamp,initial){var perfTimerName=PerfUtils.markStart("refreshText:\t"+(!this.file||this.file.fullPath));this._refreshInProgress=!0,this._masterEditor?this._masterEditor._resetText(text):(this._text=text,initial||this._notifyDocumentChange([{text:text.split(/\r?\n/)}])),this._updateTimestamp(newTimestamp),this.isDirty&&this._markClean(),this._refreshInProgress=!1,this._lineEndings=FileUtils.sniffLineEndings(text),this._lineEndings||(this._lineEndings=FileUtils.getPlatformLineEndings()),exports.trigger("_documentRefreshed",this),PerfUtils.addMeasurement(perfTimerName)},Document.prototype.replaceRange=function(text,start,end,origin){this._ensureMasterEditor(),this._masterEditor._codeMirror.replaceRange(text,start,end,origin)},Document.prototype.getRange=function(start,end){return this._ensureMasterEditor(),this._masterEditor._codeMirror.getRange(start,end)},Document.prototype.getLine=function(lineNum){return this._ensureMasterEditor(),this._masterEditor._codeMirror.getLine(lineNum)},Document.prototype.posFromIndex=function(index){if(this._masterEditor)return this._masterEditor._codeMirror.posFromIndex(index);for(var text=this._text||"",line=0,ch=0,i=0;i0&&oneOrEach(edits[index-1].edit,function(prevEdit){if(CodeMirror.cmpPos(edit.end,prevEdit.start)>0)throw new Error("Document.doMultipleEdits(): Overlapping edits specified")}))})}),this.batchOperation(function(){_.each(edits,function(editDesc,index){oneOrEach(editDesc.edit,function(edit){if(edit){self.replaceRange(edit.text,edit.start,edit.end,origin);var textLines=edit.text.split("\n");_.each(result,function(selections,selIndex){selections&&oneOrEach(selections,function(sel){(sel.isBeforeEdit||selIndex!==index)&&(sel.start=self.adjustPosForChange(sel.start,textLines,edit.start,edit.end),sel.end=self.adjustPosForChange(sel.end,textLines,edit.start,edit.end))})})}})})}),result=_.chain(result).filter(function(item){return void 0!==item}).flatten().sort(function(sel1,sel2){return CodeMirror.cmpPos(sel1.start,sel2.start)}).value(),_.each(result,function(item){delete item.isBeforeEdit}),result},Document.prototype.toString=function(){var dirtyInfo=this.isDirty?" (dirty!)":" (clean)",editorInfo=this._masterEditor?" (Editable)":" (Non-editable)",refInfo=" refs:"+this._refCount;return"[Document "+this.file.fullPath+dirtyInfo+editorInfo+refInfo+"]"},Document.prototype.getLanguage=function(){return this.language},Document.prototype._updateLanguage=function(){var oldLanguage=this.language;this.language=LanguageManager.getLanguageForPath(this.file.fullPath),oldLanguage&&oldLanguage!==this.language&&this.trigger("languageChanged",oldLanguage,this.language)},Document.prototype._notifyFilePathChanged=function(){this._updateLanguage()},Document.prototype.isUntitled=function(){return this.file instanceof InMemoryFile},Document.prototype.reload=function(){var $deferred=$.Deferred(),self=this;return FileUtils.readAsText(this.file,!0).done(function(text,readTimestamp){self.refreshText(text,readTimestamp),$deferred.resolve()}).fail(function(error){console.log("Error reloading contents of "+self.file.fullPath,error),$deferred.reject()}),$deferred.promise()},EventDispatcher.makeEventDispatcher(exports),exports.Document=Document});