Destroys an editor object if a document is no longer referenced
@param {!Document} doc - document to destroy
966090
function _destroyEditorIfNotNeeded(document) {
        if (!(document instanceof DocumentManager.Document)) {
            throw new Error("_destroyEditorIfUnneeded() should be passed a Document");
        }
        if (document._masterEditor) {
            // findPaneForDocument tries to locate the pane in which the document
            //  is either opened or will be opened (in the event that the document is
            //  in a working set but has yet to be opened) and then asks the pane
            //  to destroy the view if it doesn't need it anymore
            var pane = _findPaneForDocument(document);

            if (pane) {
                // let the pane deceide if it wants to destroy the view if it's no needed
                pane.destroyViewIfNotNeeded(document._masterEditor);
            } else {
                // in this case, the document isn't referenced at all so just destroy it
                document._masterEditor.destroy();
            }
        }
    }
181097
@Nonnull
  public T delete(@Nonnull DocumentReference documentReference) {
    return performDelete(documentReference, Precondition.NONE);
  }
325306
function emptyEditorWhenDeleting() {
        function serializeRng(rng) {
          var body = dom.create("body");
          var contents = rng.cloneContents();
          body.appendChild(contents);
          return selection.serializer.serialize(body, { format: 'html' });
        }

        function allContentsSelected(rng) {
          if (!rng.setStart) {
            if (rng.item) {
              return false;
            }

            var bodyRng = rng.duplicate();
            bodyRng.moveToElementText(editor.getBody());
            return RangeUtils.compareRanges(rng, bodyRng);
          }

          var selection = serializeRng(rng);

          var allRng = dom.createRng();
          allRng.selectNode(editor.getBody());

          var allSelection = serializeRng(allRng);
          return selection === allSelection;
        }

        editor.on('keydown', function (e) {
          var keyCode = e.keyCode, isCollapsed, body;

          // Empty the editor if it's needed for example backspace at <p><b>|</b></p>
          if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) {
            isCollapsed = editor.selection.isCollapsed();
            body = editor.getBody();

            // Selection is collapsed but the editor isn't empty
            if (isCollapsed && !dom.isEmpty(body)) {
              return;
            }

            // Selection isn't collapsed but not all the contents is selected
            if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
              return;
            }

            // Manually empty the editor
            e.preventDefault();
            editor.setContent('');

            if (body.firstChild && dom.isBlock(body.firstChild)) {
              editor.selection.setCursorLocation(body.firstChild, 0);
            } else {
              editor.selection.setCursorLocation(body, 0);
            }

            editor.nodeChanged();
          }
        });
      }
910886
function() {
    if(this._oCellEditor) {
        if(this._oCellEditor.cancel) {
            this._oCellEditor.cancel();
        }
        // Backward compatibility
        else if(this._oCellEditor.isActive) {
            this.resetCellEditor();
            //TODO: preserve values for the event?
            this.fireEvent("editorCancelEvent", {editor:this._oCellEditor});
        }

    }
}
542302
def remove(self, document):
        
        assert '_id' in document, 'Document must have an id'
        self.db.execute("delete from %s where id = ?" % self.name, (document['_id'],))
1225660
function(doc) {
    this._removeNodes(doc.getElementsByTagName('script'), function(scriptNode) {
      scriptNode.nodeValue = "";
      scriptNode.removeAttribute('src');
      return true;
    });
    this._removeNodes(doc.getElementsByTagName('noscript'));
  }
713822
function destroyEditOverlay() {
  if (overlay) {
    overlay.parentNode.removeChild(overlay);
    overlay = null;
  }

  document.removeEventListener('click', handleDocumentClick);
  document.removeEventListener('keyup', handleDocumentKeyup);
  document.removeEventListener('mousedown', handleDocumentMousedown);
  document.removeEventListener('mousemove', handleDocumentMousemove);
  document.removeEventListener('mouseup', handleDocumentMouseup);
  enableUserSelect();
}
1030126
function (options, callback) {
  var Deleter = {}
  // Delete all docs with the IDs found in deleteBatch
  Deleter.deleteBatch = function (deleteBatch, APICallback) {
    tryDeleteBatch(options, deleteBatch, function (err) {
      return APICallback(err)
    })
  }
  // Flush the db (delete all entries)
  Deleter.flush = function (APICallback) {
    flush(options, function (err) {
      return APICallback(err)
    })
  }
  return callback(null, Deleter)
}
634377
function closeFullEditor(file) {
        DeprecationWarning.deprecationWarning("Use CommandManager.execute(Commands.FILE_CLOSE, {File: file} instead of DocumentManager.closeFullEditor()", true);
        CommandManager.execute(Commands.FILE_CLOSE, {File: file});
    }
201641
function removeUnreferencedElements() {

  var referencedIDs = findReferencedElements();

  var alwaysKeepTags = ['font', 'style', 'metadata', 'script', 'title', 'desc'];
  function removeUnreferencedElementsInTag(node) {
    _($(node).children()).each(function(node) {
      
      // scour:
      // > we only remove if it is not one of our tags we always keep (see above)
      if(_(alwaysKeepTags).indexOf(node.name) !== -1) {
        return;
      }
      var $node = $(node);
      var id = $node.attr('id');
      if(!_(referencedIDs).has(id)) {
        if(node.name == 'g') {
          // scour:
          // > we only inspect the children of a group in a defs if the group
          // > is not referenced anywhere else
          removeUnreferencedElementsInTag(node);
        } else {
          $(node).remove();
        }
      }
    });
  }
  // scour:
  // > Remove most unreferenced elements inside defs
  _($('defs')).each(removeUnreferencedElementsInTag);

  // scour:
  // > Remove certain unreferenced elements outside of defs
  var identifiedElements = $('* > linearGradient[id], * > radialGradient[id], * > pattern[id]');
  
  _(identifiedElements).each(function(node) {
    var id = $(node).attr('id');
    if(!_(referencedIDs).has(id)) {
      $(node).remove();
    }
  });

}
102426
function(doc) {
      if (!this._props) {
        return doc;
      }

      return this._props.reduce(function(obj, prop) {
        if (doc.hasOwnProperty(prop)) {
          obj[prop] = doc[prop];
        }

        return obj;
      }, {});
    }
117977
def _destructively_move(self, dest_doc):
        ''' 

        '''

        if dest_doc is self:
            raise RuntimeError("Attempted to overwrite a document with itself")

        dest_doc.clear()
        # we have to remove ALL roots before adding any
        # to the new doc or else models referenced from multiple
        # roots could be in both docs at once, which isn't allowed.
        roots = []
        self._push_all_models_freeze()
        try:
            while self.roots:
                r = next(iter(self.roots))
                self.remove_root(r)
                roots.append(r)
        finally:
            self._pop_all_models_freeze()
        for r in roots:
            if r.document is not None:
                raise RuntimeError("Somehow we didn't detach %r" % (r))
        if len(self._all_models) != 0:
            raise RuntimeError("_all_models still had stuff in it: %r" % (self._all_models))
        for r in roots:
            dest_doc.add_root(r)

        dest_doc.title = self.title
964894
function() {
        OpenLayers.Element.removeClass(document.body, "olDragDown");
        this.documentEvents = false;
        OpenLayers.Event.stopObserving(document, "mousemove", this._docMove);
        OpenLayers.Event.stopObserving(document, "mouseup", this._docUp);
    }
104737
function Editor(options) {
    this.options = options;
    window.indentUnit = options.indentUnit;
    this.parent = parent;
    this.doc = document;
    var container = this.container = this.doc.body;
    this.win = window;
    this.history = new History(container, options.undoDepth, options.undoDelay, this);
    var self = this;

    if (!Editor.Parser)
      throw "No parser loaded.";
    if (options.parserConfig && Editor.Parser.configure)
      Editor.Parser.configure(options.parserConfig);

    if (!options.readOnly)
      select.setCursorPos(container, {node: null, offset: 0});

    this.dirty = [];
    this.importCode(options.content || "");
    this.history.onChange = options.onChange;

    if (!options.readOnly) {
      if (options.continuousScanning !== false) {
        this.scanner = this.documentScanner(options.passTime);
        this.delayScanning();
      }

      function setEditable() {
        // In IE, designMode frames can not run any scripts, so we use
        // contentEditable instead.
        if (document.body.contentEditable != undefined && internetExplorer)
          document.body.contentEditable = "true";
        else
          document.designMode = "on";

        document.documentElement.style.borderWidth = "0";
        if (!options.textWrapping)
          container.style.whiteSpace = "nowrap";
      }

      // If setting the frame editable fails, try again when the user
      // focus it (happens when the frame is not visible on
      // initialisation, in Firefox).
      try {
        setEditable();
      }
      catch(e) {
        var focusEvent = addEventHandler(document, "focus", function() {
          focusEvent();
          setEditable();
        }, true);
      }

      addEventHandler(document, "keydown", method(this, "keyDown"));
      addEventHandler(document, "keypress", method(this, "keyPress"));
      addEventHandler(document, "keyup", method(this, "keyUp"));

      function cursorActivity() {self.cursorActivity(false);}
      addEventHandler(document.body, "mouseup", cursorActivity);
      addEventHandler(document.body, "cut", cursorActivity);

      // workaround for a gecko bug [?] where going forward and then
      // back again breaks designmode (no more cursor)
      if (gecko)
        addEventHandler(this.win, "pagehide", function(){self.unloaded = true;});

      addEventHandler(document.body, "paste", function(event) {
        cursorActivity();
        var text = null;
        try {
          var clipboardData = event.clipboardData || window.clipboardData;
          if (clipboardData) text = clipboardData.getData('Text');
        }
        catch(e) {}
        if (text !== null) {
          event.stop();
          self.replaceSelection(text);
          select.scrollToCursor(self.container);
        }
      });

      if (this.options.autoMatchParens)
        addEventHandler(document.body, "click", method(this, "scheduleParenHighlight"));
    }
    else if (!options.textWrapping) {
      container.style.whiteSpace = "nowrap";
    }
  }
1146471
function doClose(file) {
            if (!promptOnly) {
                MainViewManager._close(paneId, file);
                HealthLogger.fileClosed(file);
            }
        }
193643
function(doc, fields) {
	return Object.keys(fields).reduce((prev, key) => {
		let val

		if (fields[key].hasOwnProperty('referenceCollection')) {
			const displayField = fields[key].referenceCollection.defaultField

			if (Array.isArray(doc[key])) {
				val = doc[key].map(data => {
					return data[displayField]
				})
			} else {
				val = doc[key][displayField]
			}
		} else {
			val = doc[key]
		}
		return Object.assign({}, prev, {
			[key]: val
		})
	}, { _id: doc._id })
}
318773
def delete_doc(self, doc_id, revision):
        ''''''
        d = defer.Deferred()

        self.increase_stat('delete_doc')

        try:
            doc = self._get_doc(doc_id)
            if doc['_rev'] != revision:
                raise ConflictError("Document update conflict.")
            if doc.get('_deleted', None):
                raise NotFoundError('%s deleted' % doc_id)
            doc['_deleted'] = True
            self._expire_cache(doc['_id'])
            for key in doc.keys():
                if key in ['_rev', '_deleted', '_id']:
                    continue
                del(doc[key])
            self.log('Marking document %r as deleted', doc_id)
            del self._attachments[doc['_id']]
            self._update_rev(doc)
            self._analize_changes(doc)
            d.callback(Response(ok=True, id=doc_id, rev=doc['_rev']))
        except (ConflictError, NotFoundError, ) as e:
            d.errback(e)

        return d