From a901d356152cce345a41e7cef8ecf64504ad3651 Mon Sep 17 00:00:00 2001 From: Carlo Cardella Date: Wed, 25 Jan 2023 08:45:42 -0800 Subject: [PATCH] Unexpected behavior when no text is selected with JSON options Fixes #38 --- CHANGELOG.md | 6 ++++++ src/modules/json.ts | 35 +++++++++++++++++++++++++++-------- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61ae2fa..e7753cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,12 @@ See the [list of open enhancements on GitHub](https://github.com/carlocardella/v ## Log +## [2.13.1] - 2023-01-25 + +### Fixed + +* [#38 Unexpected behavior when no text is selected with JSON options](https://github.com/carlocardella/vscode-TextToolbox/issues/38) + ## [2.13.0] - 2023-01-24 ### Fixed diff --git a/src/modules/json.ts b/src/modules/json.ts index 2b46beb..e259144 100644 --- a/src/modules/json.ts +++ b/src/modules/json.ts @@ -1,5 +1,6 @@ import { getActiveEditor, getTextFromSelection } from "./helpers"; import * as jsonic from "jsonic"; +import { Selection } from "vscode"; /** * Transforms a text string into proper JSON format, optionally can fix syntax errors. @@ -13,7 +14,15 @@ export async function stringifyJson(fixJson: boolean): Promise { } editor.edit((editBuilder) => { - editor.selections.forEach((s) => { + let selections: Selection[] = []; + + if (editor.selection.isEmpty) { + selections.push(new Selection(0, 0, editor.document.lineCount, editor.document.lineAt(editor.document.lineCount - 1).text.length)); + } else { + selections = editor.selections.map((s) => s); + } + + selections.forEach((s) => { let newJson: string = ""; let selectionText = getTextFromSelection(editor, s); if (fixJson) { @@ -40,7 +49,15 @@ export async function minifyJson(): Promise { } editor.edit((editBuilder) => { - editor.selections.forEach((s) => { + let selections: Selection[] = []; + + if (editor.selection.isEmpty) { + selections.push(new Selection(0, 0, editor.document.lineCount, editor.document.lineAt(editor.document.lineCount - 1).text.length)); + } else { + selections = editor.selections.map((s) => s); + } + + selections.forEach((s) => { let selectionText = getTextFromSelection(editor, s); let newJson = JSON.stringify(jsonic(selectionText!)); @@ -57,13 +74,15 @@ export function escapeWin32PathInJson() { return; } - editor.edit((editBuilder) => { - editor.selections.forEach((selection) => { - const text = getTextFromSelection(editor, selection); - const newText = text!.replace(/\\/g, "\\\\"); - editBuilder.replace(selection, newText); + if (!editor.selection.isEmpty) { + editor.edit((editBuilder) => { + editor.selections.forEach((selection) => { + const text = getTextFromSelection(editor, selection); + const newText = text!.replace(/\\/g, "\\\\"); + editBuilder.replace(selection, newText); + }); }); - }); + } return; }