Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/frontend/codemirror/extensions/diff-apply.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import * as CodeMirror from "codemirror";67// We define the diffApply extension separately so it can be applied to CodeMirror's8// in iframes, e.g., Jupyter's.910export function cm_define_diffApply_extension(cm) {11// applies a diff and returns last pos modified12cm.defineExtension("diffApply", function (diff) {13// @ts-ignore14const editor = this;15const next_pos = function (16val: string,17pos: CodeMirror.Position18): CodeMirror.Position {19// This functions answers the question:20// If you were to insert the string val at the CodeMirror position pos21// in a codemirror document, at what position (in codemirror) would22// the inserted string end at?23const number_of_newlines = (val.match(/\n/g) || []).length;24if (number_of_newlines === 0) {25return { line: pos.line, ch: pos.ch + val.length };26} else {27return {28line: pos.line + number_of_newlines,29ch: val.length - val.lastIndexOf("\n") - 1,30};31}32};3334let pos: CodeMirror.Position = { line: 0, ch: 0 }; // start at the beginning35let last_pos: CodeMirror.Position | undefined = undefined;36for (let chunk of diff) {37const op = chunk[0]; // 0 = stay same; -1 = delete; +1 = add38const val = chunk[1]; // the actual text to leave same, delete, or add39const pos1 = next_pos(val, pos);4041switch (op) {42case 0: // stay the same43// Move our pos pointer to the next position44pos = pos1;45break;46//console.log("skipping to ", pos1)47case -1: // delete48// Delete until where val ends; don't change pos pointer.49editor.replaceRange("", pos, pos1);50last_pos = pos;51break;52//console.log("deleting from ", pos, " to ", pos1)53case +1: // insert54// Insert the new text right here.55editor.replaceRange(val, pos);56//console.log("inserted new text at ", pos)57// Move our pointer to just beyond the text we just inserted.58pos = pos1;59last_pos = pos1;60break;61}62}63return last_pos;64});65}6667cm_define_diffApply_extension(CodeMirror);686970