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/project/formatters/latex-format.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { writeFile, unlink } from "fs";6import { file } from "tmp";7import { callback } from "awaiting";8import { spawn } from "child_process";9import { replace_all } from "@cocalc/util/misc";1011interface ParserOptions {12parser: string;13tabWidth?: number;14useTabs?: boolean;15}1617function close(proc, cb): void {18proc.on("close", (code) => cb(undefined, code));19}2021export async function latex_format(22input: string,23options: ParserOptions24): Promise<string> {25// create input temp file26const input_path: string = await callback(file, { postfix: ".tex" });27try {28await callback(writeFile, input_path, input);29// spawn the latexindent script.30const latexindent = spawn("latexindent", [input_path]);31let output: string = "";32// read data as it is produced.33latexindent.stdout.on("data", (data) => (output += data.toString()));34// wait for subprocess to close.35const code = await callback(close, latexindent);36if (code) {37throw Error(`latexindent exited with code ${code}`);38}39// now process the result according to the options.40if (!options.useTabs) {41// replace tabs by spaces42let tab_width = 2;43if (options.tabWidth !== undefined) {44tab_width = options.tabWidth;45}46let SPACES = "";47for (let i = 0; i < tab_width; i++) {48SPACES += " ";49}50output = replace_all(output, "\t", SPACES);51}52// latexindent also annoyingly introduces a lot of whitespace lines.53const lines: string[] = output.split("\n"),54lines2: string[] = [];55for (let i = 0; i < lines.length; i++) {56if (/\S/.test(lines[i])) {57lines2.push(lines[i]);58} else {59lines2.push("");60}61output = lines2.join("\n");62}63return output;64} finally {65unlink(input_path, () => {});66}67}686970