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/addon/delete-trailing-whitespace.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { defineExtension, Editor } from "codemirror";6import { delete_trailing_whitespace } from "@cocalc/util/misc";7import { ChangeObject } from "./types";89type OmittedLines = { [line: number]: boolean };1011// Delete all trailing whitespace from the editor's buffer.12defineExtension(13"delete_trailing_whitespace",14function (opts: { omit_lines?: OmittedLines } = {}): void {15// @ts-ignore -- I don't know how to type this...16const cm: Editor = this;17if (opts.omit_lines == null) {18opts.omit_lines = {};19}20// We *could* easily make a one-line version of this function that21// just uses setValue. However, that would mess up the undo22// history (!), and potentially feel jumpy.23let changeObj: ChangeObject | undefined = undefined;24let currentObj: ChangeObject | undefined = undefined;25const val = cm.getValue();26const text1 = val.split("\n");27const text2 = delete_trailing_whitespace(val).split("\n"); // a very fast regexp.28const pos = cm.getCursor();29if (text1.length !== text2.length) {30// invariant: the number of lines cannot change!31console.log(32"Internal error -- there is a bug in delete_trailing_whitespace; please report."33);34return;35}36opts.omit_lines[pos.line] = true;37for (let i = 0; i < text1.length; i++) {38if (opts.omit_lines[i]) {39continue;40}41if (text1[i].length !== text2[i].length) {42const obj = {43from: { line: i, ch: text2[i].length },44to: { line: i, ch: text1[i].length },45text: [""],46};47if (changeObj == null) {48changeObj = obj;49currentObj = changeObj;50} else {51if (currentObj != null) {52currentObj.next = obj;53}54currentObj = obj;55}56}57}58if (changeObj != null) {59(cm as any).apply_changeObj(changeObj);60}61}62);636465