diff --git a/ansi_regex.ts b/ansi_regex.ts new file mode 100644 index 0000000..52aaf42 --- /dev/null +++ b/ansi_regex.ts @@ -0,0 +1,7 @@ +export function ansiRegex({ onlyFirst = false } = {}): RegExp { + const pattern = [ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", + ].join("|"); + return new RegExp(pattern, onlyFirst ? undefined : "g"); +} diff --git a/mod.ts b/mod.ts index 843ef58..e30c816 100644 --- a/mod.ts +++ b/mod.ts @@ -39,3 +39,5 @@ export type AsyncStream = Deno.Writer; export * from "./tty_async.ts"; export * from "./tty_sync.ts"; export * from "./wcwidth.ts"; +export * from "./ansi_regex.ts"; +export * from "./strip_ansi.ts"; diff --git a/strip_ansi.ts b/strip_ansi.ts new file mode 100644 index 0000000..dbe0bc1 --- /dev/null +++ b/strip_ansi.ts @@ -0,0 +1,5 @@ +import { ansiRegex } from "./mod.ts"; + +export function stripAnsi(dirty: string): string { + return dirty.replace(ansiRegex(), ""); +} diff --git a/wcwidth.ts b/wcwidth.ts index 7f74b9e..8dbffc2 100644 --- a/wcwidth.ts +++ b/wcwidth.ts @@ -29,7 +29,7 @@ export type Defaults = { * This implementation assumes that characters are encoded in ISO 10646. */ export function wcswidth( - str: any, + str: string, { nul = 0, control = 0 }: Defaults = {}, ): number { const opts = { nul, control }; @@ -45,7 +45,7 @@ export function wcswidth( return s; } -function wcwidth(ucs: any, { nul = 0, control = 0 }: Defaults = {}): number { +function wcwidth(ucs: number, { nul = 0, control = 0 }: Defaults = {}): number { // test for 8-bit control characters if (ucs === 0) return nul; if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) return control; @@ -74,7 +74,7 @@ function wcwidth(ucs: any, { nul = 0, control = 0 }: Defaults = {}): number { ); } -function bisearch(ucs: any): boolean { +function bisearch(ucs: number): boolean { var min = 0; var max = combining.length - 1; var mid;