From cac31ceaa9381457359815772b9487cd3221048c Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 23 Mar 2022 17:44:56 -0500 Subject: [PATCH 01/78] added getLeadingSpaces() function Added function that would return the number of leading spaces on a line --- src/commands/text.ts | 296 +++++++++++++++++++++---------------------- 1 file changed, 147 insertions(+), 149 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 8e3beaf..508c256 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -1,168 +1,166 @@ -import * as vscode from 'vscode'; -import * as pl from '../pylex'; - -import { CommandEntry } from './commandEntry'; - -export const textCommands: CommandEntry[] = [ - { - name: 'mind-reader.getIndent', - callback: getIndent, - }, - - { - name: 'mind-reader.runLineContext', - callback: runLineContext, - }, - - { - name: 'mind-reader.runCursorContext', - callback: runCursorContext - } -] - -function getIndent(): void { - let editor = vscode.window.activeTextEditor; - if(editor) - { - let lineNum = editor.selection.active.line + 1; - let textLine = editor.document.lineAt(lineNum - 1); - if(textLine.isEmptyOrWhitespace) +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.textCommands = void 0; +const vscode = require("vscode"); +const pl = require("../pylex"); +exports.textCommands = [ { - vscode.window.showInformationMessage("Line number " + lineNum.toString() + " Is Empty"); - } - else + name: 'mind-reader.getIndent', + callback: getIndent, + }, { - // Grab tab format from open document - let tabFmt = { - size: editor.options.tabSize as number, - hard: !editor.options.insertSpaces - }; - let i = pl.Lexer.getIndent(textLine.text, tabFmt); - vscode.window.showInformationMessage("Line Number " + lineNum.toString() + " Indentation " + i.toString()); + name: 'mind-reader.getLeadingSpaces', + callback: getLeadingSpaces, + }, + { + name: 'mind-reader.runLineContext', + callback: runLineContext, + }, + { + name: 'mind-reader.runCursorContext', + callback: runCursorContext + } +]; +function getIndent() { + let editor = vscode.window.activeTextEditor; + if (editor) { + let lineNum = editor.selection.active.line + 1; + let textLine = editor.document.lineAt(lineNum - 1); + if (textLine.isEmptyOrWhitespace) { + vscode.window.showInformationMessage("Line number " + lineNum.toString() + " Is Empty"); + } + else { + // Grab tab format from open document + let tabFmt = { + size: editor.options.tabSize, + hard: !editor.options.insertSpaces + }; + let i = pl.Lexer.getIndent(textLine.text, tabFmt); + vscode.window.showInformationMessage("Line Number " + lineNum.toString() + " Indentation " + i.toString()); + } + } + else { + vscode.window.showErrorMessage('No document currently active'); } - } - else{ - vscode.window.showErrorMessage('No document currently active'); - } - } +function getLeadingSpaces() { + let editor = vscode.window.activeTextEditor; -function runLineContext(): void { - let editor = vscode.window.activeTextEditor; - if (editor){ - // current text and line number - let editorText = editor.document.getText(); - let line = editor.selection.active.line; - - // get tab info settings - let size = parseInt(editor.options.tabSize as string); - let hard = !editor.options.insertSpaces; - - // initialize parser - let parser = new pl.Parser(editorText, {size, hard}); - parser.parse(); - - let context = parser.context(line); - - // build text - let contentString = createContextString(context, line); - vscode.window.showInformationMessage(contentString); - } else { - vscode.window.showErrorMessage('No document currently active'); - } + if (editor) { + let lineNum = editor.selection.active.line + 1; + let textLine = editor.document.lineAt(lineNum - 1); + if(textLine.isEmptyOrWhitespace) { + vscode.window.showInformationMessage("Line number " + lineNum.toString() + " Is Empty"); + } + else { + let numSpaces = textLine.firstNonWhitespaceCharacterIndex; + vscode.window.showInformationMessage("Line Number " + lineNum.toString() + numSpaces.toString()) + " Leading Spaces "; + } + } + else { + vscode.window.showErrorMessage('No document currently active'); + } } - -function createContextString(context: pl.LexNode[], line: number): string { +function runLineContext() { + let editor = vscode.window.activeTextEditor; + if (editor) { + // current text and line number + let editorText = editor.document.getText(); + let line = editor.selection.active.line; + // get tab info settings + let size = parseInt(editor.options.tabSize); + let hard = !editor.options.insertSpaces; + // initialize parser + let parser = new pl.Parser(editorText, { size, hard }); + parser.parse(); + let context = parser.context(line); + // build text + let contentString = createContextString(context, line); + vscode.window.showInformationMessage(contentString); + } + else { + vscode.window.showErrorMessage('No document currently active'); + } +} +function createContextString(context, line) { if (context.length < 1) { - throw new Error('Cannot create context string for empty context'); + throw new Error('Cannot create context string for empty context'); } - - let contextString = 'Line ' + (line+1); // 1 based + let contextString = 'Line ' + (line + 1); // 1 based if (context[0].token && context[0].token.attr) { - contextString += ': ' + context[0].token.type.toString() + ' ' + context[0].token.attr.toString(); + contextString += ': ' + context[0].token.type.toString() + ' ' + context[0].token.attr.toString(); } for (let i = 1; i < context.length; i++) { - let node = context[i]; - if (node.label === 'root') { - // root - contextString += ' in the Document Root'; - continue; - } - - if (node.token!.type !== pl.PylexSymbol.EMPTY && - node.token!.type !== pl.PylexSymbol.INDENT) { - contextString += ' inside ' + node.token!.type.toString(); - if (node.token!.attr) { - contextString += ' ' + node.token!.attr.toString(); + let node = context[i]; + if (node.label === 'root') { + // root + contextString += ' in the Document Root'; + continue; + } + if (node.token.type !== pl.PylexSymbol.EMPTY && + node.token.type !== pl.PylexSymbol.INDENT) { + contextString += ' inside ' + node.token.type.toString(); + if (node.token.attr) { + contextString += ' ' + node.token.attr.toString(); + } } - } } return contextString; } - // find up to `n` words around the cursor, where `n` is // the value of `#mindReader.reader.contextWindow` -function runCursorContext(): void { - let editor = vscode.window.activeTextEditor; - if (!editor) { - vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); - return; - } - - const cursorPos: vscode.Position = editor.selection.active; - const text: string = editor.document.lineAt(cursorPos).text; - const windowSize: number = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow')!; - - let trimmedText = text.trimStart(); // trim leading whitespace - let leadingWS = text.length - trimmedText.length; // # of characters of leading whitespace - trimmedText = trimmedText.trimEnd(); // trim trailing whitespace - let pos = leadingWS; - let maxPos = text.length; - - // clamp cursor start/end to new range - let col = cursorPos.character; // effective column of the cursor position - if (col < leadingWS) { - // move effective start to first non-whitespace character in the line - col = leadingWS; - } else if (col > leadingWS + trimmedText.length - 1) { - // move effective end to last non-whitespace character in the line - col = leadingWS + trimmedText.length - 1; - } - - // generate list of space separate words with range data (start, end) - // TODO: can find user position to be done in one pass - let spaceWords: {word: string, start: number, end: number}[] = []; - while (pos < maxPos && trimmedText.length > 0) { - let word = trimmedText.replace(/ .*/, ''); - spaceWords.push({word, start: pos, end: pos+word.length}); - - // remove processed word from trimmed text - const oldText = trimmedText; - trimmedText = trimmedText.replace(/[^ ]+/, '').trimStart(); - - // update pos to start of next word - pos += oldText.length - trimmedText.length; - } - - // find word the user is in - let contextStart: number = -1, contextEnd: number = -1; - for (let i = 0; i < spaceWords.length; i++) { - if (col >= spaceWords[i].start && col <= spaceWords[i].end) { - // found the word - contextStart = Math.max(0, i - windowSize); // clamp start index - contextEnd = Math.min(spaceWords.length, i + windowSize + 1); // clamp end index - - // construct cursor context string - let contextString = ''; - for (let i = contextStart; i < contextEnd; i++) { - contextString += spaceWords[i].word + ' '; - } - - // output cursor context string - vscode.window.showInformationMessage(contextString); - - return; +function runCursorContext() { + let editor = vscode.window.activeTextEditor; + if (!editor) { + vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); + return; + } + const cursorPos = editor.selection.active; + const text = editor.document.lineAt(cursorPos).text; + const windowSize = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); + let trimmedText = text.trimStart(); // trim leading whitespace + let leadingWS = text.length - trimmedText.length; // # of characters of leading whitespace + trimmedText = trimmedText.trimEnd(); // trim trailing whitespace + let pos = leadingWS; + let maxPos = text.length; + // clamp cursor start/end to new range + let col = cursorPos.character; // effective column of the cursor position + if (col < leadingWS) { + // move effective start to first non-whitespace character in the line + col = leadingWS; + } + else if (col > leadingWS + trimmedText.length - 1) { + // move effective end to last non-whitespace character in the line + col = leadingWS + trimmedText.length - 1; + } + // generate list of space separate words with range data (start, end) + // TODO: can find user position to be done in one pass + let spaceWords = []; + while (pos < maxPos && trimmedText.length > 0) { + let word = trimmedText.replace(/ .*/, ''); + spaceWords.push({ word, start: pos, end: pos + word.length }); + // remove processed word from trimmed text + const oldText = trimmedText; + trimmedText = trimmedText.replace(/[^ ]+/, '').trimStart(); + // update pos to start of next word + pos += oldText.length - trimmedText.length; + } + // find word the user is in + let contextStart = -1, contextEnd = -1; + for (let i = 0; i < spaceWords.length; i++) { + if (col >= spaceWords[i].start && col <= spaceWords[i].end) { + // found the word + contextStart = Math.max(0, i - windowSize); // clamp start index + contextEnd = Math.min(spaceWords.length, i + windowSize + 1); // clamp end index + // construct cursor context string + let contextString = ''; + for (let i = contextStart; i < contextEnd; i++) { + contextString += spaceWords[i].word + ' '; + } + // output cursor context string + vscode.window.showInformationMessage(contextString); + return; + } } - } } - +//# sourceMappingURL=text.js.map From d76cc3d06d09cc5691281497d70b52972b5cfbd0 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 23 Mar 2022 17:46:44 -0500 Subject: [PATCH 02/78] fixed output type-o on getLeadingSpaces() Fixed issue with the output not displaying as intended in the getLeadingSpaces() function --- src/commands/text.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 508c256..511220c 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -54,7 +54,7 @@ function getLeadingSpaces() { } else { let numSpaces = textLine.firstNonWhitespaceCharacterIndex; - vscode.window.showInformationMessage("Line Number " + lineNum.toString() + numSpaces.toString()) + " Leading Spaces "; + vscode.window.showInformationMessage("Line Number " + lineNum.toString() + ": " + numSpaces.toString() + " Leading Spaces "); } } else { From cfcbfd43fc29d5ce5ee359e93fd6df698f268872 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 23 Mar 2022 18:20:44 -0500 Subject: [PATCH 03/78] added fetchLineNumber(editor) and getLineNumber() added helper function fetchLineNumber(editor) to return the line number that the cursor is on and refactored the code to make use of this helper function in various places. Also added function getLineNumber() which will output the current line number the cursor is on. --- src/commands/text.ts | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 511220c..99eb15a 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -4,6 +4,10 @@ exports.textCommands = void 0; const vscode = require("vscode"); const pl = require("../pylex"); exports.textCommands = [ + { + name: 'mind-reader.getLineNumber', + callback: getLineNumber, + }, { name: 'mind-reader.getIndent', callback: getIndent, @@ -21,10 +25,30 @@ exports.textCommands = [ callback: runCursorContext } ]; +/* Helper Function + * This function returns the line number of the active text editor window + */ +function fetchLineNumber(editor) { + return editor.selection.active.line + 1; +} + +// Function that outputs the current line number the cursor is on +function getLineNumber() { + let editor = vscode.window.activeTextEditor; + + if (editor) { + let lineNum = fetchLineNumber(editor); + vscode.window.showInformationMessage("Line " + lineNum.toString()); + } + else { + vscode.window.showErrorMessage('No document currently active'); + } +} + function getIndent() { let editor = vscode.window.activeTextEditor; if (editor) { - let lineNum = editor.selection.active.line + 1; + let lineNum = fetchLineNumber(editor); let textLine = editor.document.lineAt(lineNum - 1); if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage("Line number " + lineNum.toString() + " Is Empty"); @@ -43,18 +67,22 @@ function getIndent() { vscode.window.showErrorMessage('No document currently active'); } } +/* Function -> Returns the number of leading spaces on the line the cursor is on + * This is done by returning the index of the first non whitespace character + * Since this index is a 0-index, the returned number will correspond to the number of leading spaces + */ function getLeadingSpaces() { let editor = vscode.window.activeTextEditor; if (editor) { - let lineNum = editor.selection.active.line + 1; + let lineNum = fetchLineNumber(editor); let textLine = editor.document.lineAt(lineNum - 1); if(textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage("Line number " + lineNum.toString() + " Is Empty"); } else { let numSpaces = textLine.firstNonWhitespaceCharacterIndex; - vscode.window.showInformationMessage("Line Number " + lineNum.toString() + ": " + numSpaces.toString() + " Leading Spaces "); + vscode.window.showInformationMessage("Line Number " + lineNum.toString() + " Has " + numSpaces.toString()+ " Leading Spaces "); } } else { From 6915cd5b44305dacdbbbbfcd5575b5851e8f2cdd Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 23 Mar 2022 21:42:05 -0500 Subject: [PATCH 04/78] leading spaces alternative method Added an alternative method for calculating the leading spaces instead of taking the index of the first non-whitespace character. Leaving it commented out, but still there as an alternative in-case something goes wrong w/ the index method. --- src/commands/text.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/commands/text.ts b/src/commands/text.ts index 99eb15a..03c4132 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -82,6 +82,7 @@ function getLeadingSpaces() { } else { let numSpaces = textLine.firstNonWhitespaceCharacterIndex; + // let numSpaces = textLine.text.length - textLine.text.trimStart().length; // Alternative method, same result by calculating the leading spaces vscode.window.showInformationMessage("Line Number " + lineNum.toString() + " Has " + numSpaces.toString()+ " Leading Spaces "); } } From 3525963bb095771c0e0c7c0a3740b17d278bf771 Mon Sep 17 00:00:00 2001 From: John Date: Wed, 23 Mar 2022 22:53:46 -0500 Subject: [PATCH 05/78] Switch from string concatination to interpolation Improves concision. --- src/commands/text.ts | 18 +++++++++--------- src/pylex/token.ts | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 03c4132..2ef811c 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -14,7 +14,7 @@ exports.textCommands = [ }, { name: 'mind-reader.getLeadingSpaces', - callback: getLeadingSpaces, + callback: getLeadingSpaces, }, { name: 'mind-reader.runLineContext', @@ -25,7 +25,7 @@ exports.textCommands = [ callback: runCursorContext } ]; -/* Helper Function +/* Helper Function * This function returns the line number of the active text editor window */ function fetchLineNumber(editor) { @@ -35,14 +35,14 @@ function fetchLineNumber(editor) { // Function that outputs the current line number the cursor is on function getLineNumber() { let editor = vscode.window.activeTextEditor; - + if (editor) { let lineNum = fetchLineNumber(editor); - vscode.window.showInformationMessage("Line " + lineNum.toString()); + vscode.window.showInformationMessage(`Line ${lineNum.toString()}`); } else { vscode.window.showErrorMessage('No document currently active'); - } + } } function getIndent() { @@ -51,7 +51,7 @@ function getIndent() { let lineNum = fetchLineNumber(editor); let textLine = editor.document.lineAt(lineNum - 1); if (textLine.isEmptyOrWhitespace) { - vscode.window.showInformationMessage("Line number " + lineNum.toString() + " Is Empty"); + vscode.window.showInformationMessage(`"Line ${lineNum.toString()} is Empty`); } else { // Grab tab format from open document @@ -60,7 +60,7 @@ function getIndent() { hard: !editor.options.insertSpaces }; let i = pl.Lexer.getIndent(textLine.text, tabFmt); - vscode.window.showInformationMessage("Line Number " + lineNum.toString() + " Indentation " + i.toString()); + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`); } } else { @@ -78,12 +78,12 @@ function getLeadingSpaces() { let lineNum = fetchLineNumber(editor); let textLine = editor.document.lineAt(lineNum - 1); if(textLine.isEmptyOrWhitespace) { - vscode.window.showInformationMessage("Line number " + lineNum.toString() + " Is Empty"); + vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); } else { let numSpaces = textLine.firstNonWhitespaceCharacterIndex; // let numSpaces = textLine.text.length - textLine.text.trimStart().length; // Alternative method, same result by calculating the leading spaces - vscode.window.showInformationMessage("Line Number " + lineNum.toString() + " Has " + numSpaces.toString()+ " Leading Spaces "); + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`); } } else { diff --git a/src/pylex/token.ts b/src/pylex/token.ts index b6a54e0..54e62be 100644 --- a/src/pylex/token.ts +++ b/src/pylex/token.ts @@ -53,7 +53,7 @@ export default class LineToken { * @return A string representation of the token */ toString(): string { - return this.type + ", linenr:" + (this.linenr+1) + ", indentLevel: " + this.indentLevel + ", attr: " + this.attr; + return `${this.type}, linenr: ${this.linenr+1}, indentLevel: ${this.indentLevel}, attr: ${this.attr}`; } } From d8c923e13ce46f6b6a5ac02da80cbb073ff889b1 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 24 Mar 2022 04:01:24 -0500 Subject: [PATCH 06/78] Changed leading spaces logic Added new logic to pl.Lexer to find number of leading spaces by either arithmetic or by finding the index position of the first non-whitespace character. Also added a boolean flag to switch easily between the two methods using ternary logic. Added comments explaining functionality. Fixed code spacing to be more uniform in style. --- src/commands/text.ts | 80 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 70 insertions(+), 10 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 2ef811c..23ce5b2 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -1,8 +1,10 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.textCommands = void 0; + const vscode = require("vscode"); const pl = require("../pylex"); + exports.textCommands = [ { name: 'mind-reader.getLineNumber', @@ -25,6 +27,7 @@ exports.textCommands = [ callback: runCursorContext } ]; + /* Helper Function * This function returns the line number of the active text editor window */ @@ -32,6 +35,13 @@ function fetchLineNumber(editor) { return editor.selection.active.line + 1; } +/* Helper Function + * This function returns the text from the current line of the active text editor window + */ +function fetchTextLine(editor) { + return editor.document.lineAt(fetchLineNumber(editor) - 1); +} + // Function that outputs the current line number the cursor is on function getLineNumber() { let editor = vscode.window.activeTextEditor; @@ -47,9 +57,11 @@ function getLineNumber() { function getIndent() { let editor = vscode.window.activeTextEditor; + if (editor) { let lineNum = fetchLineNumber(editor); - let textLine = editor.document.lineAt(lineNum - 1); + let textLine = fetchTextLine(editor); + if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`"Line ${lineNum.toString()} is Empty`); } @@ -60,38 +72,70 @@ function getIndent() { hard: !editor.options.insertSpaces }; let i = pl.Lexer.getIndent(textLine.text, tabFmt); - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`); + + // Ternary operator to change the tense of 'indent' to 'indents' for the output if i is greater than 1 + (i > 1) ? + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`) : + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); } } else { vscode.window.showErrorMessage('No document currently active'); } } + /* Function -> Returns the number of leading spaces on the line the cursor is on - * This is done by returning the index of the first non whitespace character - * Since this index is a 0-index, the returned number will correspond to the number of leading spaces + * There are two methods that can be used to find the leading spaces: + * method 1: + * calculates the number of leading spaces by finding the length of the current line + * then subtracting from that the length of the text after trimming the whitespace at the start + * which will equal the number of whitespace characters + * + * TO-USE: set calculateLeadingSpaces to true + * + * method 2 (default): + * finds the index position of the first non-whitespace character in a 0-index + * this number will equal the number of spaces preceding the non-whitespace character + * due to the nature of 0-indexes. + * + * TO-USE: set calculateLeadingSpaces to false */ function getLeadingSpaces() { let editor = vscode.window.activeTextEditor; if (editor) { - let lineNum = fetchLineNumber(editor); - let textLine = editor.document.lineAt(lineNum - 1); - if(textLine.isEmptyOrWhitespace) { + const lineNum = fetchLineNumber(editor); + const textLine = fetchTextLine(editor); + + if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); } else { - let numSpaces = textLine.firstNonWhitespaceCharacterIndex; - // let numSpaces = textLine.text.length - textLine.text.trimStart().length; // Alternative method, same result by calculating the leading spaces - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`); + /* + * set true to use method 1: find the number of leading spaces through arithmetic + * set false to use method 2: find the index position of the first non-whitespace character in a 0-index + * + * default: false + */ + const calculateLeadingSpaces = false; // change boolean value to change method + const numSpaces = (calculateLeadingSpaces === true) ? + pl.Lexer.getLeadingSpacesByArithmetic(textLine) : + pl.Lexer.getLeadingSpacesByIndex(textLine); + + /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is greater than 1 */ + (numSpaces > 1) ? + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`) : + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); } } else { vscode.window.showErrorMessage('No document currently active'); } } + function runLineContext() { let editor = vscode.window.activeTextEditor; + if (editor) { // current text and line number let editorText = editor.document.getText(); @@ -105,27 +149,34 @@ function runLineContext() { let context = parser.context(line); // build text let contentString = createContextString(context, line); + vscode.window.showInformationMessage(contentString); } else { vscode.window.showErrorMessage('No document currently active'); } } + function createContextString(context, line) { if (context.length < 1) { throw new Error('Cannot create context string for empty context'); } + let contextString = 'Line ' + (line + 1); // 1 based + if (context[0].token && context[0].token.attr) { contextString += ': ' + context[0].token.type.toString() + ' ' + context[0].token.attr.toString(); } + for (let i = 1; i < context.length; i++) { let node = context[i]; + if (node.label === 'root') { // root contextString += ' in the Document Root'; continue; } + if (node.token.type !== pl.PylexSymbol.EMPTY && node.token.type !== pl.PylexSymbol.INDENT) { contextString += ' inside ' + node.token.type.toString(); @@ -136,14 +187,17 @@ function createContextString(context, line) { } return contextString; } + // find up to `n` words around the cursor, where `n` is // the value of `#mindReader.reader.contextWindow` function runCursorContext() { let editor = vscode.window.activeTextEditor; + if (!editor) { vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); return; } + const cursorPos = editor.selection.active; const text = editor.document.lineAt(cursorPos).text; const windowSize = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); @@ -154,6 +208,7 @@ function runCursorContext() { let maxPos = text.length; // clamp cursor start/end to new range let col = cursorPos.character; // effective column of the cursor position + if (col < leadingWS) { // move effective start to first non-whitespace character in the line col = leadingWS; @@ -162,11 +217,14 @@ function runCursorContext() { // move effective end to last non-whitespace character in the line col = leadingWS + trimmedText.length - 1; } + // generate list of space separate words with range data (start, end) // TODO: can find user position to be done in one pass let spaceWords = []; + while (pos < maxPos && trimmedText.length > 0) { let word = trimmedText.replace(/ .*/, ''); + spaceWords.push({ word, start: pos, end: pos + word.length }); // remove processed word from trimmed text const oldText = trimmedText; @@ -176,6 +234,7 @@ function runCursorContext() { } // find word the user is in let contextStart = -1, contextEnd = -1; + for (let i = 0; i < spaceWords.length; i++) { if (col >= spaceWords[i].start && col <= spaceWords[i].end) { // found the word @@ -183,6 +242,7 @@ function runCursorContext() { contextEnd = Math.min(spaceWords.length, i + windowSize + 1); // clamp end index // construct cursor context string let contextString = ''; + for (let i = contextStart; i < contextEnd; i++) { contextString += spaceWords[i].word + ' '; } From e67f731bc679c3d35fac6751e817c9c57e102fff Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 24 Mar 2022 04:03:17 -0500 Subject: [PATCH 07/78] added 2 functions added functions getLeadingSpacesByArithmetic and getLeadingSpacesByIndex to facilitate functionality of finding the number of leading spaces via two methods. --- src/pylex/lexer.ts | 402 +++++++++++++++++++++++---------------------- 1 file changed, 205 insertions(+), 197 deletions(-) diff --git a/src/pylex/lexer.ts b/src/pylex/lexer.ts index 1f7c336..aa1235c 100644 --- a/src/pylex/lexer.ts +++ b/src/pylex/lexer.ts @@ -1,215 +1,223 @@ -import { LineToken } from '.'; -import { Symbol, EOFTOKEN, TabInfo } from './token'; - -type Rule = { - pattern: RegExp, - type: Symbol, -}; - +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const _1 = require("."); +const token_1 = require("./token"); /** * List of recognition patterns, in order of priority * The first item is a recognition pattern, used to recognize the token * the second item is the token type */ -const rules: Rule[] = [ - { - pattern: /^\s*def\s+(?[a-zA-Z_][a-zA-Z0-9_]*)\(/, - type: Symbol.FUNCTION - }, - { - pattern: /^\s*class\s+(?[a-zA-Z_][a-zA-Z0-9_]*)/, - type: Symbol.CLASS - }, - { - pattern: /^\s*if\s+(?[^:]+):\s*/, - type: Symbol.IF - }, - { - pattern: /^\s*elif\s+(?[^:]+):\s*$/, - type: Symbol.ELIF - }, - { - pattern: /^\s*else\s*:/, - type: Symbol.ELSE - }, - { - pattern: /^\s*for\s+(?[^:]+):\s*$/, - type: Symbol.FOR - }, - { - pattern: /^\s*while\s+(?[^:]+):\s*$/, - type: Symbol.WHILE - }, - { - pattern: /^\s*try\s*:/, - type: Symbol.TRY - }, - { - pattern: /^\s*except(\s*(?[^:]+))?:\s*$/, - type: Symbol.EXCEPT - }, - { - pattern: /^\s*finally\s*:\s*$/, - type: Symbol.FINALLY - }, - { - pattern: /^\s*with\s+(?[^:]+):\s*$/, - type: Symbol.WITH - }, +const rules = [ + { + pattern: /^\s*def\s+(?[a-zA-Z_][a-zA-Z0-9_]*)\(/, + type: token_1.Symbol.FUNCTION + }, + { + pattern: /^\s*class\s+(?[a-zA-Z_][a-zA-Z0-9_]*)/, + type: token_1.Symbol.CLASS + }, + { + pattern: /^\s*if\s+(?[^:]+):\s*/, + type: token_1.Symbol.IF + }, + { + pattern: /^\s*elif\s+(?[^:]+):\s*$/, + type: token_1.Symbol.ELIF + }, + { + pattern: /^\s*else\s*:/, + type: token_1.Symbol.ELSE + }, + { + pattern: /^\s*for\s+(?[^:]+):\s*$/, + type: token_1.Symbol.FOR + }, + { + pattern: /^\s*while\s+(?[^:]+):\s*$/, + type: token_1.Symbol.WHILE + }, + { + pattern: /^\s*try\s*:/, + type: token_1.Symbol.TRY + }, + { + pattern: /^\s*except(\s*(?[^:]+))?:\s*$/, + type: token_1.Symbol.EXCEPT + }, + { + pattern: /^\s*finally\s*:\s*$/, + type: token_1.Symbol.FINALLY + }, + { + pattern: /^\s*with\s+(?[^:]+):\s*$/, + type: token_1.Symbol.WITH + }, ]; - /** * Line-By-Line Lexer */ -export default class Lexer { - private textLines: string[] = []; // array of text lines - private pos: number = 0; - private _currToken: LineToken = EOFTOKEN; - - /** - * Calculates indentation level for a line. If using soft tabs, - * indent level rounds up (so, tabSize+1 spaces is 2 levels, - * 2*tabSize+1 is 3, etc.) - * - * @param `text` The line of text. - * @param `tabFmt` A tab information descriptor. - * @return The indent of `text` with consideration for `tabFmt`. - */ - static getIndent(text: string, tabFmt: TabInfo): number { - let leadingSpace: number = text.length - text.trimLeft().length; - let indent: number; - if (tabFmt.hard) { - // used tabs - indent = leadingSpace; - } else { - // use spaces - indent = Math.ceil(leadingSpace/tabFmt.size!); - } - - return indent; - } - - /** - * @param `text` The text to lex. - * @param `tabFmt` A tab information descriptor - */ - constructor(text?: string, private tabFmt?: TabInfo) { - // default is 4 wide expanded tabs - this.tabFmt = { - ...{size: 4, hard: false}, - ...tabFmt - }; - - if (text) { - // normalize linefeeds - text = text.replace('\r\n', '\n'); - } - this.restart(text); - } - - /** - * Restart lexer with new text. - * - * @param `text` The new text to lex. - */ - restart(text?: string): void { - this.pos = 0; - this._currToken = EOFTOKEN; // if no input, already on EOFTOKEN - if (text) { - this.textLines = text.split('\n'); - this.next(); // advance to the first token - } - } - - /** - * @return the current {@link LineToken}. - */ - currToken(): LineToken { return this._currToken; } - - /** - * Advance the position in the token stream. - * - * @return The new current token, after advancing - */ - next(): LineToken { - if (this._currToken === EOFTOKEN && this.pos > this.textLines.length) { - throw new Error('Cannot advance past end'); - } - - // Until a LineToken is found, or EOF - while (this.pos < this.textLines.length) { - let line: string = this.textLines[this.pos]; - let indent: number = Lexer.getIndent(line, this.tabFmt!); - let token: LineToken; - for (var r of rules) { - // Does line match pattern? - let match: RegExpMatchArray | null = line.match(r.pattern); - if (match) { - // Yes... - if (match.groups) { - token = new LineToken(r.type, this.pos, indent, match.groups["attr"]); - } else { - token = new LineToken(r.type, this.pos, indent); - } - - this._currToken = token; - this.pos++; - return this.currToken(); +class Lexer { + /** + * @param `text` The text to lex. + * @param `tabFmt` A tab information descriptor + */ + constructor(text, tabFmt) { + this.tabFmt = tabFmt; + this.textLines = []; // array of text lines + this.pos = 0; + this._currToken = token_1.EOFTOKEN; + // default is 4 wide expanded tabs + this.tabFmt = Object.assign({ size: 4, hard: false }, tabFmt); + if (text) { + // normalize linefeeds + text = text.replace('\r\n', '\n'); } - } - // No rules matched - - // TODO: move to rules - if (/^\s*(#.*)?$/.test(line)) { - // "empty" line - token = new LineToken(Symbol.EMPTY, this.pos, 999999); - } else { - // This is an INDENT token - token = new LineToken(Symbol.INDENT, this.pos, indent); - } - - this._currToken = token; - this.pos++; - return this.currToken(); + this.restart(text); } - - // Didn't return, must be EOF - this._currToken = EOFTOKEN; - this.pos++; - return this.currToken(); - } - - /** - * Move backwards in the token stream - * - * @param `n` The number of positions to retract. - * @return The new current token after retracting. - */ - retract(n: number = 1): LineToken { - if (this.pos - 1 - n < 0) { - // -1 because this.pos is currently on the next token - throw new RangeError('Cannot retract past start'); + /** + * Calculates indentation level for a line. If using soft tabs, + * indent level rounds up (so, tabSize+1 spaces is 2 levels, + * 2*tabSize+1 is 3, etc.) + * + * @param `text` The line of text. + * @param `tabFmt` A tab information descriptor. + * @return The indent of `text` with consideration for `tabFmt`. + */ + static getIndent(text, tabFmt) { + let leadingSpace = text.length - text.trimLeft().length; + let indent; + if (tabFmt.hard) { + // used tabs + indent = leadingSpace; + } + else { + // use spaces + indent = Math.ceil(leadingSpace / tabFmt.size); + } + return indent; } + /** + * Calculates leading spaces for a line. + * This method uses arithmetic to calculate the number of leading spaces + * + * @param `text` The line of text. + * @return The number of leading spaces of `text`. + */ + static getLeadingSpacesByArithmetic(textLine) { + const leadingSpaces = textLine.text.length - textLine.text.trimStart().length; - if (n <= 0) { - throw new RangeError('Retract distance must be positive'); + return leadingSpaces; } + /** + * Calculates leading spaces for a line. + * This method finds the index position of the first non-whitespace character + * Since the index is built using a 0-index, the position of this character + * will equal the number of spaces preceding the character. + * + * @param `text` The line of text. + * @return The number of leading spaces of `text` with respect to the index position of the first non-whitespace character. + */ + static getLeadingSpacesByIndex(textLine) { + const indexNum = textLine.firstNonWhitespaceCharacterIndex; - if (this.pos - n === 0) { - // just restart - this.pos = 0; - return this.next(); + return indexNum; } - - let c = n + 1; - while (c > 0) { - this.pos--; - while (/^\s*(#.*)?$/.test(this.textLines[this.pos])) { - // Skip empty lines - this.pos--; - } - c--; + /** + * Restart lexer with new text. + * + * @param `text` The new text to lex. + */ + restart(text) { + this.pos = 0; + this._currToken = token_1.EOFTOKEN; // if no input, already on EOFTOKEN + if (text) { + this.textLines = text.split('\n'); + this.next(); // advance to the first token + } + } + /** + * @return the current {@link LineToken}. + */ + currToken() { return this._currToken; } + /** + * Advance the position in the token stream. + * + * @return The new current token, after advancing + */ + next() { + if (this._currToken === token_1.EOFTOKEN && this.pos > this.textLines.length) { + throw new Error('Cannot advance past end'); + } + // Until a LineToken is found, or EOF + while (this.pos < this.textLines.length) { + let line = this.textLines[this.pos]; + let indent = Lexer.getIndent(line, this.tabFmt); + let token; + for (var r of rules) { + // Does line match pattern? + let match = line.match(r.pattern); + if (match) { + // Yes... + if (match.groups) { + token = new _1.LineToken(r.type, this.pos, indent, match.groups["attr"]); + } + else { + token = new _1.LineToken(r.type, this.pos, indent); + } + this._currToken = token; + this.pos++; + return this.currToken(); + } + } + // No rules matched + // TODO: move to rules + if (/^\s*(#.*)?$/.test(line)) { + // "empty" line + token = new _1.LineToken(token_1.Symbol.EMPTY, this.pos, 999999); + } + else { + // This is an INDENT token + token = new _1.LineToken(token_1.Symbol.INDENT, this.pos, indent); + } + this._currToken = token; + this.pos++; + return this.currToken(); + } + // Didn't return, must be EOF + this._currToken = token_1.EOFTOKEN; + this.pos++; + return this.currToken(); + } + /** + * Move backwards in the token stream + * + * @param `n` The number of positions to retract. + * @return The new current token after retracting. + */ + retract(n = 1) { + if (this.pos - 1 - n < 0) { + // -1 because this.pos is currently on the next token + throw new RangeError('Cannot retract past start'); + } + if (n <= 0) { + throw new RangeError('Retract distance must be positive'); + } + if (this.pos - n === 0) { + // just restart + this.pos = 0; + return this.next(); + } + let c = n + 1; + while (c > 0) { + this.pos--; + while (/^\s*(#.*)?$/.test(this.textLines[this.pos])) { + // Skip empty lines + this.pos--; + } + c--; + } + return this.next(); } - return this.next(); - } } +exports.default = Lexer; +//# sourceMappingURL=lexer.js.map From 08ec15287aedb8f21c747d9ef44485aa3dc2f674 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 24 Mar 2022 04:27:16 -0500 Subject: [PATCH 08/78] beautify code ran beautify code extension to clean-up the code --- src/commands/text.js | 258 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 258 insertions(+) create mode 100644 src/commands/text.js diff --git a/src/commands/text.js b/src/commands/text.js new file mode 100644 index 0000000..f9ab81e --- /dev/null +++ b/src/commands/text.js @@ -0,0 +1,258 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.textCommands = void 0; + +const vscode = require("vscode"); +const pl = require("../pylex"); + +exports.textCommands = [ + { + name: 'mind-reader.getLineNumber', + callback: getLineNumber, + }, + { + name: 'mind-reader.getIndent', + callback: getIndent, + }, + { + name: 'mind-reader.getLeadingSpaces', + callback: getLeadingSpaces, + }, + { + name: 'mind-reader.runLineContext', + callback: runLineContext, + }, + { + name: 'mind-reader.runCursorContext', + callback: runCursorContext + } +]; + +/* Helper Function + * This function returns the line number of the active text editor window + */ +function fetchLineNumber(editor) { + return editor.selection.active.line + 1; +} + +/* Helper Function + * This function returns the text from the current line of the active text editor window + */ +function fetchTextLine(editor) { + return editor.document.lineAt(fetchLineNumber(editor) - 1); +} + +// Function that outputs the current line number the cursor is on +function getLineNumber() { + let editor = vscode.window.activeTextEditor; + + if (editor) { + let lineNum = fetchLineNumber(editor); + vscode.window.showInformationMessage(`Line ${lineNum.toString()}`); + } else { + vscode.window.showErrorMessage('No document currently active'); + } +} + +function getIndent() { + let editor = vscode.window.activeTextEditor; + + if (editor) { + let lineNum = fetchLineNumber(editor); + let textLine = fetchTextLine(editor); + + if (textLine.isEmptyOrWhitespace) { + vscode.window.showInformationMessage(`Line ${lineNum.toString()} is Empty`); + } else { + // Grab tab format from open document + let tabFmt = { + size: editor.options.tabSize, + hard: !editor.options.insertSpaces + }; + let i = pl.Lexer.getIndent(textLine.text, tabFmt); + + // Ternary operator to change the tense of 'indent' to 'indents' for the output if i is greater than 1 + (i > 1) ? + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`): + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); + } + } else { + vscode.window.showErrorMessage('No document currently active'); + } +} + +/* Function -> Returns the number of leading spaces on the line the cursor is on + * There are two methods that can be used to find the leading spaces: + * method 1: + * calculates the number of leading spaces by finding the length of the current line + * then subtracting from that the length of the text after trimming the whitespace at the start + * which will equal the number of whitespace characters + * + * TO-USE: set calculateLeadingSpaces to true + * + * method 2 (default): + * finds the index position of the first non-whitespace character in a 0-index + * this number will equal the number of spaces preceding the non-whitespace character + * due to the nature of 0-indexes. + * + * TO-USE: set calculateLeadingSpaces to false + */ +function getLeadingSpaces() { + let editor = vscode.window.activeTextEditor; + + if (editor) { + const lineNum = fetchLineNumber(editor); + const textLine = fetchTextLine(editor); + + if (textLine.isEmptyOrWhitespace) { + vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); + } else { + /* + * set true to use method 1: find the number of leading spaces through arithmetic + * set false to use method 2: find the index position of the first non-whitespace character in a 0-index + * + * default: false + */ + const calculateLeadingSpaces = false; // change boolean value to change method + const numSpaces = (calculateLeadingSpaces === true) ? + pl.Lexer.getLeadingSpacesByArithmetic(textLine) : + pl.Lexer.getLeadingSpacesByIndex(textLine); + + /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is greater than 1 */ + (numSpaces > 1) ? + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`): + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); + } + } else { + vscode.window.showErrorMessage('No document currently active'); + } +} + +function runLineContext() { + let editor = vscode.window.activeTextEditor; + + if (editor) { + // current text and line number + let editorText = editor.document.getText(); + let line = editor.selection.active.line; + // get tab info settings + let size = parseInt(editor.options.tabSize); + let hard = !editor.options.insertSpaces; + // initialize parser + let parser = new pl.Parser(editorText, { + size, + hard + }); + parser.parse(); + let context = parser.context(line); + // build text + let contentString = createContextString(context, line); + + vscode.window.showInformationMessage(contentString); + } else { + vscode.window.showErrorMessage('No document currently active'); + } +} + +function createContextString(context, line) { + if (context.length < 1) { + throw new Error('Cannot create context string for empty context'); + } + + let contextString = 'Line ' + (line + 1); // 1 based + + if (context[0].token && context[0].token.attr) { + contextString += ': ' + context[0].token.type.toString() + ' ' + context[0].token.attr.toString(); + } + + for (let i = 1; i < context.length; i++) { + let node = context[i]; + + if (node.label === 'root') { + // root + contextString += ' in the Document Root'; + continue; + } + + if (node.token.type !== pl.PylexSymbol.EMPTY && + node.token.type !== pl.PylexSymbol.INDENT) { + contextString += ' inside ' + node.token.type.toString(); + if (node.token.attr) { + contextString += ' ' + node.token.attr.toString(); + } + } + } + return contextString; +} + +// find up to `n` words around the cursor, where `n` is +// the value of `#mindReader.reader.contextWindow` +function runCursorContext() { + let editor = vscode.window.activeTextEditor; + + if (!editor) { + vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); + return; + } + + const cursorPos = editor.selection.active; + const text = editor.document.lineAt(cursorPos).text; + const windowSize = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); + let trimmedText = text.trimStart(); // trim leading whitespace + let leadingWS = text.length - trimmedText.length; // # of characters of leading whitespace + trimmedText = trimmedText.trimEnd(); // trim trailing whitespace + let pos = leadingWS; + let maxPos = text.length; + // clamp cursor start/end to new range + let col = cursorPos.character; // effective column of the cursor position + + if (col < leadingWS) { + // move effective start to first non-whitespace character in the line + col = leadingWS; + } else if (col > leadingWS + trimmedText.length - 1) { + // move effective end to last non-whitespace character in the line + col = leadingWS + trimmedText.length - 1; + } + + // generate list of space separate words with range data (start, end) + // TODO: can find user position to be done in one pass + let spaceWords = []; + + while (pos < maxPos && trimmedText.length > 0) { + let word = trimmedText.replace(/ .*/, ''); + + spaceWords.push({ + word, + start: pos, + end: pos + word.length + }); + // remove processed word from trimmed text + const oldText = trimmedText; + trimmedText = trimmedText.replace(/[^ ]+/, '').trimStart(); + // update pos to start of next word + pos += oldText.length - trimmedText.length; + } + // find word the user is in + let contextStart = -1, + contextEnd = -1; + + for (let i = 0; i < spaceWords.length; i++) { + if (col >= spaceWords[i].start && col <= spaceWords[i].end) { + // found the word + contextStart = Math.max(0, i - windowSize); // clamp start index + contextEnd = Math.min(spaceWords.length, i + windowSize + 1); // clamp end index + // construct cursor context string + let contextString = ''; + + for (let i = contextStart; i < contextEnd; i++) { + contextString += spaceWords[i].word + ' '; + } + // output cursor context string + vscode.window.showInformationMessage(contextString); + return; + } + } +} +//# sourceMappingURL=text.js.map \ No newline at end of file From 88ddcd7c51ba2fc1ed778f9e2106ab889f551f01 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 24 Mar 2022 04:28:21 -0500 Subject: [PATCH 09/78] beautify code ran beautify code extension to clean-up the code and make it more uniform in style --- src/pylex/lexer.js | 227 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 src/pylex/lexer.js diff --git a/src/pylex/lexer.js b/src/pylex/lexer.js new file mode 100644 index 0000000..8ea195b --- /dev/null +++ b/src/pylex/lexer.js @@ -0,0 +1,227 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _1 = require("."); +const token_1 = require("./token"); +/** + * List of recognition patterns, in order of priority + * The first item is a recognition pattern, used to recognize the token + * the second item is the token type + */ +const rules = [ + { + pattern: /^\s*def\s+(?[a-zA-Z_][a-zA-Z0-9_]*)\(/, + type: token_1.Symbol.FUNCTION + }, + { + pattern: /^\s*class\s+(?[a-zA-Z_][a-zA-Z0-9_]*)/, + type: token_1.Symbol.CLASS + }, + { + pattern: /^\s*if\s+(?[^:]+):\s*/, + type: token_1.Symbol.IF + }, + { + pattern: /^\s*elif\s+(?[^:]+):\s*$/, + type: token_1.Symbol.ELIF + }, + { + pattern: /^\s*else\s*:/, + type: token_1.Symbol.ELSE + }, + { + pattern: /^\s*for\s+(?[^:]+):\s*$/, + type: token_1.Symbol.FOR + }, + { + pattern: /^\s*while\s+(?[^:]+):\s*$/, + type: token_1.Symbol.WHILE + }, + { + pattern: /^\s*try\s*:/, + type: token_1.Symbol.TRY + }, + { + pattern: /^\s*except(\s*(?[^:]+))?:\s*$/, + type: token_1.Symbol.EXCEPT + }, + { + pattern: /^\s*finally\s*:\s*$/, + type: token_1.Symbol.FINALLY + }, + { + pattern: /^\s*with\s+(?[^:]+):\s*$/, + type: token_1.Symbol.WITH + }, +]; +/** + * Line-By-Line Lexer + */ +class Lexer { + /** + * @param `text` The text to lex. + * @param `tabFmt` A tab information descriptor + */ + constructor(text, tabFmt) { + this.tabFmt = tabFmt; + this.textLines = []; // array of text lines + this.pos = 0; + this._currToken = token_1.EOFTOKEN; + // default is 4 wide expanded tabs + this.tabFmt = Object.assign({ + size: 4, + hard: false + }, tabFmt); + if (text) { + // normalize linefeeds + text = text.replace('\r\n', '\n'); + } + this.restart(text); + } + /** + * Calculates indentation level for a line. If using soft tabs, + * indent level rounds up (so, tabSize+1 spaces is 2 levels, + * 2*tabSize+1 is 3, etc.) + * + * @param `text` The line of text. + * @param `tabFmt` A tab information descriptor. + * @return The indent of `text` with consideration for `tabFmt`. + */ + static getIndent(text, tabFmt) { + let leadingSpace = text.length - text.trimLeft().length; + let indent; + if (tabFmt.hard) { + // used tabs + indent = leadingSpace; + } else { + // use spaces + indent = Math.ceil(leadingSpace / tabFmt.size); + } + return indent; + } + /** + * Calculates leading spaces for a line. + * This method uses arithmetic to calculate the number of leading spaces + * + * @param `text` The line of text. + * @return The number of leading spaces of `text`. + */ + static getLeadingSpacesByArithmetic(textLine) { + const leadingSpaces = textLine.text.length - textLine.text.trimStart().length; + + return leadingSpaces; + } + /** + * Calculates leading spaces for a line. + * This method finds the index position of the first non-whitespace character + * Since the index is built using a 0-index, the position of this character + * will equal the number of spaces preceding the character. + * + * @param `text` The line of text. + * @return The number of leading spaces of `text` with respect to the index position of the first non-whitespace character. + */ + static getLeadingSpacesByIndex(textLine) { + const indexNum = textLine.firstNonWhitespaceCharacterIndex; + + return indexNum; + } + /** + * Restart lexer with new text. + * + * @param `text` The new text to lex. + */ + restart(text) { + this.pos = 0; + this._currToken = token_1.EOFTOKEN; // if no input, already on EOFTOKEN + if (text) { + this.textLines = text.split('\n'); + this.next(); // advance to the first token + } + } + /** + * @return the current {@link LineToken}. + */ + currToken() { + return this._currToken; + } + /** + * Advance the position in the token stream. + * + * @return The new current token, after advancing + */ + next() { + if (this._currToken === token_1.EOFTOKEN && this.pos > this.textLines.length) { + throw new Error('Cannot advance past end'); + } + // Until a LineToken is found, or EOF + while (this.pos < this.textLines.length) { + let line = this.textLines[this.pos]; + let indent = Lexer.getIndent(line, this.tabFmt); + let token; + for (var r of rules) { + // Does line match pattern? + let match = line.match(r.pattern); + if (match) { + // Yes... + if (match.groups) { + token = new _1.LineToken(r.type, this.pos, indent, match.groups["attr"]); + } else { + token = new _1.LineToken(r.type, this.pos, indent); + } + this._currToken = token; + this.pos++; + return this.currToken(); + } + } + // No rules matched + // TODO: move to rules + if (/^\s*(#.*)?$/.test(line)) { + // "empty" line + token = new _1.LineToken(token_1.Symbol.EMPTY, this.pos, 999999); + } else { + // This is an INDENT token + token = new _1.LineToken(token_1.Symbol.INDENT, this.pos, indent); + } + this._currToken = token; + this.pos++; + return this.currToken(); + } + // Didn't return, must be EOF + this._currToken = token_1.EOFTOKEN; + this.pos++; + return this.currToken(); + } + /** + * Move backwards in the token stream + * + * @param `n` The number of positions to retract. + * @return The new current token after retracting. + */ + retract(n = 1) { + if (this.pos - 1 - n < 0) { + // -1 because this.pos is currently on the next token + throw new RangeError('Cannot retract past start'); + } + if (n <= 0) { + throw new RangeError('Retract distance must be positive'); + } + if (this.pos - n === 0) { + // just restart + this.pos = 0; + return this.next(); + } + let c = n + 1; + while (c > 0) { + this.pos--; + while (/^\s*(#.*)?$/.test(this.textLines[this.pos])) { + // Skip empty lines + this.pos--; + } + c--; + } + return this.next(); + } +} +exports.default = Lexer; +//# sourceMappingURL=lexer.js.map \ No newline at end of file From 125cf15a68ed50b32bd881c33a486cf0646191ea Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 24 Mar 2022 04:48:59 -0500 Subject: [PATCH 10/78] fixed plural output logic Fixed logic of output, was showing singular for '0' ie: '0 space' instead of '0 spaces' - This has been resolved. --- src/commands/text.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/commands/text.js b/src/commands/text.js index f9ab81e..5c18975 100644 --- a/src/commands/text.js +++ b/src/commands/text.js @@ -73,8 +73,8 @@ function getIndent() { }; let i = pl.Lexer.getIndent(textLine.text, tabFmt); - // Ternary operator to change the tense of 'indent' to 'indents' for the output if i is greater than 1 - (i > 1) ? + /* Ternary operator to change the tense of 'indent' to 'indents' for the output if i is 0 or greater than 1 */ + (i !== 1) ? vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`): vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); } @@ -120,8 +120,8 @@ function getLeadingSpaces() { pl.Lexer.getLeadingSpacesByArithmetic(textLine) : pl.Lexer.getLeadingSpacesByIndex(textLine); - /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is greater than 1 */ - (numSpaces > 1) ? + /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is 0 or greater than 1 */ + (numSpaces !== 1) ? vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`): vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); } From 96bca9a601ff688aae0cc9ead8d7dc7f99233456 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 09:08:07 -0500 Subject: [PATCH 11/78] js -> ts migration .js files ended up getting uploaded, beginnings of attempting to fix that mistake. Migrating changes made in .js file to .ts file --- src/commands/text.ts | 91 +++++++++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 44 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 23ce5b2..6bad4d8 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -1,5 +1,7 @@ "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", { + value: true +}); exports.textCommands = void 0; const vscode = require("vscode"); @@ -49,37 +51,34 @@ function getLineNumber() { if (editor) { let lineNum = fetchLineNumber(editor); vscode.window.showInformationMessage(`Line ${lineNum.toString()}`); - } - else { + } else { vscode.window.showErrorMessage('No document currently active'); } } function getIndent() { let editor = vscode.window.activeTextEditor; - + if (editor) { let lineNum = fetchLineNumber(editor); let textLine = fetchTextLine(editor); - + if (textLine.isEmptyOrWhitespace) { - vscode.window.showInformationMessage(`"Line ${lineNum.toString()} is Empty`); - } - else { + vscode.window.showInformationMessage(`Line ${lineNum.toString()} is Empty`); + } else { // Grab tab format from open document let tabFmt = { size: editor.options.tabSize, hard: !editor.options.insertSpaces }; let i = pl.Lexer.getIndent(textLine.text, tabFmt); - - // Ternary operator to change the tense of 'indent' to 'indents' for the output if i is greater than 1 - (i > 1) ? - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`) : + + /* Ternary operator to change the tense of 'indent' to 'indents' for the output if i is 0 or greater than 1 */ + (i !== 1) ? + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`): vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); } - } - else { + } else { vscode.window.showErrorMessage('No document currently active'); } } @@ -106,11 +105,10 @@ function getLeadingSpaces() { if (editor) { const lineNum = fetchLineNumber(editor); const textLine = fetchTextLine(editor); - + if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); - } - else { + } else { /* * set true to use method 1: find the number of leading spaces through arithmetic * set false to use method 2: find the index position of the first non-whitespace character in a 0-index @@ -121,21 +119,20 @@ function getLeadingSpaces() { const numSpaces = (calculateLeadingSpaces === true) ? pl.Lexer.getLeadingSpacesByArithmetic(textLine) : pl.Lexer.getLeadingSpacesByIndex(textLine); - - /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is greater than 1 */ - (numSpaces > 1) ? - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`) : + + /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is 0 or greater than 1 */ + (numSpaces !== 1) ? + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`): vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); } - } - else { + } else { vscode.window.showErrorMessage('No document currently active'); } } function runLineContext() { let editor = vscode.window.activeTextEditor; - + if (editor) { // current text and line number let editorText = editor.document.getText(); @@ -144,15 +141,17 @@ function runLineContext() { let size = parseInt(editor.options.tabSize); let hard = !editor.options.insertSpaces; // initialize parser - let parser = new pl.Parser(editorText, { size, hard }); + let parser = new pl.Parser(editorText, { + size, + hard + }); parser.parse(); let context = parser.context(line); // build text let contentString = createContextString(context, line); - + vscode.window.showInformationMessage(contentString); - } - else { + } else { vscode.window.showErrorMessage('No document currently active'); } } @@ -161,22 +160,22 @@ function createContextString(context, line) { if (context.length < 1) { throw new Error('Cannot create context string for empty context'); } - + let contextString = 'Line ' + (line + 1); // 1 based - + if (context[0].token && context[0].token.attr) { contextString += ': ' + context[0].token.type.toString() + ' ' + context[0].token.attr.toString(); } for (let i = 1; i < context.length; i++) { let node = context[i]; - + if (node.label === 'root') { // root contextString += ' in the Document Root'; continue; } - + if (node.token.type !== pl.PylexSymbol.EMPTY && node.token.type !== pl.PylexSymbol.INDENT) { contextString += ' inside ' + node.token.type.toString(); @@ -192,12 +191,12 @@ function createContextString(context, line) { // the value of `#mindReader.reader.contextWindow` function runCursorContext() { let editor = vscode.window.activeTextEditor; - + if (!editor) { vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); return; } - + const cursorPos = editor.selection.active; const text = editor.document.lineAt(cursorPos).text; const windowSize = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); @@ -208,24 +207,27 @@ function runCursorContext() { let maxPos = text.length; // clamp cursor start/end to new range let col = cursorPos.character; // effective column of the cursor position - + if (col < leadingWS) { // move effective start to first non-whitespace character in the line col = leadingWS; - } - else if (col > leadingWS + trimmedText.length - 1) { + } else if (col > leadingWS + trimmedText.length - 1) { // move effective end to last non-whitespace character in the line col = leadingWS + trimmedText.length - 1; } - + // generate list of space separate words with range data (start, end) // TODO: can find user position to be done in one pass let spaceWords = []; - + while (pos < maxPos && trimmedText.length > 0) { let word = trimmedText.replace(/ .*/, ''); - - spaceWords.push({ word, start: pos, end: pos + word.length }); + + spaceWords.push({ + word, + start: pos, + end: pos + word.length + }); // remove processed word from trimmed text const oldText = trimmedText; trimmedText = trimmedText.replace(/[^ ]+/, '').trimStart(); @@ -233,8 +235,9 @@ function runCursorContext() { pos += oldText.length - trimmedText.length; } // find word the user is in - let contextStart = -1, contextEnd = -1; - + let contextStart = -1, + contextEnd = -1; + for (let i = 0; i < spaceWords.length; i++) { if (col >= spaceWords[i].start && col <= spaceWords[i].end) { // found the word @@ -242,7 +245,7 @@ function runCursorContext() { contextEnd = Math.min(spaceWords.length, i + windowSize + 1); // clamp end index // construct cursor context string let contextString = ''; - + for (let i = contextStart; i < contextEnd; i++) { contextString += spaceWords[i].word + ' '; } From 9062c253cf5984ca9eb7a293ea59b93d004ed619 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 09:09:09 -0500 Subject: [PATCH 12/78] delete text.js .js file never supposed to have been uploaded, user error to blame. Removing it. --- src/commands/text.js | 258 ------------------------------------------- 1 file changed, 258 deletions(-) delete mode 100644 src/commands/text.js diff --git a/src/commands/text.js b/src/commands/text.js deleted file mode 100644 index 5c18975..0000000 --- a/src/commands/text.js +++ /dev/null @@ -1,258 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.textCommands = void 0; - -const vscode = require("vscode"); -const pl = require("../pylex"); - -exports.textCommands = [ - { - name: 'mind-reader.getLineNumber', - callback: getLineNumber, - }, - { - name: 'mind-reader.getIndent', - callback: getIndent, - }, - { - name: 'mind-reader.getLeadingSpaces', - callback: getLeadingSpaces, - }, - { - name: 'mind-reader.runLineContext', - callback: runLineContext, - }, - { - name: 'mind-reader.runCursorContext', - callback: runCursorContext - } -]; - -/* Helper Function - * This function returns the line number of the active text editor window - */ -function fetchLineNumber(editor) { - return editor.selection.active.line + 1; -} - -/* Helper Function - * This function returns the text from the current line of the active text editor window - */ -function fetchTextLine(editor) { - return editor.document.lineAt(fetchLineNumber(editor) - 1); -} - -// Function that outputs the current line number the cursor is on -function getLineNumber() { - let editor = vscode.window.activeTextEditor; - - if (editor) { - let lineNum = fetchLineNumber(editor); - vscode.window.showInformationMessage(`Line ${lineNum.toString()}`); - } else { - vscode.window.showErrorMessage('No document currently active'); - } -} - -function getIndent() { - let editor = vscode.window.activeTextEditor; - - if (editor) { - let lineNum = fetchLineNumber(editor); - let textLine = fetchTextLine(editor); - - if (textLine.isEmptyOrWhitespace) { - vscode.window.showInformationMessage(`Line ${lineNum.toString()} is Empty`); - } else { - // Grab tab format from open document - let tabFmt = { - size: editor.options.tabSize, - hard: !editor.options.insertSpaces - }; - let i = pl.Lexer.getIndent(textLine.text, tabFmt); - - /* Ternary operator to change the tense of 'indent' to 'indents' for the output if i is 0 or greater than 1 */ - (i !== 1) ? - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`): - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); - } - } else { - vscode.window.showErrorMessage('No document currently active'); - } -} - -/* Function -> Returns the number of leading spaces on the line the cursor is on - * There are two methods that can be used to find the leading spaces: - * method 1: - * calculates the number of leading spaces by finding the length of the current line - * then subtracting from that the length of the text after trimming the whitespace at the start - * which will equal the number of whitespace characters - * - * TO-USE: set calculateLeadingSpaces to true - * - * method 2 (default): - * finds the index position of the first non-whitespace character in a 0-index - * this number will equal the number of spaces preceding the non-whitespace character - * due to the nature of 0-indexes. - * - * TO-USE: set calculateLeadingSpaces to false - */ -function getLeadingSpaces() { - let editor = vscode.window.activeTextEditor; - - if (editor) { - const lineNum = fetchLineNumber(editor); - const textLine = fetchTextLine(editor); - - if (textLine.isEmptyOrWhitespace) { - vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); - } else { - /* - * set true to use method 1: find the number of leading spaces through arithmetic - * set false to use method 2: find the index position of the first non-whitespace character in a 0-index - * - * default: false - */ - const calculateLeadingSpaces = false; // change boolean value to change method - const numSpaces = (calculateLeadingSpaces === true) ? - pl.Lexer.getLeadingSpacesByArithmetic(textLine) : - pl.Lexer.getLeadingSpacesByIndex(textLine); - - /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is 0 or greater than 1 */ - (numSpaces !== 1) ? - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`): - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); - } - } else { - vscode.window.showErrorMessage('No document currently active'); - } -} - -function runLineContext() { - let editor = vscode.window.activeTextEditor; - - if (editor) { - // current text and line number - let editorText = editor.document.getText(); - let line = editor.selection.active.line; - // get tab info settings - let size = parseInt(editor.options.tabSize); - let hard = !editor.options.insertSpaces; - // initialize parser - let parser = new pl.Parser(editorText, { - size, - hard - }); - parser.parse(); - let context = parser.context(line); - // build text - let contentString = createContextString(context, line); - - vscode.window.showInformationMessage(contentString); - } else { - vscode.window.showErrorMessage('No document currently active'); - } -} - -function createContextString(context, line) { - if (context.length < 1) { - throw new Error('Cannot create context string for empty context'); - } - - let contextString = 'Line ' + (line + 1); // 1 based - - if (context[0].token && context[0].token.attr) { - contextString += ': ' + context[0].token.type.toString() + ' ' + context[0].token.attr.toString(); - } - - for (let i = 1; i < context.length; i++) { - let node = context[i]; - - if (node.label === 'root') { - // root - contextString += ' in the Document Root'; - continue; - } - - if (node.token.type !== pl.PylexSymbol.EMPTY && - node.token.type !== pl.PylexSymbol.INDENT) { - contextString += ' inside ' + node.token.type.toString(); - if (node.token.attr) { - contextString += ' ' + node.token.attr.toString(); - } - } - } - return contextString; -} - -// find up to `n` words around the cursor, where `n` is -// the value of `#mindReader.reader.contextWindow` -function runCursorContext() { - let editor = vscode.window.activeTextEditor; - - if (!editor) { - vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); - return; - } - - const cursorPos = editor.selection.active; - const text = editor.document.lineAt(cursorPos).text; - const windowSize = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); - let trimmedText = text.trimStart(); // trim leading whitespace - let leadingWS = text.length - trimmedText.length; // # of characters of leading whitespace - trimmedText = trimmedText.trimEnd(); // trim trailing whitespace - let pos = leadingWS; - let maxPos = text.length; - // clamp cursor start/end to new range - let col = cursorPos.character; // effective column of the cursor position - - if (col < leadingWS) { - // move effective start to first non-whitespace character in the line - col = leadingWS; - } else if (col > leadingWS + trimmedText.length - 1) { - // move effective end to last non-whitespace character in the line - col = leadingWS + trimmedText.length - 1; - } - - // generate list of space separate words with range data (start, end) - // TODO: can find user position to be done in one pass - let spaceWords = []; - - while (pos < maxPos && trimmedText.length > 0) { - let word = trimmedText.replace(/ .*/, ''); - - spaceWords.push({ - word, - start: pos, - end: pos + word.length - }); - // remove processed word from trimmed text - const oldText = trimmedText; - trimmedText = trimmedText.replace(/[^ ]+/, '').trimStart(); - // update pos to start of next word - pos += oldText.length - trimmedText.length; - } - // find word the user is in - let contextStart = -1, - contextEnd = -1; - - for (let i = 0; i < spaceWords.length; i++) { - if (col >= spaceWords[i].start && col <= spaceWords[i].end) { - // found the word - contextStart = Math.max(0, i - windowSize); // clamp start index - contextEnd = Math.min(spaceWords.length, i + windowSize + 1); // clamp end index - // construct cursor context string - let contextString = ''; - - for (let i = contextStart; i < contextEnd; i++) { - contextString += spaceWords[i].word + ' '; - } - // output cursor context string - vscode.window.showInformationMessage(contextString); - return; - } - } -} -//# sourceMappingURL=text.js.map \ No newline at end of file From 829a3f0b9d204b6992fe88f25cdf2e5f86d0f81c Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 09:12:09 -0500 Subject: [PATCH 13/78] .js -> .ts migrating changes made in .js file to .ts, .js file was unintended to be uploaded. User error to blame, fixing it. --- src/pylex/lexer.ts | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/pylex/lexer.ts b/src/pylex/lexer.ts index aa1235c..5fc4824 100644 --- a/src/pylex/lexer.ts +++ b/src/pylex/lexer.ts @@ -1,5 +1,7 @@ "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", { + value: true +}); const _1 = require("."); const token_1 = require("./token"); /** @@ -67,7 +69,10 @@ class Lexer { this.pos = 0; this._currToken = token_1.EOFTOKEN; // default is 4 wide expanded tabs - this.tabFmt = Object.assign({ size: 4, hard: false }, tabFmt); + this.tabFmt = Object.assign({ + size: 4, + hard: false + }, tabFmt); if (text) { // normalize linefeeds text = text.replace('\r\n', '\n'); @@ -89,8 +94,7 @@ class Lexer { if (tabFmt.hard) { // used tabs indent = leadingSpace; - } - else { + } else { // use spaces indent = Math.ceil(leadingSpace / tabFmt.size); } @@ -138,7 +142,9 @@ class Lexer { /** * @return the current {@link LineToken}. */ - currToken() { return this._currToken; } + currToken() { + return this._currToken; + } /** * Advance the position in the token stream. * @@ -160,8 +166,7 @@ class Lexer { // Yes... if (match.groups) { token = new _1.LineToken(r.type, this.pos, indent, match.groups["attr"]); - } - else { + } else { token = new _1.LineToken(r.type, this.pos, indent); } this._currToken = token; @@ -174,8 +179,7 @@ class Lexer { if (/^\s*(#.*)?$/.test(line)) { // "empty" line token = new _1.LineToken(token_1.Symbol.EMPTY, this.pos, 999999); - } - else { + } else { // This is an INDENT token token = new _1.LineToken(token_1.Symbol.INDENT, this.pos, indent); } From 641997b62000b338070dfd83ed136f92e3d40162 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 09:12:55 -0500 Subject: [PATCH 14/78] delete lexer.js .js file unintentionally uploaded, fixing that user error. --- src/pylex/lexer.js | 227 --------------------------------------------- 1 file changed, 227 deletions(-) delete mode 100644 src/pylex/lexer.js diff --git a/src/pylex/lexer.js b/src/pylex/lexer.js deleted file mode 100644 index 8ea195b..0000000 --- a/src/pylex/lexer.js +++ /dev/null @@ -1,227 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -const _1 = require("."); -const token_1 = require("./token"); -/** - * List of recognition patterns, in order of priority - * The first item is a recognition pattern, used to recognize the token - * the second item is the token type - */ -const rules = [ - { - pattern: /^\s*def\s+(?[a-zA-Z_][a-zA-Z0-9_]*)\(/, - type: token_1.Symbol.FUNCTION - }, - { - pattern: /^\s*class\s+(?[a-zA-Z_][a-zA-Z0-9_]*)/, - type: token_1.Symbol.CLASS - }, - { - pattern: /^\s*if\s+(?[^:]+):\s*/, - type: token_1.Symbol.IF - }, - { - pattern: /^\s*elif\s+(?[^:]+):\s*$/, - type: token_1.Symbol.ELIF - }, - { - pattern: /^\s*else\s*:/, - type: token_1.Symbol.ELSE - }, - { - pattern: /^\s*for\s+(?[^:]+):\s*$/, - type: token_1.Symbol.FOR - }, - { - pattern: /^\s*while\s+(?[^:]+):\s*$/, - type: token_1.Symbol.WHILE - }, - { - pattern: /^\s*try\s*:/, - type: token_1.Symbol.TRY - }, - { - pattern: /^\s*except(\s*(?[^:]+))?:\s*$/, - type: token_1.Symbol.EXCEPT - }, - { - pattern: /^\s*finally\s*:\s*$/, - type: token_1.Symbol.FINALLY - }, - { - pattern: /^\s*with\s+(?[^:]+):\s*$/, - type: token_1.Symbol.WITH - }, -]; -/** - * Line-By-Line Lexer - */ -class Lexer { - /** - * @param `text` The text to lex. - * @param `tabFmt` A tab information descriptor - */ - constructor(text, tabFmt) { - this.tabFmt = tabFmt; - this.textLines = []; // array of text lines - this.pos = 0; - this._currToken = token_1.EOFTOKEN; - // default is 4 wide expanded tabs - this.tabFmt = Object.assign({ - size: 4, - hard: false - }, tabFmt); - if (text) { - // normalize linefeeds - text = text.replace('\r\n', '\n'); - } - this.restart(text); - } - /** - * Calculates indentation level for a line. If using soft tabs, - * indent level rounds up (so, tabSize+1 spaces is 2 levels, - * 2*tabSize+1 is 3, etc.) - * - * @param `text` The line of text. - * @param `tabFmt` A tab information descriptor. - * @return The indent of `text` with consideration for `tabFmt`. - */ - static getIndent(text, tabFmt) { - let leadingSpace = text.length - text.trimLeft().length; - let indent; - if (tabFmt.hard) { - // used tabs - indent = leadingSpace; - } else { - // use spaces - indent = Math.ceil(leadingSpace / tabFmt.size); - } - return indent; - } - /** - * Calculates leading spaces for a line. - * This method uses arithmetic to calculate the number of leading spaces - * - * @param `text` The line of text. - * @return The number of leading spaces of `text`. - */ - static getLeadingSpacesByArithmetic(textLine) { - const leadingSpaces = textLine.text.length - textLine.text.trimStart().length; - - return leadingSpaces; - } - /** - * Calculates leading spaces for a line. - * This method finds the index position of the first non-whitespace character - * Since the index is built using a 0-index, the position of this character - * will equal the number of spaces preceding the character. - * - * @param `text` The line of text. - * @return The number of leading spaces of `text` with respect to the index position of the first non-whitespace character. - */ - static getLeadingSpacesByIndex(textLine) { - const indexNum = textLine.firstNonWhitespaceCharacterIndex; - - return indexNum; - } - /** - * Restart lexer with new text. - * - * @param `text` The new text to lex. - */ - restart(text) { - this.pos = 0; - this._currToken = token_1.EOFTOKEN; // if no input, already on EOFTOKEN - if (text) { - this.textLines = text.split('\n'); - this.next(); // advance to the first token - } - } - /** - * @return the current {@link LineToken}. - */ - currToken() { - return this._currToken; - } - /** - * Advance the position in the token stream. - * - * @return The new current token, after advancing - */ - next() { - if (this._currToken === token_1.EOFTOKEN && this.pos > this.textLines.length) { - throw new Error('Cannot advance past end'); - } - // Until a LineToken is found, or EOF - while (this.pos < this.textLines.length) { - let line = this.textLines[this.pos]; - let indent = Lexer.getIndent(line, this.tabFmt); - let token; - for (var r of rules) { - // Does line match pattern? - let match = line.match(r.pattern); - if (match) { - // Yes... - if (match.groups) { - token = new _1.LineToken(r.type, this.pos, indent, match.groups["attr"]); - } else { - token = new _1.LineToken(r.type, this.pos, indent); - } - this._currToken = token; - this.pos++; - return this.currToken(); - } - } - // No rules matched - // TODO: move to rules - if (/^\s*(#.*)?$/.test(line)) { - // "empty" line - token = new _1.LineToken(token_1.Symbol.EMPTY, this.pos, 999999); - } else { - // This is an INDENT token - token = new _1.LineToken(token_1.Symbol.INDENT, this.pos, indent); - } - this._currToken = token; - this.pos++; - return this.currToken(); - } - // Didn't return, must be EOF - this._currToken = token_1.EOFTOKEN; - this.pos++; - return this.currToken(); - } - /** - * Move backwards in the token stream - * - * @param `n` The number of positions to retract. - * @return The new current token after retracting. - */ - retract(n = 1) { - if (this.pos - 1 - n < 0) { - // -1 because this.pos is currently on the next token - throw new RangeError('Cannot retract past start'); - } - if (n <= 0) { - throw new RangeError('Retract distance must be positive'); - } - if (this.pos - n === 0) { - // just restart - this.pos = 0; - return this.next(); - } - let c = n + 1; - while (c > 0) { - this.pos--; - while (/^\s*(#.*)?$/.test(this.textLines[this.pos])) { - // Skip empty lines - this.pos--; - } - c--; - } - return this.next(); - } -} -exports.default = Lexer; -//# sourceMappingURL=lexer.js.map \ No newline at end of file From c087f1666ad0cccc394a1893d1e1f22dddd25a56 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 10:39:38 -0500 Subject: [PATCH 15/78] text.ts - added types --- src/commands/text.ts | 131 +++++++++++++++++++++++-------------------- 1 file changed, 69 insertions(+), 62 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 6bad4d8..a4505b4 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -1,13 +1,10 @@ "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.textCommands = void 0; +import { CommandEntry } from './commandEntry'; const vscode = require("vscode"); const pl = require("../pylex"); -exports.textCommands = [ +export const textCommands: CommandEntry[] = [ { name: 'mind-reader.getLineNumber', callback: getLineNumber, @@ -33,52 +30,53 @@ exports.textCommands = [ /* Helper Function * This function returns the line number of the active text editor window */ -function fetchLineNumber(editor) { +function fetchLineNumber(editor: any): number { return editor.selection.active.line + 1; } /* Helper Function * This function returns the text from the current line of the active text editor window */ -function fetchTextLine(editor) { +function fetchTextLine(editor: any): string { return editor.document.lineAt(fetchLineNumber(editor) - 1); } // Function that outputs the current line number the cursor is on -function getLineNumber() { - let editor = vscode.window.activeTextEditor; +function getLineNumber(): void { + let editor: any = vscode.window.activeTextEditor; if (editor) { - let lineNum = fetchLineNumber(editor); + let lineNum: number = fetchLineNumber(editor); + vscode.window.showInformationMessage(`Line ${lineNum.toString()}`); - } else { + } + else { vscode.window.showErrorMessage('No document currently active'); } } -function getIndent() { - let editor = vscode.window.activeTextEditor; +function getIndent(): void { + let editor: any = vscode.window.activeTextEditor; if (editor) { - let lineNum = fetchLineNumber(editor); - let textLine = fetchTextLine(editor); + const lineNum: number = fetchLineNumber(editor); + const textLine: any = editor.document.lineAt(lineNum - 1); if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`Line ${lineNum.toString()} is Empty`); - } else { + } + else { // Grab tab format from open document - let tabFmt = { + let tabFmt: any = { size: editor.options.tabSize, hard: !editor.options.insertSpaces }; - let i = pl.Lexer.getIndent(textLine.text, tabFmt); + let i: number = pl.Lexer.getIndent(textLine.text, tabFmt); - /* Ternary operator to change the tense of 'indent' to 'indents' for the output if i is 0 or greater than 1 */ - (i !== 1) ? - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`): - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); + vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`); } - } else { + } + else { vscode.window.showErrorMessage('No document currently active'); } } @@ -99,24 +97,25 @@ function getIndent() { * * TO-USE: set calculateLeadingSpaces to false */ -function getLeadingSpaces() { - let editor = vscode.window.activeTextEditor; +function getLeadingSpaces(): void { + let editor: any = vscode.window.activeTextEditor; if (editor) { - const lineNum = fetchLineNumber(editor); - const textLine = fetchTextLine(editor); + const lineNum: number = fetchLineNumber(editor); + const textLine: any = fetchTextLine(editor); if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); - } else { + } + else { /* * set true to use method 1: find the number of leading spaces through arithmetic * set false to use method 2: find the index position of the first non-whitespace character in a 0-index * * default: false */ - const calculateLeadingSpaces = false; // change boolean value to change method - const numSpaces = (calculateLeadingSpaces === true) ? + const calculateLeadingSpaces: boolean = false; // change boolean value to change method + const numSpaces: number = (calculateLeadingSpaces) ? pl.Lexer.getLeadingSpacesByArithmetic(textLine) : pl.Lexer.getLeadingSpacesByIndex(textLine); @@ -125,50 +124,53 @@ function getLeadingSpaces() { vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`): vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); } - } else { + } + else { vscode.window.showErrorMessage('No document currently active'); } } -function runLineContext() { - let editor = vscode.window.activeTextEditor; +function runLineContext(): void { + let editor: any = vscode.window.activeTextEditor; if (editor) { // current text and line number - let editorText = editor.document.getText(); - let line = editor.selection.active.line; + let editorText: string = editor.document.getText(); + let line: number = editor.selection.active.line; // get tab info settings - let size = parseInt(editor.options.tabSize); - let hard = !editor.options.insertSpaces; + let size: number = parseInt(editor.options.tabSize); + let hard: boolean = !editor.options.insertSpaces; // initialize parser - let parser = new pl.Parser(editorText, { + let parser: any = new pl.Parser(editorText, { size, hard }); + parser.parse(); - let context = parser.context(line); + let context: any = parser.context(line); // build text - let contentString = createContextString(context, line); + let contentString: string = createContextString(context, line); vscode.window.showInformationMessage(contentString); - } else { + } + else { vscode.window.showErrorMessage('No document currently active'); } } -function createContextString(context, line) { +function createContextString(context: any, line: number): string { if (context.length < 1) { throw new Error('Cannot create context string for empty context'); } - let contextString = 'Line ' + (line + 1); // 1 based + let contextString: string = `Line ${line + 1}`; // 1 based if (context[0].token && context[0].token.attr) { contextString += ': ' + context[0].token.type.toString() + ' ' + context[0].token.attr.toString(); } for (let i = 1; i < context.length; i++) { - let node = context[i]; + let node: any = context[i]; if (node.label === 'root') { // root @@ -184,59 +186,64 @@ function createContextString(context, line) { } } } + return contextString; } // find up to `n` words around the cursor, where `n` is // the value of `#mindReader.reader.contextWindow` -function runCursorContext() { - let editor = vscode.window.activeTextEditor; +function runCursorContext(): void { + let editor: any = vscode.window.activeTextEditor; if (!editor) { vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); return; } - const cursorPos = editor.selection.active; - const text = editor.document.lineAt(cursorPos).text; - const windowSize = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); - let trimmedText = text.trimStart(); // trim leading whitespace - let leadingWS = text.length - trimmedText.length; // # of characters of leading whitespace - trimmedText = trimmedText.trimEnd(); // trim trailing whitespace - let pos = leadingWS; - let maxPos = text.length; + const cursorPos: any = editor.selection.active; + const text: string = editor.document.lineAt(cursorPos).text; + const windowSize: number = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); + let trimmedText: string = text.trimStart(); // trim leading whitespace + let leadingWS: number = text.length - trimmedText.length; // # of characters of leading whitespace + let pos: number = leadingWS; + let maxPos: number = text.length; // clamp cursor start/end to new range - let col = cursorPos.character; // effective column of the cursor position + let col: number = cursorPos.character; // effective column of the cursor position + + trimmedText = trimmedText.trimEnd(); // trim trailing whitespace if (col < leadingWS) { // move effective start to first non-whitespace character in the line col = leadingWS; - } else if (col > leadingWS + trimmedText.length - 1) { + } + else if (col > leadingWS + trimmedText.length - 1) { // move effective end to last non-whitespace character in the line col = leadingWS + trimmedText.length - 1; } // generate list of space separate words with range data (start, end) // TODO: can find user position to be done in one pass - let spaceWords = []; + let spaceWords: any[] = []; while (pos < maxPos && trimmedText.length > 0) { - let word = trimmedText.replace(/ .*/, ''); + let word: string = trimmedText.replace(/ .*/, ''); spaceWords.push({ word, start: pos, end: pos + word.length }); + // remove processed word from trimmed text - const oldText = trimmedText; + const oldText: string = trimmedText; trimmedText = trimmedText.replace(/[^ ]+/, '').trimStart(); // update pos to start of next word pos += oldText.length - trimmedText.length; } + // find word the user is in - let contextStart = -1, - contextEnd = -1; + let contextStart: number = -1; + let contextEnd: number = -1; for (let i = 0; i < spaceWords.length; i++) { if (col >= spaceWords[i].start && col <= spaceWords[i].end) { @@ -244,7 +251,7 @@ function runCursorContext() { contextStart = Math.max(0, i - windowSize); // clamp start index contextEnd = Math.min(spaceWords.length, i + windowSize + 1); // clamp end index // construct cursor context string - let contextString = ''; + let contextString: string = ''; for (let i = contextStart; i < contextEnd; i++) { contextString += spaceWords[i].word + ' '; From a619146afc9b0fd80e7a5587e1dcb5e36662be68 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 10:44:37 -0500 Subject: [PATCH 16/78] lexter.ts - added types --- src/pylex/lexer.ts | 217 ++++++++++++++++++++++++++------------------- 1 file changed, 124 insertions(+), 93 deletions(-) diff --git a/src/pylex/lexer.ts b/src/pylex/lexer.ts index 5fc4824..9b8e8cd 100644 --- a/src/pylex/lexer.ts +++ b/src/pylex/lexer.ts @@ -1,216 +1,195 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -const _1 = require("."); -const token_1 = require("./token"); +import { LineToken } from '.'; +import { Symbol, EOFTOKEN, TabInfo } from './token'; + +type Rule = { + pattern: RegExp, + type: Symbol, +}; + /** * List of recognition patterns, in order of priority * The first item is a recognition pattern, used to recognize the token * the second item is the token type */ -const rules = [ +const rules: Rule[] = [ { pattern: /^\s*def\s+(?[a-zA-Z_][a-zA-Z0-9_]*)\(/, - type: token_1.Symbol.FUNCTION + type: Symbol.FUNCTION }, { pattern: /^\s*class\s+(?[a-zA-Z_][a-zA-Z0-9_]*)/, - type: token_1.Symbol.CLASS + type: Symbol.CLASS }, { pattern: /^\s*if\s+(?[^:]+):\s*/, - type: token_1.Symbol.IF + type: Symbol.IF }, { pattern: /^\s*elif\s+(?[^:]+):\s*$/, - type: token_1.Symbol.ELIF + type: Symbol.ELIF }, { pattern: /^\s*else\s*:/, - type: token_1.Symbol.ELSE + type: Symbol.ELSE }, { pattern: /^\s*for\s+(?[^:]+):\s*$/, - type: token_1.Symbol.FOR + type: Symbol.FOR }, { pattern: /^\s*while\s+(?[^:]+):\s*$/, - type: token_1.Symbol.WHILE + type: Symbol.WHILE }, { pattern: /^\s*try\s*:/, - type: token_1.Symbol.TRY + type: Symbol.TRY }, { pattern: /^\s*except(\s*(?[^:]+))?:\s*$/, - type: token_1.Symbol.EXCEPT + type: Symbol.EXCEPT }, { pattern: /^\s*finally\s*:\s*$/, - type: token_1.Symbol.FINALLY + type: Symbol.FINALLY }, { pattern: /^\s*with\s+(?[^:]+):\s*$/, - type: token_1.Symbol.WITH + type: Symbol.WITH }, ]; + /** * Line-By-Line Lexer */ -class Lexer { +export default class Lexer { + private textLines: string[] = []; // array of text lines + private pos: number = 0; + private _currToken: LineToken = EOFTOKEN; + /** * @param `text` The text to lex. * @param `tabFmt` A tab information descriptor */ - constructor(text, tabFmt) { - this.tabFmt = tabFmt; - this.textLines = []; // array of text lines - this.pos = 0; - this._currToken = token_1.EOFTOKEN; + constructor(text ? : string, private tabFmt ? : TabInfo) { // default is 4 wide expanded tabs - this.tabFmt = Object.assign({ - size: 4, - hard: false - }, tabFmt); + this.tabFmt = { + ...{ + size: 4, + hard: false + }, + ...tabFmt + }; + if (text) { // normalize linefeeds text = text.replace('\r\n', '\n'); } this.restart(text); } - /** - * Calculates indentation level for a line. If using soft tabs, - * indent level rounds up (so, tabSize+1 spaces is 2 levels, - * 2*tabSize+1 is 3, etc.) - * - * @param `text` The line of text. - * @param `tabFmt` A tab information descriptor. - * @return The indent of `text` with consideration for `tabFmt`. - */ - static getIndent(text, tabFmt) { - let leadingSpace = text.length - text.trimLeft().length; - let indent; - if (tabFmt.hard) { - // used tabs - indent = leadingSpace; - } else { - // use spaces - indent = Math.ceil(leadingSpace / tabFmt.size); - } - return indent; - } - /** - * Calculates leading spaces for a line. - * This method uses arithmetic to calculate the number of leading spaces - * - * @param `text` The line of text. - * @return The number of leading spaces of `text`. - */ - static getLeadingSpacesByArithmetic(textLine) { - const leadingSpaces = textLine.text.length - textLine.text.trimStart().length; - return leadingSpaces; - } - /** - * Calculates leading spaces for a line. - * This method finds the index position of the first non-whitespace character - * Since the index is built using a 0-index, the position of this character - * will equal the number of spaces preceding the character. - * - * @param `text` The line of text. - * @return The number of leading spaces of `text` with respect to the index position of the first non-whitespace character. - */ - static getLeadingSpacesByIndex(textLine) { - const indexNum = textLine.firstNonWhitespaceCharacterIndex; - - return indexNum; - } /** * Restart lexer with new text. * * @param `text` The new text to lex. */ - restart(text) { + restart(text ? : string): void { this.pos = 0; - this._currToken = token_1.EOFTOKEN; // if no input, already on EOFTOKEN + this._currToken = EOFTOKEN; // if no input, already on EOFTOKEN + if (text) { this.textLines = text.split('\n'); this.next(); // advance to the first token } } + /** * @return the current {@link LineToken}. */ - currToken() { + currToken(): LineToken { return this._currToken; } + /** * Advance the position in the token stream. * * @return The new current token, after advancing */ - next() { - if (this._currToken === token_1.EOFTOKEN && this.pos > this.textLines.length) { + next(): LineToken { + if (this._currToken === EOFTOKEN && this.pos > this.textLines.length) { throw new Error('Cannot advance past end'); } + // Until a LineToken is found, or EOF while (this.pos < this.textLines.length) { - let line = this.textLines[this.pos]; - let indent = Lexer.getIndent(line, this.tabFmt); - let token; + let line: string = this.textLines[this.pos]; + let indent: number = Lexer.getIndent(line, this.tabFmt!); + let token: LineToken; + for (var r of rules) { // Does line match pattern? - let match = line.match(r.pattern); + let match: RegExpMatchArray | null = line.match(r.pattern); if (match) { // Yes... if (match.groups) { - token = new _1.LineToken(r.type, this.pos, indent, match.groups["attr"]); - } else { - token = new _1.LineToken(r.type, this.pos, indent); + token = new LineToken(r.type, this.pos, indent, match.groups["attr"]); + } + else { + token = new LineToken(r.type, this.pos, indent); } + this._currToken = token; this.pos++; + return this.currToken(); } } // No rules matched + // TODO: move to rules if (/^\s*(#.*)?$/.test(line)) { // "empty" line - token = new _1.LineToken(token_1.Symbol.EMPTY, this.pos, 999999); - } else { + token = new LineToken(Symbol.EMPTY, this.pos, 999999); + } + else { // This is an INDENT token - token = new _1.LineToken(token_1.Symbol.INDENT, this.pos, indent); + token = new LineToken(Symbol.INDENT, this.pos, indent); } + this._currToken = token; this.pos++; + return this.currToken(); } + // Didn't return, must be EOF - this._currToken = token_1.EOFTOKEN; + this._currToken = EOFTOKEN; this.pos++; + return this.currToken(); } + /** * Move backwards in the token stream * * @param `n` The number of positions to retract. * @return The new current token after retracting. */ - retract(n = 1) { + retract(n: number = 1): LineToken { if (this.pos - 1 - n < 0) { // -1 because this.pos is currently on the next token throw new RangeError('Cannot retract past start'); } + if (n <= 0) { throw new RangeError('Retract distance must be positive'); } + if (this.pos - n === 0) { // just restart this.pos = 0; return this.next(); } + let c = n + 1; while (c > 0) { this.pos--; @@ -220,8 +199,60 @@ class Lexer { } c--; } + return this.next(); } + + /** + * Calculates indentation level for a line. If using soft tabs, + * indent level rounds up (so, tabSize+1 spaces is 2 levels, + * 2*tabSize+1 is 3, etc.) + * + * @param `text` The line of text. + * @param `tabFmt` A tab information descriptor. + * @return The indent of `text` with consideration for `tabFmt`. + */ + static getIndent(text: string, tabFmt: TabInfo): number { + let leadingSpace: number = text.length - text.trimStart().length; + let indent: number; + + if (tabFmt.hard) { + // used tabs + indent = leadingSpace; + } + else { + // use spaces + indent = Math.ceil(leadingSpace / tabFmt.size!); + } + + return indent; + } + + /** + * Calculates leading spaces for a line. + * This method uses arithmetic to calculate the number of leading spaces + * + * @param `line` The line of text. + * @return The number of leading spaces of `text`. + */ + static getLeadingSpacesByArithmetic(line: any) { + const leadingSpaces: number = line.text.length - line.text.trimStart().length; + + return leadingSpaces; + } + + /** + * Calculates leading spaces for a line. + * This method finds the index position of the first non-whitespace character + * Since the index is built using a 0-index, the position of this character + * will equal the number of spaces preceding the character. + * + * @param `text` The line of text. + * @return The number of leading spaces of `text` with respect to the index position of the first non-whitespace character. + */ + static getLeadingSpacesByIndex(text: any) { + const indexNum: number = text.firstNonWhitespaceCharacterIndex; + + return indexNum; + } } -exports.default = Lexer; -//# sourceMappingURL=lexer.js.map From 2f4800448baa957bf61ef432c6c5c1d042ed58a7 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 11:03:06 -0500 Subject: [PATCH 17/78] text.ts -> fixed type errors --- src/commands/text.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index a4505b4..d1bc2c6 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -201,9 +201,9 @@ function runCursorContext(): void { } const cursorPos: any = editor.selection.active; - const text: string = editor.document.lineAt(cursorPos).text; + const text: any = editor.document.lineAt(cursorPos).text; const windowSize: number = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); - let trimmedText: string = text.trimStart(); // trim leading whitespace + let trimmedText: any = text.trimStart(); // trim leading whitespace let leadingWS: number = text.length - trimmedText.length; // # of characters of leading whitespace let pos: number = leadingWS; let maxPos: number = text.length; @@ -262,4 +262,3 @@ function runCursorContext(): void { } } } -//# sourceMappingURL=text.js.map From ca3a5163fedfeee6c09a32af38290de52292afb6 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 11:05:38 -0500 Subject: [PATCH 18/78] lexer.ts -> fixed type errors --- src/pylex/lexer.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/pylex/lexer.ts b/src/pylex/lexer.ts index 9b8e8cd..343742b 100644 --- a/src/pylex/lexer.ts +++ b/src/pylex/lexer.ts @@ -95,7 +95,6 @@ export default class Lexer { restart(text ? : string): void { this.pos = 0; this._currToken = EOFTOKEN; // if no input, already on EOFTOKEN - if (text) { this.textLines = text.split('\n'); this.next(); // advance to the first token @@ -132,7 +131,7 @@ export default class Lexer { // Yes... if (match.groups) { token = new LineToken(r.type, this.pos, indent, match.groups["attr"]); - } + } else { token = new LineToken(r.type, this.pos, indent); } @@ -149,7 +148,7 @@ export default class Lexer { if (/^\s*(#.*)?$/.test(line)) { // "empty" line token = new LineToken(Symbol.EMPTY, this.pos, 999999); - } + } else { // This is an INDENT token token = new LineToken(Symbol.INDENT, this.pos, indent); @@ -219,7 +218,7 @@ export default class Lexer { if (tabFmt.hard) { // used tabs indent = leadingSpace; - } + } else { // use spaces indent = Math.ceil(leadingSpace / tabFmt.size!); @@ -229,9 +228,9 @@ export default class Lexer { } /** - * Calculates leading spaces for a line. + * Calculates leading spaces for a line. * This method uses arithmetic to calculate the number of leading spaces - * + * * @param `line` The line of text. * @return The number of leading spaces of `text`. */ @@ -242,11 +241,11 @@ export default class Lexer { } /** - * Calculates leading spaces for a line. + * Calculates leading spaces for a line. * This method finds the index position of the first non-whitespace character * Since the index is built using a 0-index, the position of this character * will equal the number of spaces preceding the character. - * + * * @param `text` The line of text. * @return The number of leading spaces of `text` with respect to the index position of the first non-whitespace character. */ From 3fed2aa4ad4fd7685f7f6f8f494a1b80d36800e8 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 11:13:08 -0500 Subject: [PATCH 19/78] text.ts -> removed random trailing spaces Linter was complaining about trailing spaces in random places, removed them to get rid of the errors. --- src/commands/text.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index d1bc2c6..b498178 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -49,7 +49,7 @@ function getLineNumber(): void { let lineNum: number = fetchLineNumber(editor); vscode.window.showInformationMessage(`Line ${lineNum.toString()}`); - } + } else { vscode.window.showErrorMessage('No document currently active'); } @@ -64,7 +64,7 @@ function getIndent(): void { if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`Line ${lineNum.toString()} is Empty`); - } + } else { // Grab tab format from open document let tabFmt: any = { @@ -75,7 +75,7 @@ function getIndent(): void { vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`); } - } + } else { vscode.window.showErrorMessage('No document currently active'); } @@ -87,14 +87,14 @@ function getIndent(): void { * calculates the number of leading spaces by finding the length of the current line * then subtracting from that the length of the text after trimming the whitespace at the start * which will equal the number of whitespace characters - * + * * TO-USE: set calculateLeadingSpaces to true - * + * * method 2 (default): * finds the index position of the first non-whitespace character in a 0-index * this number will equal the number of spaces preceding the non-whitespace character * due to the nature of 0-indexes. - * + * * TO-USE: set calculateLeadingSpaces to false */ function getLeadingSpaces(): void { @@ -106,12 +106,12 @@ function getLeadingSpaces(): void { if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); - } + } else { /* * set true to use method 1: find the number of leading spaces through arithmetic * set false to use method 2: find the index position of the first non-whitespace character in a 0-index - * + * * default: false */ const calculateLeadingSpaces: boolean = false; // change boolean value to change method @@ -124,7 +124,7 @@ function getLeadingSpaces(): void { vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`): vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); } - } + } else { vscode.window.showErrorMessage('No document currently active'); } @@ -152,7 +152,7 @@ function runLineContext(): void { let contentString: string = createContextString(context, line); vscode.window.showInformationMessage(contentString); - } + } else { vscode.window.showErrorMessage('No document currently active'); } @@ -215,7 +215,7 @@ function runCursorContext(): void { if (col < leadingWS) { // move effective start to first non-whitespace character in the line col = leadingWS; - } + } else if (col > leadingWS + trimmedText.length - 1) { // move effective end to last non-whitespace character in the line col = leadingWS + trimmedText.length - 1; From 50ff693d163489ef9b9b96c15fc06ea9a2dbfd28 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 13:09:16 -0500 Subject: [PATCH 20/78] text.ts -> type error fixes, lets -> const, import fixed type errors, changed most let variables to const, changed const require to imports --- src/commands/text.ts | 59 ++++++++++++++++++++++---------------------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index b498178..8621a2a 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -1,8 +1,7 @@ "use strict"; import { CommandEntry } from './commandEntry'; - -const vscode = require("vscode"); -const pl = require("../pylex"); +import vscode = require("vscode"); +import pl = require("../pylex"); export const textCommands: CommandEntry[] = [ { @@ -43,10 +42,10 @@ function fetchTextLine(editor: any): string { // Function that outputs the current line number the cursor is on function getLineNumber(): void { - let editor: any = vscode.window.activeTextEditor; + const editor: any = vscode.window.activeTextEditor; if (editor) { - let lineNum: number = fetchLineNumber(editor); + const lineNum: number = fetchLineNumber(editor); vscode.window.showInformationMessage(`Line ${lineNum.toString()}`); } @@ -56,7 +55,7 @@ function getLineNumber(): void { } function getIndent(): void { - let editor: any = vscode.window.activeTextEditor; + const editor: any = vscode.window.activeTextEditor; if (editor) { const lineNum: number = fetchLineNumber(editor); @@ -67,11 +66,11 @@ function getIndent(): void { } else { // Grab tab format from open document - let tabFmt: any = { + const tabFmt: any = { size: editor.options.tabSize, hard: !editor.options.insertSpaces }; - let i: number = pl.Lexer.getIndent(textLine.text, tabFmt); + const i: number = pl.Lexer.getIndent(textLine.text, tabFmt); vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`); } @@ -98,7 +97,7 @@ function getIndent(): void { * TO-USE: set calculateLeadingSpaces to false */ function getLeadingSpaces(): void { - let editor: any = vscode.window.activeTextEditor; + const editor: any = vscode.window.activeTextEditor; if (editor) { const lineNum: number = fetchLineNumber(editor); @@ -131,25 +130,25 @@ function getLeadingSpaces(): void { } function runLineContext(): void { - let editor: any = vscode.window.activeTextEditor; + const editor: any = vscode.window.activeTextEditor; if (editor) { // current text and line number - let editorText: string = editor.document.getText(); - let line: number = editor.selection.active.line; + const editorText: string = editor.document.getText(); + const line: string = editor.selection.active.line; // get tab info settings - let size: number = parseInt(editor.options.tabSize); - let hard: boolean = !editor.options.insertSpaces; + const size: number = parseInt(editor.options.tabSize); + const hard: boolean = !editor.options.insertSpaces; // initialize parser - let parser: any = new pl.Parser(editorText, { + const parser: any = new pl.Parser(editorText, { size, hard }); parser.parse(); - let context: any = parser.context(line); + const context: string = parser.context(line); // build text - let contentString: string = createContextString(context, line); + const contentString: string = createContextString(context, line); vscode.window.showInformationMessage(contentString); } @@ -158,7 +157,7 @@ function runLineContext(): void { } } -function createContextString(context: any, line: number): string { +function createContextString(context: any, line: string): string { if (context.length < 1) { throw new Error('Cannot create context string for empty context'); } @@ -169,8 +168,8 @@ function createContextString(context: any, line: number): string { contextString += ': ' + context[0].token.type.toString() + ' ' + context[0].token.attr.toString(); } - for (let i = 1; i < context.length; i++) { - let node: any = context[i]; + for (let i: number = 1; i < context.length; i++) { + const node: any = context[i]; if (node.label === 'root') { // root @@ -193,7 +192,7 @@ function createContextString(context: any, line: number): string { // find up to `n` words around the cursor, where `n` is // the value of `#mindReader.reader.contextWindow` function runCursorContext(): void { - let editor: any = vscode.window.activeTextEditor; + const editor: any = vscode.window.activeTextEditor; if (!editor) { vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); @@ -201,12 +200,12 @@ function runCursorContext(): void { } const cursorPos: any = editor.selection.active; - const text: any = editor.document.lineAt(cursorPos).text; - const windowSize: number = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); - let trimmedText: any = text.trimStart(); // trim leading whitespace - let leadingWS: number = text.length - trimmedText.length; // # of characters of leading whitespace + const text: string = editor.document.lineAt(cursorPos).text; + const windowSize: any = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); + let trimmedText: string = text.trimStart(); // trim leading whitespace + const leadingWS: number = text.length - trimmedText.length; // # of characters of leading whitespace let pos: number = leadingWS; - let maxPos: number = text.length; + const maxPos: number = text.length; // clamp cursor start/end to new range let col: number = cursorPos.character; // effective column of the cursor position @@ -223,10 +222,10 @@ function runCursorContext(): void { // generate list of space separate words with range data (start, end) // TODO: can find user position to be done in one pass - let spaceWords: any[] = []; + const spaceWords: any[] = []; while (pos < maxPos && trimmedText.length > 0) { - let word: string = trimmedText.replace(/ .*/, ''); + const word: string = trimmedText.replace(/ .*/, ''); spaceWords.push({ word, @@ -245,7 +244,7 @@ function runCursorContext(): void { let contextStart: number = -1; let contextEnd: number = -1; - for (let i = 0; i < spaceWords.length; i++) { + for (let i: number = 0; i < spaceWords.length; i++) { if (col >= spaceWords[i].start && col <= spaceWords[i].end) { // found the word contextStart = Math.max(0, i - windowSize); // clamp start index @@ -253,7 +252,7 @@ function runCursorContext(): void { // construct cursor context string let contextString: string = ''; - for (let i = contextStart; i < contextEnd; i++) { + for (let i: any = contextStart; i < contextEnd; i++) { contextString += spaceWords[i].word + ' '; } // output cursor context string From d19ad8f885d27188551890027a318a0153873ef8 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Fri, 25 Mar 2022 13:17:51 -0500 Subject: [PATCH 21/78] lexter.ts - let -> const, fixed type errors changed most let variables to const, fixed more type errors --- src/pylex/lexer.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/pylex/lexer.ts b/src/pylex/lexer.ts index 343742b..9135aeb 100644 --- a/src/pylex/lexer.ts +++ b/src/pylex/lexer.ts @@ -81,7 +81,7 @@ export default class Lexer { }; if (text) { - // normalize linefeeds + // normalize line feeds text = text.replace('\r\n', '\n'); } this.restart(text); @@ -120,13 +120,13 @@ export default class Lexer { // Until a LineToken is found, or EOF while (this.pos < this.textLines.length) { - let line: string = this.textLines[this.pos]; - let indent: number = Lexer.getIndent(line, this.tabFmt!); + const line: string = this.textLines[this.pos]; + const indent: number = Lexer.getIndent(line, this.tabFmt!); let token: LineToken; for (var r of rules) { // Does line match pattern? - let match: RegExpMatchArray | null = line.match(r.pattern); + const match: RegExpMatchArray | null = line.match(r.pattern); if (match) { // Yes... if (match.groups) { @@ -212,7 +212,7 @@ export default class Lexer { * @return The indent of `text` with consideration for `tabFmt`. */ static getIndent(text: string, tabFmt: TabInfo): number { - let leadingSpace: number = text.length - text.trimStart().length; + const leadingSpace: number = text.length - text.trimStart().length; let indent: number; if (tabFmt.hard) { @@ -234,7 +234,7 @@ export default class Lexer { * @param `line` The line of text. * @return The number of leading spaces of `text`. */ - static getLeadingSpacesByArithmetic(line: any) { + static getLeadingSpacesByArithmetic(line: any): number { const leadingSpaces: number = line.text.length - line.text.trimStart().length; return leadingSpaces; @@ -249,7 +249,7 @@ export default class Lexer { * @param `text` The line of text. * @return The number of leading spaces of `text` with respect to the index position of the first non-whitespace character. */ - static getLeadingSpacesByIndex(text: any) { + static getLeadingSpacesByIndex(text: any): number { const indexNum: number = text.firstNonWhitespaceCharacterIndex; return indexNum; From cf0900968f8b8d06e86d242ec5a7bcbf0abf30fe Mon Sep 17 00:00:00 2001 From: John Date: Thu, 7 Apr 2022 13:52:08 -0500 Subject: [PATCH 22/78] Define types where previously any --- src/commands/text.ts | 48 +++++++++++++++++++++++--------------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 8621a2a..e881b60 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -3,6 +3,8 @@ import { CommandEntry } from './commandEntry'; import vscode = require("vscode"); import pl = require("../pylex"); +type TextEditor = vscode.TextEditor | undefined; + export const textCommands: CommandEntry[] = [ { name: 'mind-reader.getLineNumber', @@ -29,20 +31,20 @@ export const textCommands: CommandEntry[] = [ /* Helper Function * This function returns the line number of the active text editor window */ -function fetchLineNumber(editor: any): number { - return editor.selection.active.line + 1; +function fetchLineNumber(editor: TextEditor): number { + return editor? editor.selection.active.line + 1: -1; } /* Helper Function * This function returns the text from the current line of the active text editor window */ -function fetchTextLine(editor: any): string { - return editor.document.lineAt(fetchLineNumber(editor) - 1); +function fetchTextLine(editor: TextEditor): vscode.TextLine|undefined { + return editor? editor.document.lineAt(fetchLineNumber(editor) - 1): undefined; } // Function that outputs the current line number the cursor is on function getLineNumber(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: TextEditor = vscode.window.activeTextEditor; if (editor) { const lineNum: number = fetchLineNumber(editor); @@ -55,19 +57,19 @@ function getLineNumber(): void { } function getIndent(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: TextEditor = vscode.window.activeTextEditor; if (editor) { const lineNum: number = fetchLineNumber(editor); - const textLine: any = editor.document.lineAt(lineNum - 1); + const textLine: vscode.TextLine = editor.document.lineAt(lineNum - 1); if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`Line ${lineNum.toString()} is Empty`); } else { // Grab tab format from open document - const tabFmt: any = { - size: editor.options.tabSize, + const tabFmt: pl.TabInfo = { + size: typeof editor.options.tabSize === 'number'? editor.options.tabSize: 4, hard: !editor.options.insertSpaces }; const i: number = pl.Lexer.getIndent(textLine.text, tabFmt); @@ -101,9 +103,9 @@ function getLeadingSpaces(): void { if (editor) { const lineNum: number = fetchLineNumber(editor); - const textLine: any = fetchTextLine(editor); - - if (textLine.isEmptyOrWhitespace) { + const textLine: vscode.TextLine|undefined = fetchTextLine(editor); + // If there's no line, or the line is empty, say the line is empty + if (!textLine || textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); } else { @@ -130,23 +132,23 @@ function getLeadingSpaces(): void { } function runLineContext(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: TextEditor = vscode.window.activeTextEditor; if (editor) { // current text and line number const editorText: string = editor.document.getText(); - const line: string = editor.selection.active.line; + const line: number = editor.selection.active.line; // get tab info settings - const size: number = parseInt(editor.options.tabSize); + const size: number = typeof editor.options.tabSize === 'number'? editor.options.tabSize: 4; const hard: boolean = !editor.options.insertSpaces; // initialize parser - const parser: any = new pl.Parser(editorText, { + const parser: pl.Parser = new pl.Parser(editorText, { size, hard }); parser.parse(); - const context: string = parser.context(line); + const context: pl.LexNode[] = parser.context(line); // build text const contentString: string = createContextString(context, line); @@ -157,7 +159,7 @@ function runLineContext(): void { } } -function createContextString(context: any, line: string): string { +function createContextString(context: pl.LexNode[], line: number): string { if (context.length < 1) { throw new Error('Cannot create context string for empty context'); } @@ -169,7 +171,7 @@ function createContextString(context: any, line: string): string { } for (let i: number = 1; i < context.length; i++) { - const node: any = context[i]; + const node: pl.LexNode = context[i]; if (node.label === 'root') { // root @@ -177,7 +179,7 @@ function createContextString(context: any, line: string): string { continue; } - if (node.token.type !== pl.PylexSymbol.EMPTY && + if (node.token && node.token.type !== pl.PylexSymbol.EMPTY && node.token.type !== pl.PylexSymbol.INDENT) { contextString += ' inside ' + node.token.type.toString(); if (node.token.attr) { @@ -192,14 +194,14 @@ function createContextString(context: any, line: string): string { // find up to `n` words around the cursor, where `n` is // the value of `#mindReader.reader.contextWindow` function runCursorContext(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: vscode.TextEditor | undefined = vscode.window.activeTextEditor; if (!editor) { vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); return; } - const cursorPos: any = editor.selection.active; + const cursorPos: vscode.Position = editor.selection.active; const text: string = editor.document.lineAt(cursorPos).text; const windowSize: any = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); let trimmedText: string = text.trimStart(); // trim leading whitespace @@ -252,7 +254,7 @@ function runCursorContext(): void { // construct cursor context string let contextString: string = ''; - for (let i: any = contextStart; i < contextEnd; i++) { + for (let i: number = contextStart; i < contextEnd; i++) { contextString += spaceWords[i].word + ' '; } // output cursor context string From bcfeb5a6fe3f7f394d6311374116e3d85f83b5e9 Mon Sep 17 00:00:00 2001 From: John Date: Sat, 9 Apr 2022 18:01:52 -0500 Subject: [PATCH 23/78] package.json: - Add titles for all mind-reader commands - Remove redundant keybindings - Redefine keybindings to no longer conflict with *VSCode*, JAWS, NVDA --- package.json | 192 ++++++++++++++++++++++---------------------- src/commands/nav.ts | 26 +----- 2 files changed, 99 insertions(+), 119 deletions(-) diff --git a/package.json b/package.json index 457e219..b1663c8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "mind-reader", "displayName": "Mind_Reader", - "repository": "https://github.com/SingleSemesterSnobs/Mind_Reader", + "repository": "https://github.com/We-Dont-Byte/Mind_Reader", "version": "1.0.0", "engines": { "vscode": "^1.60.0" @@ -52,20 +52,16 @@ "title": "Mind Reader Webview" }, { - "command": "mind-reader.openKeyBindWin", - "title": "Key Bindings for Windows" - }, - { - "command": "mind-reader.openKeyBindMac", - "title": "Key Bindings for Mac" + "command": "mind-reader.openKeybinds", + "title": "Mind_Reader Keybinds" }, { "command": "mind-reader.runLineContext", - "title": "Run Line Context" + "title": "Get the Context of the Current Line" }, { "command": "mind-reader.runCursorContext", - "title": "Run Cursor Context" + "title": "Get the Context of Text Under Cursor" }, { "command": "mind-reader.getIndent", @@ -81,121 +77,128 @@ }, { "command": "mind-reader.uploadCurrentFile", - "title": "Upload current file to LEGO Hub" + "title": "Upload Current File to LEGO Hub" }, { "command": "mind-reader.runProgram", - "title": "Run a program from the LEGO Hub" + "title": "Run a Program from the LEGO Hub" }, { "command": "mind-reader.stopExecution", - "title": "Stop running program on the LEGO Hub" + "title": "Stop Running Program on the LEGO Hub" }, { "command": "mind-reader.deleteProgram", - "title": "Delete a program from the LEGO Hub" + "title": "Delete a Program from the LEGO Hub" + }, + { + "command": "mind-reader.uploadCurrentFile", + "title": "Hub: Upload Current File" + }, + { + "command": "mind-reader.getLeadingSpaces", + "title": "Get Leading Spaces" + }, + { + "command": "mind-reader.getLineNumber", + "title": "Get Line Number" + }, + { + "command": "mind-reader.getQuickInputBack", + "title": "Go Back in Quick Input" + }, + { + "command": "mind-reader.gotoLine", + "title": "Go to Line" + }, + { + "command": "mind-reader.gotoSymbol", + "title": "Go to Symbol" + }, + { + "command": "mind-reader.navigateBack", + "title": "Navigate Backward" + }, + { + "command": "mind-reader.navigateForward", + "title": "Navigate Forward" + }, + { + "command": "mind-reader.nextInFiles", + "title": "Go to Next Problem in Files (Error, Warning, Info)" + }, + { + "command": "mind-reader.prevInFiles", + "title": "Go to Previous Problem in Files (Error, Warning, Info)" + }, + { + "command": "mind-reader.quickOpen", + "title": "Go to File..." + }, + { + "command": "mind-reader.quickOpenPreviousRecentlyUsedEditorInGroup", + "title": "View: Quick Open Previous Recently Used Editor in Group" + }, + { + "command": "mind-reader.showAllSymbols", + "title": "Go to Symbol in Workspace..." + }, + { + "command": "mind-reader.showProblems", + "title": "Show Problems" } ], "keybindings": [ { - "command": "mind-reader.decreaseFontScale", + "command": "editor.action.fontZoomOut", "key": "numpad_subtract", - "mac": "d" + "mac": "d", + "when": "editorTextFocus && config.mindReader.reader.screenReader != JAWS" }, { - "command": "mind-reader.increaseFontScale", + "command": "editor.action.fontZoomIn", "key": "numpad_add", - "mac": "[NumpadAdd]" + "mac": "[NumpadAdd]", + "when": "editorTextFocus && config.mindReader.reader.screenReader != JAWS" }, { - "command": "mind-reader.increaseEditorScale", + "command": "editor.action.fontZoomReset", + "key": "numpad_add", + "mac": "[NumpadAdd]", + "when": "editorTextFocus" + }, + { + "command": "workbench.action.zoomIn", "key": "shift+numpad_add", - "mac": "Shift+[NumpadAdd]" + "mac": "Shift+[NumpadAdd]", + "when": "config.mindReader.reader.screenReader != JAWS" }, { - "command": "mind-reader.decreaseEditorScale", + "command": "workbench.action.zoomOut", "key": "shift+numpad_subtract", "mac": "Shift+[NumpadSubtract]" }, { - "command": "mind-reader.resetEditorScale", + "command": "workbench.action.zoomReset", "key": "shift+enter", "mac": "Shift+[Enter]" }, - { - "command": "mind-reader.showAllSymbols", - "key": "Ctrl+T", - "mac": "Cmd+[KeyT]" - }, - { - "command": "mind-reader.gotoLine", - "key": "CTRL+G", - "mac": "Cmd+[KeyG]" - }, - { - "command": "mind-reader.quickOpen", - "key": "CTRL+P", - "mac": "Cmd+[KeyP]" - }, - { - "command": "mind-reader.gotoSymbol", - "key": "Ctrl+Shift+O", - "mac": "Cmd+Shift+[KeyO]" - }, - { - "command": "mind-reader.showProblems", - "key": "Ctrl+Shift+M", - "mac": "Cmd+Shift+[KeyM]" - }, - { - "command": "mind-reader.nextInFiles", - "key": "F8", - "mac": "[F8]" - }, - { - "command": "mind-reader.prevInFiles", - "key": "Shift+F8", - "mac": "Shift+[F8]" - }, - { - "command": "mind-reader.quickOpenPreviousRecentlyUsedEditorInGroup", - "key": "Ctrl+Tab", - "mac": "Cmd+[Tab]" - }, - { - "command": "mind-reader.navigateBack", - "key": "Ctrl+Alt+-", - "mac": "Cmd+Alt+[Minus]" - }, - { - "command": "mind-reader.getQuickInputBack", - "key": "Ctrl+Alt+-", - "mac": "Cmd+Alt+[Minus]" - }, - { - "command": "mind-reader.navigateForward", - "key": "Ctrl+Shift+-", - "mac": "Cmd+Shift+[Minus]" - }, - { - "command": "mind-reader.selectTheme", - "key": "Ctrl+Shift+1", - "mac": "Cmd+Shift+[Digit1]" - }, { "command": "mind-reader.getIndent", - "key": "Shift+Tab", - "mac": "Shift+[Tab]" + "key": "Ctrl+Shift+/ I", + "mac": "Cmd+Shift+[Slash] I", + "when": "activeEditor" }, { - "command": "mind-reader.openKeyBindWin", - "key": "Ctrl+Shift+8", - "mac": "Cmd+Shift+8" + "command": "mind-reader.getLeadingSpaces", + "key": "Ctrl+Shift+/ S", + "mac": "Cmd+Shift+[Slash] S", + "when": "activeEditor" }, { - "command": "mind-reader.openKeyBindMac", - "key": "Ctrl+Shift+9", - "mac": "Cmd+Shift+9" + "command": "mind-reader.openKeybinds", + "key": "Ctrl+Shift+/ K", + "mac": "Cmd+Shift+[Slash] K" } ], "menus": { @@ -247,12 +250,7 @@ "when": "activeEditor" }, { - "command": "mind-reader.openKeyBindWin", - "group": "mind-reader", - "when": "activeEditor" - }, - { - "command": "mind-reader.openKeyBindMac", + "command": "mind-reader.openKeybinds", "group": "mind-reader", "when": "activeEditor" } @@ -270,7 +268,7 @@ "mindReader.productType": { "type": "string", "description": "Specifies the LEGO® product.", - "default": "MINDSTORMS EV3", + "default": "SPIKE Prime", "enum": [ "MINDSTORMS EV3", "SPIKE Prime" @@ -285,11 +283,13 @@ "description": "Specifies which screen reader to optimize for.", "default": "NVDA", "enum": [ + "JAWS", "NVDA", "Orca", "VoiceOver" ], "enumDescriptions": [ + "Job Access With Speech (Windows)", "NonVisual Desktop Access (Windows)", "Orca (Linux)", "Apple VoiceOver (macOS)" diff --git a/src/commands/nav.ts b/src/commands/nav.ts index f694e40..613348b 100755 --- a/src/commands/nav.ts +++ b/src/commands/nav.ts @@ -8,17 +8,13 @@ export const navCommands: CommandEntry[] = [ name: 'mind-reader.openWebview', callback: openWebview, }, - { - name: 'mind-reader.openKeyBindWin', - callback: () => openKeyBindWin('Windows') - }, - { - name: 'mind-reader.openKeyBindMac', - callback: () => openKeyBindWin('Mac'), + name: "mind-reader.openKeybinds", + callback: () => vscode.commands.executeCommand("workbench.action.openGlobalKeybindings", "mind-reader"), }, //Navigation Keys...... + // TODO: Why is this here? Extensions can rebind existing keybinds. { name: 'mind-reader.showAllSymbols', callback: () => vscode.commands.executeCommand('workbench.action.showAllSymbols'), @@ -97,20 +93,4 @@ function getWebviewContent(filepath: string) { return fs.readFileSync(filepath, {encoding: 'utf-8'}); } -function openKeyBindWin(os: 'Mac' | 'Windows'): void { - //vscode.commands.executeCommand('workbench.action.zoomOut'); - const panel = vscode.window.createWebviewPanel( - 'mindReader', // Identifies the type of the webview. Used internally - 'MR Key Bindings', // Title of the panel displayed to the user - vscode.ViewColumn.One, // Editor column to show the new webview panel in. - {} - ); // Webview options. More on these later. - - if (os === 'Windows') { - panel.webview.html = getWebviewContent('media/html/winkeys.html'); - } else if (os === 'Mac') { - panel.webview.html = getWebviewContent('media/html/mackeys.html'); - } -} - From bcbd20a0bfdb9e1ec3ed03211716ddf82189d6ec Mon Sep 17 00:00:00 2001 From: John Date: Sat, 9 Apr 2022 21:12:26 -0500 Subject: [PATCH 24/78] package.json: - Specify groups for commands - Specify which LEGO Hub - Clarify when keybinds should work - Define keybinds for 'getLineNumber', 'runLineContext' - Remove more redundant keybinds --- package.json | 143 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 84 insertions(+), 59 deletions(-) diff --git a/package.json b/package.json index b1663c8..b832300 100644 --- a/package.json +++ b/package.json @@ -15,37 +15,40 @@ "main": "./out/extension.js", "contributes": { "commands": [ - { - "command": "mind-reader.helloWorld", - "title": "Hello World" - }, { "command": "mind-reader.increaseFontScale", - "title": "Increase Font Scale" + "title": "Increase Font Scale", + "category": "Mind Reader" }, { "command": "mind-reader.decreaseFontScale", - "title": "Decrease Font Scale" + "title": "Decrease Font Scale", + "category": "Mind Reader" }, { "command": "mind-reader.resetFontScale", - "title": "Reset Font Scale" + "title": "Reset Font Scale", + "category": "Mind Reader" }, { "command": "mind-reader.increaseEditorScale", - "title": "Increase Editor Scale" + "title": "Increase Editor Scale", + "category": "Mind Reader" }, { "command": "mind-reader.decreaseEditorScale", - "title": "Decrease Editor Scale" + "title": "Decrease Editor Scale", + "category": "Mind Reader" }, { "command": "mind-reader.resetEditorScale", - "title": "Reset Editor Scale" + "title": "Reset Editor Scale", + "category": "Mind Reader" }, { "command": "mind-reader.selectTheme", - "title": "Select Theme" + "title": "Select Theme", + "category": "Mind Reader" }, { "command": "mind-reader.openWebview", @@ -53,87 +56,108 @@ }, { "command": "mind-reader.openKeybinds", - "title": "Mind_Reader Keybinds" + "title": "Edit Keybinds", + "category": "Mind Reader" }, { "command": "mind-reader.runLineContext", - "title": "Get the Context of the Current Line" + "title": "Get the Context of the Current Line", + "category": "Mind Reader" }, { "command": "mind-reader.runCursorContext", - "title": "Get the Context of Text Under Cursor" + "title": "Get the Context of Text Under Cursor", + "category": "Mind Reader" }, { "command": "mind-reader.getIndent", - "title": "Get Line Indentation" + "title": "Get Line Indentation", + "category": "Mind_Reader" }, { "command": "mind-reader.connectHub", - "title": "Connect LEGO Hub" + "title": "Connect LEGO SPIKE Prime Hub", + "category": "SPIKE Prime" }, { "command": "mind-reader.disconnectHub", - "title": "Disconnect LEGO Hub" + "title": "Disconnect LEGO SPIKE Prime Hub", + "category": "SPIKE Prime" }, { "command": "mind-reader.uploadCurrentFile", - "title": "Upload Current File to LEGO Hub" + "title": "Upload Current File to LEGO SPIKE Prime Hub", + "category": "SPIKE Prime" }, { "command": "mind-reader.runProgram", - "title": "Run a Program from the LEGO Hub" + "title": "Run a Program on the LEGO SPIKE Prime Hub", + "category": "SPIKE Prime" }, { "command": "mind-reader.stopExecution", - "title": "Stop Running Program on the LEGO Hub" + "title": "Stop Running Program on the LEGO SPIKE Prime Hub", + "category": "SPIKE Prime" }, { "command": "mind-reader.deleteProgram", - "title": "Delete a Program from the LEGO Hub" + "title": "Delete a Program from the LEGO SPIKE Prime Hub", + "category": "SPIKE Prime" }, { "command": "mind-reader.uploadCurrentFile", - "title": "Hub: Upload Current File" + "title": "Upload Current File to the LEGO SPIKE Prime Hub", + "category": "SPIKE Prime" }, { "command": "mind-reader.getLeadingSpaces", - "title": "Get Leading Spaces" + "title": "Get Leading Spaces", + "category": "Mind Reader" }, { "command": "mind-reader.getLineNumber", - "title": "Get Line Number" + "title": "Get Line Number", + "category": "Mind Reader" }, { "command": "mind-reader.getQuickInputBack", - "title": "Go Back in Quick Input" + "title": "Go Back in Quick Input", + "category": "Mind Reader" }, { "command": "mind-reader.gotoLine", - "title": "Go to Line" + "title": "Go to Line", + "category": "Mind Reader" }, { "command": "mind-reader.gotoSymbol", - "title": "Go to Symbol" + "title": "Go to Symbol", + "category": "Mind Reader" }, { "command": "mind-reader.navigateBack", - "title": "Navigate Backward" + "title": "Navigate Backward", + "category": "Mind Reader" }, { "command": "mind-reader.navigateForward", - "title": "Navigate Forward" + "title": "Navigate Forward", + "category": "Mind Reader" }, { "command": "mind-reader.nextInFiles", - "title": "Go to Next Problem in Files (Error, Warning, Info)" + "title": "Go to Next Problem in Files (Error, Warning, Info)", + "category": "Mind Reader" }, { "command": "mind-reader.prevInFiles", - "title": "Go to Previous Problem in Files (Error, Warning, Info)" + "title": "Go to Previous Problem in Files (Error, Warning, Info)", + "category": "Mind Reader" }, { "command": "mind-reader.quickOpen", - "title": "Go to File..." + "title": "Go to File...", + "category": "Mind Reader" }, { "command": "mind-reader.quickOpenPreviousRecentlyUsedEditorInGroup", @@ -141,59 +165,60 @@ }, { "command": "mind-reader.showAllSymbols", - "title": "Go to Symbol in Workspace..." + "title": "Go to Symbol in Workspace...", + "category": "Mind Reader" }, { "command": "mind-reader.showProblems", - "title": "Show Problems" + "title": "Show Problems", + "category": "Mind Reader" + }, + { + "command": "mind-reader.showCommands", + "title": "Show All Commands", + "category": "Mind Reader" } ], "keybindings": [ { "command": "editor.action.fontZoomOut", - "key": "numpad_subtract", - "mac": "d", + "key": "Shift+Alt+z -", "when": "editorTextFocus && config.mindReader.reader.screenReader != JAWS" }, { "command": "editor.action.fontZoomIn", - "key": "numpad_add", - "mac": "[NumpadAdd]", + "key": "Shift+Alt+z =", "when": "editorTextFocus && config.mindReader.reader.screenReader != JAWS" }, { "command": "editor.action.fontZoomReset", - "key": "numpad_add", - "mac": "[NumpadAdd]", - "when": "editorTextFocus" - }, - { - "command": "workbench.action.zoomIn", - "key": "shift+numpad_add", - "mac": "Shift+[NumpadAdd]", - "when": "config.mindReader.reader.screenReader != JAWS" - }, - { - "command": "workbench.action.zoomOut", - "key": "shift+numpad_subtract", - "mac": "Shift+[NumpadSubtract]" - }, - { - "command": "workbench.action.zoomReset", - "key": "shift+enter", - "mac": "Shift+[Enter]" + "key": "Shift+Alt+z 0", + "when": "editorTextFocus && config.mindReader.reader.screenReader != JAWS" }, { "command": "mind-reader.getIndent", "key": "Ctrl+Shift+/ I", "mac": "Cmd+Shift+[Slash] I", - "when": "activeEditor" + "when": "editorTextFocus" }, { "command": "mind-reader.getLeadingSpaces", "key": "Ctrl+Shift+/ S", "mac": "Cmd+Shift+[Slash] S", - "when": "activeEditor" + "when": "editorTextFocus", + "comment": "Requires python language" + }, + { + "command": "mind-reader.getLineNumber", + "key": "Ctrl+Shift+/ L", + "mac": "Cmd+Shift+[Slash] L", + "when": "editorTextFocus" + }, + { + "command": "mind-reader.runLineContext", + "key": "Ctrl+Shift+/ C", + "mac": "Cmd+Shift+[Slash] C", + "when": "editorTextFocus && editorLangId == python" }, { "command": "mind-reader.openKeybinds", From 388cf1dfcfc3aa9d8a97bf832af9b924f55c4f89 Mon Sep 17 00:00:00 2001 From: John Date: Sat, 9 Apr 2022 21:14:56 -0500 Subject: [PATCH 25/78] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0b60dfa..ba4285a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ out dist node_modules .vscode-test/ +*.code-workspace *.vsix From de3c9bf43591043dedf9bbc3ff09c4856d51f023 Mon Sep 17 00:00:00 2001 From: John Date: Sat, 9 Apr 2022 21:19:11 -0500 Subject: [PATCH 26/78] ev3Manager: - Start work on ev3 support - Explore functionality of ev3dev-Browser - Realize it's super limited --- package.json | 4 ++++ src/commands/hub.ts | 11 +++++++++++ src/ev3Manager.ts | 31 +++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 src/ev3Manager.ts diff --git a/package.json b/package.json index b832300..993fd07 100644 --- a/package.json +++ b/package.json @@ -224,6 +224,10 @@ "command": "mind-reader.openKeybinds", "key": "Ctrl+Shift+/ K", "mac": "Cmd+Shift+[Slash] K" + }, + { + "command": "mind-reader.ev3.test", + "key": "Ctrl+E Ctrl+V" } ], "menus": { diff --git a/src/commands/hub.ts b/src/commands/hub.ts index 1b8bd03..d9bf735 100755 --- a/src/commands/hub.ts +++ b/src/commands/hub.ts @@ -1,6 +1,7 @@ import * as vscode from 'vscode'; import * as path from 'path'; import HubManager from '../hubManager'; +import EV3Manager from '../ev3Manager'; import { CommandEntry } from './commandEntry'; @@ -34,10 +35,20 @@ export const hubCommands: CommandEntry[] = [ name: 'mind-reader.deleteProgram', callback: deleteProgram }, + { + name: 'mind-reader.ev3.test', + callback: ev3test + } ]; // Current connected hub let hub: HubManager | null = null; +let ev3: EV3Manager | null = null; + +async function ev3test(): Promise { + ev3 = await EV3Manager.activate(); + ev3.test(); +} async function connectHub(): Promise { if (hub && hub.isOpen()) { diff --git a/src/ev3Manager.ts b/src/ev3Manager.ts new file mode 100644 index 0000000..a251476 --- /dev/null +++ b/src/ev3Manager.ts @@ -0,0 +1,31 @@ +import * as vscode from 'vscode'; +//import * as fs from 'fs'; +//import { logger } from './extension'; + + + +export default class EV3Manager { + private ev3devBrowser: vscode.Extension | undefined = vscode.extensions.getExtension("ev3dev.ev3dev-browser"); + + private constructor() {} + public test() { + //console.log(this.ev3devBrowser); + // This seems to be the only thing we, as an extension, + // are allowed to do with this other extension. + vscode.commands.executeCommand("ev3devBrowser.action.pickDevice", null); + } + public static activate(): Promise { + return new Promise (async (resolve) => { + try { + let mgr = new EV3Manager(); + // Wait for ev3devBrowser to start + await mgr.ev3devBrowser?.activate(); + // Return ev3Manager + return resolve(mgr); + } + catch (err) { + throw err; + } + }); + } +} \ No newline at end of file From 17c410eae242575f7f5e2cfeccfa7081f585e85e Mon Sep 17 00:00:00 2001 From: John Date: Thu, 14 Apr 2022 14:27:07 -0500 Subject: [PATCH 27/78] Oops: Upload all files changed on VM in the last 5 days. Commit info lost. --- src/commands/hub.ts | 9 +++++---- src/commands/text.ts | 16 +++++++++++----- src/pylex/lexer.ts | 20 +++++++++----------- 3 files changed, 25 insertions(+), 20 deletions(-) diff --git a/src/commands/hub.ts b/src/commands/hub.ts index d9bf735..55c9c3a 100755 --- a/src/commands/hub.ts +++ b/src/commands/hub.ts @@ -1,7 +1,7 @@ import * as vscode from 'vscode'; import * as path from 'path'; import HubManager from '../hubManager'; -import EV3Manager from '../ev3Manager'; +//import EV3Manager from '../ev3Manager'; import { CommandEntry } from './commandEntry'; @@ -34,22 +34,23 @@ export const hubCommands: CommandEntry[] = [ { name: 'mind-reader.deleteProgram', callback: deleteProgram - }, + }/*, { name: 'mind-reader.ev3.test', callback: ev3test - } + }*/ ]; // Current connected hub let hub: HubManager | null = null; +/* let ev3: EV3Manager | null = null; async function ev3test(): Promise { ev3 = await EV3Manager.activate(); ev3.test(); } - +*/ async function connectHub(): Promise { if (hub && hub.isOpen()) { vscode.window.showWarningMessage('LEGO Hub is already connected, reconnecting...'); diff --git a/src/commands/text.ts b/src/commands/text.ts index e881b60..6c0cae2 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -167,23 +167,29 @@ function createContextString(context: pl.LexNode[], line: number): string { let contextString: string = `Line ${line + 1}`; // 1 based if (context[0].token && context[0].token.attr) { - contextString += ': ' + context[0].token.type.toString() + ' ' + context[0].token.attr.toString(); + let tokenTypeString: string = ` ${context[0].token.type.toString()}`; + contextString += `:${tokenTypeString !== 'INDENT'?tokenTypeString:" " + } ${context[0].token.attr.toString()}`; } for (let i: number = 1; i < context.length; i++) { const node: pl.LexNode = context[i]; - + const inside: string = "in"; if (node.label === 'root') { // root - contextString += ' in the Document Root'; + if (vscode.window.activeTextEditor?.document.uri) { + contextString += ` ${inside} ${vscode.workspace.asRelativePath(vscode.window.activeTextEditor?.document.uri)}`; + } else { + contextString += ` ${inside} the Document`; + } continue; } if (node.token && node.token.type !== pl.PylexSymbol.EMPTY && node.token.type !== pl.PylexSymbol.INDENT) { - contextString += ' inside ' + node.token.type.toString(); + contextString += ` ${inside} ${node.token.type.toString()}`; if (node.token.attr) { - contextString += ' ' + node.token.attr.toString(); + contextString += ` ${node.token.attr.toString()}`; } } } diff --git a/src/pylex/lexer.ts b/src/pylex/lexer.ts index 9135aeb..92e48ea 100644 --- a/src/pylex/lexer.ts +++ b/src/pylex/lexer.ts @@ -56,6 +56,14 @@ const rules: Rule[] = [ pattern: /^\s*with\s+(?[^:]+):\s*$/, type: Symbol.WITH }, + { + pattern: /^\s*(#.*)?$/, + type: Symbol.EMPTY + }, + { + pattern: /\s*(?[^#]+)?$/, + type: Symbol.INDENT + } ]; /** @@ -143,17 +151,7 @@ export default class Lexer { } } // No rules matched - - // TODO: move to rules - if (/^\s*(#.*)?$/.test(line)) { - // "empty" line - token = new LineToken(Symbol.EMPTY, this.pos, 999999); - } - else { - // This is an INDENT token - token = new LineToken(Symbol.INDENT, this.pos, indent); - } - + token = new LineToken(Symbol.EMPTY, this.pos, 999999); this._currToken = token; this.pos++; From 2fdd176dd6ca5dc9122791f4c1db556d4b5a2f4c Mon Sep 17 00:00:00 2001 From: John Date: Sun, 24 Apr 2022 02:34:03 -0700 Subject: [PATCH 28/78] createContextString: Improve formatting somewhat --- src/commands/text.ts | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 6c0cae2..7cf5306 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -165,26 +165,17 @@ function createContextString(context: pl.LexNode[], line: number): string { } let contextString: string = `Line ${line + 1}`; // 1 based - + // Print the current line if (context[0].token && context[0].token.attr) { - let tokenTypeString: string = ` ${context[0].token.type.toString()}`; - contextString += `:${tokenTypeString !== 'INDENT'?tokenTypeString:" " + let tokenTypeString: string = `${context[0].token.type.toString()}`; + contextString += `: ${tokenTypeString !== 'INDENT'?tokenTypeString:"" } ${context[0].token.attr.toString()}`; } for (let i: number = 1; i < context.length; i++) { const node: pl.LexNode = context[i]; const inside: string = "in"; - if (node.label === 'root') { - // root - if (vscode.window.activeTextEditor?.document.uri) { - contextString += ` ${inside} ${vscode.workspace.asRelativePath(vscode.window.activeTextEditor?.document.uri)}`; - } else { - contextString += ` ${inside} the Document`; - } - continue; - } - + // Node contains information relevant to the current line if (node.token && node.token.type !== pl.PylexSymbol.EMPTY && node.token.type !== pl.PylexSymbol.INDENT) { contextString += ` ${inside} ${node.token.type.toString()}`; @@ -192,6 +183,16 @@ function createContextString(context: pl.LexNode[], line: number): string { contextString += ` ${node.token.attr.toString()}`; } } + // Node is the document root + if (node.label === 'root') { + // Append the name (relative path) of the document in the workspace + if (vscode.window.activeTextEditor?.document.uri) { + contextString += ` ${inside} ${vscode.workspace.asRelativePath(vscode.window.activeTextEditor?.document.uri)}`; + } else { + contextString += ` ${inside} the Document`; + } + continue; + } } return contextString; From 1f25b3c787ae72d832f5127ae59ad49e62e84346 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 26 Apr 2022 01:19:31 -0700 Subject: [PATCH 29/78] setup-development: upgrade-windows.ps1: Update NodeJS, NVDA, VSCode, etc. Upbdate NPM dependencies If VSCode Electron ver. known, electron-rebuild with it install-windows.ps1 Instal git Clone the mind-reader repo Run upgrade-windows.ps1 from the newly cloned repo --- package-lock.json | 4 +- setup-development/install-windows.ps1 | 169 ++++++++++++++++++ setup-development/upgrade-windows.ps1 | 192 +++++++++++++++++++++ setup-development/winget/dependencies.json | 35 ++++ 4 files changed, 398 insertions(+), 2 deletions(-) create mode 100644 setup-development/install-windows.ps1 create mode 100644 setup-development/upgrade-windows.ps1 create mode 100644 setup-development/winget/dependencies.json diff --git a/package-lock.json b/package-lock.json index 82ed2a5..e3d6f86 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "mind-reader", - "version": "0.0.1", + "version": "1.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "mind-reader", - "version": "0.0.1", + "version": "1.0.0", "dependencies": { "serialport": "^9.2.5" }, diff --git a/setup-development/install-windows.ps1 b/setup-development/install-windows.ps1 new file mode 100644 index 0000000..9c646cd --- /dev/null +++ b/setup-development/install-windows.ps1 @@ -0,0 +1,169 @@ +<# +.synopsis +Dependency installer for Mind-Reader on Windows. +This sets up a development environment from a BARE windows install. + +.description +Install Git for Windows, clone the Mind-Reader repository, and install all dependencies. + +The script uses winget (A.K.A. "App Installer") to download and install the latest versions of each dependency, defined in winget/dependencies.json + +Winget comes preinstalled on Windows 11 (21H2)/10 (21H1) or newer, and can be installed on Windows 10 1704+ through the Windows Store. +If you download Microsoft's developer VM, you have it! +As WinGet is built into Windows, it sidesteps any annoying third-party package managers, and is the lowest common denominator for package installation. + +.link +https://github.com/We-Dont-Byte/Mind_Reader/ + +.parameter GitDir +Path to clone the git repo into (Default: $HOME/git/) + +.parameter AllowAdministrator +Force-allow running this script as Administrator (not recommended, despite the frequent UAC prompts!) + +.parameter NoPrompt +Disable all prompts for user input, and all waiting. (not recommended when combined with AllowAdministrator!) + +.parameter ForceInstall +Force installation/upgrade of all modules, even if already present on the system. + +.parameter DryRun +Perform a "dry run" of the script, changing directories and running commands, but without modifying anything. + +.example +./install-windows.ps1 +Perform a default upgrade of all Mind_Reader dependencies + +.example +./install-windows.ps1 -DryRun +Perform a dry run of the upgrade process, so you can evaluate what commands will be run + +.example +./install-windows.ps1 -NoPrompt +Don't prompt for user input when upgrading + +.example +./install-windows.ps1 AllowAdministrator +Allow script to run as Administrator +#> + +param ( + [string]$GitDir = "$HOME/git/", # Path to clone the git repo into + [switch]$h, [switch]$Help, # Get help + [switch]$AllowAdministrator, # Force allow installation as administrator + [switch]$NoPrompt, # Disable the 3-second wait and press-any-key prompt + [switch]$ForceInstall, # Always try to install + [switch]$DryRun # Run script without installing +) + +$SetupPath = 'Mind_Reader/setup-development' + +if ($h -or $Help) { + Get-Help ./install-windows.ps1 + exit +} + + +# .description +# Command-Available: Checks whether a given command is available. +# If command is available, returns $false +function Command-Available { + param ($command) + # Use a wildcard here so the command doesn't throw an exception we'd have to trycatch + # It's not a filthy hack if it's elegant! + RETURN (Get-Command -Name $command*) +} + +#.description +# Dry-Run a powershell statement +function Dry-Run { + param ([string] $command) + $prompt = "> " + if ($DryRun) { + Write-Host "$prompt$command [dry]" -ForegroundColor darkgray + } + else { + Write-Host "$prompt$command" -ForegroundColor white + Invoke-Expression $command + } +} + +#.description +# Reload-Path: Reload the Path environment variable +function Reload-Path { + Write-Output "Reloading Path..." + #* Courtesy of user [mpen](https://stackoverflow.com/users/65387/mpen) on [StackOverflow](https://stackoverflow.com/a/31845512) + $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") +} + + +# Check if Winget is available +if ( $NoWinget -or -not (Command-Available winget) ) { + Write-Warning "[ Warning ]: It looks like winget isn't available.`n" + Write-Host "Update 'App Installer' through the Microsoft Store, or grab the '.msixbundle' from the winget-cli repository:" + Write-Host "( https://github.com/microsoft/winget-cli/releases/latest )`n" -ForegroundColor White + exit +} + +# Check if the user ran the script with administrator privileges. +# Warn them. +if ( ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5-32-544') ) { + # If an administrator requests installation as administator, + # for example, to keep UAC prompts to a minimum, allow it. + if ($AllowAdministrator) { + Write-Warning "Script was run as Administrator. Exit now if you didn't mean to do this!" + # If you pass NoPrompt as an arg, you're very aware of the damage this script could do to your build env, and you just don't care + # The true chad of sysadmins. + if (!$NoPrompt) { + for ( $i = 3; $i -gt 0; $i--) { + Write-Host "Press Ctrl+C to exit. Continuing in $i...`r" -NoNewLine + sleep 1 + } + Write-Host "Press any key to continue... " + [void][Console]::ReadKey(1) # Equivalent to Command Prompt's `pause` command + } + } else { + # Throw a fatal error if the user tries to run as administrator. + Throw "Script must be run as a normal user." + } +} + +# Install Git +if ( -not (Command-Available git) ) { + Write-Host "`nInstalling Git with winget..." + Dry-Run 'winget install --id Git.Git' + Reload-Path + if ( -not (Command-Available git)) { + Throw "Git failed to install. Aborting." + } +} else { + Write-Host "Git already installed." -ForegroundColor green +} + +# Create git directory in GitDir +if ( -not (Test-Path "$GitDir") ) { + Dry-Run "mkdir '$GitDir'" +} + +# Clone the repository in GitDir +$dir = $pwd +cd $GitDir +Dry-Run "git clone 'https://github.com/We-Dont-Byte/Mind_Reader.git'" +# TODO: Change this during merge onto main branch +Dry-Run "git checkout johnBreaux" + +# Run the install script +if ( -not (Test-Path "$SetupPath")) { + Throw "Repository contains no subdirectory '$SetupPath'." +} +cd $SetupPath +# Run upgrade-windows to install the rest of the dependency chain. +$args = if ($AllowAdministrator) {" -AllowAdministrator"} else {""} +$args += if ($DryRun) {" -DryRun"} else {""} +PowerShell ("./upgrade-windows.ps1 -Install -NoPrompt" + $args) + + +cd $dir +if ( -not $NoPrompt ) { + Write-Host "Press any key to exit."; [void][Console]::ReadKey(1) +} \ No newline at end of file diff --git a/setup-development/upgrade-windows.ps1 b/setup-development/upgrade-windows.ps1 new file mode 100644 index 0000000..edc4d79 --- /dev/null +++ b/setup-development/upgrade-windows.ps1 @@ -0,0 +1,192 @@ +<# +.synopsis +Dependency updater for Mind-Reader on Windows. +This script expects to be run from Mind_Reader/setup-development + +.description +Updates dependencies (NodeJS, Python, etc.), VSCode, NVDA + +The script uses winget (A.K.A. "App Installer") to download and install the latest versions of each dependency, defined in winget/dependencies.json + +Winget comes preinstalled on Windows 11 (21H2)/10 (21H1) or newer, and can be installed on Windows 10 1704+ through the Windows Store. +If you download Microsoft's developer VM, you have it! +As WinGet is built into Windows, it sidesteps any annoying third-party package managers, and is the lowest common denominator for package installation. + +.link +https://github.com/We-Dont-Byte/Mind_Reader/ + +.parameter GitDir +Path to clone the git repo into (Default: $HOME/git/) + +.parameter AllowAdministrator +Force-allow running this script as Administrator (not recommended, despite the frequent UAC prompts!) + +.parameter NoPrompt +Disable all prompts for user input, and all waiting. (not recommended when combined with AllowAdministrator!) + +.parameter Install +Force installation/upgrade of all modules, even if already present on the system. + +.parameter DryRun +Perform a "dry run" of the script, changing directories and running commands, but without modifying anything. + +.example +./upgrade-windows.ps1 +Perform a default upgrade of all Mind_Reader dependencies + +.example +./upgrade-windows.ps1 -DryRun +Perform a dry run of the upgrade process, so you can evaluate what commands will be run + +.example +./upgrade-windows.ps1 -NoPrompt +Don't prompt for user input when upgrading + +.example +./upgrade-windows.ps1 -AllowAdministrator +Allow script to be run as Administrator +#> + +param ( + [switch]$AllowAdministrator, # Force allow installation as administrator + [switch]$NoPrompt, # Disable the 3-second wait and press-any-key prompt + [switch]$Install, # Perform all installations, even when commands are present + [switch]$DryRun, # Run script without installing + [switch]$NoWinget # Pretend Winget doesn't exist +) + +# .description +# Command-Available: Checks whether a given command is available. +# If command is available, returns $false +function Command-Available { + param ($command) + # Use a wildcard here so the command doesn't throw an exception we'd have to trycatch + # It's not a filthy hack if it's elegant! + RETURN (Get-Command -Name $command*) +} + +#.description +# Dry-Run a powershell statement +function Dry-Run { + param ([string] $command) + $prompt = "> " + if ($DryRun) { + Write-Host "$prompt$command [dry]" -ForegroundColor darkgray + } + else { + Write-Host "$prompt$command" -ForegroundColor white + Invoke-Expression $command + } +} + +#.description +# Reload-Path: Reload the Path environment variable +function Reload-Path { + Write-Output "Reloading Path..." + #* Courtesy of user [mpen](https://stackoverflow.com/users/65387/mpen) on [StackOverflow](https://stackoverflow.com/a/31845512) + $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") +} + + +# Check if Winget is available +if ( $NoWinget -or -not (Command-Available winget) ) { + Write-Warning "[ Warning ]: It looks like winget isn't available.`n" + Write-Host "Update 'App Installer' through the Microsoft Store, or grab the '.msixbundle' from the winget-cli repository:" + Write-Host "( https://github.com/microsoft/winget-cli/releases/latest )`n" -ForegroundColor White + exit +} + +# Check if the user ran the script with administrator privileges. +# Warn them. +if ( ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5-32-544') ) { + # If an administrator requests installation as administator, + # for example, to keep UAC prompts to a minimum, allow it. + if ($AllowAdministrator) { + # If you pass -AllowAdministrator -NoPrompt as an arg, you're very aware of the damage this script could do to your build env, and you just don't care + # The true chad of sysadmins. + if (!$NoPrompt) { + Write-Warning "Script was run as Administrator. Exit now if you didn't mean to do this!" + for ( $i = 3; $i -gt 0; $i--) { + Write-Host "Press Ctrl+C to exit. Continuing in $i...`r" -NoNewLine + sleep 1 + } + + Write-Host "Press any key to continue... " + [void][Console]::ReadKey(1) # Equivalent to Command Prompt's `pause` command + } + } else { + # Throw a fatal error if the user tries to run as administrator. + Throw "Script must be run as a normal user." + } +} + +# Import the packages from dependencies.json (autogenerated file, do not edit!) +Write-Host "`nInstalling packages with winget..." +Dry-Run 'winget import winget/dependencies.json' +# Reload the PATH, so we can use some of those sweet new commands we just installed +Reload-Path + +# Check whether everything is available now: +$error = 0 +if ( -not (Command-Available code) ) { + $error += 1; Write-Host -ForegroundColor red "Visual Studio Code not available" +} +if ( -not (Command-Available node) ) { + $error += 2; Write-Host -ForegroundColor red "NodeJS not available" +} +if ( -not (Command-Available npm ) ) { + $error += 4; Write-Host -ForegroundColor red "Node Package Manager not available"; +} +if ( $error ) { exit } + +# Check if electron-rebuild is installed, if not, install it +if ( ($Install) -or -not (Command-Available electron-rebuild) ) { + Write-Host "`nInstalling Electron-Rebuild..." + Dry-Run 'npm install -g electron-rebuild' + Reload-Path + if ( -not (Command-Available electron-rebuild)) { + Throw "electron-rebuild failed to install. Aborting." + } +} else { + Write-Host "`nElectron-Rebuild already installed." -ForegroundColor green +} + +# We're about to do some path traversal, so save the current directory +$prev_directory = $pwd + +# install NodeJS dependencies for this extension +Write-Host "`nInstalling NodeJS Dependencies..." +cd .. +Dry-Run 'npm install' + +# if we're on a known VSCode version, go ahead and run electron-rebuild +switch -Regex (code --version) { +<# "1\.6[7-9]\.[0-9]+" { + #?: Do we update this in the future, or stop maintaining it and remove this entire switch block? + } #> + "1\.66\.[0-9]+" { # 1.66 + Write-Host "`nRebuilding Electron for your version of VSCode..." + Dry-Run 'electron-rebuild --version="17.2.0"' + Write-Host "Done!" -ForegroundColor green + break + } + "\d+\.\d+\.\d+" { # Anything else + Write-Host "`nOpen Visual Studio Code, select the `"Help`" tab in the Toolbar, and go to `"About`".`nYou should see a page that looks like the following:" -ForegroundColor darkcyan + + Write-Host " `(i`) Visual Studio Code`n`n Version: 1.66.2 `(user setup`)`n Commit: [Commit ID]`n Date: 2022-04-11T07:46:01.075Z`n Electron: 17.2.0`n [ ... ]" -ForegroundColor White + + Write-Host "Note the Electron version `(17.2.0 in the above example`)." -ForegroundColor darkcyan + + Write-Host "Run the command " -NoNewLine + Write-Host "electron-rebuild --version ELECTRON_VERSION" -NoNewLine -ForegroundColor green + Write-Host " in Mind-Reader`'s root folder.`n" + break # Don't process the next items in the collection. + } + default { } # Leave blank +} + +# Return from whence we came +cd $prev_directory +if ( -not $NoPrompt ) { + Write-Host "Press any key to exit."; [void][Console]::ReadKey(1) +} \ No newline at end of file diff --git a/setup-development/winget/dependencies.json b/setup-development/winget/dependencies.json new file mode 100644 index 0000000..64780e6 --- /dev/null +++ b/setup-development/winget/dependencies.json @@ -0,0 +1,35 @@ +{ + "$schema": "https://aka.ms/winget-packages.schema.2.0.json", + "CreationDate": "2022-04-23T21:13:03.702-00:00", + "Sources": [ + { + "Packages": [ + { + "PackageIdentifier": "Microsoft.VisualStudio.2019.BuildTools" + }, + { + "PackageIdentifier": "Python.Python.3" + }, + { + "PackageIdentifier": "Git.Git" + }, + { + "PackageIdentifier": "OpenJS.NodeJS.LTS" + }, + { + "PackageIdentifier": "Microsoft.VisualStudioCode" + }, + { + "PackageIdentifier": "NVAccess.NVDA" + } + ], + "SourceDetails": { + "Argument": "https://winget.azureedge.net/cache", + "Identifier": "Microsoft.Winget.Source_8wekyb3d8bbwe", + "Name": "winget", + "Type": "Microsoft.PreIndexed.Package" + } + } + ], + "WinGetVersion": "1.2.10271" +} \ No newline at end of file From 3d9eac7350f97e07f87582a8a96567c658d47c18 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 26 Apr 2022 02:01:13 -0700 Subject: [PATCH 30/78] install: hotpatch Fixes Visual Studio Build Tools installation --- setup-development/install-windows.ps1 | 3 +++ setup-development/upgrade-windows.ps1 | 1 + setup-development/winget/dependencies.json | 3 --- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/setup-development/install-windows.ps1 b/setup-development/install-windows.ps1 index 9c646cd..06adda9 100644 --- a/setup-development/install-windows.ps1 +++ b/setup-development/install-windows.ps1 @@ -150,7 +150,10 @@ $dir = $pwd cd $GitDir Dry-Run "git clone 'https://github.com/We-Dont-Byte/Mind_Reader.git'" # TODO: Change this during merge onto main branch +cd Mind_reader Dry-Run "git checkout johnBreaux" +cd .. +# END TODO # Run the install script if ( -not (Test-Path "$SetupPath")) { diff --git a/setup-development/upgrade-windows.ps1 b/setup-development/upgrade-windows.ps1 index edc4d79..dbff3f3 100644 --- a/setup-development/upgrade-windows.ps1 +++ b/setup-development/upgrade-windows.ps1 @@ -122,6 +122,7 @@ if ( ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5 # Import the packages from dependencies.json (autogenerated file, do not edit!) Write-Host "`nInstalling packages with winget..." +Dry-Run 'winget install Microsoft.VisualStudio.2022.BuildTools --override "--wait --quiet --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"' Dry-Run 'winget import winget/dependencies.json' # Reload the PATH, so we can use some of those sweet new commands we just installed Reload-Path diff --git a/setup-development/winget/dependencies.json b/setup-development/winget/dependencies.json index 64780e6..ab7f2f6 100644 --- a/setup-development/winget/dependencies.json +++ b/setup-development/winget/dependencies.json @@ -4,9 +4,6 @@ "Sources": [ { "Packages": [ - { - "PackageIdentifier": "Microsoft.VisualStudio.2019.BuildTools" - }, { "PackageIdentifier": "Python.Python.3" }, From 40778b52fc9ee92d5cbdb02e3e66e8faedc36ed7 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 26 Apr 2022 02:19:14 -0700 Subject: [PATCH 31/78] Finish installation by opening VSCode --- setup-development/install-windows.ps1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/setup-development/install-windows.ps1 b/setup-development/install-windows.ps1 index 06adda9..6aba77d 100644 --- a/setup-development/install-windows.ps1 +++ b/setup-development/install-windows.ps1 @@ -165,6 +165,8 @@ $args = if ($AllowAdministrator) {" -AllowAdministrator"} else {""} $args += if ($DryRun) {" -DryRun"} else {""} PowerShell ("./upgrade-windows.ps1 -Install -NoPrompt" + $args) +# Open VSCode in the repository location +code . cd $dir if ( -not $NoPrompt ) { From 2948765ba8646137e78a36ed2e124ca606cd23c2 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 26 Apr 2022 02:41:15 -0700 Subject: [PATCH 32/78] Move install files to new directory Open VSCode in the new repo after installation --- setup-development/{ => windows}/install-windows.ps1 | 9 ++++++--- setup-development/{ => windows}/upgrade-windows.ps1 | 4 ++-- setup-development/{ => windows}/winget/dependencies.json | 0 3 files changed, 8 insertions(+), 5 deletions(-) rename setup-development/{ => windows}/install-windows.ps1 (96%) rename setup-development/{ => windows}/upgrade-windows.ps1 (98%) rename setup-development/{ => windows}/winget/dependencies.json (100%) diff --git a/setup-development/install-windows.ps1 b/setup-development/windows/install-windows.ps1 similarity index 96% rename from setup-development/install-windows.ps1 rename to setup-development/windows/install-windows.ps1 index 6aba77d..36bb44f 100644 --- a/setup-development/install-windows.ps1 +++ b/setup-development/windows/install-windows.ps1 @@ -56,7 +56,8 @@ param ( [switch]$DryRun # Run script without installing ) -$SetupPath = 'Mind_Reader/setup-development' +$RepoPath = "$GitDir\Mind_Reader" +$SetupPath = "$RepoPath\setup-development\windows" if ($h -or $Help) { Get-Help ./install-windows.ps1 @@ -166,9 +167,11 @@ $args += if ($DryRun) {" -DryRun"} else {""} PowerShell ("./upgrade-windows.ps1 -Install -NoPrompt" + $args) # Open VSCode in the repository location -code . +Write-Host "`nOpening Visual Studio Code" +cd $RepoPath +Dry-Run "code ." cd $dir if ( -not $NoPrompt ) { - Write-Host "Press any key to exit."; [void][Console]::ReadKey(1) + Write-Host "`nPress any key to exit."; [void][Console]::ReadKey(1) } \ No newline at end of file diff --git a/setup-development/upgrade-windows.ps1 b/setup-development/windows/upgrade-windows.ps1 similarity index 98% rename from setup-development/upgrade-windows.ps1 rename to setup-development/windows/upgrade-windows.ps1 index dbff3f3..e9cdd18 100644 --- a/setup-development/upgrade-windows.ps1 +++ b/setup-development/windows/upgrade-windows.ps1 @@ -157,7 +157,7 @@ $prev_directory = $pwd # install NodeJS dependencies for this extension Write-Host "`nInstalling NodeJS Dependencies..." -cd .. +cd ..\.. Dry-Run 'npm install' # if we're on a known VSCode version, go ahead and run electron-rebuild @@ -189,5 +189,5 @@ switch -Regex (code --version) { # Return from whence we came cd $prev_directory if ( -not $NoPrompt ) { - Write-Host "Press any key to exit."; [void][Console]::ReadKey(1) + Write-Host "`nPress any key to exit."; [void][Console]::ReadKey(1) } \ No newline at end of file diff --git a/setup-development/winget/dependencies.json b/setup-development/windows/winget/dependencies.json similarity index 100% rename from setup-development/winget/dependencies.json rename to setup-development/windows/winget/dependencies.json From 5a7fc30e4c250e305aab5aa2bc4feb3d2e5970f2 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 27 Apr 2022 11:55:01 -0500 Subject: [PATCH 33/78] Update package.json --- package.json | 46 ++++++++++++++++++---------------------------- 1 file changed, 18 insertions(+), 28 deletions(-) diff --git a/package.json b/package.json index 457e219..aecd638 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "mind-reader", "displayName": "Mind_Reader", - "repository": "https://github.com/SingleSemesterSnobs/Mind_Reader", + "repository": "https://github.com/We-Dont-Byte/Mind_Reader", "version": "1.0.0", "engines": { "vscode": "^1.60.0" @@ -14,8 +14,7 @@ ], "main": "./out/extension.js", "contributes": { - "commands": [ - { + "commands": [{ "command": "mind-reader.helloWorld", "title": "Hello World" }, @@ -96,8 +95,7 @@ "title": "Delete a program from the LEGO Hub" } ], - "keybindings": [ - { + "keybindings": [{ "command": "mind-reader.decreaseFontScale", "key": "numpad_subtract", "mac": "d" @@ -199,14 +197,11 @@ } ], "menus": { - "editor/context": [ - { - "submenu": "mind-reader.editor.context", - "group": "mind-reader" - } - ], - "mind-reader.editor.context": [ - { + "editor/context": [{ + "submenu": "mind-reader.editor.context", + "group": "mind-reader" + }], + "mind-reader.editor.context": [{ "command": "mind-reader.increaseEditorScale", "group": "mind-reader", "when": "activeEditor" @@ -258,12 +253,10 @@ } ] }, - "submenus": [ - { - "id": "mind-reader.editor.context", - "label": "Mind_Reader" - } - ], + "submenus": [{ + "id": "mind-reader.editor.context", + "label": "Mind_Reader" + }], "configuration": { "title": "Mind_Reader", "properties": { @@ -312,8 +305,7 @@ } }, "views": { - "MindReader": [ - { + "MindReader": [{ "id": "accessActions", "name": "Access Actions", "icon": "media/dep.svg", @@ -328,13 +320,11 @@ ] }, "viewsContainers": { - "activitybar": [ - { - "id": "MindReader", - "title": "MindReader Actions", - "icon": "media/dep.svg" - } - ] + "activitybar": [{ + "id": "MindReader", + "title": "MindReader Actions", + "icon": "media/dep.svg" + }] } }, "scripts": { From 0634a90f58f529e7c828666bf032507c6afaba1f Mon Sep 17 00:00:00 2001 From: John Date: Wed, 27 Apr 2022 11:55:09 -0500 Subject: [PATCH 34/78] Fix fresh install (Path was out of date) --- setup-development/windows/install-windows.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup-development/windows/install-windows.ps1 b/setup-development/windows/install-windows.ps1 index 36bb44f..9d391f0 100644 --- a/setup-development/windows/install-windows.ps1 +++ b/setup-development/windows/install-windows.ps1 @@ -64,7 +64,6 @@ if ($h -or $Help) { exit } - # .description # Command-Available: Checks whether a given command is available. # If command is available, returns $false @@ -165,6 +164,7 @@ cd $SetupPath $args = if ($AllowAdministrator) {" -AllowAdministrator"} else {""} $args += if ($DryRun) {" -DryRun"} else {""} PowerShell ("./upgrade-windows.ps1 -Install -NoPrompt" + $args) +Reload-Path # Open VSCode in the repository location Write-Host "`nOpening Visual Studio Code" From 7d615c0bca159d6a2570e7bfb55c582c8b437c1d Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 27 Apr 2022 11:58:14 -0500 Subject: [PATCH 35/78] Added linehighlighter.ts --- src/lineHighlighter.ts | 364 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 364 insertions(+) create mode 100644 src/lineHighlighter.ts diff --git a/src/lineHighlighter.ts b/src/lineHighlighter.ts new file mode 100644 index 0000000..9896a4e --- /dev/null +++ b/src/lineHighlighter.ts @@ -0,0 +1,364 @@ +/** +* ? ██╗ ██╗██╗ ██████╗ ██╗ ██╗██╗ ██╗ ██████╗ ██╗ ██╗████████╗ ██╗████████╗ +* ? ██║ ██║██║██╔════╝ ██║ ██║██║ ██║██╔════╝ ██║ ██║╚══██╔══╝ ██║╚══██╔══╝ +* ? ███████║██║██║ ███╗███████║██║ ██║██║ ███╗███████║ ██║ █████╗██║ ██║ +* ? ██╔══██║██║██║ ██║██╔══██║██║ ██║██║ ██║██╔══██║ ██║ ╚════╝██║ ██║ +* ? ██║ ██║██║╚██████╔╝██║ ██║███████╗██║╚██████╔╝██║ ██║ ██║ ██║ ██║ +* ? ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ +**/ +import { Position, window, workspace, TextEditorDecorationType, TextEditor, WorkspaceConfiguration, Range } from 'vscode'; + +export { lineHighlighter }; + +let highlightStyle: TextEditorDecorationType; + +function lineHighlighter(): void { + let highlightStyle : TextEditorDecorationType = getHighlighterStyle(); + let activeTextEditor : TextEditor | undefined = window.activeTextEditor; + let isEnabled : boolean | undefined = getHighlighterStatus(); + let multiLineIsEnabled: boolean | undefined = getMultiLineHighlighterStatus(); + + /** + * Trigger the line highlight when the extension + * loads so current line gets highlighted + */ + triggerHighlight(); + + /** + * Trigger for when the active text editor changes + */ + window.onDidChangeActiveTextEditor((editor) => { + if (!editor) { + return; + } + + triggerHighlight(); + }); + + /** + * Trigger for when text selection changes + */ + window.onDidChangeTextEditorSelection((editor) => { + if (!editor.textEditor) { + console.error(`[*] onDidChangeTextEditorSelection(${editor}) -> no active text editor`); + return; + } + + triggerHighlight(); + }); + + /** + * Trigger for when the text document changes + */ + workspace.onDidChangeTextDocument((editor) => { + if (!activeTextEditor) { + console.error(`[*] onDidChangeTextDocument(${editor}) -> no active text editor`); + return; + } + + triggerHighlight(); + }); + + /** + * Trigger for when the window state changes + */ + window.onDidChangeWindowState((editor) => { + if (!editor) { + return; + } + + triggerHighlight(); + }); + + /** + * Trigger for when configuration changes + */ + workspace.onDidChangeConfiguration((editor) => { + if (!editor) { + return; + } + + // Dump existing styling + highlightStyle.dispose(); + // check if line highlighter is enable/disabled + isEnabled = getHighlighterStatus(); + multiLineIsEnabled = getMultiLineHighlighterStatus(); + // get new line highlighter styling + highlightStyle = getHighlighterStyle(); + // trigger highlight with new styling + triggerHighlight(); + }); + + /** + * main function that triggers the highlights + */ + function triggerHighlight(): void { + if (!activeTextEditor) { + console.error("[*] NO Active Text Editor"); + return; + } + + /** + * Sets the activeTextEditor to the current active window + */ + activeTextEditor = window.activeTextEditor; + if (activeTextEditor !== undefined) { + /** + * If the line highlighter function is enabled + * set the decorations with our chosen highlighting style on the selection + * otherwise (highlighter is disabled) dump our highlighting style + */ + // (isEnabled) + // ? activeTextEditor!.setDecorations(highlightStyle, activeTextEditor!.selections) + // : highlightStyle.dispose(); + switch (isEnabled) { + case true: // isEnabled is true + switch (multiLineIsEnabled) { + case true: // isEnabled is true and multiLineIsEnabled is true + // const startLine = activeTextEditor!.selection.start; + // const endLine = activeTextEditor!.selection.end; + // const rangeToHighlight = { range: new Range(startLine, endLine) }; + // activeTextEditor!.setDecorations(highlightStyle, [rangeToHighlight]); + // const currentLineRange = activeTextEditor!.document.lineAt(activeTextEditor!.selection.anchor).range; + // activeTextEditor!.setDecorations(highlightStyle, [currentLineRange]); + // const startLine = activeTextEditor!.selection.start.line; + // const endLine = activeTextEditor!.selection.end; + // const rangeToHighlight = { range: new Range(startLine, endLine) }; + activeTextEditor.setDecorations(highlightStyle, activeTextEditor.selections); + break; + case false: // isEnabled is true and multiLineIsEnabled is false + switch (activeTextEditor.selection.isSingleLine) { + case true: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting a single line + let currentPosition = []; + for (let i = 0; i < activeTextEditor.selections.length; i++) { + currentPosition[i] = { range: new Range(activeTextEditor.selections[i].anchor, activeTextEditor.selections[i].anchor) }; + } + + activeTextEditor.setDecorations(highlightStyle, currentPosition); + // const currentLine = activeTextEditor.selection.active.line; + // const newDecoration = { range: new Range(currentPosition, currentPosition) }; + // const singleLineHighlight = { range: new Range(activeTextEditor!.selection.anchor.line, activeTextEditor!.selection.anchor.line) }; + // activeTextEditor!.setDecorations(highlightStyle, [singleLineRange]); + // activeTextEditor.setDecorations(highlightStyle, [activeTextEditor.selection]); + break; + case false: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting multiple lines + // Dispose of our highlighting style so multiple lines aren't all highlighted when clicking and dragging to highlight + // highlightStyle.dispose(); + activeTextEditor.setDecorations(highlightStyle, []); + // Since we disposed of our highlighting style, we need to re-acquire it for highlighting to continue to work after clicking and dragging to highlight + // highlightStyle = getHighlighterStyle(); + break; + default: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting something else - break out of 3rd switch + break; + } + break; + default: // isEnabled is true and multiLineIsEnabled is undetected - break out of 2nd switch statement + break; + } + break; + case false: // isEnabled is false + highlightStyle.dispose(); + break; + default: // break out of initial switch is true or false not found + break; + } + + // Track new position, without this the line the the cursor begins on will never get styled + new Position(activeTextEditor.selection.start.line, activeTextEditor.selection.start.character); + } + } + + /** + * Function to get the user configured highlighting styles, or use defaults + * + * Designed with user configuration in mind, able to control different sides + * independently from each other (in most cases). This allows for many different + * configurations. + * + * @returns highlighterStyle + */ + function getHighlighterStyle(): TextEditorDecorationType { + // Used so we don't have to type out workspace.getConfiguration('mind-reader.lineHighlight') on every line, ie: shorthand + const userConfig: WorkspaceConfiguration = workspace.getConfiguration('mind-reader.lineHighlight'); + + const borderWidthTop : string = userConfig.get('borderWidthTop') || "0"; + const borderWidthRight : string = userConfig.get('borderWidthRight') || "0"; + const borderWidthBottom : string = userConfig.get('borderWidthBottom') || "2px"; + const borderWidthLeft : string = userConfig.get('borderWidthLeft') || "0"; + + const borderStyleTop : string = userConfig.get('borderStyleTop') || "solid"; + const borderStyleRight : string = userConfig.get('borderStyleRight') || "solid"; + const borderStyleBottom : string = userConfig.get('borderStyleBottom') || "solid"; + const borderStyleLeft : string = userConfig.get('borderStyleLeft') || "solid"; + + const borderColorTop : string = userConfig.get('borderColorTop') || "#191970"; + const borderColorRight : string = userConfig.get('borderColorRight') || "#191970"; + const borderColorBottom : string = userConfig.get('borderColorBottom') || "#191970"; + const borderColorLeft : string = userConfig.get('borderColorLeft') || "#191970"; + + const backgroundColor : string = userConfig.get('backgroundColor') || "#00fa9a"; + + const fontStyle : string = userConfig.get('fontStyle') || "normal"; + const fontWeight : string = userConfig.get('fontWeight') || "normal"; + const outlineColor : string = userConfig.get('outlineColor') || "#191970"; + const outlineStyle : string = userConfig.get('outlineStyle') || "solid"; + const outlineWidth : string = userConfig.get('outlineWidth') || "0"; + const textDecoration : string = userConfig.get('textDecoration') || "normal"; + const textColor : string = userConfig.get('textColor') || "normal"; + + // Combine all our styling into a single variable to return + const highlighterStyle : TextEditorDecorationType = window.createTextEditorDecorationType({ + isWholeLine : true, + backgroundColor : `${backgroundColor}`, + fontStyle : `${fontStyle}`, + fontWeight : `${fontWeight}`, + textDecoration : `${textDecoration}`, + color : `${textColor}`, + borderColor : `${borderColorTop} ${borderColorRight} ${borderColorBottom} ${borderColorLeft}`, + borderWidth : `${borderWidthTop} ${borderWidthRight} ${borderWidthBottom} ${borderWidthLeft}`, + borderStyle : `${borderStyleTop} ${borderStyleRight} ${borderStyleBottom} ${borderStyleLeft}`, + outlineColor : `${outlineColor}`, + outlineWidth : `${outlineWidth}`, + outlineStyle : `${outlineStyle}`, + }); + + // Return our variable + return highlighterStyle; + } + + /** + * Function to retrieve the 'isEnabled' status + * + * This will determine if the line highlighter will display or not + * - enabled -> will show + * - disabled -> will not show + * + * @returns enabledStatus + */ + function getHighlighterStatus(): boolean | undefined { + // set a boolean variable + let enabledStatus: boolean | undefined; + + /*** + * if "isEnabled" is missing from the settings (aka undefined) + * - set our variable to true (default) + * otherwise, "isEnabled" is listed in the settings + * - so we just pull its value + */ + (workspace.getConfiguration("mind-reader.lineHighlight").get("isEnabled") === undefined) + ? (enabledStatus = true) + : (enabledStatus = workspace.getConfiguration("mind-reader.lineHighlight").get("isEnabled")); + + // return the enabledStatus + return enabledStatus; + } + + function getMultiLineHighlighterStatus(): boolean | undefined { + // set a boolean variable + let multiLineIsEnabled: boolean | undefined; + + /*** + * if "isEnabled" is missing from the settings (aka undefined) + * - set our variable to true (default) + * otherwise, "isEnabled" is listed in the settings + * - so we just pull its value + */ + (workspace.getConfiguration("mind-reader.lineHighlight").get("multiLineIsEnabled") === undefined) + ? (multiLineIsEnabled = true) + : (multiLineIsEnabled = workspace.getConfiguration("mind-reader.lineHighlight").get("multiLineIsEnabled")); + + // return the enabledStatus + return multiLineIsEnabled; + } +} + +// Clean-up after ourself +export function deactivate() { + // when the plugin is terminated remove all highlighting + if (highlightStyle !== undefined) { + highlightStyle.dispose(); + } +} + + /** + * Border Width Settings + * borderWidthTop = Top Border Width + * borderWidthRight = Right Border Width * Right border is a little finicky, I have all others at 1px, but need 15px for this one to match + * borderWidthBottom = Bottom Border Width + * borderWidthLeft = Left Border Width + * + * Uses CSS so should accept: + * thin | medium | thick + * px + * rem + * em + * cm + * % - Weird behavior + * inherit + * + * If no value is found in the settings, we set the value after the double pipes (||) instead + */ + + /** + * Border Style Settings + * borderStyleTop = Top Border Style + * borderStyleRight = Right Border Style + * borderStyleBottom = Bottom Border Style + * borderStyleLeft = Left Border Style + * + * Uses CSS so should accept: (Some of them I can't tell a difference, but they do something) + * none + * hidden + * dotted + * dashed + * solid + * double + * groove + * ridge + * inset + * outset + * + * If no value is found in the settings, we set the value after the double pipes (||) instead + */ + + /** + * Border Color Settings + * borderColorRight = Right Border Color + * borderColorBottom = Bottom Border Color + * borderColorTop = Top Border Color + * borderColorLeft = Left Border Color + * + * Uses CSS so should accept: (Some of them I can't tell a difference, but they do something) + * none - This one doesn't play nice + * string value like "red" | "blue" | "orange" etc - https://www.w3schools.com/cssref/css_colors.asp + * # + * rgb(###, ###, ###) + * rgba(###, ###, ###, ###) + * hsla(##, ##%, ##%, .#); + * inherit - This one has weird behavior as well + * + * If no value is found in the settings, we set the value after the double pipes (||) instead + */ + + /** + * Color of the background + * + * Uses CSS so should accept: + * none - This one doesn't play nice + * string value like "red" | "blue" | "orange" etc - https://www.w3schools.com/cssref/css_colors.asp + * # + * rgb(###, ###, ###) + * rgba(###, ###, ###, ###) + * hsla(##, ##%, ##%, .#); + * inherit - This one has weird behavior as well + * + * If no value is found in the settings, we set the value after the double pipes (||) instead + */ + + /** + * font-style: normal|italic|oblique|initial|inherit + */ + + /** + * font-weight: normal|bold|bolder|lighter|number|initial|inherit + */ \ No newline at end of file From 16869aa5b66cd24974cd67faaa42977f29065672 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 27 Apr 2022 11:59:16 -0500 Subject: [PATCH 36/78] Added linehighlighter added linehighlighter to be activated --- src/extension.ts | 47 ++++++++++++++++++++++------------------------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/src/extension.ts b/src/extension.ts index 5496408..2aa31e5 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,49 +1,46 @@ -import * as vscode from 'vscode'; -import * as pl from './pylex'; +import * as vscode from "vscode"; +import * as pl from "./pylex"; +import CommandNodeProvider from "./commandNodeProvider"; +import Logger from "./log"; +import { lineHighlighter } from "./lineHighlighter"; -import { - accessCommands, - hubCommands, - navCommands, - textCommands -} from './commands'; - -import CommandNodeProvider from './commandNodeProvider'; -import Logger from './log'; +import { accessCommands, hubCommands, navCommands, textCommands } from "./commands"; // Output Logger -const product: string = vscode.workspace.getConfiguration('mindReader').get('productType')!; -const outputChannel = vscode.window.createOutputChannel(product + " Output"); -export const logger = new Logger(outputChannel); +const product: string = vscode.workspace.getConfiguration("mindReader").get("productType")!; +const outputChannel = vscode.window.createOutputChannel(product + " Output"); +export const logger = new Logger(outputChannel); let parser: pl.Parser = new pl.Parser(); export function activate(context: vscode.ExtensionContext) { - vscode.window.showInformationMessage('Mind_Reader is loaded!'); + vscode.window.showInformationMessage("Mind_Reader is loaded!"); - parser.parse('Beep Boop'); + lineHighlighter(); + + parser.parse("Beep Boop"); const allCommands = [ accessCommands, hubCommands, navCommands, - textCommands + textCommands, ].flat(1); // Register Commands - allCommands.forEach(command => { - let disposable = vscode.commands.registerCommand( - command.name, - command.callback + allCommands.forEach((command) => { + context.subscriptions.push( + vscode.commands.registerCommand(command.name, command.callback) ); - context.subscriptions.push(disposable); }); - let accessProvider = new CommandNodeProvider([accessCommands, textCommands].flat(1)); - vscode.window.registerTreeDataProvider('accessActions', accessProvider); + let accessProvider = new CommandNodeProvider( + [accessCommands, textCommands].flat(1) + ); + vscode.window.registerTreeDataProvider("accessActions", accessProvider); let hubProvider = new CommandNodeProvider(hubCommands); - vscode.window.registerTreeDataProvider('hubActions', hubProvider); + vscode.window.registerTreeDataProvider("hubActions", hubProvider); } export function deactivate() {} From 5d3dc7acea95a7920f96d1e076ce731fcd503a32 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 27 Apr 2022 12:00:59 -0500 Subject: [PATCH 37/78] added new function added fetchNumberOfSelectedLines and getNumberOfSelectedLines --- src/commands/text.ts | 97 ++++++++++++++++++++++++++++++++------------ 1 file changed, 70 insertions(+), 27 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 8621a2a..7c0c122 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -16,6 +16,10 @@ export const textCommands: CommandEntry[] = [ name: 'mind-reader.getLeadingSpaces', callback: getLeadingSpaces, }, + { + name: 'mind-reader.getNumberOfSelectedLines', + callback: getNumberOfSelectedLines, + }, { name: 'mind-reader.runLineContext', callback: runLineContext, @@ -27,20 +31,54 @@ export const textCommands: CommandEntry[] = [ ]; /* Helper Function - * This function returns the line number of the active text editor window +* This function returns the number of selected lines in the active text editor window +*/ +function fetchNumberOfSelectedLines(editor: vscode.TextEditor | undefined): number { + let numberOfSelectedLines: number = 0; + + if (editor) { + numberOfSelectedLines = editor.selections.reduce((prev, curr) => prev + (curr.end.line - curr.start.line), 1); + } + + return numberOfSelectedLines; +} + +/* Helper Function +* This function returns the line number of the active text editor window */ function fetchLineNumber(editor: any): number { return editor.selection.active.line + 1; } /* Helper Function - * This function returns the text from the current line of the active text editor window - */ +* This function returns the text from the current line of the active text editor window +*/ function fetchTextLine(editor: any): string { return editor.document.lineAt(fetchLineNumber(editor) - 1); } -// Function that outputs the current line number the cursor is on +/** Function + * Function to return the number of selected (highlighted) lines + * Changes output to 'Line' for 1 line and 'Lines' for all other instances + */ +function getNumberOfSelectedLines(): void { + const editor: any = vscode.window.activeTextEditor; + + if (editor) { + const numberOfSelectedLines: number = fetchNumberOfSelectedLines(editor); + + (numberOfSelectedLines !== 1) + ? vscode.window.showInformationMessage(`${numberOfSelectedLines.toString()} Lines Selected`) + : vscode.window.showInformationMessage(`${numberOfSelectedLines.toString()} Line Selected`); + } + else { + vscode.window.showErrorMessage('No document currently active'); + } +} + +/** Function + * Outputs the current line number the cursor is on + */ function getLineNumber(): void { const editor: any = vscode.window.activeTextEditor; @@ -54,6 +92,9 @@ function getLineNumber(): void { } } +/** Function + * Used to get the number of indents on a line + */ function getIndent(): void { const editor: any = vscode.window.activeTextEditor; @@ -72,7 +113,9 @@ function getIndent(): void { }; const i: number = pl.Lexer.getIndent(textLine.text, tabFmt); - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`); + (i !== 1) + ? vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`) + : vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); } } else { @@ -100,8 +143,8 @@ function getLeadingSpaces(): void { const editor: any = vscode.window.activeTextEditor; if (editor) { - const lineNum: number = fetchLineNumber(editor); - const textLine: any = fetchTextLine(editor); + const lineNum : number = fetchLineNumber(editor); + const textLine: any = fetchTextLine(editor); if (textLine.isEmptyOrWhitespace) { vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); @@ -114,14 +157,14 @@ function getLeadingSpaces(): void { * default: false */ const calculateLeadingSpaces: boolean = false; // change boolean value to change method - const numSpaces: number = (calculateLeadingSpaces) ? - pl.Lexer.getLeadingSpacesByArithmetic(textLine) : - pl.Lexer.getLeadingSpacesByIndex(textLine); + const numSpaces: number = (calculateLeadingSpaces) + ? pl.Lexer.getLeadingSpacesByArithmetic(textLine) + : pl.Lexer.getLeadingSpacesByIndex(textLine); /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is 0 or greater than 1 */ - (numSpaces !== 1) ? - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`): - vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); + (numSpaces !== 1) + ? vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`) + : vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); } } else { @@ -134,13 +177,13 @@ function runLineContext(): void { if (editor) { // current text and line number - const editorText: string = editor.document.getText(); - const line: string = editor.selection.active.line; + const editorText: string = editor.document.getText(); + const line : string = editor.selection.active.line; // get tab info settings - const size: number = parseInt(editor.options.tabSize); - const hard: boolean = !editor.options.insertSpaces; + const size : number = parseInt(editor.options.tabSize); + const hard : boolean = !editor.options.insertSpaces; // initialize parser - const parser: any = new pl.Parser(editorText, { + const parser : any = new pl.Parser(editorText, { size, hard }); @@ -199,15 +242,15 @@ function runCursorContext(): void { return; } - const cursorPos: any = editor.selection.active; - const text: string = editor.document.lineAt(cursorPos).text; - const windowSize: any = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); - let trimmedText: string = text.trimStart(); // trim leading whitespace - const leadingWS: number = text.length - trimmedText.length; // # of characters of leading whitespace - let pos: number = leadingWS; - const maxPos: number = text.length; + const cursorPos : any = editor.selection.active; + const text : string = editor.document.lineAt(cursorPos).text; + const windowSize : any = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); + let trimmedText: string = text.trimStart(); // trim leading whitespace + const leadingWS : number = text.length - trimmedText.length; // # of characters of leading whitespace + let pos : number = leadingWS; + const maxPos : number = text.length; // clamp cursor start/end to new range - let col: number = cursorPos.character; // effective column of the cursor position + let col : number = cursorPos.character; // effective column of the cursor position trimmedText = trimmedText.trimEnd(); // trim trailing whitespace @@ -242,7 +285,7 @@ function runCursorContext(): void { // find word the user is in let contextStart: number = -1; - let contextEnd: number = -1; + let contextEnd : number = -1; for (let i: number = 0; i < spaceWords.length; i++) { if (col >= spaceWords[i].start && col <= spaceWords[i].end) { From dd10e928ef3d0e8464032f86b9eaf9379a67da7a Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 27 Apr 2022 12:01:44 -0500 Subject: [PATCH 38/78] updated webview --- src/commands/nav.ts | 170 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 140 insertions(+), 30 deletions(-) diff --git a/src/commands/nav.ts b/src/commands/nav.ts index f694e40..a9be064 100755 --- a/src/commands/nav.ts +++ b/src/commands/nav.ts @@ -1,24 +1,21 @@ -import * as vscode from 'vscode'; -import * as fs from 'fs'; +import * as vscode from "vscode"; +// import * as fs from "fs"; +// import * as os from 'os'; -import { CommandEntry } from './commandEntry'; +import { CommandEntry } from "./commandEntry"; export const navCommands: CommandEntry[] = [ { name: 'mind-reader.openWebview', callback: openWebview, }, - { - name: 'mind-reader.openKeyBindWin', - callback: () => openKeyBindWin('Windows') - }, - { - name: 'mind-reader.openKeyBindMac', - callback: () => openKeyBindWin('Mac'), + name: "mind-reader.openKeybinds", + callback: () => vscode.commands.executeCommand("workbench.action.openGlobalKeybindings", "mind-reader"), }, //Navigation Keys...... + // TODO: Why is this here? Extensions can rebind existing keybinds. { name: 'mind-reader.showAllSymbols', callback: () => vscode.commands.executeCommand('workbench.action.showAllSymbols'), @@ -82,35 +79,148 @@ export const navCommands: CommandEntry[] = [ // COMMAND CALLBACK IMPLEMENTATIONS function openWebview(): void { - //vscode.commands.executeCommand('workbench.action.zoomOut'); const panel = vscode.window.createWebviewPanel( - 'mindReader', // Identifies the type of the webview. Used internally - 'Mind Reader', // Title of the panel displayed to the user + "mindReader", // Identifies the type of the webview. Used internally + "Mind Reader", // Title of the panel displayed to the user vscode.ViewColumn.One, // Editor column to show the new webview panel in. {} ); // Webview options. More on these later. - panel.webview.html = getWebviewContent('media/html/main.html'); + panel.webview.html = getWebviewContent(); } -function getWebviewContent(filepath: string) { - return fs.readFileSync(filepath, {encoding: 'utf-8'}); +// function getWebviewContent(filepath: string) { +// return fs.readFileSync(filepath, {encoding: 'utf-8'}); +// } + +function getWebviewContent() { + return ` + + + + + Mind Reader + + + +

+

Welcome to Mind_Reader!

+

We are the Single Semester Snobs and this is our tool to Help Blind Students Program Lego Mindstorms Robots in Python.

+
    +
  • + This tool includes features such as a hotkey that says how many spaces in the text starts, an Accessibility Pane, + Audio Alerts, and an advanced settings window. +
    + The tool has hotkeys for both PC and Mac commands. +
  • +
  • This system is intended for everyone, but primarily for students K-12 who are visually impaired.
  • +
  • + Our goal is to provide an enhanced experience for students who are visually impaired that is transparent to + sighted students. +
    + This allows for everyone to use the same software solution, whether or not they are + vision impaired. +
  • +
+

Use the following key binding to bring up a page for all key bindings for windows +
+ Control and Shift and 8 +

+

Use this key binding to do the same for mac computers: +
+ Command and Shift and 9 +

+

This is the Lego Spike Prime! +

+ +

+ Get the robot! + + `; } -function openKeyBindWin(os: 'Mac' | 'Windows'): void { - //vscode.commands.executeCommand('workbench.action.zoomOut'); - const panel = vscode.window.createWebviewPanel( - 'mindReader', // Identifies the type of the webview. Used internally - 'MR Key Bindings', // Title of the panel displayed to the user - vscode.ViewColumn.One, // Editor column to show the new webview panel in. - {} - ); // Webview options. More on these later. +// export function getPlatform(): 'windows' | 'mac' | 'linux' | undefined { +// let platform: 'windows' | 'mac' | 'linux' | undefined; - if (os === 'Windows') { - panel.webview.html = getWebviewContent('media/html/winkeys.html'); - } else if (os === 'Mac') { - panel.webview.html = getWebviewContent('media/html/mackeys.html'); - } -} +// if (os.platform().toUpperCase() === 'WIN32') { +// platform = 'windows'; +// return platform; +// } +// if (os.platform().toUpperCase() === 'DARWIN') { +// platform = 'mac'; +// return platform; +// } +// if (os.platform().toUpperCase() === 'linux') { +// platform = 'linux'; +// return platform; +// } + +// platform = undefined; +// return platform; +// } + +// function getDocumentWorkspaceFolder(): string | undefined { +// const fileName = vscode.window.activeTextEditor?.document.fileName; +// return vscode.workspace.workspaceFolders +// ?.map((folder) => folder.uri.fsPath) +// .filter((fsPath) => fileName?.startsWith(fsPath))[0]; +// } + +// function openKeyBindWin(): void { +// //vscode.commands.executeCommand('workbench.action.zoomOut'); +// const panel = vscode.window.createWebviewPanel( +// 'mindReader', // Identifies the type of the webview. Used internally +// 'MR Key Bindings', // Title of the panel displayed to the user +// vscode.ViewColumn.One, // Editor column to show the new webview panel in. +// {} +// ); // Webview options. More on these later. + +// const userPlatform: 'windows' | 'mac' | 'linux' | undefined = getPlatform(); + +// switch (userPlatform) { +// case 'windows': +// if(vscode.workspace.workspaceFolders !== undefined) { +// let wf = vscode.workspace.workspaceFolders[0].uri.path; +// let f = vscode.workspace.workspaceFolders[0].uri.fsPath; +// const message = `YOUR-EXTENSION: folder: ${wf} - ${f}`; +// vscode.window.showInformationMessage(message); +// } +// else { +// const message = "YOUR-EXTENSION: Working folder not found, open a folder an try again" ; +// vscode.window.showErrorMessage(message); +// } +// // panel.webview.html = getWebviewContent('media/html/winkeys.html'); +// break; +// case 'mac': +// // panel.webview.html = getWebviewContent('media/html/mackeys.html'); +// break; +// case 'linux': +// // panel.webview.html = getWebviewContent('media/html/linuxkeys.html'); +// break; +// default: +// // panel.webview.html = getWebviewContent("../../media/html/main.html"); +// break; +// } +// } + +// function openKeyBindWin(os: 'Mac' | 'Windows'): void { +// //vscode.commands.executeCommand('workbench.action.zoomOut'); +// const panel = vscode.window.createWebviewPanel( +// 'mindReader', // Identifies the type of the webview. Used internally +// 'MR Key Bindings', // Title of the panel displayed to the user +// vscode.ViewColumn.One, // Editor column to show the new webview panel in. +// {} +// ); // Webview options. More on these later. + +// if (os === 'Windows') { +// panel.webview.html = getWebviewContent('WINDOWS'); +// // panel.webview.html = getWebviewContent('/media/html/winkeys.html'); +// } else if (os === 'Mac') { +// panel.webview.html = getWebviewContent('MAC'); +// // panel.webview.html = getWebviewContent('/media/html/mackeys.html'); +// } +// } + +//vscode.commands.executeCommand('workbench.action.openGlobalKeybindings'); From 34af00139656242c3f57981ccd9eedac0ed03733 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 27 Apr 2022 12:07:13 -0500 Subject: [PATCH 39/78] Deleted linehighlighter wrong version --- src/lineHighlighter.ts | 364 ----------------------------------------- 1 file changed, 364 deletions(-) delete mode 100644 src/lineHighlighter.ts diff --git a/src/lineHighlighter.ts b/src/lineHighlighter.ts deleted file mode 100644 index 9896a4e..0000000 --- a/src/lineHighlighter.ts +++ /dev/null @@ -1,364 +0,0 @@ -/** -* ? ██╗ ██╗██╗ ██████╗ ██╗ ██╗██╗ ██╗ ██████╗ ██╗ ██╗████████╗ ██╗████████╗ -* ? ██║ ██║██║██╔════╝ ██║ ██║██║ ██║██╔════╝ ██║ ██║╚══██╔══╝ ██║╚══██╔══╝ -* ? ███████║██║██║ ███╗███████║██║ ██║██║ ███╗███████║ ██║ █████╗██║ ██║ -* ? ██╔══██║██║██║ ██║██╔══██║██║ ██║██║ ██║██╔══██║ ██║ ╚════╝██║ ██║ -* ? ██║ ██║██║╚██████╔╝██║ ██║███████╗██║╚██████╔╝██║ ██║ ██║ ██║ ██║ -* ? ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ -**/ -import { Position, window, workspace, TextEditorDecorationType, TextEditor, WorkspaceConfiguration, Range } from 'vscode'; - -export { lineHighlighter }; - -let highlightStyle: TextEditorDecorationType; - -function lineHighlighter(): void { - let highlightStyle : TextEditorDecorationType = getHighlighterStyle(); - let activeTextEditor : TextEditor | undefined = window.activeTextEditor; - let isEnabled : boolean | undefined = getHighlighterStatus(); - let multiLineIsEnabled: boolean | undefined = getMultiLineHighlighterStatus(); - - /** - * Trigger the line highlight when the extension - * loads so current line gets highlighted - */ - triggerHighlight(); - - /** - * Trigger for when the active text editor changes - */ - window.onDidChangeActiveTextEditor((editor) => { - if (!editor) { - return; - } - - triggerHighlight(); - }); - - /** - * Trigger for when text selection changes - */ - window.onDidChangeTextEditorSelection((editor) => { - if (!editor.textEditor) { - console.error(`[*] onDidChangeTextEditorSelection(${editor}) -> no active text editor`); - return; - } - - triggerHighlight(); - }); - - /** - * Trigger for when the text document changes - */ - workspace.onDidChangeTextDocument((editor) => { - if (!activeTextEditor) { - console.error(`[*] onDidChangeTextDocument(${editor}) -> no active text editor`); - return; - } - - triggerHighlight(); - }); - - /** - * Trigger for when the window state changes - */ - window.onDidChangeWindowState((editor) => { - if (!editor) { - return; - } - - triggerHighlight(); - }); - - /** - * Trigger for when configuration changes - */ - workspace.onDidChangeConfiguration((editor) => { - if (!editor) { - return; - } - - // Dump existing styling - highlightStyle.dispose(); - // check if line highlighter is enable/disabled - isEnabled = getHighlighterStatus(); - multiLineIsEnabled = getMultiLineHighlighterStatus(); - // get new line highlighter styling - highlightStyle = getHighlighterStyle(); - // trigger highlight with new styling - triggerHighlight(); - }); - - /** - * main function that triggers the highlights - */ - function triggerHighlight(): void { - if (!activeTextEditor) { - console.error("[*] NO Active Text Editor"); - return; - } - - /** - * Sets the activeTextEditor to the current active window - */ - activeTextEditor = window.activeTextEditor; - if (activeTextEditor !== undefined) { - /** - * If the line highlighter function is enabled - * set the decorations with our chosen highlighting style on the selection - * otherwise (highlighter is disabled) dump our highlighting style - */ - // (isEnabled) - // ? activeTextEditor!.setDecorations(highlightStyle, activeTextEditor!.selections) - // : highlightStyle.dispose(); - switch (isEnabled) { - case true: // isEnabled is true - switch (multiLineIsEnabled) { - case true: // isEnabled is true and multiLineIsEnabled is true - // const startLine = activeTextEditor!.selection.start; - // const endLine = activeTextEditor!.selection.end; - // const rangeToHighlight = { range: new Range(startLine, endLine) }; - // activeTextEditor!.setDecorations(highlightStyle, [rangeToHighlight]); - // const currentLineRange = activeTextEditor!.document.lineAt(activeTextEditor!.selection.anchor).range; - // activeTextEditor!.setDecorations(highlightStyle, [currentLineRange]); - // const startLine = activeTextEditor!.selection.start.line; - // const endLine = activeTextEditor!.selection.end; - // const rangeToHighlight = { range: new Range(startLine, endLine) }; - activeTextEditor.setDecorations(highlightStyle, activeTextEditor.selections); - break; - case false: // isEnabled is true and multiLineIsEnabled is false - switch (activeTextEditor.selection.isSingleLine) { - case true: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting a single line - let currentPosition = []; - for (let i = 0; i < activeTextEditor.selections.length; i++) { - currentPosition[i] = { range: new Range(activeTextEditor.selections[i].anchor, activeTextEditor.selections[i].anchor) }; - } - - activeTextEditor.setDecorations(highlightStyle, currentPosition); - // const currentLine = activeTextEditor.selection.active.line; - // const newDecoration = { range: new Range(currentPosition, currentPosition) }; - // const singleLineHighlight = { range: new Range(activeTextEditor!.selection.anchor.line, activeTextEditor!.selection.anchor.line) }; - // activeTextEditor!.setDecorations(highlightStyle, [singleLineRange]); - // activeTextEditor.setDecorations(highlightStyle, [activeTextEditor.selection]); - break; - case false: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting multiple lines - // Dispose of our highlighting style so multiple lines aren't all highlighted when clicking and dragging to highlight - // highlightStyle.dispose(); - activeTextEditor.setDecorations(highlightStyle, []); - // Since we disposed of our highlighting style, we need to re-acquire it for highlighting to continue to work after clicking and dragging to highlight - // highlightStyle = getHighlighterStyle(); - break; - default: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting something else - break out of 3rd switch - break; - } - break; - default: // isEnabled is true and multiLineIsEnabled is undetected - break out of 2nd switch statement - break; - } - break; - case false: // isEnabled is false - highlightStyle.dispose(); - break; - default: // break out of initial switch is true or false not found - break; - } - - // Track new position, without this the line the the cursor begins on will never get styled - new Position(activeTextEditor.selection.start.line, activeTextEditor.selection.start.character); - } - } - - /** - * Function to get the user configured highlighting styles, or use defaults - * - * Designed with user configuration in mind, able to control different sides - * independently from each other (in most cases). This allows for many different - * configurations. - * - * @returns highlighterStyle - */ - function getHighlighterStyle(): TextEditorDecorationType { - // Used so we don't have to type out workspace.getConfiguration('mind-reader.lineHighlight') on every line, ie: shorthand - const userConfig: WorkspaceConfiguration = workspace.getConfiguration('mind-reader.lineHighlight'); - - const borderWidthTop : string = userConfig.get('borderWidthTop') || "0"; - const borderWidthRight : string = userConfig.get('borderWidthRight') || "0"; - const borderWidthBottom : string = userConfig.get('borderWidthBottom') || "2px"; - const borderWidthLeft : string = userConfig.get('borderWidthLeft') || "0"; - - const borderStyleTop : string = userConfig.get('borderStyleTop') || "solid"; - const borderStyleRight : string = userConfig.get('borderStyleRight') || "solid"; - const borderStyleBottom : string = userConfig.get('borderStyleBottom') || "solid"; - const borderStyleLeft : string = userConfig.get('borderStyleLeft') || "solid"; - - const borderColorTop : string = userConfig.get('borderColorTop') || "#191970"; - const borderColorRight : string = userConfig.get('borderColorRight') || "#191970"; - const borderColorBottom : string = userConfig.get('borderColorBottom') || "#191970"; - const borderColorLeft : string = userConfig.get('borderColorLeft') || "#191970"; - - const backgroundColor : string = userConfig.get('backgroundColor') || "#00fa9a"; - - const fontStyle : string = userConfig.get('fontStyle') || "normal"; - const fontWeight : string = userConfig.get('fontWeight') || "normal"; - const outlineColor : string = userConfig.get('outlineColor') || "#191970"; - const outlineStyle : string = userConfig.get('outlineStyle') || "solid"; - const outlineWidth : string = userConfig.get('outlineWidth') || "0"; - const textDecoration : string = userConfig.get('textDecoration') || "normal"; - const textColor : string = userConfig.get('textColor') || "normal"; - - // Combine all our styling into a single variable to return - const highlighterStyle : TextEditorDecorationType = window.createTextEditorDecorationType({ - isWholeLine : true, - backgroundColor : `${backgroundColor}`, - fontStyle : `${fontStyle}`, - fontWeight : `${fontWeight}`, - textDecoration : `${textDecoration}`, - color : `${textColor}`, - borderColor : `${borderColorTop} ${borderColorRight} ${borderColorBottom} ${borderColorLeft}`, - borderWidth : `${borderWidthTop} ${borderWidthRight} ${borderWidthBottom} ${borderWidthLeft}`, - borderStyle : `${borderStyleTop} ${borderStyleRight} ${borderStyleBottom} ${borderStyleLeft}`, - outlineColor : `${outlineColor}`, - outlineWidth : `${outlineWidth}`, - outlineStyle : `${outlineStyle}`, - }); - - // Return our variable - return highlighterStyle; - } - - /** - * Function to retrieve the 'isEnabled' status - * - * This will determine if the line highlighter will display or not - * - enabled -> will show - * - disabled -> will not show - * - * @returns enabledStatus - */ - function getHighlighterStatus(): boolean | undefined { - // set a boolean variable - let enabledStatus: boolean | undefined; - - /*** - * if "isEnabled" is missing from the settings (aka undefined) - * - set our variable to true (default) - * otherwise, "isEnabled" is listed in the settings - * - so we just pull its value - */ - (workspace.getConfiguration("mind-reader.lineHighlight").get("isEnabled") === undefined) - ? (enabledStatus = true) - : (enabledStatus = workspace.getConfiguration("mind-reader.lineHighlight").get("isEnabled")); - - // return the enabledStatus - return enabledStatus; - } - - function getMultiLineHighlighterStatus(): boolean | undefined { - // set a boolean variable - let multiLineIsEnabled: boolean | undefined; - - /*** - * if "isEnabled" is missing from the settings (aka undefined) - * - set our variable to true (default) - * otherwise, "isEnabled" is listed in the settings - * - so we just pull its value - */ - (workspace.getConfiguration("mind-reader.lineHighlight").get("multiLineIsEnabled") === undefined) - ? (multiLineIsEnabled = true) - : (multiLineIsEnabled = workspace.getConfiguration("mind-reader.lineHighlight").get("multiLineIsEnabled")); - - // return the enabledStatus - return multiLineIsEnabled; - } -} - -// Clean-up after ourself -export function deactivate() { - // when the plugin is terminated remove all highlighting - if (highlightStyle !== undefined) { - highlightStyle.dispose(); - } -} - - /** - * Border Width Settings - * borderWidthTop = Top Border Width - * borderWidthRight = Right Border Width * Right border is a little finicky, I have all others at 1px, but need 15px for this one to match - * borderWidthBottom = Bottom Border Width - * borderWidthLeft = Left Border Width - * - * Uses CSS so should accept: - * thin | medium | thick - * px - * rem - * em - * cm - * % - Weird behavior - * inherit - * - * If no value is found in the settings, we set the value after the double pipes (||) instead - */ - - /** - * Border Style Settings - * borderStyleTop = Top Border Style - * borderStyleRight = Right Border Style - * borderStyleBottom = Bottom Border Style - * borderStyleLeft = Left Border Style - * - * Uses CSS so should accept: (Some of them I can't tell a difference, but they do something) - * none - * hidden - * dotted - * dashed - * solid - * double - * groove - * ridge - * inset - * outset - * - * If no value is found in the settings, we set the value after the double pipes (||) instead - */ - - /** - * Border Color Settings - * borderColorRight = Right Border Color - * borderColorBottom = Bottom Border Color - * borderColorTop = Top Border Color - * borderColorLeft = Left Border Color - * - * Uses CSS so should accept: (Some of them I can't tell a difference, but they do something) - * none - This one doesn't play nice - * string value like "red" | "blue" | "orange" etc - https://www.w3schools.com/cssref/css_colors.asp - * # - * rgb(###, ###, ###) - * rgba(###, ###, ###, ###) - * hsla(##, ##%, ##%, .#); - * inherit - This one has weird behavior as well - * - * If no value is found in the settings, we set the value after the double pipes (||) instead - */ - - /** - * Color of the background - * - * Uses CSS so should accept: - * none - This one doesn't play nice - * string value like "red" | "blue" | "orange" etc - https://www.w3schools.com/cssref/css_colors.asp - * # - * rgb(###, ###, ###) - * rgba(###, ###, ###, ###) - * hsla(##, ##%, ##%, .#); - * inherit - This one has weird behavior as well - * - * If no value is found in the settings, we set the value after the double pipes (||) instead - */ - - /** - * font-style: normal|italic|oblique|initial|inherit - */ - - /** - * font-weight: normal|bold|bolder|lighter|number|initial|inherit - */ \ No newline at end of file From 2bbc5bce1fc4f6ad60b252623bd1292f328a098b Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 27 Apr 2022 12:07:33 -0500 Subject: [PATCH 40/78] Added lineHighlighter.ts --- src/lineHighlighter.ts | 364 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 364 insertions(+) create mode 100644 src/lineHighlighter.ts diff --git a/src/lineHighlighter.ts b/src/lineHighlighter.ts new file mode 100644 index 0000000..90ad27e --- /dev/null +++ b/src/lineHighlighter.ts @@ -0,0 +1,364 @@ +/** +* ? ██╗ ██╗██╗ ██████╗ ██╗ ██╗██╗ ██╗ ██████╗ ██╗ ██╗████████╗ ██╗████████╗ +* ? ██║ ██║██║██╔════╝ ██║ ██║██║ ██║██╔════╝ ██║ ██║╚══██╔══╝ ██║╚══██╔══╝ +* ? ███████║██║██║ ███╗███████║██║ ██║██║ ███╗███████║ ██║ █████╗██║ ██║ +* ? ██╔══██║██║██║ ██║██╔══██║██║ ██║██║ ██║██╔══██║ ██║ ╚════╝██║ ██║ +* ? ██║ ██║██║╚██████╔╝██║ ██║███████╗██║╚██████╔╝██║ ██║ ██║ ██║ ██║ +* ? ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ +**/ +import { Position, window, workspace, TextEditorDecorationType, TextEditor, WorkspaceConfiguration, Range } from 'vscode'; + +export { lineHighlighter }; + +let highlightStyle: TextEditorDecorationType; + +function lineHighlighter(): void { + let highlightStyle : TextEditorDecorationType = getHighlighterStyle(); + let activeTextEditor : TextEditor | undefined = window.activeTextEditor; + let isEnabled : boolean | undefined = getHighlighterStatus(); + let multiLineIsEnabled: boolean | undefined = getMultiLineHighlighterStatus(); + + /** + * Trigger the line highlight when the extension + * loads so current line gets highlighted + */ + triggerHighlight(); + + /** + * Trigger for when the active text editor changes + */ + window.onDidChangeActiveTextEditor((editor) => { + if (!editor) { + return; + } + + triggerHighlight(); + }); + + /** + * Trigger for when text selection changes + */ + window.onDidChangeTextEditorSelection((editor) => { + if (!editor.textEditor) { + console.error(`[*] onDidChangeTextEditorSelection(${editor}) -> no active text editor`); + return; + } + + triggerHighlight(); + }); + + /** + * Trigger for when the text document changes + */ + workspace.onDidChangeTextDocument((editor) => { + if (!activeTextEditor) { + console.error(`[*] onDidChangeTextDocument(${editor}) -> no active text editor`); + return; + } + + triggerHighlight(); + }); + + /** + * Trigger for when the window state changes + */ + window.onDidChangeWindowState((editor) => { + if (!editor) { + return; + } + + triggerHighlight(); + }); + + /** + * Trigger for when configuration changes + */ + workspace.onDidChangeConfiguration((editor) => { + if (!editor) { + return; + } + + // Dump existing styling + highlightStyle.dispose(); + // check if line highlighter is enable/disabled + isEnabled = getHighlighterStatus(); + multiLineIsEnabled = getMultiLineHighlighterStatus(); + // get new line highlighter styling + highlightStyle = getHighlighterStyle(); + // trigger highlight with new styling + triggerHighlight(); + }); + + /** + * main function that triggers the highlights + */ + function triggerHighlight(): void { + if (!activeTextEditor) { + console.error("[*] NO Active Text Editor"); + return; + } + + /** + * Sets the activeTextEditor to the current active window + */ + activeTextEditor = window.activeTextEditor; + if (activeTextEditor !== undefined) { + /** + * If the line highlighter function is enabled + * set the decorations with our chosen highlighting style on the selection + * otherwise (highlighter is disabled) dump our highlighting style + */ + // (isEnabled) + // ? activeTextEditor!.setDecorations(highlightStyle, activeTextEditor!.selections) + // : highlightStyle.dispose(); + switch (isEnabled) { + case true: // isEnabled is true + switch (multiLineIsEnabled) { + case true: // isEnabled is true and multiLineIsEnabled is true + // const startLine = activeTextEditor!.selection.start; + // const endLine = activeTextEditor!.selection.end; + // const rangeToHighlight = { range: new Range(startLine, endLine) }; + // activeTextEditor!.setDecorations(highlightStyle, [rangeToHighlight]); + // const currentLineRange = activeTextEditor!.document.lineAt(activeTextEditor!.selection.anchor).range; + // activeTextEditor!.setDecorations(highlightStyle, [currentLineRange]); + // const startLine = activeTextEditor!.selection.start.line; + // const endLine = activeTextEditor!.selection.end; + // const rangeToHighlight = { range: new Range(startLine, endLine) }; + activeTextEditor.setDecorations(highlightStyle, activeTextEditor.selections); + break; + case false: // isEnabled is true and multiLineIsEnabled is false + switch (activeTextEditor.selection.isSingleLine) { + case true: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting a single line + let currentPosition = []; + for (let i = 0; i < activeTextEditor.selections.length; i++) { + currentPosition[i] = { range: new Range(activeTextEditor.selections[i].anchor, activeTextEditor.selections[i].anchor) }; + } + + activeTextEditor.setDecorations(highlightStyle, currentPosition); + // const currentLine = activeTextEditor.selection.active.line; + // const newDecoration = { range: new Range(currentPosition, currentPosition) }; + // const singleLineHighlight = { range: new Range(activeTextEditor!.selection.anchor.line, activeTextEditor!.selection.anchor.line) }; + // activeTextEditor!.setDecorations(highlightStyle, [singleLineRange]); + // activeTextEditor.setDecorations(highlightStyle, [activeTextEditor.selection]); + break; + case false: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting multiple lines + // Dispose of our highlighting style so multiple lines aren't all highlighted when clicking and dragging to highlight + // highlightStyle.dispose(); + activeTextEditor.setDecorations(highlightStyle, []); + // Since we disposed of our highlighting style, we need to re-acquire it for highlighting to continue to work after clicking and dragging to highlight + // highlightStyle = getHighlighterStyle(); + break; + default: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting something else - break out of 3rd switch + break; + } + break; + default: // isEnabled is true and multiLineIsEnabled is undetected - break out of 2nd switch statement + break; + } + break; + case false: // isEnabled is false + highlightStyle.dispose(); + break; + default: // break out of initial switch is true or false not found + break; + } + + // Track new position, without this the line the the cursor begins on will never get styled + new Position(activeTextEditor.selection.start.line, activeTextEditor.selection.start.character); + } + } + + /** + * Function to get the user configured highlighting styles, or use defaults + * + * Designed with user configuration in mind, able to control different sides + * independently from each other (in most cases). This allows for many different + * configurations. + * + * @returns highlighterStyle + */ + function getHighlighterStyle(): TextEditorDecorationType { + // Used so we don't have to type out workspace.getConfiguration('mind-reader.lineHighlight') on every line, ie: shorthand + const userConfig: WorkspaceConfiguration = workspace.getConfiguration('mind-reader.lineHighlight'); + + const borderWidthTop : string = userConfig.get('borderWidthTop') || "1px"; + const borderWidthRight : string = userConfig.get('borderWidthRight') || "16px"; + const borderWidthBottom : string = userConfig.get('borderWidthBottom') || "1px"; + const borderWidthLeft : string = userConfig.get('borderWidthLeft') || "1px"; + + const borderStyleTop : string = userConfig.get('borderStyleTop') || "solid"; + const borderStyleRight : string = userConfig.get('borderStyleRight') || "solid"; + const borderStyleBottom : string = userConfig.get('borderStyleBottom') || "solid"; + const borderStyleLeft : string = userConfig.get('borderStyleLeft') || "solid"; + + const borderColorTop : string = userConfig.get('borderColorTop') || "#FFFFFF"; + const borderColorRight : string = userConfig.get('borderColorRight') || "#FFFFFF"; + const borderColorBottom : string = userConfig.get('borderColorBottom') || "#FFFFFF"; + const borderColorLeft : string = userConfig.get('borderColorLeft') || "#FFFFFF"; + + const backgroundColor : string = userConfig.get('backgroundColor') || "#232C5C"; + + const fontStyle : string = userConfig.get('fontStyle') || "normal"; + const fontWeight : string = userConfig.get('fontWeight') || "bolder"; + const outlineColor : string = userConfig.get('outlineColor') || "#4866FE"; + const outlineStyle : string = userConfig.get('outlineStyle') || "solid"; + const outlineWidth : string = userConfig.get('outlineWidth') || "1px"; + const textDecoration : string = userConfig.get('textDecoration') || "none"; + const textColor : string = userConfig.get('textColor') || "#FFFFFF"; + + // Combine all our styling into a single variable to return + const highlighterStyle : TextEditorDecorationType = window.createTextEditorDecorationType({ + isWholeLine : true, + backgroundColor : `${backgroundColor}`, + fontStyle : `${fontStyle}`, + fontWeight : `${fontWeight}`, + textDecoration : `${textDecoration}`, + color : `${textColor}`, + borderColor : `${borderColorTop} ${borderColorRight} ${borderColorBottom} ${borderColorLeft}`, + borderWidth : `${borderWidthTop} ${borderWidthRight} ${borderWidthBottom} ${borderWidthLeft}`, + borderStyle : `${borderStyleTop} ${borderStyleRight} ${borderStyleBottom} ${borderStyleLeft}`, + outlineColor : `${outlineColor}`, + outlineWidth : `${outlineWidth}`, + outlineStyle : `${outlineStyle}`, + }); + + // Return our variable + return highlighterStyle; + } + + /** + * Function to retrieve the 'isEnabled' status + * + * This will determine if the line highlighter will display or not + * - enabled -> will show + * - disabled -> will not show + * + * @returns enabledStatus + */ + function getHighlighterStatus(): boolean | undefined { + // set a boolean variable + let enabledStatus: boolean | undefined; + + /*** + * if "isEnabled" is missing from the settings (aka undefined) + * - set our variable to true (default) + * otherwise, "isEnabled" is listed in the settings + * - so we just pull its value + */ + (workspace.getConfiguration("mind-reader.lineHighlight").get("isEnabled") === undefined) + ? (enabledStatus = true) + : (enabledStatus = workspace.getConfiguration("mind-reader.lineHighlight").get("isEnabled")); + + // return the enabledStatus + return enabledStatus; + } + + function getMultiLineHighlighterStatus(): boolean | undefined { + // set a boolean variable + let multiLineIsEnabled: boolean | undefined; + + /*** + * if "isEnabled" is missing from the settings (aka undefined) + * - set our variable to true (default) + * otherwise, "isEnabled" is listed in the settings + * - so we just pull its value + */ + (workspace.getConfiguration("mind-reader.lineHighlight").get("multiLineIsEnabled") === undefined) + ? (multiLineIsEnabled = true) + : (multiLineIsEnabled = workspace.getConfiguration("mind-reader.lineHighlight").get("multiLineIsEnabled")); + + // return the enabledStatus + return multiLineIsEnabled; + } +} + +// Clean-up after ourself +export function deactivate() { + // when the plugin is terminated remove all highlighting + if (highlightStyle !== undefined) { + highlightStyle.dispose(); + } +} + + /** + * Border Width Settings + * borderWidthTop = Top Border Width + * borderWidthRight = Right Border Width * Right border is a little finicky, I have all others at 1px, but need 15px for this one to match + * borderWidthBottom = Bottom Border Width + * borderWidthLeft = Left Border Width + * + * Uses CSS so should accept: + * thin | medium | thick + * px + * rem + * em + * cm + * % - Weird behavior + * inherit + * + * If no value is found in the settings, we set the value after the double pipes (||) instead + */ + + /** + * Border Style Settings + * borderStyleTop = Top Border Style + * borderStyleRight = Right Border Style + * borderStyleBottom = Bottom Border Style + * borderStyleLeft = Left Border Style + * + * Uses CSS so should accept: (Some of them I can't tell a difference, but they do something) + * none + * hidden + * dotted + * dashed + * solid + * double + * groove + * ridge + * inset + * outset + * + * If no value is found in the settings, we set the value after the double pipes (||) instead + */ + + /** + * Border Color Settings + * borderColorRight = Right Border Color + * borderColorBottom = Bottom Border Color + * borderColorTop = Top Border Color + * borderColorLeft = Left Border Color + * + * Uses CSS so should accept: (Some of them I can't tell a difference, but they do something) + * none - This one doesn't play nice + * string value like "red" | "blue" | "orange" etc - https://www.w3schools.com/cssref/css_colors.asp + * # + * rgb(###, ###, ###) + * rgba(###, ###, ###, ###) + * hsla(##, ##%, ##%, .#); + * inherit - This one has weird behavior as well + * + * If no value is found in the settings, we set the value after the double pipes (||) instead + */ + + /** + * Color of the background + * + * Uses CSS so should accept: + * none - This one doesn't play nice + * string value like "red" | "blue" | "orange" etc - https://www.w3schools.com/cssref/css_colors.asp + * # + * rgb(###, ###, ###) + * rgba(###, ###, ###, ###) + * hsla(##, ##%, ##%, .#); + * inherit - This one has weird behavior as well + * + * If no value is found in the settings, we set the value after the double pipes (||) instead + */ + + /** + * font-style: normal|italic|oblique|initial|inherit + */ + + /** + * font-weight: normal|bold|bolder|lighter|number|initial|inherit + */ \ No newline at end of file From e8afacef18cd43ba05d83d18ccad74346f2c3d70 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 28 Apr 2022 17:30:55 -0500 Subject: [PATCH 41/78] Install scripts: - Windows: - install: Move repo URI into variable Remove -NoWinget check (was unused) - upgrade: Change -NoWinget to disable updating with winget (can take a while) Create function to check install of node packages which are put on Path. - Linux: - Install: Port install-windows to some linux distros Support for Apt (Ubuntu, possibly Debian/Mint) Support for Pacman (Arch/Manjaro/Garuda) - Upgrade: Port upgrade-windows to some linux distros --- setup-development/linux/install-linux.sh | 60 +++++++++++ .../linux/package-managers/apt.dependencies | 4 + .../package-managers/pacman.dependencies | 5 + setup-development/linux/upgrade-linux.sh | 100 ++++++++++++++++++ setup-development/windows/install-windows.ps1 | 12 ++- setup-development/windows/upgrade-windows.ps1 | 56 ++++++---- 6 files changed, 214 insertions(+), 23 deletions(-) create mode 100644 setup-development/linux/install-linux.sh create mode 100644 setup-development/linux/package-managers/apt.dependencies create mode 100644 setup-development/linux/package-managers/pacman.dependencies create mode 100644 setup-development/linux/upgrade-linux.sh diff --git a/setup-development/linux/install-linux.sh b/setup-development/linux/install-linux.sh new file mode 100644 index 0000000..ea6590d --- /dev/null +++ b/setup-development/linux/install-linux.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +#* linux-install.sh: First-run setup script +#* Ensures git is installed, clones the repo, and then runs + +export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' +ELEVATE='';if (( $UID != 0 )); then ELEVATE='sudo';fi + +help () { + echo "Usage: $0 [-g path/to/git/directory]" + exit 0 +} + + +GITDIR = "~/git" + +# Get option flags: +dry=false +while getopts ghd arg; do + case $arg in + g) GITDIR="$OPTARG";; + h) help;; + d) dry=true;; + esac +done + +function dryrun { + if $dry; then + echo "> $* [dry]"; + else + echo "> $*" + $@ +} + +SETUPDIR= "Mind_Reader/setup-development" +REPOURI = "https://github.com/We-Dont-Byte/Mind_Reader.git" + +# Install git +if which git; then + echo "Git already installed." +elif which pacman; then + # using pacman + dryrun $ELEVATE pacman -Sy git +elif which apt; then + # using apt + dryrun $ELEVATE apt-get update && \ + dryrun $ELEVATE apt-get install git -y +fi #? TODO: other package managers? + +echo Cloning repository into "$GITDIR" +dryrun mkdir "$GITDIR" +cd $GITDIR && git clone "$REPOURI" + +# TODO: remove this when merging! + cd Mind_Reader + dryrun git checkout origin/johnBreaux +# TODO: remove this when merging! + +cd "$GITDIR/$SETUPDIR" +bash ./linux-update.sh \ No newline at end of file diff --git a/setup-development/linux/package-managers/apt.dependencies b/setup-development/linux/package-managers/apt.dependencies new file mode 100644 index 0000000..05070de --- /dev/null +++ b/setup-development/linux/package-managers/apt.dependencies @@ -0,0 +1,4 @@ +apt-transport-https +build-essential +python3 +wget diff --git a/setup-development/linux/package-managers/pacman.dependencies b/setup-development/linux/package-managers/pacman.dependencies new file mode 100644 index 0000000..89859bb --- /dev/null +++ b/setup-development/linux/package-managers/pacman.dependencies @@ -0,0 +1,5 @@ +base-devel +code +git +nvm +python3 diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh new file mode 100644 index 0000000..1246b6e --- /dev/null +++ b/setup-development/linux/upgrade-linux.sh @@ -0,0 +1,100 @@ +#!/bin/bash + +#* linux-update.sh: Install and update dependencies of Mind_Reader, on linux. +#* Heads-up, this expects to be run from Mind_Reader/setup-development/linux. + + +# If run with bash -vx, print useful information instead of just a + sign +export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' +# If run as root, it could be because sudo isn't installed (some people disagree with sudo, especially on Arch) +ELEVATE='';if (( $UID != 0 )); then;ELEVATE='sudo';fi + +# Get option flags: +dry=false +while getopts d arg; do + case $arg in + d) dry=true;; + esac +done + +function dryrun { + if $dry; then + echo "> $* [dry]"; + else + echo "> $*" + $@ +} + +# Set these variables if you need to install for a different architecture +# Valid architectures are "x64", "arm64", "armhf" +arch="" +case (uname -i) in + "x86_64") arch="x64";; + "armv[6-8]*") arch="armhf";; + "aarch64") arch="arm64";; + *) echo "Architecture '$(uname -i)' unknown. Assuming x86_64..." + arch="x64";; +esac + +if which pacman; then + # Install dependencies with pacman + dryrun $ELEVATE pacman -S - < package-managers/pacman.dependencies +elif which apt-get; then + # Install dependencies using apt-get + dryrun xargs -a ./package-managers/apt.dependencies $ELEVATE apt-get install -y + + # Install Node Version Manager (nvm) + # TODO: Find a better way to install nvm on Ubuntu, the official NodeJS for <20.04 is so out of date it's unsupported. + dryrun curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash + + # Check if vscode exists, if not, install it. + # Microsoft doesn't put it in any Ubuntu repos, you have to get it straight from them. + # This does have the side effect, however, of installing the official repository + if !(which code); then + #* Install VSCode + vscodepackagename="code_amd64.deb" + dryrun wget "https://code.visualstudio.com/sha/download?build=stable&os=linux-deb-$arch" -O ./code.deb + dryrun $ELEVATE apt install ./code.deb + dryrun rm ./code.deb + fi +fi + +cdir=$(pwd) +# Go back to source tree root +cd ../.. + +# Check the VSCode version +nodeversion="node" +electronversion = "" +#* Note: +#* When adding support for new VSCode versions, update this case +#* By the time you're working on this project, things are likely going to differ! +case (code --version) in + #* Each version of VSCode has a corresponding Electron version and Node version + #* These are used when + 1.66.*) electronversion = "17.2.0"; nodeversion = "16.13.0";; + *) ;; +esac + +# Install NodeJS and npm +dryrun nvm install "$nodeversion" +dryrun nvm use "$nodeversion" + +# Use npm to install electron-rebuild and yo +dryrun npm install electron-rebuild yo generator-code + +# use npm to acquire dependencies for Mind-Reader +dryrun npm install + +# Use electron-rebuild to rebuild electron +if (( electronversion != "" )); then + dryrun electron-rebuild --version $electronversion +else + printf "%s/n%s/n%s/n%s/n" \ + "Open Visual Studio Code, select the 'Help' tab in the toolbar, and go to 'About'." \ + "Find the line that says 'Electron: [electron version]'" \ + "Run the command below, filling in the Electron version with the one from that menu:" \ + "electron-rebuild --version [electron version]" +fi + +cd $cdir \ No newline at end of file diff --git a/setup-development/windows/install-windows.ps1 b/setup-development/windows/install-windows.ps1 index 9d391f0..ac864db 100644 --- a/setup-development/windows/install-windows.ps1 +++ b/setup-development/windows/install-windows.ps1 @@ -56,6 +56,7 @@ param ( [switch]$DryRun # Run script without installing ) +$RepoURI = "https://github.com/We-Dont-Byte/Mind_Reader.git" $RepoPath = "$GitDir\Mind_Reader" $SetupPath = "$RepoPath\setup-development\windows" @@ -98,8 +99,8 @@ function Reload-Path { # Check if Winget is available -if ( $NoWinget -or -not (Command-Available winget) ) { - Write-Warning "[ Warning ]: It looks like winget isn't available.`n" +if ( -not (Command-Available winget) ) { + Write-Warning "It looks like winget isn't available.`n" Write-Host "Update 'App Installer' through the Microsoft Store, or grab the '.msixbundle' from the winget-cli repository:" Write-Host "( https://github.com/microsoft/winget-cli/releases/latest )`n" -ForegroundColor White exit @@ -148,12 +149,13 @@ if ( -not (Test-Path "$GitDir") ) { # Clone the repository in GitDir $dir = $pwd cd $GitDir -Dry-Run "git clone 'https://github.com/We-Dont-Byte/Mind_Reader.git'" -# TODO: Change this during merge onto main branch +Dry-Run "git clone '$RepoURI'" + +# TODO: Remove this when merging cd Mind_reader Dry-Run "git checkout johnBreaux" cd .. -# END TODO +# TODO: Remove this when merging # Run the install script if ( -not (Test-Path "$SetupPath")) { diff --git a/setup-development/windows/upgrade-windows.ps1 b/setup-development/windows/upgrade-windows.ps1 index e9cdd18..809a5fe 100644 --- a/setup-development/windows/upgrade-windows.ps1 +++ b/setup-development/windows/upgrade-windows.ps1 @@ -52,7 +52,7 @@ param ( [switch]$NoPrompt, # Disable the 3-second wait and press-any-key prompt [switch]$Install, # Perform all installations, even when commands are present [switch]$DryRun, # Run script without installing - [switch]$NoWinget # Pretend Winget doesn't exist + [switch]$NoWinget # Don't update dependdencies with winget ) # .description @@ -89,8 +89,8 @@ function Reload-Path { # Check if Winget is available -if ( $NoWinget -or -not (Command-Available winget) ) { - Write-Warning "[ Warning ]: It looks like winget isn't available.`n" +if ( -not (Command-Available winget) ) { + Write-Warning "It looks like winget isn't available.`n" Write-Host "Update 'App Installer' through the Microsoft Store, or grab the '.msixbundle' from the winget-cli repository:" Write-Host "( https://github.com/microsoft/winget-cli/releases/latest )`n" -ForegroundColor White exit @@ -121,11 +121,13 @@ if ( ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5 } # Import the packages from dependencies.json (autogenerated file, do not edit!) -Write-Host "`nInstalling packages with winget..." -Dry-Run 'winget install Microsoft.VisualStudio.2022.BuildTools --override "--wait --quiet --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"' -Dry-Run 'winget import winget/dependencies.json' -# Reload the PATH, so we can use some of those sweet new commands we just installed -Reload-Path +if ( -not $NoWinget) { + Write-Host "`nInstalling packages with winget..." + Dry-Run 'winget install Microsoft.VisualStudio.2022.BuildTools --override "--wait --quiet --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"' + Dry-Run "winget import winget/dependencies.json" + # Reload the PATH, so we can use some of those sweet new commands we just installed + Reload-Path +} # Check whether everything is available now: $error = 0 @@ -140,25 +142,43 @@ if ( -not (Command-Available npm ) ) { } if ( $error ) { exit } -# Check if electron-rebuild is installed, if not, install it -if ( ($Install) -or -not (Command-Available electron-rebuild) ) { - Write-Host "`nInstalling Electron-Rebuild..." - Dry-Run 'npm install -g electron-rebuild' - Reload-Path - if ( -not (Command-Available electron-rebuild)) { - Throw "electron-rebuild failed to install. Aborting." +# .description +# EnsureNodePackageInstalled: +# Checks for the presence of a cmdlet with a given name +# If it's not found, attempt to install it using npm +# If it's still not found, abort (this may not be good behavior?) +function EnsureNodePackageInstalled { + param ( + [string[]]$command + ) + if ( ($Install) -or -not (Command-Available $command[0]) ) { + Write-Host "`nInstalling $($command[0])..." + Dry-Run "npm install -g $([string]$command)" + Reload-Path + if ( -not (Command-Available $command[0])) { + Throw "$command failed to install. Aborting." + } + } else { + Write-Host "`n$($command[0]) already installed." -ForegroundColor green } -} else { - Write-Host "`nElectron-Rebuild already installed." -ForegroundColor green } +# Check if electron-rebuild is installed, if not, install it +EnsureNodePackageInstalled electron-rebuild + +# These are useful (but not necessary) packages to have installed when working on new VSCode extensions +EnsureNodePackageInstalled yo, generator-code + # We're about to do some path traversal, so save the current directory $prev_directory = $pwd # install NodeJS dependencies for this extension Write-Host "`nInstalling NodeJS Dependencies..." cd ..\.. -Dry-Run 'npm install' +Dry-Run "npm install" + +# Run npm audit fix to upgrade vulnerable dependencies, except breaking changes. +Dry-Run "npm audit fix" # if we're on a known VSCode version, go ahead and run electron-rebuild switch -Regex (code --version) { From e749399793d36add91e2f14d4893d39d8609490f Mon Sep 17 00:00:00 2001 From: John Date: Thu, 28 Apr 2022 17:38:47 -0500 Subject: [PATCH 42/78] Fix assignments in bash scripts --- setup-development/linux/install-linux.sh | 8 ++++---- setup-development/linux/upgrade-linux.sh | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/setup-development/linux/install-linux.sh b/setup-development/linux/install-linux.sh index ea6590d..d4918a5 100644 --- a/setup-development/linux/install-linux.sh +++ b/setup-development/linux/install-linux.sh @@ -4,7 +4,7 @@ #* Ensures git is installed, clones the repo, and then runs export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' -ELEVATE='';if (( $UID != 0 )); then ELEVATE='sudo';fi +ELEVATE='';if (( $UID !=0 )); then ELEVATE='sudo';fi help () { echo "Usage: $0 [-g path/to/git/directory]" @@ -12,7 +12,7 @@ help () { } -GITDIR = "~/git" +GITDIR="~/git" # Get option flags: dry=false @@ -32,8 +32,8 @@ function dryrun { $@ } -SETUPDIR= "Mind_Reader/setup-development" -REPOURI = "https://github.com/We-Dont-Byte/Mind_Reader.git" +SETUPDIR="Mind_Reader/setup-development" +REPOURI="https://github.com/We-Dont-Byte/Mind_Reader.git" # Install git if which git; then diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index 1246b6e..aa59c1d 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -7,7 +7,7 @@ # If run with bash -vx, print useful information instead of just a + sign export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' # If run as root, it could be because sudo isn't installed (some people disagree with sudo, especially on Arch) -ELEVATE='';if (( $UID != 0 )); then;ELEVATE='sudo';fi +ELEVATE='';if (( $UID !=0 )); then;ELEVATE='sudo';fi # Get option flags: dry=false @@ -65,14 +65,14 @@ cd ../.. # Check the VSCode version nodeversion="node" -electronversion = "" +electronversion="" #* Note: #* When adding support for new VSCode versions, update this case #* By the time you're working on this project, things are likely going to differ! case (code --version) in #* Each version of VSCode has a corresponding Electron version and Node version #* These are used when - 1.66.*) electronversion = "17.2.0"; nodeversion = "16.13.0";; + 1.66.*) electronversion="17.2.0"; nodeversion="16.13.0";; *) ;; esac @@ -87,7 +87,7 @@ dryrun npm install electron-rebuild yo generator-code dryrun npm install # Use electron-rebuild to rebuild electron -if (( electronversion != "" )); then +if (( electronversion !="" )); then dryrun electron-rebuild --version $electronversion else printf "%s/n%s/n%s/n%s/n" \ From c2141e9c6286a91c61b0fdd0254216e2a8b6d04d Mon Sep 17 00:00:00 2001 From: John Date: Thu, 28 Apr 2022 17:41:19 -0500 Subject: [PATCH 43/78] Ugh. --- setup-development/linux/install-linux.sh | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/setup-development/linux/install-linux.sh b/setup-development/linux/install-linux.sh index d4918a5..6b075b1 100644 --- a/setup-development/linux/install-linux.sh +++ b/setup-development/linux/install-linux.sh @@ -12,13 +12,13 @@ help () { } -GITDIR="~/git" +gitdir="~/git" # Get option flags: dry=false while getopts ghd arg; do case $arg in - g) GITDIR="$OPTARG";; + g) gitdir="$OPTARG";; h) help;; d) dry=true;; esac @@ -32,8 +32,8 @@ function dryrun { $@ } -SETUPDIR="Mind_Reader/setup-development" -REPOURI="https://github.com/We-Dont-Byte/Mind_Reader.git" +setupdir="Mind_Reader/setup-development" +repouri="https://github.com/We-Dont-Byte/Mind_Reader.git" # Install git if which git; then @@ -47,14 +47,14 @@ elif which apt; then dryrun $ELEVATE apt-get install git -y fi #? TODO: other package managers? -echo Cloning repository into "$GITDIR" -dryrun mkdir "$GITDIR" -cd $GITDIR && git clone "$REPOURI" +echo Cloning repository into "$gitdir" +dryrun mkdir "$gitdir" +cd $gitdir && git clone "$repouri" # TODO: remove this when merging! cd Mind_Reader dryrun git checkout origin/johnBreaux # TODO: remove this when merging! -cd "$GITDIR/$SETUPDIR" +cd "$gitdir/$setupdir" bash ./linux-update.sh \ No newline at end of file From 8266780775c93f5f2f3156a6f4d463f96d6b1ca7 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 28 Apr 2022 17:43:21 -0500 Subject: [PATCH 44/78] fi --- setup-development/linux/install-linux.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/setup-development/linux/install-linux.sh b/setup-development/linux/install-linux.sh index 6b075b1..38c465e 100644 --- a/setup-development/linux/install-linux.sh +++ b/setup-development/linux/install-linux.sh @@ -30,6 +30,7 @@ function dryrun { else echo "> $*" $@ + fi } setupdir="Mind_Reader/setup-development" From 41b3c37ed3556fb292fb54c5bea06abd4e596639 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 28 Apr 2022 18:10:31 -0500 Subject: [PATCH 45/78] Linux: Apt: Fix installation issues. --- setup-development/linux/install-linux.sh | 13 +++++++------ setup-development/linux/upgrade-linux.sh | 16 ++++++++++------ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/setup-development/linux/install-linux.sh b/setup-development/linux/install-linux.sh index 38c465e..572727e 100644 --- a/setup-development/linux/install-linux.sh +++ b/setup-development/linux/install-linux.sh @@ -7,12 +7,12 @@ export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' ELEVATE='';if (( $UID !=0 )); then ELEVATE='sudo';fi help () { - echo "Usage: $0 [-g path/to/git/directory]" + echo "Usage: $0 [-d] [-g path/to/git/directory]" exit 0 } -gitdir="~/git" +gitdir=~/git # Get option flags: dry=false @@ -33,7 +33,7 @@ function dryrun { fi } -setupdir="Mind_Reader/setup-development" +setupdir="Mind_Reader/setup-development/linux" repouri="https://github.com/We-Dont-Byte/Mind_Reader.git" # Install git @@ -50,12 +50,13 @@ fi #? TODO: other package managers? echo Cloning repository into "$gitdir" dryrun mkdir "$gitdir" -cd $gitdir && git clone "$repouri" +cd $gitdir && dryrun git clone "$repouri" # TODO: remove this when merging! cd Mind_Reader - dryrun git checkout origin/johnBreaux + dryrun git checkout johnBreaux # TODO: remove this when merging! cd "$gitdir/$setupdir" -bash ./linux-update.sh \ No newline at end of file +pwd +bash ./upgrade-linux.sh $@ diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index aa59c1d..32093ea 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -7,7 +7,7 @@ # If run with bash -vx, print useful information instead of just a + sign export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' # If run as root, it could be because sudo isn't installed (some people disagree with sudo, especially on Arch) -ELEVATE='';if (( $UID !=0 )); then;ELEVATE='sudo';fi +ELEVATE='';if (( $UID !=0 )); then ELEVATE='sudo';fi # Get option flags: dry=false @@ -23,12 +23,13 @@ function dryrun { else echo "> $*" $@ + fi } # Set these variables if you need to install for a different architecture # Valid architectures are "x64", "arm64", "armhf" arch="" -case (uname -i) in +case `uname -i` in "x86_64") arch="x64";; "armv[6-8]*") arch="armhf";; "aarch64") arch="arm64";; @@ -46,6 +47,9 @@ elif which apt-get; then # Install Node Version Manager (nvm) # TODO: Find a better way to install nvm on Ubuntu, the official NodeJS for <20.04 is so out of date it's unsupported. dryrun curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash + export NVM_DIR="$HOME/.nvm" + [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm + [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion # Check if vscode exists, if not, install it. # Microsoft doesn't put it in any Ubuntu repos, you have to get it straight from them. @@ -69,7 +73,7 @@ electronversion="" #* Note: #* When adding support for new VSCode versions, update this case #* By the time you're working on this project, things are likely going to differ! -case (code --version) in +case `code --version` in #* Each version of VSCode has a corresponding Electron version and Node version #* These are used when 1.66.*) electronversion="17.2.0"; nodeversion="16.13.0";; @@ -87,14 +91,14 @@ dryrun npm install electron-rebuild yo generator-code dryrun npm install # Use electron-rebuild to rebuild electron -if (( electronversion !="" )); then +if [ "$electronversion" != "" ]; then dryrun electron-rebuild --version $electronversion else - printf "%s/n%s/n%s/n%s/n" \ + printf "%s\n%s\n%s\n%s\n" \ "Open Visual Studio Code, select the 'Help' tab in the toolbar, and go to 'About'." \ "Find the line that says 'Electron: [electron version]'" \ "Run the command below, filling in the Electron version with the one from that menu:" \ "electron-rebuild --version [electron version]" fi -cd $cdir \ No newline at end of file +cd $cdir From 97e54a59310d40f0b26f146e10f5aa3a16c74e2e Mon Sep 17 00:00:00 2001 From: John Date: Thu, 28 Apr 2022 18:16:33 -0500 Subject: [PATCH 46/78] npm is a mess. --- setup-development/linux/upgrade-linux.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index 32093ea..be0be59 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -76,7 +76,7 @@ electronversion="" case `code --version` in #* Each version of VSCode has a corresponding Electron version and Node version #* These are used when - 1.66.*) electronversion="17.2.0"; nodeversion="16.13.0";; + 1.66.*) electronversion="17.2.0"; nodeversion="16.14.2";; *) ;; esac @@ -90,6 +90,9 @@ dryrun npm install electron-rebuild yo generator-code # use npm to acquire dependencies for Mind-Reader dryrun npm install +# automatically update vulnerable packages, if possible +dryrun npm audit fix + # Use electron-rebuild to rebuild electron if [ "$electronversion" != "" ]; then dryrun electron-rebuild --version $electronversion From cc26efacd4b8694752dfb0c46af76d3320f246e8 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 28 Apr 2022 18:30:25 -0500 Subject: [PATCH 47/78] Node you fiendish beast, bow before my install script --- setup-development/linux/upgrade-linux.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index be0be59..1ce271a 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -77,7 +77,7 @@ case `code --version` in #* Each version of VSCode has a corresponding Electron version and Node version #* These are used when 1.66.*) electronversion="17.2.0"; nodeversion="16.14.2";; - *) ;; + *) nodeversion="--lts";; esac # Install NodeJS and npm From d5389c5ed3bd5ac34b442c8568ad769cffb254c0 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 29 Apr 2022 02:45:05 -0500 Subject: [PATCH 48/78] Pacman is entirely broken. Oh well. --- setup-development/linux/upgrade-linux.sh | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index 1ce271a..3e1084d 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -39,17 +39,18 @@ esac if which pacman; then # Install dependencies with pacman - dryrun $ELEVATE pacman -S - < package-managers/pacman.dependencies + cat ./package-managers/pacman.dependencies | dryrun $ELEVATE pacman -S - + elif which apt-get; then # Install dependencies using apt-get dryrun xargs -a ./package-managers/apt.dependencies $ELEVATE apt-get install -y # Install Node Version Manager (nvm) # TODO: Find a better way to install nvm on Ubuntu, the official NodeJS for <20.04 is so out of date it's unsupported. - dryrun curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash - export NVM_DIR="$HOME/.nvm" - [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm - [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion + curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | dryrun bash + dryrun export NVM_DIR="$HOME/.nvm" + dryrun [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm + dryrun [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion # Check if vscode exists, if not, install it. # Microsoft doesn't put it in any Ubuntu repos, you have to get it straight from them. From 971e6fe2fb36100f4ee549599bda70b30a98e8f8 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 29 Apr 2022 02:46:42 -0500 Subject: [PATCH 49/78] hubmanager: receiveData: Ignore numbered non-error status messages coming in on message channel --- src/hubManager.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/hubManager.ts b/src/hubManager.ts index 8d5bf7b..13dda7e 100644 --- a/src/hubManager.ts +++ b/src/hubManager.ts @@ -76,12 +76,14 @@ export default class HubManager { // get full lines in buffer - let msgs = this.receiveBuffer.split(/\r/); // split by newline + let msgs = this.receiveBuffer.split(/[\r>]/); // split by newline this.receiveBuffer = msgs.pop()!; // store unhandled data - msgs = msgs.filter(x => !x.startsWith('{"m":0,"p":')); // drop sensor broadcast response spam + msgs = msgs.filter(x => !x.match(/{"m":\d+,"p":/)); // drop sensor broadcast response spam for (const msg of msgs) { + // check if message is actually json + if (!msg.includes("{")) { continue; } // check if this msg is a response to a pending request try { let json: { [key: string]: any }; @@ -112,11 +114,15 @@ export default class HubManager { case 'runtime_error': logger.error(Buffer.from(params[3], 'base64').toString()); break; + case 2: + logger.info(`Battery at ${params[0]}V`); + break; } vscode.window.showErrorMessage("Program Error."); + console.log(`Program error: ${msg}`); } } catch (err) { - console.log('Could not parse JSON:', msg); + console.log('Could not parse JSON:', msg, err); } } } From f86f2cb6b9a5420ca1fd706d31db300f98c129fd Mon Sep 17 00:00:00 2001 From: John Date: Sat, 30 Apr 2022 13:01:04 -0500 Subject: [PATCH 50/78] Powershellize the windows install-scripts - Replace powershell aliases with canonical Cmdlet names - Update function names to only use approved Verbs --- setup-development/windows/install-windows.ps1 | 52 ++++++++--------- setup-development/windows/upgrade-windows.ps1 | 58 +++++++++---------- 2 files changed, 55 insertions(+), 55 deletions(-) diff --git a/setup-development/windows/install-windows.ps1 b/setup-development/windows/install-windows.ps1 index ac864db..86c2d36 100644 --- a/setup-development/windows/install-windows.ps1 +++ b/setup-development/windows/install-windows.ps1 @@ -66,9 +66,9 @@ if ($h -or $Help) { } # .description -# Command-Available: Checks whether a given command is available. +# Get-CommandAvailable: Checks whether a given command is available. # If command is available, returns $false -function Command-Available { +function Get-CommandAvailable { param ($command) # Use a wildcard here so the command doesn't throw an exception we'd have to trycatch # It's not a filthy hack if it's elegant! @@ -76,8 +76,8 @@ function Command-Available { } #.description -# Dry-Run a powershell statement -function Dry-Run { +# Invoke-DryRun a powershell statement +function Invoke-DryRun { param ([string] $command) $prompt = "> " if ($DryRun) { @@ -90,8 +90,8 @@ function Dry-Run { } #.description -# Reload-Path: Reload the Path environment variable -function Reload-Path { +# Reset-Path: Reload the Path environment variable +function Reset-Path { Write-Output "Reloading Path..." #* Courtesy of user [mpen](https://stackoverflow.com/users/65387/mpen) on [StackOverflow](https://stackoverflow.com/a/31845512) $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") @@ -99,7 +99,7 @@ function Reload-Path { # Check if Winget is available -if ( -not (Command-Available winget) ) { +if ( -not (Get-CommandAvailable winget) ) { Write-Warning "It looks like winget isn't available.`n" Write-Host "Update 'App Installer' through the Microsoft Store, or grab the '.msixbundle' from the winget-cli repository:" Write-Host "( https://github.com/microsoft/winget-cli/releases/latest )`n" -ForegroundColor White @@ -118,7 +118,7 @@ if ( ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5 if (!$NoPrompt) { for ( $i = 3; $i -gt 0; $i--) { Write-Host "Press Ctrl+C to exit. Continuing in $i...`r" -NoNewLine - sleep 1 + Start-Sleep 1 } Write-Host "Press any key to continue... " [void][Console]::ReadKey(1) # Equivalent to Command Prompt's `pause` command @@ -130,11 +130,11 @@ if ( ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5 } # Install Git -if ( -not (Command-Available git) ) { +if ( -not (Get-CommandAvailable git) ) { Write-Host "`nInstalling Git with winget..." - Dry-Run 'winget install --id Git.Git' - Reload-Path - if ( -not (Command-Available git)) { + Invoke-DryRun 'winget install --id Git.Git' + Reset-Path + if ( -not (Get-CommandAvailable git)) { Throw "Git failed to install. Aborting." } } else { @@ -143,37 +143,37 @@ if ( -not (Command-Available git) ) { # Create git directory in GitDir if ( -not (Test-Path "$GitDir") ) { - Dry-Run "mkdir '$GitDir'" + Invoke-DryRun "mkdir '$GitDir'" } # Clone the repository in GitDir $dir = $pwd -cd $GitDir -Dry-Run "git clone '$RepoURI'" +Set-Location $GitDir +Invoke-DryRun "git clone '$RepoURI'" # TODO: Remove this when merging -cd Mind_reader -Dry-Run "git checkout johnBreaux" -cd .. +Set-Location Mind_reader +Invoke-DryRun "git checkout johnBreaux" +Set-Location .. # TODO: Remove this when merging # Run the install script if ( -not (Test-Path "$SetupPath")) { Throw "Repository contains no subdirectory '$SetupPath'." } -cd $SetupPath +Set-Location $SetupPath # Run upgrade-windows to install the rest of the dependency chain. -$args = if ($AllowAdministrator) {" -AllowAdministrator"} else {""} -$args += if ($DryRun) {" -DryRun"} else {""} -PowerShell ("./upgrade-windows.ps1 -Install -NoPrompt" + $args) -Reload-Path +$upgradeArgs = if ($AllowAdministrator) {" -AllowAdministrator"} else {""} +$upgradeArgs += if ($DryRun) {" -DryRun"} else {""} +PowerShell ("./upgrade-windows.ps1 -Install -NoPrompt" + $upgradeArgs) +Reset-Path # Open VSCode in the repository location Write-Host "`nOpening Visual Studio Code" -cd $RepoPath -Dry-Run "code ." +Set-Location $RepoPath +Invoke-DryRun "code ." -cd $dir +Set-Location $dir if ( -not $NoPrompt ) { Write-Host "`nPress any key to exit."; [void][Console]::ReadKey(1) } \ No newline at end of file diff --git a/setup-development/windows/upgrade-windows.ps1 b/setup-development/windows/upgrade-windows.ps1 index 809a5fe..09094bb 100644 --- a/setup-development/windows/upgrade-windows.ps1 +++ b/setup-development/windows/upgrade-windows.ps1 @@ -56,9 +56,9 @@ param ( ) # .description -# Command-Available: Checks whether a given command is available. +# Get-CommandAvailable: Checks whether a given command is available. # If command is available, returns $false -function Command-Available { +function Get-CommandAvailable { param ($command) # Use a wildcard here so the command doesn't throw an exception we'd have to trycatch # It's not a filthy hack if it's elegant! @@ -66,8 +66,8 @@ function Command-Available { } #.description -# Dry-Run a powershell statement -function Dry-Run { +# Invoke-Dryrun a powershell statement +function Invoke-Dryrun { param ([string] $command) $prompt = "> " if ($DryRun) { @@ -80,8 +80,8 @@ function Dry-Run { } #.description -# Reload-Path: Reload the Path environment variable -function Reload-Path { +# Reset-Path: Reload the Path environment variable +function Reset-Path { Write-Output "Reloading Path..." #* Courtesy of user [mpen](https://stackoverflow.com/users/65387/mpen) on [StackOverflow](https://stackoverflow.com/a/31845512) $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") @@ -89,7 +89,7 @@ function Reload-Path { # Check if Winget is available -if ( -not (Command-Available winget) ) { +if ( -not (Get-CommandAvailable winget) ) { Write-Warning "It looks like winget isn't available.`n" Write-Host "Update 'App Installer' through the Microsoft Store, or grab the '.msixbundle' from the winget-cli repository:" Write-Host "( https://github.com/microsoft/winget-cli/releases/latest )`n" -ForegroundColor White @@ -108,14 +108,14 @@ if ( ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5 Write-Warning "Script was run as Administrator. Exit now if you didn't mean to do this!" for ( $i = 3; $i -gt 0; $i--) { Write-Host "Press Ctrl+C to exit. Continuing in $i...`r" -NoNewLine - sleep 1 + Start-Sleep 1 } Write-Host "Press any key to continue... " [void][Console]::ReadKey(1) # Equivalent to Command Prompt's `pause` command } } else { - # Throw a fatal error if the user tries to run as administrator. + # Throw a fatal errorOccurred if the user tries to run as administrator. Throw "Script must be run as a normal user." } } @@ -123,24 +123,24 @@ if ( ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5 # Import the packages from dependencies.json (autogenerated file, do not edit!) if ( -not $NoWinget) { Write-Host "`nInstalling packages with winget..." - Dry-Run 'winget install Microsoft.VisualStudio.2022.BuildTools --override "--wait --quiet --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"' - Dry-Run "winget import winget/dependencies.json" + Invoke-Dryrun 'winget install Microsoft.VisualStudio.2022.BuildTools --override "--wait --quiet --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"' + Invoke-Dryrun "winget import winget/dependencies.json" # Reload the PATH, so we can use some of those sweet new commands we just installed - Reload-Path + Reset-Path } # Check whether everything is available now: -$error = 0 -if ( -not (Command-Available code) ) { - $error += 1; Write-Host -ForegroundColor red "Visual Studio Code not available" +$errorOccurred = 0 +if ( -not (Get-CommandAvailable code) ) { + $errorOccurred += 1; Write-Host -ForegroundColor red "Visual Studio Code not available" } -if ( -not (Command-Available node) ) { - $error += 2; Write-Host -ForegroundColor red "NodeJS not available" +if ( -not (Get-CommandAvailable node) ) { + $errorOccurred += 2; Write-Host -ForegroundColor red "NodeJS not available" } -if ( -not (Command-Available npm ) ) { - $error += 4; Write-Host -ForegroundColor red "Node Package Manager not available"; +if ( -not (Get-CommandAvailable npm ) ) { + $errorOccurred += 4; Write-Host -ForegroundColor red "Node Package Manager not available"; } -if ( $error ) { exit } +if ( $errorOccurred ) { exit } # .description # EnsureNodePackageInstalled: @@ -151,11 +151,11 @@ function EnsureNodePackageInstalled { param ( [string[]]$command ) - if ( ($Install) -or -not (Command-Available $command[0]) ) { + if ( ($Install) -or -not (Get-CommandAvailable $command[0]) ) { Write-Host "`nInstalling $($command[0])..." - Dry-Run "npm install -g $([string]$command)" - Reload-Path - if ( -not (Command-Available $command[0])) { + Invoke-Dryrun "npm install -g $([string]$command)" + Reset-Path + if ( -not (Get-CommandAvailable $command[0])) { Throw "$command failed to install. Aborting." } } else { @@ -174,11 +174,11 @@ $prev_directory = $pwd # install NodeJS dependencies for this extension Write-Host "`nInstalling NodeJS Dependencies..." -cd ..\.. -Dry-Run "npm install" +Set-Location ..\.. +Invoke-Dryrun "npm install" # Run npm audit fix to upgrade vulnerable dependencies, except breaking changes. -Dry-Run "npm audit fix" +Invoke-Dryrun "npm audit fix" # if we're on a known VSCode version, go ahead and run electron-rebuild switch -Regex (code --version) { @@ -187,7 +187,7 @@ switch -Regex (code --version) { } #> "1\.66\.[0-9]+" { # 1.66 Write-Host "`nRebuilding Electron for your version of VSCode..." - Dry-Run 'electron-rebuild --version="17.2.0"' + Invoke-Dryrun 'electron-rebuild --version="17.2.0"' Write-Host "Done!" -ForegroundColor green break } @@ -207,7 +207,7 @@ switch -Regex (code --version) { } # Return from whence we came -cd $prev_directory +Set-Location $prev_directory if ( -not $NoPrompt ) { Write-Host "`nPress any key to exit."; [void][Console]::ReadKey(1) } \ No newline at end of file From 34d89386ea965a6b400bf9aca2adf9ad67340736 Mon Sep 17 00:00:00 2001 From: John Date: Sat, 30 Apr 2022 17:12:36 -0500 Subject: [PATCH 51/78] Name improvements, new tokens, new behavior. Name improvements: - runLineContext changed to "Get Line Scope". - runCursorContext changed to "Get Words Under Cursor". New tokens: - STATEMENT: Replaces INDENT. Stores entire line of python statement, not including comments, in attr. - COMMENT: Stores entire comment line in attr. - INVALID: Invalid token, used when parser can't figure out a line. Should never be seen. New behavior: - Get Line Scope now reads out the comment your cursor is in. - Implemented fractional indentation notifications (disabled) --- package.json | 12 ++++++------ src/commands/text.ts | 10 +++++----- src/pylex/lexer.ts | 15 ++++++++++----- src/pylex/parser.ts | 5 +++-- src/pylex/token.ts | 4 +++- 5 files changed, 27 insertions(+), 19 deletions(-) diff --git a/package.json b/package.json index 993fd07..3d48b19 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "repository": "https://github.com/We-Dont-Byte/Mind_Reader", "version": "1.0.0", "engines": { - "vscode": "^1.60.0" + "vscode": "^1.66.0" }, "categories": [ "Other" @@ -60,13 +60,13 @@ "category": "Mind Reader" }, { - "command": "mind-reader.runLineContext", - "title": "Get the Context of the Current Line", + "command": "mind-reader.getLineScope", + "title": "Get Scope of the Current Line", "category": "Mind Reader" }, { - "command": "mind-reader.runCursorContext", - "title": "Get the Context of Text Under Cursor", + "command": "mind-reader.getWordsUnderCursor", + "title": "Get Words Under the Cursor", "category": "Mind Reader" }, { @@ -215,7 +215,7 @@ "when": "editorTextFocus" }, { - "command": "mind-reader.runLineContext", + "command": "mind-reader.getLineScope", "key": "Ctrl+Shift+/ C", "mac": "Cmd+Shift+[Slash] C", "when": "editorTextFocus && editorLangId == python" diff --git a/src/commands/text.ts b/src/commands/text.ts index 7cf5306..abdbc30 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -19,11 +19,11 @@ export const textCommands: CommandEntry[] = [ callback: getLeadingSpaces, }, { - name: 'mind-reader.runLineContext', + name: 'mind-reader.getLineScope', callback: runLineContext, }, { - name: 'mind-reader.runCursorContext', + name: 'mind-reader.getWordsUnderCursor', callback: runCursorContext } ]; @@ -168,16 +168,16 @@ function createContextString(context: pl.LexNode[], line: number): string { // Print the current line if (context[0].token && context[0].token.attr) { let tokenTypeString: string = `${context[0].token.type.toString()}`; - contextString += `: ${tokenTypeString !== 'INDENT'?tokenTypeString:"" + contextString += `: ${tokenTypeString !== pl.PylexSymbol.STATEMENT?tokenTypeString:"" } ${context[0].token.attr.toString()}`; } for (let i: number = 1; i < context.length; i++) { const node: pl.LexNode = context[i]; - const inside: string = "in"; + const inside: string = "inside"; // Node contains information relevant to the current line if (node.token && node.token.type !== pl.PylexSymbol.EMPTY && - node.token.type !== pl.PylexSymbol.INDENT) { + node.token.type !== pl.PylexSymbol.STATEMENT) { contextString += ` ${inside} ${node.token.type.toString()}`; if (node.token.attr) { contextString += ` ${node.token.attr.toString()}`; diff --git a/src/pylex/lexer.ts b/src/pylex/lexer.ts index 92e48ea..89a17b6 100644 --- a/src/pylex/lexer.ts +++ b/src/pylex/lexer.ts @@ -57,12 +57,16 @@ const rules: Rule[] = [ type: Symbol.WITH }, { - pattern: /^\s*(#.*)?$/, + pattern: /^\s*#+\s*(?.*)\s*$/, + type: Symbol.COMMENT + }, + { + pattern: /^\s*$/, type: Symbol.EMPTY }, { - pattern: /\s*(?[^#]+)?$/, - type: Symbol.INDENT + pattern: /^\s*(?[^#]+)+\s*$/, + type: Symbol.STATEMENT } ]; @@ -151,7 +155,7 @@ export default class Lexer { } } // No rules matched - token = new LineToken(Symbol.EMPTY, this.pos, 999999); + token = new LineToken(Symbol.INVALID, this.pos, 999999); this._currToken = token; this.pos++; @@ -218,7 +222,8 @@ export default class Lexer { indent = leadingSpace; } else { - // use spaces + // used spaces + //? indent = Math.round(leadingSpace / tabFmt.size! * 10) / 10; // fractional indentation support? indent = Math.ceil(leadingSpace / tabFmt.size!); } diff --git a/src/pylex/parser.ts b/src/pylex/parser.ts index 9a2fb18..d6771a8 100644 --- a/src/pylex/parser.ts +++ b/src/pylex/parser.ts @@ -74,8 +74,9 @@ export default class Parser { return children; } - if (this.lexer.currToken().type === Symbol.INDENT || - this.lexer.currToken().type === Symbol.EMPTY) { + if (this.lexer.currToken().type === Symbol.STATEMENT || + this.lexer.currToken().type === Symbol.EMPTY || + this.lexer.currToken().type === Symbol.INVALID) { const label = this.lexer.currToken().type; // regular code, advance and stay in same block children.push(new LexNode( diff --git a/src/pylex/token.ts b/src/pylex/token.ts index 54e62be..9d9a457 100644 --- a/src/pylex/token.ts +++ b/src/pylex/token.ts @@ -16,8 +16,10 @@ export enum Symbol { EXCEPT = "except", FINALLY = "finally", WITH = "with", - INDENT = "INDENT", // Indent token, default if not EOF, only contains indent information + STATEMENT = "statement", // Indent token, contains non-empty code lines + COMMENT = "comment", EMPTY = "EMPTY", // empty line, used only to associate with the previous line + INVALID = "INVALID", EOF = "EOF" } From e0b2e5ee929234d51f83205badb6ead83208014e Mon Sep 17 00:00:00 2001 From: John Date: Sat, 30 Apr 2022 17:17:28 -0500 Subject: [PATCH 52/78] Update tests to match new behavior --- src/test/suites/pylex/lexer.test.ts | 26 +++-- src/test/suites/pylex/node.test.ts | 2 +- src/test/suites/pylex/parser.test.ts | 157 ++++++++++++++------------- src/test/util.ts | 8 +- 4 files changed, 101 insertions(+), 92 deletions(-) diff --git a/src/test/suites/pylex/lexer.test.ts b/src/test/suites/pylex/lexer.test.ts index 14bebd0..e863a19 100644 --- a/src/test/suites/pylex/lexer.test.ts +++ b/src/test/suites/pylex/lexer.test.ts @@ -12,7 +12,7 @@ suite('Lexer Test Suite', () => { }); test('Empty String', () => { - let l: Lexer = new Lexer(undefined); + let l: Lexer = new Lexer(""); assert.deepStrictEqual(l.currToken(), EOFTOKEN); }); @@ -22,18 +22,19 @@ suite('Lexer Test Suite', () => { }); test('Whitespace', () => { - let l: Lexer = new Lexer(' \t\t'.repeat(4).repeat(4)); - assert.deepStrictEqual(l.currToken(), new LineToken(Symbol.EMPTY, 0, 999999)); + let s: string = ' '.repeat(4).repeat(4); + let l: Lexer = new Lexer(s); + assert.deepStrictEqual(l.currToken(), new LineToken(Symbol.EMPTY, 0, s.length/4)); }); test('Comment', () => { - let l: Lexer = new Lexer('# ur mom eats toes'); - assert.deepStrictEqual(l.currToken(), new LineToken(Symbol.EMPTY, 0, 999999)); + let l: Lexer = new Lexer('# this is a comment'); + assert.deepStrictEqual(l.currToken(), new LineToken(Symbol.COMMENT, 0, 0, 'this is a comment')); }); test('Non-Whitespace with no construct', () => { let l: Lexer = new Lexer('foobar'); - assert.deepStrictEqual(l.currToken(), new LineToken(Symbol.INDENT, 0, 0)); + assert.deepStrictEqual(l.currToken(), new LineToken(Symbol.STATEMENT, 0, 0, 'foobar')); }); test('getIndent() accuracy, spaces', () => { @@ -50,11 +51,14 @@ suite('Lexer Test Suite', () => { } }); - test('getIndent() accuracy, spaces with incomplete tab', () => { + test('getIndent() accuracy, spaces with incomplete indentation', () => { + let size: number = 4; for (var i = 0; i < 100; i++) { for (var j = 1; j <= 3; j++) { - let l: Lexer = new Lexer(' '.repeat(i) + ' '.repeat(j) + 'foobar', {size: 4, hard: false}); - assert.strictEqual(l.currToken().indentLevel, i+1); + let l: Lexer = new Lexer(' '.repeat(i) + ' '.repeat(j) + 'foobar', {size: size, hard: false}); + // TODO: Swap these out when fractional indentation is used + //assert.strictEqual(l.currToken().indentLevel, i + (Math.round(j / size * 100) / 100)); + assert.strictEqual(l.currToken().indentLevel, i + 1); } } }); @@ -150,7 +154,7 @@ suite('Lexer Test Suite', () => { test('retract() 1-100', () => { let lines: string[] = Array.from(Array(100), (_, i) => 'line' + i); let reference: LineToken[] = lines.map((_, i) => { - return new LineToken(Symbol.INDENT, i, 0); + return new LineToken(Symbol.STATEMENT, i, 0, `line${i}`); }); for (var i = 0; i < 100; i++) { @@ -169,7 +173,7 @@ suite('Lexer Test Suite', () => { test('2 full lex and retract passes', () => { let lines: string[] = Array.from(Array(100), (_, i)=> 'line' + i); let reference: LineToken[] = lines.map((_, i) => { - return new LineToken(Symbol.INDENT, i, 0); + return new LineToken(Symbol.STATEMENT, i, 0, `line${i}`); }); let l: Lexer = new Lexer(lines.join('\n')); diff --git a/src/test/suites/pylex/node.test.ts b/src/test/suites/pylex/node.test.ts index 85e7fec..381cfd1 100644 --- a/src/test/suites/pylex/node.test.ts +++ b/src/test/suites/pylex/node.test.ts @@ -13,7 +13,7 @@ suite('LexNode Test Suite', () => { }); test('children() of leaf', () => { - let n: LexNode = new LexNode('leafLexNode', vscode.TreeItemCollapsibleState.None, new LineToken(Symbol.INDENT, 0, 0)); + let n: LexNode = new LexNode('leafLexNode', vscode.TreeItemCollapsibleState.None, new LineToken(Symbol.STATEMENT, 0, 0)); assert.strictEqual(n.children(), null); }); diff --git a/src/test/suites/pylex/parser.test.ts b/src/test/suites/pylex/parser.test.ts index b92a5ae..5793d77 100644 --- a/src/test/suites/pylex/parser.test.ts +++ b/src/test/suites/pylex/parser.test.ts @@ -7,7 +7,7 @@ import LexNode from '../../../pylex/node'; import LineToken from '../../../pylex/token'; import { Symbol } from '../../../pylex/token'; -import { root,indent,empty } from '../../util'; +import { root, statement } from '../../util'; /** * Test Descriptor @@ -23,23 +23,24 @@ const tests: ParserTest[] = [ { name: 'Single Empty Line', input: [''], output: root(null) }, { name: 'Single Whitespace Only Line', - input: [' '], + input: [' '], // length 20 output: root([ - empty(0) + new LexNode(Symbol.EMPTY, 0, new LineToken(Symbol.EMPTY, 0, 20 / 4)) // 4 spaces per indent ]) }, { name: 'Single Comment Only Line', - input: ['# ur mom likes peas'], + input: ['# this is a comment'], output: root([ - empty(0) + new LexNode(Symbol.EMPTY, 0, new LineToken(Symbol.COMMENT, 0, 0, "this is a comment")) ]) }, { name: 'Single Non-Control Line', input: ['my_age = 42'], output: root([ - indent(0, 0) + //statement(0, 0) + new LexNode("name", 0, new LineToken(Symbol.STATEMENT, 0, 0, 'my_age = 42')) ]) }, { @@ -55,7 +56,10 @@ const tests: ParserTest[] = [ 'bar = "Blue M&Ms make me happy <:)"', 'reba = "A hard working gal"' ], - output: root([indent(0,0), indent(1,0)]), + output: root([ + new LexNode("name", 0, new LineToken(Symbol.STATEMENT, 0, 0, 'bar = "Blue M&Ms make me happy <:)"')), + new LexNode("name", 0, new LineToken(Symbol.STATEMENT, 1, 0, 'reba = "A hard working gal"')) + ]), }, { @@ -66,11 +70,13 @@ const tests: ParserTest[] = [ 'billy = "Scrubbly Bubbles!"' ], output: root([ - new LexNode('if radioshack', - vscode.TreeItemCollapsibleState.None, + new LexNode('if radioshack', 0, new LineToken(Symbol.IF, 0, 0, 'radioshack'), - [indent(1, 1)]), - indent(2, 0) + [ + new LexNode('print radioshack.hours', 0, new LineToken(Symbol.STATEMENT, 1, 1, 'print radioshack.hours')) + ] + ), + new LexNode('billy = "Scrubbly Bubbles!"', 0, new LineToken(Symbol.STATEMENT, 2, 0, 'billy = "Scrubbly Bubbles!"')) ]) }, @@ -82,11 +88,12 @@ const tests: ParserTest[] = [ ' print radioshack.hours' ], output: root([ - indent(0, 0), - new LexNode('if radioshack', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.IF, 1, 0, 'radioshack'), - [indent(2, 1)]) + new LexNode('billy = "Scrubbly Bubbles!"', 0, new LineToken(Symbol.STATEMENT, 0, 0, 'billy = "Scrubbly Bubbles!"')), + new LexNode('if radioshack', 0, new LineToken(Symbol.IF, 1, 0, 'radioshack'), + [ + new LexNode('print radioshack.hours', 0, new LineToken(Symbol.STATEMENT, 2, 1, 'print radioshack.hours')) + ] + ) ]) }, @@ -101,15 +108,18 @@ const tests: ParserTest[] = [ ' print("You really eat this?")', ], output: root([ - new LexNode('if yummy', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.IF, 0, 0, 'yummy'), [indent(1, 1)]), - new LexNode('elif just_ok', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.ELIF, 2, 0, 'just_ok'), [indent(3, 1)]), - new LexNode('else', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.ELSE, 4, 0), [indent(5,1)]), + new LexNode('if yummy', 0, new LineToken(Symbol.IF, 0, 0, 'yummy'), + [ + statement(1, 1, 'print("HOoray!")') + ]), + new LexNode('elif just_ok', 0, new LineToken(Symbol.ELIF, 2, 0, 'just_ok'), + [ + statement(3, 1, 'print("Do you have anything else?")') + ]), + new LexNode('else', 0, new LineToken(Symbol.ELSE, 4, 0), + [ + statement(5, 1, 'print("You really eat this?")') + ]), ]) }, @@ -122,13 +132,14 @@ const tests: ParserTest[] = [ ], output: root([ new LexNode('if yummy', - vscode.TreeItemCollapsibleState.None, + 0, new LineToken(Symbol.IF, 0, 0, 'yummy'), [ - new LexNode('if in_my_tummy', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.IF, 1, 1, 'in_my_tummy'), - [indent(2, 2)]) + new LexNode('if in_my_tummy', 0, new LineToken(Symbol.IF, 1, 1, 'in_my_tummy'), + [ + statement(2, 2, 'exclaim("Scrumdiddlyumptious!")') + ] + ) ], ) ]) @@ -141,23 +152,20 @@ const tests: ParserTest[] = [ ' if in_my_tummy:', ' exclaim("Scrumdiddlyumptious!")', 'else:', - ' exclaim("DAESGUSTEN~)"' + ' exclaim("DISGUSTING!")' ], output: root([ - new LexNode('if yummy', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.IF, 0, 0, 'yummy'), + new LexNode('if yummy', 0, new LineToken(Symbol.IF, 0, 0, 'yummy'), [ - new LexNode('if in_my_tummy', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.IF, 1, 1, 'in_my_tummy'), - [indent(2, 2)]) + new LexNode('if in_my_tummy', 0, new LineToken(Symbol.IF, 1, 1, 'in_my_tummy'), + [ + statement(2, 2, 'exclaim("Scrumdiddlyumptious!")') + ] + ) ] ), - new LexNode('else', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.ELSE, 3, 0), - [indent(4, 1)] + new LexNode('else', 0, new LineToken(Symbol.ELSE, 3, 0), + [statement(4, 1, 'exclaim("DISGUSTING!")')] ) ]) }, @@ -168,31 +176,27 @@ const tests: ParserTest[] = [ 'if yummy:', ' if in_my_tummy:', ' if looks_like_a_mummy:', - ' print("you have a spot on your tummy"', + ' print("you have a spot on your tummy")', 'else:', ' print("Food is food...")' ], output: root([ new LexNode('if yummy', - vscode.TreeItemCollapsibleState.None, + 0, new LineToken(Symbol.IF, 0, 0, 'yummy'), [ - new LexNode('if in_my_tummy', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.IF, 1, 1, 'in_my_tummy'), + new LexNode('if in_my_tummy', 0, new LineToken(Symbol.IF, 1, 1, 'in_my_tummy'), [ - new LexNode('if looks_like_a_mummy', - vscode.TreeItemCollapsibleState.None, - new LineToken(Symbol.IF, 2, 2, 'looks_like_a_mummy'), - [indent(3, 3)]) + new LexNode('if looks_like_a_mummy', 0, new LineToken(Symbol.IF, 2, 2, 'looks_like_a_mummy'), + [statement(3, 3, 'print("you have a spot on your tummy")')]) ] ) ] ), - new LexNode('else', - vscode.TreeItemCollapsibleState.None, + new LexNode('else', + 0, new LineToken(Symbol.ELSE, 4, 0), - [indent(5, 1)] + [statement(5, 1, 'print("Food is food...")')] ) ]) }, @@ -203,44 +207,42 @@ const tests: ParserTest[] = [ 'if yummy:', ' if in_my_tummy:', ' if looks_like_a_mummy:', - ' print("you have a spot on your tummy"', + ' print("you have a spot on your tummy")', ' else:', - ' print("eek! a zombie!)', + ' print("eek! a zombie!")', ' elif in_my_mouth:', - ' print("itll be in my tummy soon!"', + ' print("itll be in my tummy soon!")', 'else:', ' print("Food is food...")' ], output: root([ - new LexNode('if yummy', - vscode.TreeItemCollapsibleState.None, + new LexNode('if yummy', 0, new LineToken(Symbol.IF, 0, 0, 'yummy'), [ - new LexNode('if in_my_tummy', - vscode.TreeItemCollapsibleState.None, + new LexNode('if in_my_tummy', 0, new LineToken(Symbol.IF, 1, 1, 'in_my_tummy'), [ new LexNode('if looks_like_a_mummy', - vscode.TreeItemCollapsibleState.None, + 0, new LineToken(Symbol.IF, 2, 2, 'looks_like_a_mummy'), - [indent(3, 3)]), + [statement(3, 3, 'print("you have a spot on your tummy")')]), new LexNode('else', - vscode.TreeItemCollapsibleState.None, + 0, new LineToken(Symbol.ELSE, 4, 2), - [indent(5, 3)]) + [statement(5, 3, 'print("eek! a zombie!")')]) ] ), new LexNode('elif in_my_mouth', - vscode.TreeItemCollapsibleState.None, + 0, new LineToken(Symbol.ELIF, 6, 1, 'in_my_mouth'), - [indent(7, 2)] + [statement(7, 2, 'print("itll be in my tummy soon!")')] ) ] ), - new LexNode('else', - vscode.TreeItemCollapsibleState.None, + new LexNode('else', + 0, new LineToken(Symbol.ELSE, 8, 0), - [indent(9, 1)] + [statement(9, 1, 'print("Food is food...")')] ) ]) }, @@ -248,21 +250,24 @@ const tests: ParserTest[] = [ name: 'Multiline Block', input: [ 'if yummy:', - ' print("you have a spot on your tummy"', + ' print("you have a spot on your tummy")', ' print("eek! a zombie!)', - ' print("itll be in my tummy soon!"', + ' print("itll be in my tummy soon!")', 'else:', ' print("Food is food...")' ], output: root([ new LexNode('if yummy', 0, new LineToken(Symbol.IF, 0, 0, 'yummy'), [ - indent(1, 1), - indent(2, 1), - indent(3, 1), + statement(1, 1, 'print("you have a spot on your tummy")'), + statement(2, 1, 'print("eek! a zombie!)'), + statement(3, 1, 'print("itll be in my tummy soon!")'), ] ), - new LexNode('else', 0, new LineToken(Symbol.ELSE, 4, 0), [indent(5, 1)]) + new LexNode('else', 0, new LineToken(Symbol.ELSE, 4, 0), + [ + statement(5, 1, 'print("Food is food...")') + ]) ]) } ]; diff --git a/src/test/util.ts b/src/test/util.ts index b7c0f12..0e392d2 100644 --- a/src/test/util.ts +++ b/src/test/util.ts @@ -50,19 +50,19 @@ function root(nodes: LexNode[] | null): LexNode { } /* short hand for returning an indentation token for a certain line and indentation */ -function indent(linenr: number, indentLevel: number): LexNode { - return new LexNode('INDENT', 0, new LineToken(PylexSymbol.INDENT, linenr, indentLevel)); +function statement(linenr: number, indentLevel: number, text: string = ""): LexNode { + return new LexNode(PylexSymbol.STATEMENT, 0, new LineToken(PylexSymbol.STATEMENT, linenr, indentLevel, text)); } /* short hand for returning an empty token for a certain line*/ function empty(linenr: number): LexNode { - return new LexNode('EMPTY', 0, new LineToken(PylexSymbol.EMPTY, linenr, 999999)); + return new LexNode(PylexSymbol.EMPTY, 0, new LineToken(PylexSymbol.EMPTY, linenr, 999999)); } export { deparent, root, - indent, + statement as statement, empty }; From c17b718ce65c6312f13c3d9e2e9b9da853189be9 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Sun, 1 May 2022 20:22:26 -0500 Subject: [PATCH 53/78] Added New Function Added Senior Design Day Spring 2022 suggestion of selecting the leading whitespace characters. Had to refactor getLeadingWhitespace to include a helper function. Also added imports for vscode. Finally shifted helper functions together and added comments. --- src/commands/text.ts | 220 ++++++++++++++++++++++++++++--------------- 1 file changed, 145 insertions(+), 75 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 7c0c122..6e72604 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -1,7 +1,7 @@ "use strict"; -import { CommandEntry } from './commandEntry'; -import vscode = require("vscode"); -import pl = require("../pylex"); +import pl = require("../pylex"); +import { CommandEntry } from './commandEntry'; +import { Position, Selection, TextEditor, TextLine, window, workspace } from "vscode"; export const textCommands: CommandEntry[] = [ { @@ -16,6 +16,10 @@ export const textCommands: CommandEntry[] = [ name: 'mind-reader.getLeadingSpaces', callback: getLeadingSpaces, }, + { + name: 'mind-reader.selectLeadingWhitespace', + callback: selectLeadingWhitespace + }, { name: 'mind-reader.getNumberOfSelectedLines', callback: getNumberOfSelectedLines, @@ -30,10 +34,54 @@ export const textCommands: CommandEntry[] = [ } ]; -/* Helper Function -* This function returns the number of selected lines in the active text editor window +/** Helper Function + * + * @param editor + * @returns numSpaces + ** There are two methods that can be used to find the leading spaces: + ** method 1: + ** calculates the number of leading spaces by finding the length of the current line + ** then subtracting from that the length of the text after trimming the whitespace at the start + ** which will equal the number of whitespace characters + ** + ** TO-USE: set calculateLeadingSpaces to true + ** + ** method 2 (default): + ** finds the index position of the first non-whitespace character in a 0-index + ** this number will equal the number of spaces preceding the non-whitespace character + ** due to the nature of 0-indexes. + ** + ** TO-USE: set calculateLeadingSpaces to false + */ +function fetchNumberOfLeadingSpaces(editor: TextEditor | undefined): number { + let numSpaces: number = 0; + + + if (editor) { + /* + * set true to use method 1: find the number of leading spaces through arithmetic + * set false to use method 2: find the index position of the first non-whitespace character in a 0-index + * default: false + */ + const calculateLeadingSpaces: boolean = false; // change boolean value to change method + const lineNum: number = (fetchLineNumber(editor) - 1); // We want the line index, so we remove the 1 we added to the result in fetchLineNumber + const line : any = editor.document.lineAt(lineNum); + + /* If true, calculate by arithmetic otherwise get index */ + numSpaces = (calculateLeadingSpaces) + ? pl.Lexer.getLeadingSpacesByArithmetic(line) + : pl.Lexer.getLeadingSpacesByIndex(line); + } + + return numSpaces; +} + +/** Helper Function +* * This function returns the number of selected lines in the active text editor window + @param editor + @returns numberOfSelectedLines */ -function fetchNumberOfSelectedLines(editor: vscode.TextEditor | undefined): number { +function fetchNumberOfSelectedLines(editor: TextEditor | undefined): number { let numberOfSelectedLines: number = 0; if (editor) { @@ -43,67 +91,71 @@ function fetchNumberOfSelectedLines(editor: vscode.TextEditor | undefined): numb return numberOfSelectedLines; } -/* Helper Function -* This function returns the line number of the active text editor window +/** Helper Function + ** This function returns the line number of the active text editor window + * @param editor + * @returns editor!.selection.active.line + 1 */ -function fetchLineNumber(editor: any): number { - return editor.selection.active.line + 1; +function fetchLineNumber(editor: TextEditor | undefined): number { + return editor!.selection.active.line + 1; // line numbers start at 1, not 0, so we add 1 to the result } -/* Helper Function -* This function returns the text from the current line of the active text editor window -*/ -function fetchTextLine(editor: any): string { - return editor.document.lineAt(fetchLineNumber(editor) - 1); +/** Helper Function + ** This function returns the text from the current line of the active text editor window + * @param editor + * @returns editor.document.lineAt(fetchLineNumber(editor) - 1) + */ +function fetchLine(editor: TextEditor | undefined): TextLine { + return editor!.document.lineAt(fetchLineNumber(editor) - 1); // We want the line index, so we remove the 1 we added to the result in fetchLineNumber } -/** Function +/* Function * Function to return the number of selected (highlighted) lines * Changes output to 'Line' for 1 line and 'Lines' for all other instances */ function getNumberOfSelectedLines(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: any = window.activeTextEditor; if (editor) { const numberOfSelectedLines: number = fetchNumberOfSelectedLines(editor); (numberOfSelectedLines !== 1) - ? vscode.window.showInformationMessage(`${numberOfSelectedLines.toString()} Lines Selected`) - : vscode.window.showInformationMessage(`${numberOfSelectedLines.toString()} Line Selected`); + ? window.showInformationMessage(`${numberOfSelectedLines.toString()} Lines Selected`) + : window.showInformationMessage(`${numberOfSelectedLines.toString()} Line Selected`); } else { - vscode.window.showErrorMessage('No document currently active'); + window.showErrorMessage('No document currently active'); } } -/** Function +/* Function * Outputs the current line number the cursor is on */ function getLineNumber(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: any = window.activeTextEditor; if (editor) { const lineNum: number = fetchLineNumber(editor); - vscode.window.showInformationMessage(`Line ${lineNum.toString()}`); + window.showInformationMessage(`Line ${lineNum.toString()}`); } else { - vscode.window.showErrorMessage('No document currently active'); + window.showErrorMessage('No document currently active'); } } -/** Function +/* Function * Used to get the number of indents on a line */ function getIndent(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: any = window.activeTextEditor; if (editor) { - const lineNum: number = fetchLineNumber(editor); - const textLine: any = editor.document.lineAt(lineNum - 1); + const lineNum: number = (fetchLineNumber(editor) - 1); // We want the line index, so we remove the 1 we added to the result in fetchLineNumber + const line : any = editor.document.lineAt(lineNum); - if (textLine.isEmptyOrWhitespace) { - vscode.window.showInformationMessage(`Line ${lineNum.toString()} is Empty`); + if (line.isEmptyOrWhitespace) { + window.showInformationMessage(`Line ${lineNum.toString()} is Empty`); } else { // Grab tab format from open document @@ -111,69 +163,85 @@ function getIndent(): void { size: editor.options.tabSize, hard: !editor.options.insertSpaces }; - const i: number = pl.Lexer.getIndent(textLine.text, tabFmt); + const i: number = pl.Lexer.getIndent(line.text, tabFmt); (i !== 1) - ? vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`) - : vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); + ? window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`) + : window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); } } else { - vscode.window.showErrorMessage('No document currently active'); + window.showErrorMessage('No document currently active'); } } -/* Function -> Returns the number of leading spaces on the line the cursor is on - * There are two methods that can be used to find the leading spaces: - * method 1: - * calculates the number of leading spaces by finding the length of the current line - * then subtracting from that the length of the text after trimming the whitespace at the start - * which will equal the number of whitespace characters - * - * TO-USE: set calculateLeadingSpaces to true - * - * method 2 (default): - * finds the index position of the first non-whitespace character in a 0-index - * this number will equal the number of spaces preceding the non-whitespace character - * due to the nature of 0-indexes. - * - * TO-USE: set calculateLeadingSpaces to false +/* Function + * Returns the number of leading spaces on the line the cursor is on */ function getLeadingSpaces(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: any = window.activeTextEditor; if (editor) { const lineNum : number = fetchLineNumber(editor); - const textLine: any = fetchTextLine(editor); + const line : any = fetchLine(editor); - if (textLine.isEmptyOrWhitespace) { - vscode.window.showInformationMessage(`Line ${lineNum.toString()} is empty`); + if (line.isEmptyOrWhitespace) { + window.showInformationMessage(`Line ${lineNum.toString()} is empty`); } else { - /* - * set true to use method 1: find the number of leading spaces through arithmetic - * set false to use method 2: find the index position of the first non-whitespace character in a 0-index - * - * default: false - */ - const calculateLeadingSpaces: boolean = false; // change boolean value to change method - const numSpaces: number = (calculateLeadingSpaces) - ? pl.Lexer.getLeadingSpacesByArithmetic(textLine) - : pl.Lexer.getLeadingSpacesByIndex(textLine); + const numSpaces = fetchNumberOfLeadingSpaces(editor); /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is 0 or greater than 1 */ (numSpaces !== 1) - ? vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`) - : vscode.window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); + ? window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`) + : window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); } } else { - vscode.window.showErrorMessage('No document currently active'); + window.showErrorMessage('No document currently active'); + } +} + +/* Function + * Selects the leading whitespace at the beginning of a line + * This feature was a request from Senior Design Day Spring 2022 + */ +function selectLeadingWhitespace(): void { + const editor : any = window.activeTextEditor; + + if (editor) { + const numSpaces = fetchNumberOfLeadingSpaces(editor); // This will be used for the output message + const lineNum : number = (fetchLineNumber(editor) - 1); // We want the line index, so we remove the 1 we added to the result in fetchLineNumber + + /* If numSpaces isn't greater than 1, then there is no leading whitespace to select */ + if (numSpaces >= 1) { + const line : any = editor.document.lineAt(lineNum); // Get our line + const startPos: any = line.range.start.character; // Start at the starting character position + const endPos : any = line.firstNonWhitespaceCharacterIndex; // End at the first non whitespace character index + + /* Apply our selection */ + editor.selection = new Selection(new Position(lineNum, startPos), new Position(lineNum, endPos)); + /* After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted */ + window.showTextDocument(editor.document); + + + /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is 0 or greater than 1 */ + (numSpaces !== 1) + ? window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces selected`) + : window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space selected`); + } + else { + window.showErrorMessage(`Line ${lineNum.toString()}: No leading spaces to select!`); // No whitespace to select + window.showTextDocument(editor.document); // Refocus editor + } + } + else { + window.showErrorMessage('No document currently active'); // No active document } } function runLineContext(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: any = window.activeTextEditor; if (editor) { // current text and line number @@ -193,10 +261,10 @@ function runLineContext(): void { // build text const contentString: string = createContextString(context, line); - vscode.window.showInformationMessage(contentString); + window.showInformationMessage(contentString); } else { - vscode.window.showErrorMessage('No document currently active'); + window.showErrorMessage('No document currently active'); } } @@ -232,19 +300,21 @@ function createContextString(context: any, line: string): string { return contextString; } -// find up to `n` words around the cursor, where `n` is -// the value of `#mindReader.reader.contextWindow` +/* + * find up to `n` words around the cursor, where `n` is + * the value of `#mindReader.reader.contextWindow` + */ function runCursorContext(): void { - const editor: any = vscode.window.activeTextEditor; + const editor: any = window.activeTextEditor; if (!editor) { - vscode.window.showErrorMessage('RunCursorContext: No Active Editor'); + window.showErrorMessage('RunCursorContext: No Active Editor'); return; } const cursorPos : any = editor.selection.active; const text : string = editor.document.lineAt(cursorPos).text; - const windowSize : any = vscode.workspace.getConfiguration('mindReader').get('reader.contextWindow'); + const windowSize : any = workspace.getConfiguration('mindReader').get('reader.contextWindow'); let trimmedText: string = text.trimStart(); // trim leading whitespace const leadingWS : number = text.length - trimmedText.length; // # of characters of leading whitespace let pos : number = leadingWS; @@ -299,7 +369,7 @@ function runCursorContext(): void { contextString += spaceWords[i].word + ' '; } // output cursor context string - vscode.window.showInformationMessage(contextString); + window.showInformationMessage(contextString); return; } } From cc1c23a16fb9f12cb4772e201934fdd8ba139fe6 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 4 May 2022 19:27:17 -0500 Subject: [PATCH 54/78] added function, fixed bug Added function for selectLeadingSpaces, fixed bug which was reporting the wrong line number on some functions, added window focusing to most of the functions --- src/commands/text.ts | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 6e72604..14300cc 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -64,8 +64,7 @@ function fetchNumberOfLeadingSpaces(editor: TextEditor | undefined): number { * default: false */ const calculateLeadingSpaces: boolean = false; // change boolean value to change method - const lineNum: number = (fetchLineNumber(editor) - 1); // We want the line index, so we remove the 1 we added to the result in fetchLineNumber - const line : any = editor.document.lineAt(lineNum); + const line : any = fetchLine(editor); /* If true, calculate by arithmetic otherwise get index */ numSpaces = (calculateLeadingSpaces) @@ -126,6 +125,8 @@ function getNumberOfSelectedLines(): void { else { window.showErrorMessage('No document currently active'); } + + window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted } /* Function @@ -142,6 +143,8 @@ function getLineNumber(): void { else { window.showErrorMessage('No document currently active'); } + + window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted } /* Function @@ -151,14 +154,14 @@ function getIndent(): void { const editor: any = window.activeTextEditor; if (editor) { - const lineNum: number = (fetchLineNumber(editor) - 1); // We want the line index, so we remove the 1 we added to the result in fetchLineNumber - const line : any = editor.document.lineAt(lineNum); + const lineNum: number = (fetchLineNumber(editor)); + const line : any = fetchLine(editor); if (line.isEmptyOrWhitespace) { window.showInformationMessage(`Line ${lineNum.toString()} is Empty`); } else { - // Grab tab format from open document + /* Grab tab format from open document */ const tabFmt: any = { size: editor.options.tabSize, hard: !editor.options.insertSpaces @@ -173,6 +176,8 @@ function getIndent(): void { else { window.showErrorMessage('No document currently active'); } + + window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted } /* Function @@ -200,6 +205,8 @@ function getLeadingSpaces(): void { else { window.showErrorMessage('No document currently active'); } + + window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted } /* Function @@ -207,22 +214,21 @@ function getLeadingSpaces(): void { * This feature was a request from Senior Design Day Spring 2022 */ function selectLeadingWhitespace(): void { - const editor : any = window.activeTextEditor; + const editor : any = window.activeTextEditor; if (editor) { - const numSpaces = fetchNumberOfLeadingSpaces(editor); // This will be used for the output message - const lineNum : number = (fetchLineNumber(editor) - 1); // We want the line index, so we remove the 1 we added to the result in fetchLineNumber + const numSpaces = fetchNumberOfLeadingSpaces(editor); // This will be used for the output message + const lineNum : number = (fetchLineNumber(editor)); // Get the displayed line number /* If numSpaces isn't greater than 1, then there is no leading whitespace to select */ if (numSpaces >= 1) { - const line : any = editor.document.lineAt(lineNum); // Get our line + const line : any = fetchLine(editor); const startPos: any = line.range.start.character; // Start at the starting character position const endPos : any = line.firstNonWhitespaceCharacterIndex; // End at the first non whitespace character index /* Apply our selection */ - editor.selection = new Selection(new Position(lineNum, startPos), new Position(lineNum, endPos)); - /* After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted */ - window.showTextDocument(editor.document); + /* We need to subtract 1 from lineNum because we added 1 during the fetchLineNumber above and we want the 0-index for position, so remove it */ + editor.selection = new Selection(new Position((lineNum - 1), startPos), new Position((lineNum - 1), endPos)); /* Ternary operator to change the tense of 'space' to 'spaces' for the output if numSpaces is 0 or greater than 1 */ @@ -232,12 +238,13 @@ function selectLeadingWhitespace(): void { } else { window.showErrorMessage(`Line ${lineNum.toString()}: No leading spaces to select!`); // No whitespace to select - window.showTextDocument(editor.document); // Refocus editor } } else { window.showErrorMessage('No document currently active'); // No active document } + + window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted } function runLineContext(): void { From af9308744b34f214a8c91f1555d4674c0af00d8d Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 4 May 2022 19:28:10 -0500 Subject: [PATCH 55/78] added user config options Added configuration options for the line highlighter feature --- package.json | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 107 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index aecd638..491a94a 100644 --- a/package.json +++ b/package.json @@ -297,10 +297,115 @@ "type": "string", "markdownDescription": "The default port to try and establish a connection on." }, - "mindReader.connection.clearOutputOnRun": { + "mindReader.lineHighlighter.isEnabled": { "type": "boolean", - "description": "Whether to clear the output each time the program is run", + "description": "Enable/Disable the line highlighter", "default": "true" + }, + "mindReader.lineHighlighter.multiLineIsEnabled": { + "type": "boolean", + "description": "Turn off the line highlighter if highlighting multiple lines", + "default": "false" + }, + "mindReader.lineHighlighter.backgroundColor": { + "type": "string", + "markdownDescription": "Set the background color of the line highlighter", + "default": "#232C5C" + }, + "mindReader.lineHighlighter.outlineColor": { + "type": "string", + "markdownDescription": "Set the outline color of the line highlighter", + "default": "#4866FE" + }, + "mindReader.lineHighlighter.outlineWidth": { + "type": "string", + "markdownDescription": "Set the outline width of the line highlighter", + "default": "1px" + }, + "mindReader.lineHighlighter.outlineStyle": { + "type": "string", + "markdownDescription": "Set the outline style of the line highlighter", + "default": "solid" + }, + "mindReader.lineHighlighter.borderColorTop": { + "type": "string", + "markdownDescription": "Set the top border color of the line highlighter", + "default": "#FFFFFF" + }, + "mindReader.lineHighlighter.borderColorRight": { + "type": "string", + "markdownDescription": "Set the right border color of the line highlighter", + "default": "#FFFFFF" + }, + "mindReader.lineHighlighter.borderColorBottom": { + "type": "string", + "markdownDescription": "Set the bottom border color of the line highlighter", + "default": "#FFFFFF" + }, + "mindReader.lineHighlighter.borderColorLeft": { + "type": "string", + "markdownDescription": "Set the left border color of the line highlighter", + "default": "#FFFFFF" + }, + "mindReader.lineHighlighter.borderWidthTop": { + "type": "string", + "markdownDescription": "Set the top border width of the line highlighter", + "default": "1px" + }, + "mindReader.lineHighlighter.borderWidthRight": { + "type": "string", + "markdownDescription": "Set the right border width of the line highlighter", + "default": "16px" + }, + "mindReader.lineHighlighter.borderWidthBottom": { + "type": "string", + "markdownDescription": "Set the bottom border width of the line highlighter", + "default": "1px" + }, + "mindReader.lineHighlighter.borderWidthLeft": { + "type": "string", + "markdownDescription": "Set the left border width of the line highlighter", + "default": "1px" + }, + "mindReader.lineHighlighter.borderStyleTop": { + "type": "string", + "markdownDescription": "Set the top border style of the line highlighter", + "default": "solid" + }, + "mindReader.lineHighlighter.borderStyleRight": { + "type": "string", + "markdownDescription": "Set the right border style of the line highlighter", + "default": "solid" + }, + "mindReader.lineHighlighter.borderStyleBottom": { + "type": "string", + "markdownDescription": "Set the bottom border style of the line highlighter", + "default": "solid" + }, + "mindReader.lineHighlighter.borderStyleLeft": { + "type": "string", + "markdownDescription": "Set the left border style of the line highlighter", + "default": "solid" + }, + "mindReader.lineHighlighter.fontStyle": { + "type": "string", + "markdownDescription": "Set the font style of the line highlighter", + "default": "normal" + }, + "mindReader.lineHighlighter.fontWeight": { + "type": "string", + "markdownDescription": "Set the font weight of the line highlighter", + "default": "bolder" + }, + "mindReader.lineHighlighter.textDecoration": { + "type": "string", + "markdownDescription": "Set the text decoration of the line highlighter", + "default": "none" + }, + "mindReader.lineHighlighter.textColor": { + "type": "string", + "markdownDescription": "Set the text color of the line highlighter", + "default": "#FFFFFF" } } }, From cc8fbc26ad711d961703a8df79aa625811e04f56 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Wed, 4 May 2022 19:40:33 -0500 Subject: [PATCH 56/78] Cleaned Up Code Removed commented out code, added comments, etc --- src/lineHighlighter.ts | 187 +++++++++++------------------------------ 1 file changed, 48 insertions(+), 139 deletions(-) diff --git a/src/lineHighlighter.ts b/src/lineHighlighter.ts index 90ad27e..65445f7 100644 --- a/src/lineHighlighter.ts +++ b/src/lineHighlighter.ts @@ -6,6 +6,7 @@ * ? ██║ ██║██║╚██████╔╝██║ ██║███████╗██║╚██████╔╝██║ ██║ ██║ ██║ ██║ * ? ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ **/ +'use strict'; import { Position, window, workspace, TextEditorDecorationType, TextEditor, WorkspaceConfiguration, Range } from 'vscode'; export { lineHighlighter }; @@ -19,8 +20,7 @@ function lineHighlighter(): void { let multiLineIsEnabled: boolean | undefined = getMultiLineHighlighterStatus(); /** - * Trigger the line highlight when the extension - * loads so current line gets highlighted + * Trigger the line highlight when the extension loads so current line gets highlighted */ triggerHighlight(); @@ -40,7 +40,6 @@ function lineHighlighter(): void { */ window.onDidChangeTextEditorSelection((editor) => { if (!editor.textEditor) { - console.error(`[*] onDidChangeTextEditorSelection(${editor}) -> no active text editor`); return; } @@ -50,9 +49,8 @@ function lineHighlighter(): void { /** * Trigger for when the text document changes */ - workspace.onDidChangeTextDocument((editor) => { + workspace.onDidChangeTextDocument(() => { if (!activeTextEditor) { - console.error(`[*] onDidChangeTextDocument(${editor}) -> no active text editor`); return; } @@ -78,15 +76,11 @@ function lineHighlighter(): void { return; } - // Dump existing styling - highlightStyle.dispose(); - // check if line highlighter is enable/disabled - isEnabled = getHighlighterStatus(); - multiLineIsEnabled = getMultiLineHighlighterStatus(); - // get new line highlighter styling - highlightStyle = getHighlighterStyle(); - // trigger highlight with new styling - triggerHighlight(); + highlightStyle.dispose(); // Dump existing styling + isEnabled = getHighlighterStatus(); // check if line highlighter is enable/disabled + multiLineIsEnabled = getMultiLineHighlighterStatus(); // Check if multiline highlighting is enabled/disabled + highlightStyle = getHighlighterStyle(); // get new line highlighter styling + triggerHighlight(); // trigger highlight with new styling }); /** @@ -94,7 +88,6 @@ function lineHighlighter(): void { */ function triggerHighlight(): void { if (!activeTextEditor) { - console.error("[*] NO Active Text Editor"); return; } @@ -108,78 +101,77 @@ function lineHighlighter(): void { * set the decorations with our chosen highlighting style on the selection * otherwise (highlighter is disabled) dump our highlighting style */ - // (isEnabled) - // ? activeTextEditor!.setDecorations(highlightStyle, activeTextEditor!.selections) - // : highlightStyle.dispose(); switch (isEnabled) { - case true: // isEnabled is true + case true: /* isEnabled is true */ switch (multiLineIsEnabled) { - case true: // isEnabled is true and multiLineIsEnabled is true - // const startLine = activeTextEditor!.selection.start; - // const endLine = activeTextEditor!.selection.end; - // const rangeToHighlight = { range: new Range(startLine, endLine) }; - // activeTextEditor!.setDecorations(highlightStyle, [rangeToHighlight]); - // const currentLineRange = activeTextEditor!.document.lineAt(activeTextEditor!.selection.anchor).range; - // activeTextEditor!.setDecorations(highlightStyle, [currentLineRange]); - // const startLine = activeTextEditor!.selection.start.line; - // const endLine = activeTextEditor!.selection.end; - // const rangeToHighlight = { range: new Range(startLine, endLine) }; + case true: /* isEnabled is true and multiLineIsEnabled is true */ activeTextEditor.setDecorations(highlightStyle, activeTextEditor.selections); break; - case false: // isEnabled is true and multiLineIsEnabled is false + case false: /* isEnabled is true and multiLineIsEnabled is false */ switch (activeTextEditor.selection.isSingleLine) { - case true: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting a single line + case true: /* isEnabled is true and multiLineIsEnabled is false and VSCode is reporting a single line */ let currentPosition = []; for (let i = 0; i < activeTextEditor.selections.length; i++) { currentPosition[i] = { range: new Range(activeTextEditor.selections[i].anchor, activeTextEditor.selections[i].anchor) }; } activeTextEditor.setDecorations(highlightStyle, currentPosition); - // const currentLine = activeTextEditor.selection.active.line; - // const newDecoration = { range: new Range(currentPosition, currentPosition) }; - // const singleLineHighlight = { range: new Range(activeTextEditor!.selection.anchor.line, activeTextEditor!.selection.anchor.line) }; - // activeTextEditor!.setDecorations(highlightStyle, [singleLineRange]); - // activeTextEditor.setDecorations(highlightStyle, [activeTextEditor.selection]); break; - case false: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting multiple lines + case false: /* isEnabled is true and multiLineIsEnabled is false and VSCode is reporting multiple lines */ // Dispose of our highlighting style so multiple lines aren't all highlighted when clicking and dragging to highlight - // highlightStyle.dispose(); - activeTextEditor.setDecorations(highlightStyle, []); - // Since we disposed of our highlighting style, we need to re-acquire it for highlighting to continue to work after clicking and dragging to highlight - // highlightStyle = getHighlighterStyle(); + activeTextEditor.setDecorations(highlightStyle, []); // This will dispose of a single editor instead of all editors break; - default: // isEnabled is true and multiLineIsEnabled is false and VSCode is reporting something else - break out of 3rd switch + default: /* isEnabled is true and multiLineIsEnabled is false and VSCode is reporting something else - break out of 3rd switch */ break; } break; - default: // isEnabled is true and multiLineIsEnabled is undetected - break out of 2nd switch statement + default: /* isEnabled is true and multiLineIsEnabled is undetected - break out of 2nd switch statement */ break; } break; - case false: // isEnabled is false + case false: /* isEnabled is false */ highlightStyle.dispose(); break; - default: // break out of initial switch is true or false not found + default: /* break out of initial switch if 'true or false' is not found */ break; } - // Track new position, without this the line the the cursor begins on will never get styled + // Keep track of position new Position(activeTextEditor.selection.start.line, activeTextEditor.selection.start.character); } } /** - * Function to get the user configured highlighting styles, or use defaults + * * Function to get the user configured highlighting styles, or use defaults * - * Designed with user configuration in mind, able to control different sides - * independently from each other (in most cases). This allows for many different - * configurations. + * * Designed with user configuration in mind, able to control different sides + * * independently from each other (in most cases). This allows for many different + * * configurations. + * + * ? Colors Can be input with the following values: + * * https://www.w3schools.com/cssref/css_colors.asp for string based color values + * * Hex -> # | rgb(###, ###, ###) | rgba(###, ###, ###, ###) | hsla(##, ##%, ##%, .#) + * + * ? Width Input Values + * ! Some work better than others, if one isn't working try a different method: + * * thin | medium | thick | px | rem | em | cm | % | inherit + * + * ? Other values + * * font-style : normal|italic|oblique|initial|inherit; + * * font-weight : normal|bold|bolder|lighter|number|initial|inherit; + * * border-style : none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset|initial|inherit; + * * outline-style : none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset|initial|inherit; + * * outline-width : medium|thin|thick|length|initial|inherit; + * * border-width : medium|thin|thick|length|initial|inherit; + * ! https://www.w3schools.com/cssref/pr_text_text-decoration.asp for text-decoration + * + * ! borderWidthRight acts weirdly, on my system 16px works best with the other directions set to 1px * * @returns highlighterStyle */ function getHighlighterStyle(): TextEditorDecorationType { - // Used so we don't have to type out workspace.getConfiguration('mind-reader.lineHighlight') on every line, ie: shorthand - const userConfig: WorkspaceConfiguration = workspace.getConfiguration('mind-reader.lineHighlight'); + // Used so we don't have to type out workspace.getConfiguration('mindReader.lineHighlighter') on every line, ie: shorthand + const userConfig: WorkspaceConfiguration = workspace.getConfiguration('mindReader.lineHighlighter'); const borderWidthTop : string = userConfig.get('borderWidthTop') || "1px"; const borderWidthRight : string = userConfig.get('borderWidthRight') || "16px"; @@ -245,9 +237,9 @@ function lineHighlighter(): void { * otherwise, "isEnabled" is listed in the settings * - so we just pull its value */ - (workspace.getConfiguration("mind-reader.lineHighlight").get("isEnabled") === undefined) + (workspace.getConfiguration("mindReader.lineHighlighter").get("isEnabled") === undefined) ? (enabledStatus = true) - : (enabledStatus = workspace.getConfiguration("mind-reader.lineHighlight").get("isEnabled")); + : (enabledStatus = workspace.getConfiguration("mindReader.lineHighlighter").get("isEnabled")); // return the enabledStatus return enabledStatus; @@ -263,9 +255,9 @@ function lineHighlighter(): void { * otherwise, "isEnabled" is listed in the settings * - so we just pull its value */ - (workspace.getConfiguration("mind-reader.lineHighlight").get("multiLineIsEnabled") === undefined) + (workspace.getConfiguration("mindReader.lineHighlighter").get("multiLineIsEnabled") === undefined) ? (multiLineIsEnabled = true) - : (multiLineIsEnabled = workspace.getConfiguration("mind-reader.lineHighlight").get("multiLineIsEnabled")); + : (multiLineIsEnabled = workspace.getConfiguration("mindReader.lineHighlighter").get("multiLineIsEnabled")); // return the enabledStatus return multiLineIsEnabled; @@ -279,86 +271,3 @@ export function deactivate() { highlightStyle.dispose(); } } - - /** - * Border Width Settings - * borderWidthTop = Top Border Width - * borderWidthRight = Right Border Width * Right border is a little finicky, I have all others at 1px, but need 15px for this one to match - * borderWidthBottom = Bottom Border Width - * borderWidthLeft = Left Border Width - * - * Uses CSS so should accept: - * thin | medium | thick - * px - * rem - * em - * cm - * % - Weird behavior - * inherit - * - * If no value is found in the settings, we set the value after the double pipes (||) instead - */ - - /** - * Border Style Settings - * borderStyleTop = Top Border Style - * borderStyleRight = Right Border Style - * borderStyleBottom = Bottom Border Style - * borderStyleLeft = Left Border Style - * - * Uses CSS so should accept: (Some of them I can't tell a difference, but they do something) - * none - * hidden - * dotted - * dashed - * solid - * double - * groove - * ridge - * inset - * outset - * - * If no value is found in the settings, we set the value after the double pipes (||) instead - */ - - /** - * Border Color Settings - * borderColorRight = Right Border Color - * borderColorBottom = Bottom Border Color - * borderColorTop = Top Border Color - * borderColorLeft = Left Border Color - * - * Uses CSS so should accept: (Some of them I can't tell a difference, but they do something) - * none - This one doesn't play nice - * string value like "red" | "blue" | "orange" etc - https://www.w3schools.com/cssref/css_colors.asp - * # - * rgb(###, ###, ###) - * rgba(###, ###, ###, ###) - * hsla(##, ##%, ##%, .#); - * inherit - This one has weird behavior as well - * - * If no value is found in the settings, we set the value after the double pipes (||) instead - */ - - /** - * Color of the background - * - * Uses CSS so should accept: - * none - This one doesn't play nice - * string value like "red" | "blue" | "orange" etc - https://www.w3schools.com/cssref/css_colors.asp - * # - * rgb(###, ###, ###) - * rgba(###, ###, ###, ###) - * hsla(##, ##%, ##%, .#); - * inherit - This one has weird behavior as well - * - * If no value is found in the settings, we set the value after the double pipes (||) instead - */ - - /** - * font-style: normal|italic|oblique|initial|inherit - */ - - /** - * font-weight: normal|bold|bolder|lighter|number|initial|inherit - */ \ No newline at end of file From 630391b5fe97138d0be9702e8bef12d2674eed4d Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 5 May 2022 11:51:12 -0500 Subject: [PATCH 57/78] Many Changes Added settings for line highlighter, added contributors section, added bugs section, added homepage section, changed all instances of mindReader to mind-reader, changed all instances of Mind_Reader to Mind Reader --- package.json | 476 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 307 insertions(+), 169 deletions(-) diff --git a/package.json b/package.json index 491a94a..23a4863 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,53 @@ { "name": "mind-reader", - "displayName": "Mind_Reader", - "repository": "https://github.com/We-Dont-Byte/Mind_Reader", + "displayName": "Mind Reader", + "homepage": "https://github.com/We-Dont-Byte/Mind_Reader/wiki", + "repository": { + "type": "git", + "url": "https://github.com/We-Dont-Byte/Mind_Reader" + }, + "bugs": { + "type": "git", + "url": "https://github.com/We-Dont-Byte/Mind_Reader/issues" + }, + "contributors": [ + { + "name" : "Jake Grossman", + "email" : "JacobGrossman2@my.unt.edu" + }, + { + "name" : "Cal Wooten", + "email" : "calwooten@my.unt.edu" + }, + { + "name" : "Josiah Mosesn", + "email" : "josiahmoses@my.unt.edu" + }, + { + "name" : "Sophia Drewfs", + "email" : "sophiadrewfs@my.unt.edu" + }, + { + "name" : "John Breaux", + "email" : "JohnBreaux@my.unt.edu" + }, + { + "name" : "Thomas Lane", + "email" : "ThomasLane2@my.unt.edu" + }, + { + "name" : "Ryan Tolbert", + "email" : "RyanTolbert@my.unt.edu" + }, + { + "name" : "Kendrick Johnson", + "email" : "KendrickJohnson@my.unt.edu" + }, + { + "name" : "Pedro Alvarez", + "email" : "PedroAlvarez3@my.unt.edu" + } + ], "version": "1.0.0", "engines": { "vscode": "^1.60.0" @@ -15,10 +61,6 @@ "main": "./out/extension.js", "contributes": { "commands": [{ - "command": "mind-reader.helloWorld", - "title": "Hello World" - }, - { "command": "mind-reader.increaseFontScale", "title": "Increase Font Scale" }, @@ -66,9 +108,25 @@ "command": "mind-reader.runCursorContext", "title": "Run Cursor Context" }, + { + "command": "mind-reader.getLineNumber", + "title": "Get The Current Line Number" + }, { "command": "mind-reader.getIndent", - "title": "Get Line Indentation" + "title": "Get The Number Of Line Indentation" + }, + { + "command": "mind-reader.getLeadingSpaces", + "title": "Get The Number Of Leading Spaces" + }, + { + "command": "mind-reader.selectLeadingWhitespace", + "title": "Select The Leading Whitespace" + }, + { + "command": "mind-reader.getNumberOfSelectedLines", + "title": "Get The Number Of Selected Lines" }, { "command": "mind-reader.connectHub", @@ -95,105 +153,126 @@ "title": "Delete a program from the LEGO Hub" } ], - "keybindings": [{ + "keybindings": [ + { + "command": "mind-reader.selectTheme", + "key": "", + "mac": "" + }, + { "command": "mind-reader.decreaseFontScale", - "key": "numpad_subtract", - "mac": "d" + "key": "", + "mac": "" }, { "command": "mind-reader.increaseFontScale", - "key": "numpad_add", - "mac": "[NumpadAdd]" + "key": "", + "mac": "" }, { "command": "mind-reader.increaseEditorScale", - "key": "shift+numpad_add", - "mac": "Shift+[NumpadAdd]" + "key": "", + "mac": "" }, { "command": "mind-reader.decreaseEditorScale", - "key": "shift+numpad_subtract", - "mac": "Shift+[NumpadSubtract]" + "key": "", + "mac": "" }, { "command": "mind-reader.resetEditorScale", - "key": "shift+enter", - "mac": "Shift+[Enter]" + "key": "", + "mac": "" }, { "command": "mind-reader.showAllSymbols", - "key": "Ctrl+T", - "mac": "Cmd+[KeyT]" + "key": "", + "mac": "" }, { "command": "mind-reader.gotoLine", - "key": "CTRL+G", - "mac": "Cmd+[KeyG]" + "key": "", + "mac": "" }, { "command": "mind-reader.quickOpen", - "key": "CTRL+P", - "mac": "Cmd+[KeyP]" + "key": "", + "mac": "" }, { "command": "mind-reader.gotoSymbol", - "key": "Ctrl+Shift+O", - "mac": "Cmd+Shift+[KeyO]" + "key": "", + "mac": "" }, { "command": "mind-reader.showProblems", - "key": "Ctrl+Shift+M", - "mac": "Cmd+Shift+[KeyM]" + "key": "", + "mac": "" }, { "command": "mind-reader.nextInFiles", - "key": "F8", - "mac": "[F8]" + "key": "", + "mac": "" }, { "command": "mind-reader.prevInFiles", - "key": "Shift+F8", - "mac": "Shift+[F8]" + "key": "", + "mac": "" }, { "command": "mind-reader.quickOpenPreviousRecentlyUsedEditorInGroup", - "key": "Ctrl+Tab", - "mac": "Cmd+[Tab]" + "key": "", + "mac": "" }, { "command": "mind-reader.navigateBack", - "key": "Ctrl+Alt+-", - "mac": "Cmd+Alt+[Minus]" + "key": "", + "mac": "" }, { "command": "mind-reader.getQuickInputBack", - "key": "Ctrl+Alt+-", - "mac": "Cmd+Alt+[Minus]" + "key": "", + "mac": "" }, { "command": "mind-reader.navigateForward", - "key": "Ctrl+Shift+-", - "mac": "Cmd+Shift+[Minus]" + "key": "", + "mac": "" }, { - "command": "mind-reader.selectTheme", - "key": "Ctrl+Shift+1", - "mac": "Cmd+Shift+[Digit1]" + "command": "mind-reader.getLineNumber", + "key": "", + "mac": "" }, { "command": "mind-reader.getIndent", - "key": "Shift+Tab", - "mac": "Shift+[Tab]" + "key": "", + "mac": "" + }, + { + "command": "mind-reader.getLeadingSpaces", + "key": "", + "mac": "" + }, + { + "command": "mind-reader.selectLeadingWhitespace", + "key": "", + "mac": "" + }, + { + "command": "mind-reader.getNumberOfSelectedLines", + "key": "", + "mac": "" }, { "command": "mind-reader.openKeyBindWin", - "key": "Ctrl+Shift+8", - "mac": "Cmd+Shift+8" + "key": "", + "mac": "" }, { "command": "mind-reader.openKeyBindMac", - "key": "Ctrl+Shift+9", - "mac": "Cmd+Shift+9" + "key": "", + "mac": "" } ], "menus": { @@ -201,8 +280,14 @@ "submenu": "mind-reader.editor.context", "group": "mind-reader" }], - "mind-reader.editor.context": [{ - "command": "mind-reader.increaseEditorScale", + "mind-reader.editor.context": [ + { + "command": "mind-reader.selectTheme", + "group": "mind-reader", + "when": "activeEditor" + }, + { + "command": "mind-reader.increaseFontScale", "group": "mind-reader", "when": "activeEditor" }, @@ -232,7 +317,27 @@ "when": "activeEditor" }, { - "command": "mind-reader.selectTheme", + "command": "mind-reader.getLineNumber", + "group": "mind-reader", + "when": "activeEditor" + }, + { + "command": "mind-reader.getIndent", + "group": "mind-reader", + "when": "activeEditor" + }, + { + "command": "mind-reader.getLeadingSpaces", + "group": "mind-reader", + "when": "activeEditor" + }, + { + "command": "mind-reader.selectLeadingWhitespace", + "group": "mind-reader", + "when": "activeEditor" + }, + { + "command": "mind-reader.getNumberOfSelectedLines", "group": "mind-reader", "when": "activeEditor" }, @@ -255,12 +360,14 @@ }, "submenus": [{ "id": "mind-reader.editor.context", - "label": "Mind_Reader" + "label": "Mind Reader" }], - "configuration": { - "title": "Mind_Reader", + "configuration": [{ + "title": "Mind Reader", + "order": 0, "properties": { - "mindReader.productType": { + "mind-reader.productType": { + "order": 1, "type": "string", "description": "Specifies the LEGO® product.", "default": "MINDSTORMS EV3", @@ -273,7 +380,8 @@ "LEGO® Education SPIKE™ Prime Set (45678)" ] }, - "mindReader.reader.screenReader": { + "mind-reader.reader.screenReader": { + "order": 0, "type": "string", "description": "Specifies which screen reader to optimize for.", "default": "NVDA", @@ -288,127 +396,157 @@ "Apple VoiceOver (macOS)" ] }, - "mindReader.reader.contextWindow": { + "mind-reader.reader.contextWindow": { + "order": 3, "type": "number", "description": "The number of words around the cursor to use when reading the cursor context", "default": 1 }, - "mindReader.connection.portPath": { + "mind-reader.connection.portPath": { + "order": 2, "type": "string", "markdownDescription": "The default port to try and establish a connection on." - }, - "mindReader.lineHighlighter.isEnabled": { - "type": "boolean", - "description": "Enable/Disable the line highlighter", - "default": "true" - }, - "mindReader.lineHighlighter.multiLineIsEnabled": { - "type": "boolean", - "description": "Turn off the line highlighter if highlighting multiple lines", - "default": "false" - }, - "mindReader.lineHighlighter.backgroundColor": { - "type": "string", - "markdownDescription": "Set the background color of the line highlighter", - "default": "#232C5C" - }, - "mindReader.lineHighlighter.outlineColor": { - "type": "string", - "markdownDescription": "Set the outline color of the line highlighter", - "default": "#4866FE" - }, - "mindReader.lineHighlighter.outlineWidth": { - "type": "string", - "markdownDescription": "Set the outline width of the line highlighter", - "default": "1px" - }, - "mindReader.lineHighlighter.outlineStyle": { - "type": "string", - "markdownDescription": "Set the outline style of the line highlighter", - "default": "solid" - }, - "mindReader.lineHighlighter.borderColorTop": { - "type": "string", - "markdownDescription": "Set the top border color of the line highlighter", - "default": "#FFFFFF" - }, - "mindReader.lineHighlighter.borderColorRight": { - "type": "string", - "markdownDescription": "Set the right border color of the line highlighter", - "default": "#FFFFFF" - }, - "mindReader.lineHighlighter.borderColorBottom": { - "type": "string", - "markdownDescription": "Set the bottom border color of the line highlighter", - "default": "#FFFFFF" - }, - "mindReader.lineHighlighter.borderColorLeft": { - "type": "string", - "markdownDescription": "Set the left border color of the line highlighter", - "default": "#FFFFFF" - }, - "mindReader.lineHighlighter.borderWidthTop": { - "type": "string", - "markdownDescription": "Set the top border width of the line highlighter", - "default": "1px" - }, - "mindReader.lineHighlighter.borderWidthRight": { - "type": "string", - "markdownDescription": "Set the right border width of the line highlighter", - "default": "16px" - }, - "mindReader.lineHighlighter.borderWidthBottom": { - "type": "string", - "markdownDescription": "Set the bottom border width of the line highlighter", - "default": "1px" - }, - "mindReader.lineHighlighter.borderWidthLeft": { - "type": "string", - "markdownDescription": "Set the left border width of the line highlighter", - "default": "1px" - }, - "mindReader.lineHighlighter.borderStyleTop": { - "type": "string", - "markdownDescription": "Set the top border style of the line highlighter", - "default": "solid" - }, - "mindReader.lineHighlighter.borderStyleRight": { - "type": "string", - "markdownDescription": "Set the right border style of the line highlighter", - "default": "solid" - }, - "mindReader.lineHighlighter.borderStyleBottom": { - "type": "string", - "markdownDescription": "Set the bottom border style of the line highlighter", - "default": "solid" - }, - "mindReader.lineHighlighter.borderStyleLeft": { - "type": "string", - "markdownDescription": "Set the left border style of the line highlighter", - "default": "solid" - }, - "mindReader.lineHighlighter.fontStyle": { - "type": "string", - "markdownDescription": "Set the font style of the line highlighter", - "default": "normal" - }, - "mindReader.lineHighlighter.fontWeight": { - "type": "string", - "markdownDescription": "Set the font weight of the line highlighter", - "default": "bolder" - }, - "mindReader.lineHighlighter.textDecoration": { - "type": "string", - "markdownDescription": "Set the text decoration of the line highlighter", - "default": "none" - }, - "mindReader.lineHighlighter.textColor": { - "type": "string", - "markdownDescription": "Set the text color of the line highlighter", - "default": "#FFFFFF" } } }, + { + "title": "Line Highlighter [Must Close Settings And RESTART VSCode For The Line Highlighter To Function]", + "order": 1, + "properties": { + "mind-reader.lineHighlighter.isEnabled": { + "order": 4, + "type": "boolean", + "markdownDescription": "Enable/Disable the line highlighter.\n\n\n* `Enabled (our default)`: Checked: Line Highlighter is turned `ON`\n* `Disabled`: Unchecked: Line Highlighter is turned `OFF`\n\n### `NOTE`: You Must Close Settings And RESTART Visual Studio Code For The Line Highlighter To Function\n#### Even If No Changes Were Made", + "default": "true" + }, + "mind-reader.lineHighlighter.multiLineIsEnabled": { + "order": 5, + "type": "boolean", + "markdownDescription": "Temporarily Disable highlighting when highlighting multiple lines.\n\n\n* `Enabled`: Checked: Multiline Highlighting is turned `ON`:\n* * When you click and drag line highlights will be applied to all lines\n* `Disabled (our default)`: Unchecked: Multiline Highlighting is turned `OFF`:\n* * When you click and drag the line highlighter will disable itself then re-enable itself when you click onto a single line.", + "default": "false" + }, + "mind-reader.lineHighlighter.backgroundColor": { + "order": 6, + "type": "string", + "markdownDescription": "Set the background color to be used by the line highlighter.\n\nSyntax: _color_ or `transparent`\n\nAvailable color formats include:\n* `HEX(A)`: for Hexadecimal Colors: `#RRGGBB` or `#RRGGBBAA` to add transparency\n* `RGB(A)`: for RGB Colors: `rgb(red, green, blue)` or `rgba(red, green, blue, alpha)`\n* `HSL(A)`: for HSL Colors: `hsl(hue, saturation, lightness)` or `hsla(hue, saturation, lightness, alpha)`\n* `Predefined Color Names`: 140 color names are predefined in the HTML and CSS color specification: `blue`, `red`, `coral`, `brown`, [etc...](https://www.w3schools.com/colors/colors_names.asp)\n* `None`: For no color to be applied: Sometimes VSCode will pull a color from your theme, other times it uses black\n* `#232C5C` is our default", + "default": "#232C5C" + }, + "mind-reader.lineHighlighter.outlineColor": { + "order": 7, + "type": "string", + "markdownDescription": "Set the outline color to be used by the line highlighter.\n\nSyntax: _color_ or `transparent`\n\nAvailable color formats include:\n* `HEX(A)`: for Hexadecimal Colors: `#RRGGBB` or `#RRGGBBAA` to add transparency\n* `RGB(A)`: for RGB Colors: `rgb(red, green, blue)` or `rgba(red, green, blue, alpha)`\n* `HSL(A)`: for HSL Colors: `hsl(hue, saturation, lightness)` or `hsla(hue, saturation, lightness, alpha)`\n* `Predefined Color Names`: 140 color names are predefined in the HTML and CSS color specification: `blue`, `red`, `coral`, `brown`, [etc...](https://www.w3schools.com/colors/colors_names.asp)\n* `None`: For no color to be applied: Sometimes VSCode will pull a color from your theme, other times it uses black\n* `#4866FE` is our default", + "default": "#4866FE" + }, + "mind-reader.lineHighlighter.outlineWidth": { + "order": 8, + "type": "string", + "markdownDescription": "Set the outline width to be used by the line highlighter.\n\nSyntax: `medium` or `thin` or `thick` or `length` or `none`\n* `medium`: Specifies a medium outline. (usual default)\n* `thin`: Specifies a thin outline\n* `thick`: Specifies a thick outline\n* `length`: you to define the thickness of the outline in [length](https://www.w3schools.com/cssref/css_units.asp) units.\n* `none`: No outline width will be applied\n* `1px` is our default", + "default": "1px" + }, + "mind-reader.lineHighlighter.outlineStyle": { + "order": 9, + "type": "string", + "markdownDescription": "Set the outline style to be used by the line highlighter.\n\nSyntax: `none` or `hidden` or `dotted` or `dashed` or `solid` or `double` or `groove` or `ridge` or `inset` or `outset`\n* `none`: No border will be applied (usual default)\n* `hidden`: The same as `none`\n* `dotted`: Dotted border\n* `dashed`: Dashed border\n* `solid (our default)`: Solid border\n* `double`: Double border\n* `groove`: 3D grooved border, depends on the outline-color value.\n* `ridge`: 3D ridged border, depends on the outline-color value.\n* `inset`: 3D inset border, depends on the outline-color value.\n* `outset`: 3D outset border, depends on the outline-color value.", + "default": "solid" + }, + "mind-reader.lineHighlighter.borderColorTop": { + "order": 10, + "type": "string", + "markdownDescription": "Set the top border color to be used by the line highlighter.\n\nSyntax: _color_ or `transparent`\n\nAvailable color formats include:\n* `HEX(A)`: for Hexadecimal Colors: `#RRGGBB` or `#RRGGBBAA` to add transparency\n* `RGB(A)`: for RGB Colors: `rgb(red, green, blue)` or `rgba(red, green, blue, alpha)`\n* `HSL(A)`: for HSL Colors: `hsl(hue, saturation, lightness)` or `hsla(hue, saturation, lightness, alpha)`\n* `Predefined Color Names`: 140 color names are predefined in the HTML and CSS color specification: `blue`, `red`, `coral`, `brown`, [etc...](https://www.w3schools.com/colors/colors_names.asp)\n* `None`: For no color to be applied: Sometimes VSCode will pull a color from your theme, other times it uses black\n* `#FFFFFF` is our default", + "default": "#FFFFFF" + }, + "mind-reader.lineHighlighter.borderColorRight": { + "order": 11, + "type": "string", + "markdownDescription": "Set the right border color to be used by the line highlighter.\n\nSyntax: _color_ or `transparent`\n\nAvailable color formats include:\n* `HEX(A)`: for Hexadecimal Colors: `#RRGGBB` or `#RRGGBBAA` to add transparency\n* `RGB(A)`: for RGB Colors: `rgb(red, green, blue)` or `rgba(red, green, blue, alpha)`\n* `HSL(A)`: for HSL Colors: `hsl(hue, saturation, lightness)` or `hsla(hue, saturation, lightness, alpha)`\n* `Predefined Color Names`: 140 color names are predefined in the HTML and CSS color specification: `blue`, `red`, `coral`, `brown`, [etc...](https://www.w3schools.com/colors/colors_names.asp)\n* `None`: For no color to be applied: Sometimes VSCode will pull a color from your theme, other times it uses black\n* `#FFFFFF` is our default", + "default": "#FFFFFF" + }, + "mind-reader.lineHighlighter.borderColorBottom": { + "order": 12, + "type": "string", + "markdownDescription": "Set the bottom border color to be used by the line highlighter.\n\nSyntax: _color_ or `transparent`\n\nAvailable color formats include:\n* `HEX(A)`: for Hexadecimal Colors: `#RRGGBB` or `#RRGGBBAA` to add transparency\n* `RGB(A)`: for RGB Colors: `rgb(red, green, blue)` or `rgba(red, green, blue, alpha)`\n* `HSL(A)`: for HSL Colors: `hsl(hue, saturation, lightness)` or `hsla(hue, saturation, lightness, alpha)`\n* `Predefined Color Names`: 140 color names are predefined in the HTML and CSS color specification: `blue`, `red`, `coral`, `brown`, [etc...](https://www.w3schools.com/colors/colors_names.asp)\n* `None`: For no color to be applied: Sometimes VSCode will pull a color from your theme, other times it uses black\n* `#FFFFFF` is our default", + "default": "#FFFFFF" + }, + "mind-reader.lineHighlighter.borderColorLeft": { + "order": 13, + "type": "string", + "markdownDescription": "Set the left border color to be used by the line highlighter.\n\nSyntax: _color_ or `transparent`\n\nAvailable color formats include:\n* `HEX(A)`: for Hexadecimal Colors: `#RRGGBB` or `#RRGGBBAA` to add transparency\n* `RGB(A)`: for RGB Colors: `rgb(red, green, blue)` or `rgba(red, green, blue, alpha)`\n* `HSL(A)`: for HSL Colors: `hsl(hue, saturation, lightness)` or `hsla(hue, saturation, lightness, alpha)`\n* `Predefined Color Names`: 140 color names are predefined in the HTML and CSS color specification: `blue`, `red`, `coral`, `brown`, [etc...](https://www.w3schools.com/colors/colors_names.asp)\n* `None`: For no color to be applied: Sometimes VSCode will pull a color from your theme, other times it uses black\n* `#FFFFFF` is our default", + "default": "#FFFFFF" + }, + "mind-reader.lineHighlighter.borderWidthTop": { + "order": 14, + "type": "string", + "markdownDescription": "Set the top border width to be used by the line highlighter.\n\nSyntax: `medium` or `thin` or `thick` or `length` or `none`\n* `medium`: Specifies a medium border. (usual default)\n* `thin`: Specifies a thin border\n* `thick`: Specifies a thick border\n* `length`: you to define the thickness of the border in [length](https://www.w3schools.com/cssref/css_units.asp) units.\n* `none`: No border width will be applied\n* `1px` is our default", + "default": "1px" + }, + "mind-reader.lineHighlighter.borderWidthRight": { + "order": 15, + "type": "string", + "markdownDescription": "Set the right border width to be used by the line highlighter.\n\nSyntax: `medium` or `thin` or `thick` or `length` or `none`\n* `medium`: Specifies a medium border. (usual default)\n* `thin`: Specifies a thin border\n* `thick`: Specifies a thick border\n* `length`: you to define the thickness of the border in [length](https://www.w3schools.com/cssref/css_units.asp) units.\n* `none`: No border width will be applied\n* `16px` is our default\n\n#### \nborderWidthRight exhibits odd behavior, play around with different sizes to find what works best for your environment.", + "default": "16px" + }, + "mind-reader.lineHighlighter.borderWidthBottom": { + "order": 16, + "type": "string", + "markdownDescription": "Set the bottom border width to be used by the line highlighter.\n\nSyntax: `medium` or `thin` or `thick` or `length` or `none`\n* `medium`: Specifies a medium border. (usual default)\n* `thin`: Specifies a thin border\n* `thick`: Specifies a thick border\n* `length`: you to define the thickness of the border in [length](https://www.w3schools.com/cssref/css_units.asp) units.\n* `none`: No border width will be applied\n* `1px` is our default", + "default": "1px" + }, + "mind-reader.lineHighlighter.borderWidthLeft": { + "order": 17, + "type": "string", + "markdownDescription": "Set the left border width to be used by the line highlighter.\n\nSyntax: `medium` or `thin` or `thick` or `length` or `none`\n* `medium`: Specifies a medium border. (usual default)\n* `thin`: Specifies a thin border\n* `thick`: Specifies a thick border\n* `length`: you to define the thickness of the border in [length](https://www.w3schools.com/cssref/css_units.asp) units.\n* `none`: No border width will be applied\n* `1px` is our default", + "default": "1px" + }, + "mind-reader.lineHighlighter.borderStyleTop": { + "order": 18, + "type": "string", + "markdownDescription": "Set the top border style to be used by the line highlighter.\n\nSyntax: `none` or `hidden` or `dotted` or `dashed` or `solid` or `double` or `groove` or `ridge` or `inset` or `outset`\n* `none`: No border will be applied (usual default)\n* `hidden`: The same as `none`\n* `dotted`: Dotted border\n* `dashed`: Dashed border\n* `solid (our default)`: Solid border\n* `double`: Double border\n* `groove`: 3D grooved border, depends on the border-color value.\n* `ridge`: 3D ridged border, depends on the border-color value.\n* `inset`: 3D inset border, depends on the border-color value.\n* `outset`: 3D outset border, depends on the border-color value.", + "default": "solid" + }, + "mind-reader.lineHighlighter.borderStyleRight": { + "order": 19, + "type": "string", + "markdownDescription": "Set the right border style to be used by the line highlighter.\n\nSyntax: `none` or `hidden` or `dotted` or `dashed` or `solid` or `double` or `groove` or `ridge` or `inset` or `outset`\n* `none`: No border will be applied (usual default)\n* `hidden`: The same as `none`\n* `dotted`: Dotted border\n* `dashed`: Dashed border\n* `solid (our default)`: Solid border\n* `double`: Double border\n* `groove`: 3D grooved border, depends on the border-color value.\n* `ridge`: 3D ridged border, depends on the border-color value.\n* `inset`: 3D inset border, depends on the border-color value.\n* `outset`: 3D outset border, depends on the border-color value.", + "default": "solid" + }, + "mind-reader.lineHighlighter.borderStyleBottom": { + "order": 20, + "type": "string", + "markdownDescription": "Set the bottom border style to be used by the line highlighter.\n\nSyntax: `none` or `hidden` or `dotted` or `dashed` or `solid` or `double` or `groove` or `ridge` or `inset` or `outset`\n* `none`: No border will be applied (usual default)\n* `hidden`: The same as `none`\n* `dotted`: Dotted border\n* `dashed`: Dashed border\n* `solid (our default)`: Solid border\n* `double`: Double border\n* `groove`: 3D grooved border, depends on the border-color value.\n* `ridge`: 3D ridged border, depends on the border-color value.\n* `inset`: 3D inset border, depends on the border-color value.\n* `outset`: 3D outset border, depends on the border-color value.", + "default": "solid" + }, + "mind-reader.lineHighlighter.borderStyleLeft": { + "order": 21, + "type": "string", + "markdownDescription": "Set the left border style to be used by the line highlighter.\n\nSyntax: `none` or `hidden` or `dotted` or `dashed` or `solid` or `double` or `groove` or `ridge` or `inset` or `outset`\n* `none`: No border will be applied (usual default)\n* `hidden`: The same as `none`\n* `dotted`: Dotted border\n* `dashed`: Dashed border\n* `solid (our default)`: Solid border\n* `double`: Double border\n* `groove`: 3D grooved border, depends on the border-color value.\n* `ridge`: 3D ridged border, depends on the border-color value.\n* `inset`: 3D inset border, depends on the border-color value.\n* `outset`: 3D outset border, depends on the border-color value.", + "default": "solid" + }, + "mind-reader.lineHighlighter.fontStyle": { + "order": 22, + "type": "string", + "markdownDescription": "Set the font style to be used by the line highlighter.\n\nSyntax: `normal` or `italic` or `oblique` or `none`\n* `normal (our default)`: Displays a normal font style. This is default\n* `italic`: Displays an italic font style\n* `oblique`: Displays an oblique font style\n* `none`: No font style will be applied", + "default": "normal" + }, + "mind-reader.lineHighlighter.fontWeight": { + "order": 23, + "type": "string", + "markdownDescription": "Set the font weight to be used by the line highlighter.\n\nSyntax: `normal` or `bold` or `bolder` or `lighter` or _number_ or `none`\n* `normal`: Normal Characters. (usual default)\n* `bold`: Thick Characters\n* `bolder (our default)`: Thicker Characters\n* `lighter`: Lighter Characters\n * _number_: From `thin` to `thick` characters: `100`, `200`, `300`, `400`, `500`, `600`, `700`, `800`, or `900`: `400` is the same as normal, and `700` is the same as bold.\n* `none`: No font weight will be applied", + "default": "bolder" + }, + "mind-reader.lineHighlighter.textDecoration": { + "order": 24, + "type": "string", + "markdownDescription": "Set the text decoration to be used by the line highlighter.\n\nSyntax: `(text-decoration-line)` `(text-decoration-color)` `(text-decoration-style)` `(text-decoration-thickness)`\n* `text-decoration-line (required)`: Sets the kind of text decoration to use: `underline`, `overline`, `line-through`\n* `text-decoration-color`: Sets the color of the text decoration\n* `text-decoration-style`: Sets the style of the text decoration: `solid`, `wavy`, `dotted`, `dashed`, `double`\n* `text-decoration-thickness`: Sets the thickness of the decoration line\n* `none (our default)`: No text decorations will be applied\n\n`Examples`:\n1. underline blue wavy 5px\n2. line-through\n3. underline overline dotted red", + "default": "none" + }, + "mind-reader.lineHighlighter.textColor": { + "order": 25, + "type": "string", + "markdownDescription": "Set the text color to be used by the line highlighter.\n\nSyntax: _color_ or `transparent`\n\nAvailable color formats include:\n* `HEX(A)`: for Hexadecimal Colors: `#RRGGBB` or `#RRGGBBAA` to add transparency\n* `RGB(A)`: for RGB Colors: `rgb(red, green, blue)` or `rgba(red, green, blue, alpha)`\n* `HSL(A)`: for HSL Colors: `hsl(hue, saturation, lightness)` or `hsla(hue, saturation, lightness, alpha)`\n* `Predefined Color Names`: 140 color names are predefined in the HTML and CSS color specification: `blue`, `red`, `coral`, `brown`, [etc...](https://www.w3schools.com/colors/colors_names.asp)\n* `None`: For no color to be applied: Sometimes VSCode will pull a color from your theme, other times it uses black\n* `#FFFFFF` is our default", + "default": "#FFFFFF" + } + } + }], "views": { "MindReader": [{ "id": "accessActions", From 940a8ed3177110583303da5547bb7847d6b2de58 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 5 May 2022 11:53:02 -0500 Subject: [PATCH 58/78] Configuration Variables Updated Updated configuration variables to match package.json calls, added TODO line at the top --- src/lineHighlighter.ts | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/src/lineHighlighter.ts b/src/lineHighlighter.ts index 65445f7..e8ebc13 100644 --- a/src/lineHighlighter.ts +++ b/src/lineHighlighter.ts @@ -5,6 +5,7 @@ * ? ██╔══██║██║██║ ██║██╔══██║██║ ██║██║ ██║██╔══██║ ██║ ╚════╝██║ ██║ * ? ██║ ██║██║╚██████╔╝██║ ██║███████╗██║╚██████╔╝██║ ██║ ██║ ██║ ██║ * ? ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ +* TODO: Add ability for user to change options through a command pallette configurator **/ 'use strict'; import { Position, window, workspace, TextEditorDecorationType, TextEditor, WorkspaceConfiguration, Range } from 'vscode'; @@ -151,27 +152,27 @@ function lineHighlighter(): void { * ? Colors Can be input with the following values: * * https://www.w3schools.com/cssref/css_colors.asp for string based color values * * Hex -> # | rgb(###, ###, ###) | rgba(###, ###, ###, ###) | hsla(##, ##%, ##%, .#) - * + * * ? Width Input Values * ! Some work better than others, if one isn't working try a different method: - * * thin | medium | thick | px | rem | em | cm | % | inherit + * * thin | medium | thick | px | rem | em | cm * * ? Other values - * * font-style : normal|italic|oblique|initial|inherit; - * * font-weight : normal|bold|bolder|lighter|number|initial|inherit; - * * border-style : none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset|initial|inherit; - * * outline-style : none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset|initial|inherit; - * * outline-width : medium|thin|thick|length|initial|inherit; - * * border-width : medium|thin|thick|length|initial|inherit; - * ! https://www.w3schools.com/cssref/pr_text_text-decoration.asp for text-decoration - * + * * font-style : none|normal|italic|oblique; + * * font-weight : none|normal|bold|bolder|lighter|number; + * * border-style : none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset; + * * outline-style : none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset; + * * outline-width : none|medium|thin|thick|length; + * * border-width : none|medium|thin|thick|length; + * ? https://www.w3schools.com/cssref/pr_text_text-decoration.asp for text-decoration + * * ! borderWidthRight acts weirdly, on my system 16px works best with the other directions set to 1px * * @returns highlighterStyle */ function getHighlighterStyle(): TextEditorDecorationType { - // Used so we don't have to type out workspace.getConfiguration('mindReader.lineHighlighter') on every line, ie: shorthand - const userConfig: WorkspaceConfiguration = workspace.getConfiguration('mindReader.lineHighlighter'); + // Used so we don't have to type out workspace.getConfiguration('mind-reader.lineHighlighter') on every line, ie: shorthand + const userConfig: WorkspaceConfiguration = workspace.getConfiguration('mind-reader.lineHighlighter'); const borderWidthTop : string = userConfig.get('borderWidthTop') || "1px"; const borderWidthRight : string = userConfig.get('borderWidthRight') || "16px"; @@ -237,9 +238,9 @@ function lineHighlighter(): void { * otherwise, "isEnabled" is listed in the settings * - so we just pull its value */ - (workspace.getConfiguration("mindReader.lineHighlighter").get("isEnabled") === undefined) + (workspace.getConfiguration("mind-reader.lineHighlighter").get("isEnabled") === undefined) ? (enabledStatus = true) - : (enabledStatus = workspace.getConfiguration("mindReader.lineHighlighter").get("isEnabled")); + : (enabledStatus = workspace.getConfiguration("mind-reader.lineHighlighter").get("isEnabled")); // return the enabledStatus return enabledStatus; @@ -255,9 +256,9 @@ function lineHighlighter(): void { * otherwise, "isEnabled" is listed in the settings * - so we just pull its value */ - (workspace.getConfiguration("mindReader.lineHighlighter").get("multiLineIsEnabled") === undefined) + (workspace.getConfiguration("mind-reader.lineHighlighter").get("multiLineIsEnabled") === undefined) ? (multiLineIsEnabled = true) - : (multiLineIsEnabled = workspace.getConfiguration("mindReader.lineHighlighter").get("multiLineIsEnabled")); + : (multiLineIsEnabled = workspace.getConfiguration("mind-reader.lineHighlighter").get("multiLineIsEnabled")); // return the enabledStatus return multiLineIsEnabled; From bb0b1be0d41e0bfe0041f3600a8ae61120d5d070 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 5 May 2022 11:54:32 -0500 Subject: [PATCH 59/78] Updated Messages Changed the wording of the loading message --- src/extension.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/extension.ts b/src/extension.ts index 2aa31e5..fcc634a 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -14,8 +14,7 @@ export const logger = new Logger(outputChannel); let parser: pl.Parser = new pl.Parser(); export function activate(context: vscode.ExtensionContext) { - vscode.window.showInformationMessage("Mind_Reader is loaded!"); - + // Engage LineHighlighter lineHighlighter(); parser.parse("Beep Boop"); @@ -41,6 +40,8 @@ export function activate(context: vscode.ExtensionContext) { let hubProvider = new CommandNodeProvider(hubCommands); vscode.window.registerTreeDataProvider("hubActions", hubProvider); + + vscode.window.showInformationMessage("Mind Reader finished loading!"); } export function deactivate() {} From a10200f2bca5ad7694ede14db3d473c68525d0d1 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 5 May 2022 11:56:39 -0500 Subject: [PATCH 60/78] Updated indention Indention was incorrect, fixed. --- src/pylex/lexer.ts | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/src/pylex/lexer.ts b/src/pylex/lexer.ts index 9135aeb..b5b1f9a 100644 --- a/src/pylex/lexer.ts +++ b/src/pylex/lexer.ts @@ -1,9 +1,9 @@ -import { LineToken } from '.'; +import { LineToken } from '.'; import { Symbol, EOFTOKEN, TabInfo } from './token'; type Rule = { pattern: RegExp, - type: Symbol, + type : Symbol, }; /** @@ -11,8 +11,7 @@ type Rule = { * The first item is a recognition pattern, used to recognize the token * the second item is the token type */ -const rules: Rule[] = [ - { +const rules: Rule[] = [{ pattern: /^\s*def\s+(?[a-zA-Z_][a-zA-Z0-9_]*)\(/, type: Symbol.FUNCTION }, @@ -62,8 +61,8 @@ const rules: Rule[] = [ * Line-By-Line Lexer */ export default class Lexer { - private textLines: string[] = []; // array of text lines - private pos: number = 0; + private textLines : string[] = []; // array of text lines + private pos : number = 0; private _currToken: LineToken = EOFTOKEN; /** @@ -93,8 +92,8 @@ export default class Lexer { * @param `text` The new text to lex. */ restart(text ? : string): void { - this.pos = 0; - this._currToken = EOFTOKEN; // if no input, already on EOFTOKEN + this.pos = 0; + this._currToken = EOFTOKEN; // if no input, already on EOFTOKEN if (text) { this.textLines = text.split('\n'); this.next(); // advance to the first token @@ -120,9 +119,9 @@ export default class Lexer { // Until a LineToken is found, or EOF while (this.pos < this.textLines.length) { - const line: string = this.textLines[this.pos]; + const line : string = this.textLines[this.pos]; const indent: number = Lexer.getIndent(line, this.tabFmt!); - let token: LineToken; + let token : LineToken; for (var r of rules) { // Does line match pattern? @@ -131,8 +130,7 @@ export default class Lexer { // Yes... if (match.groups) { token = new LineToken(r.type, this.pos, indent, match.groups["attr"]); - } - else { + } else { token = new LineToken(r.type, this.pos, indent); } @@ -148,8 +146,7 @@ export default class Lexer { if (/^\s*(#.*)?$/.test(line)) { // "empty" line token = new LineToken(Symbol.EMPTY, this.pos, 999999); - } - else { + } else { // This is an INDENT token token = new LineToken(Symbol.INDENT, this.pos, indent); } @@ -218,8 +215,7 @@ export default class Lexer { if (tabFmt.hard) { // used tabs indent = leadingSpace; - } - else { + } else { // use spaces indent = Math.ceil(leadingSpace / tabFmt.size!); } From 09b4d41054ad426550e000012495460a1fdbf6d0 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 5 May 2022 11:59:42 -0500 Subject: [PATCH 62/78] Code cleaned Removed commented out code --- src/commands/nav.ts | 92 --------------------------------------------- 1 file changed, 92 deletions(-) diff --git a/src/commands/nav.ts b/src/commands/nav.ts index a9be064..a33775b 100755 --- a/src/commands/nav.ts +++ b/src/commands/nav.ts @@ -1,6 +1,4 @@ import * as vscode from "vscode"; -// import * as fs from "fs"; -// import * as os from 'os'; import { CommandEntry } from "./commandEntry"; @@ -89,10 +87,6 @@ function openWebview(): void { panel.webview.html = getWebviewContent(); } -// function getWebviewContent(filepath: string) { -// return fs.readFileSync(filepath, {encoding: 'utf-8'}); -// } - function getWebviewContent() { return ` @@ -138,89 +132,3 @@ function getWebviewContent() { `; } - -// export function getPlatform(): 'windows' | 'mac' | 'linux' | undefined { -// let platform: 'windows' | 'mac' | 'linux' | undefined; - -// if (os.platform().toUpperCase() === 'WIN32') { -// platform = 'windows'; -// return platform; -// } - -// if (os.platform().toUpperCase() === 'DARWIN') { -// platform = 'mac'; -// return platform; -// } - -// if (os.platform().toUpperCase() === 'linux') { -// platform = 'linux'; -// return platform; -// } - -// platform = undefined; -// return platform; -// } - -// function getDocumentWorkspaceFolder(): string | undefined { -// const fileName = vscode.window.activeTextEditor?.document.fileName; -// return vscode.workspace.workspaceFolders -// ?.map((folder) => folder.uri.fsPath) -// .filter((fsPath) => fileName?.startsWith(fsPath))[0]; -// } - -// function openKeyBindWin(): void { -// //vscode.commands.executeCommand('workbench.action.zoomOut'); -// const panel = vscode.window.createWebviewPanel( -// 'mindReader', // Identifies the type of the webview. Used internally -// 'MR Key Bindings', // Title of the panel displayed to the user -// vscode.ViewColumn.One, // Editor column to show the new webview panel in. -// {} -// ); // Webview options. More on these later. - -// const userPlatform: 'windows' | 'mac' | 'linux' | undefined = getPlatform(); - -// switch (userPlatform) { -// case 'windows': -// if(vscode.workspace.workspaceFolders !== undefined) { -// let wf = vscode.workspace.workspaceFolders[0].uri.path; -// let f = vscode.workspace.workspaceFolders[0].uri.fsPath; -// const message = `YOUR-EXTENSION: folder: ${wf} - ${f}`; -// vscode.window.showInformationMessage(message); -// } -// else { -// const message = "YOUR-EXTENSION: Working folder not found, open a folder an try again" ; -// vscode.window.showErrorMessage(message); -// } -// // panel.webview.html = getWebviewContent('media/html/winkeys.html'); -// break; -// case 'mac': -// // panel.webview.html = getWebviewContent('media/html/mackeys.html'); -// break; -// case 'linux': -// // panel.webview.html = getWebviewContent('media/html/linuxkeys.html'); -// break; -// default: -// // panel.webview.html = getWebviewContent("../../media/html/main.html"); -// break; -// } -// } - -// function openKeyBindWin(os: 'Mac' | 'Windows'): void { -// //vscode.commands.executeCommand('workbench.action.zoomOut'); -// const panel = vscode.window.createWebviewPanel( -// 'mindReader', // Identifies the type of the webview. Used internally -// 'MR Key Bindings', // Title of the panel displayed to the user -// vscode.ViewColumn.One, // Editor column to show the new webview panel in. -// {} -// ); // Webview options. More on these later. - -// if (os === 'Windows') { -// panel.webview.html = getWebviewContent('WINDOWS'); -// // panel.webview.html = getWebviewContent('/media/html/winkeys.html'); -// } else if (os === 'Mac') { -// panel.webview.html = getWebviewContent('MAC'); -// // panel.webview.html = getWebviewContent('/media/html/mackeys.html'); -// } -// } - -//vscode.commands.executeCommand('workbench.action.openGlobalKeybindings'); From b51507b76f95c8cc73e389b862507f9214d5affc Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 5 May 2022 12:07:13 -0500 Subject: [PATCH 63/78] Version increase Major version increase: 1.0.0 -> 2.0.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 23a4863..3b9af28 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "email" : "PedroAlvarez3@my.unt.edu" } ], - "version": "1.0.0", + "version": "2.0.0", "engines": { "vscode": "^1.60.0" }, From be60f884fee676e810e05cfbc4a80b539503d8d2 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Thu, 5 May 2022 12:15:39 -0500 Subject: [PATCH 64/78] naming scheme changed mindReader to mind-reader to be consistent with other parts of the extension --- src/commands/nav.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/nav.ts b/src/commands/nav.ts index a33775b..57f8ef7 100755 --- a/src/commands/nav.ts +++ b/src/commands/nav.ts @@ -78,7 +78,7 @@ export const navCommands: CommandEntry[] = [ // COMMAND CALLBACK IMPLEMENTATIONS function openWebview(): void { const panel = vscode.window.createWebviewPanel( - "mindReader", // Identifies the type of the webview. Used internally + "mind-reader", // Identifies the type of the webview. Used internally "Mind Reader", // Title of the panel displayed to the user vscode.ViewColumn.One, // Editor column to show the new webview panel in. {} From 9ef756838bc621eecefa6f095074d071fd92399f Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 16:12:55 -0500 Subject: [PATCH 65/78] Attempt fix setup script on Linux Also update CC BY-SA notice of attribution --- .../package-managers/pacman.dependencies | 3 +- setup-development/linux/upgrade-linux.sh | 50 ++++++++++++++----- setup-development/windows/install-windows.ps1 | 2 +- setup-development/windows/upgrade-windows.ps1 | 2 +- .../windows/winget/dependencies.json | 3 -- src/pylex/token.ts | 2 +- 6 files changed, 42 insertions(+), 20 deletions(-) diff --git a/setup-development/linux/package-managers/pacman.dependencies b/setup-development/linux/package-managers/pacman.dependencies index 89859bb..1b50f89 100644 --- a/setup-development/linux/package-managers/pacman.dependencies +++ b/setup-development/linux/package-managers/pacman.dependencies @@ -1,5 +1,4 @@ base-devel -code git -nvm +wget python3 diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index 3e1084d..25ef70a 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -3,7 +3,6 @@ #* linux-update.sh: Install and update dependencies of Mind_Reader, on linux. #* Heads-up, this expects to be run from Mind_Reader/setup-development/linux. - # If run with bash -vx, print useful information instead of just a + sign export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' # If run as root, it could be because sudo isn't installed (some people disagree with sudo, especially on Arch) @@ -26,6 +25,31 @@ function dryrun { fi } +# Get whether the user is running in Windows Subsystem for Linux +function getwsl { + grep "[Mm]icrosoft" /proc/version > /dev/null + return $? +} + +# Get the user's default login shell +function getsh { + #* This code was created by user [Todd A. Jacobs](https://stackoverflow.com/users/1301972/todd-a-jacobs) on [StackOverflow](https://stackoverflow.com/a/11059152) and is used in accordance with Creative Commons CC BY-SA 3.0 + getent passwd $LOGNAME | cut -d: -f7 +} + +# Install NVM (this is gross, but the recommended way to install nvm) +function installnvm { + # nvm's install script tries to be smart, so we have to work around its supposed cleverness + usershell=`getsh` + wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | dryrun "$usershell" + # Reload profile + case $usershell in + */bash) dryrun . ~/.bashrc ~/.bashprofile;; + */zsh) dryrun . ~/.zshrc;; + *) "Your shell, $usershell, is currently unsupported by nvm. It's up to you to set up your development environment."; exit;; + esac +} + # Set these variables if you need to install for a different architecture # Valid architectures are "x64", "arm64", "armhf" arch="" @@ -39,29 +63,31 @@ esac if which pacman; then # Install dependencies with pacman + printf "Installing dependencies with pacman...\n" cat ./package-managers/pacman.dependencies | dryrun $ELEVATE pacman -S - + # If not in Windows Subsystem for Linux, install vscode + [[ !(getwsl) ]] && dryrun $ELEVATE pacman -S code + # Install Node Version Manager + installnvm elif which apt-get; then # Install dependencies using apt-get + printf "Installing dependencies with apt...\n" dryrun xargs -a ./package-managers/apt.dependencies $ELEVATE apt-get install -y - - # Install Node Version Manager (nvm) - # TODO: Find a better way to install nvm on Ubuntu, the official NodeJS for <20.04 is so out of date it's unsupported. - curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | dryrun bash - dryrun export NVM_DIR="$HOME/.nvm" - dryrun [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm - dryrun [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion - # Check if vscode exists, if not, install it. # Microsoft doesn't put it in any Ubuntu repos, you have to get it straight from them. # This does have the side effect, however, of installing the official repository - if !(which code); then + # Don't attempt to install vscode if running in WSL; it can cause problems. + if !(which code) && !(getwsl); then #* Install VSCode vscodepackagename="code_amd64.deb" dryrun wget "https://code.visualstudio.com/sha/download?build=stable&os=linux-deb-$arch" -O ./code.deb dryrun $ELEVATE apt install ./code.deb dryrun rm ./code.deb fi + # Install Node Version Manager (nvm) + installnvm + fi cdir=$(pwd) @@ -76,7 +102,7 @@ electronversion="" #* By the time you're working on this project, things are likely going to differ! case `code --version` in #* Each version of VSCode has a corresponding Electron version and Node version - #* These are used when + #* These are used when configuring nvm 1.66.*) electronversion="17.2.0"; nodeversion="16.14.2";; *) nodeversion="--lts";; esac @@ -95,7 +121,7 @@ dryrun npm install dryrun npm audit fix # Use electron-rebuild to rebuild electron -if [ "$electronversion" != "" ]; then +if [[ "$electronversion" != "" ]]; then dryrun electron-rebuild --version $electronversion else printf "%s\n%s\n%s\n%s\n" \ diff --git a/setup-development/windows/install-windows.ps1 b/setup-development/windows/install-windows.ps1 index 86c2d36..3b48a01 100644 --- a/setup-development/windows/install-windows.ps1 +++ b/setup-development/windows/install-windows.ps1 @@ -93,7 +93,7 @@ function Invoke-DryRun { # Reset-Path: Reload the Path environment variable function Reset-Path { Write-Output "Reloading Path..." - #* Courtesy of user [mpen](https://stackoverflow.com/users/65387/mpen) on [StackOverflow](https://stackoverflow.com/a/31845512) + #* This code was created by user [mpen](https://stackoverflow.com/users/65387/mpen) on [StackOverflow](https://stackoverflow.com/a/31845512) and is used in accordance with Creative Commons CC BY-SA 3.0 $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") } diff --git a/setup-development/windows/upgrade-windows.ps1 b/setup-development/windows/upgrade-windows.ps1 index 09094bb..9778fe7 100644 --- a/setup-development/windows/upgrade-windows.ps1 +++ b/setup-development/windows/upgrade-windows.ps1 @@ -83,7 +83,7 @@ function Invoke-Dryrun { # Reset-Path: Reload the Path environment variable function Reset-Path { Write-Output "Reloading Path..." - #* Courtesy of user [mpen](https://stackoverflow.com/users/65387/mpen) on [StackOverflow](https://stackoverflow.com/a/31845512) + #* This code was created by user [mpen](https://stackoverflow.com/users/65387/mpen) on [StackOverflow](https://stackoverflow.com/a/31845512) and is used in accordance with Creative Commons CC BY-SA 3.0 $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") } diff --git a/setup-development/windows/winget/dependencies.json b/setup-development/windows/winget/dependencies.json index ab7f2f6..a20180d 100644 --- a/setup-development/windows/winget/dependencies.json +++ b/setup-development/windows/winget/dependencies.json @@ -15,9 +15,6 @@ }, { "PackageIdentifier": "Microsoft.VisualStudioCode" - }, - { - "PackageIdentifier": "NVAccess.NVDA" } ], "SourceDetails": { diff --git a/src/pylex/token.ts b/src/pylex/token.ts index 9d9a457..dcd7e18 100644 --- a/src/pylex/token.ts +++ b/src/pylex/token.ts @@ -17,7 +17,7 @@ export enum Symbol { FINALLY = "finally", WITH = "with", STATEMENT = "statement", // Indent token, contains non-empty code lines - COMMENT = "comment", + COMMENT = "Comment", EMPTY = "EMPTY", // empty line, used only to associate with the previous line INVALID = "INVALID", EOF = "EOF" From e78470d6f7600e6dbe00213cee3b7b9e9431862e Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 16:30:25 -0500 Subject: [PATCH 66/78] Print progress information in install script. --- setup-development/linux/install-linux.sh | 7 +++++-- setup-development/linux/upgrade-linux.sh | 8 +++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/setup-development/linux/install-linux.sh b/setup-development/linux/install-linux.sh index 572727e..99c2dea 100644 --- a/setup-development/linux/install-linux.sh +++ b/setup-development/linux/install-linux.sh @@ -48,7 +48,7 @@ elif which apt; then dryrun $ELEVATE apt-get install git -y fi #? TODO: other package managers? -echo Cloning repository into "$gitdir" +echo "Cloning repository into $gitdir" dryrun mkdir "$gitdir" cd $gitdir && dryrun git clone "$repouri" @@ -58,5 +58,8 @@ cd $gitdir && dryrun git clone "$repouri" # TODO: remove this when merging! cd "$gitdir/$setupdir" -pwd bash ./upgrade-linux.sh $@ + +echo "Opening VS Code..." +cd $gitdir/Mind_Reader +code . \ No newline at end of file diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index 25ef70a..f7a0e89 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -108,23 +108,28 @@ case `code --version` in esac # Install NodeJS and npm +printf "\nInstalling node $nodeversion\n" dryrun nvm install "$nodeversion" dryrun nvm use "$nodeversion" # Use npm to install electron-rebuild and yo +printf "Installing electron-rebuild, yo, and generator-code\n" dryrun npm install electron-rebuild yo generator-code # use npm to acquire dependencies for Mind-Reader +printf "\nAcquiring dependencies...\n" dryrun npm install # automatically update vulnerable packages, if possible +printf "\nUpdating vulnerable packages, if possible...\n" dryrun npm audit fix # Use electron-rebuild to rebuild electron if [[ "$electronversion" != "" ]]; then + printf "\nRebuilding electron with version $electronversion...\n" dryrun electron-rebuild --version $electronversion else - printf "%s\n%s\n%s\n%s\n" \ + printf "\n%s\n%s\n%s\n%s\n" \ "Open Visual Studio Code, select the 'Help' tab in the toolbar, and go to 'About'." \ "Find the line that says 'Electron: [electron version]'" \ "Run the command below, filling in the Electron version with the one from that menu:" \ @@ -132,3 +137,4 @@ else fi cd $cdir +echo "Done!" From 63d0b5aee3daa5854d0b7aaac8281af8d096bde0 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 16:31:48 -0500 Subject: [PATCH 67/78] Newline --- setup-development/linux/install-linux.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup-development/linux/install-linux.sh b/setup-development/linux/install-linux.sh index 99c2dea..608223a 100644 --- a/setup-development/linux/install-linux.sh +++ b/setup-development/linux/install-linux.sh @@ -48,7 +48,7 @@ elif which apt; then dryrun $ELEVATE apt-get install git -y fi #? TODO: other package managers? -echo "Cloning repository into $gitdir" +printf "\nCloning repository into $gitdir\n" dryrun mkdir "$gitdir" cd $gitdir && dryrun git clone "$repouri" From fecdf31c1f02d82727321a482fbd43c9fdf8e3c8 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 16:45:48 -0500 Subject: [PATCH 68/78] Visual Studio Code updated New Electron version is 17.4.1 --- setup-development/linux/upgrade-linux.sh | 3 +- setup-development/windows/upgrade-windows.ps1 | 51 ++++++++++--------- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index f7a0e89..87ca655 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -103,7 +103,8 @@ electronversion="" case `code --version` in #* Each version of VSCode has a corresponding Electron version and Node version #* These are used when configuring nvm - 1.66.*) electronversion="17.2.0"; nodeversion="16.14.2";; + 1.66.*) electronversion="17.2.0"; nodeversion="16.13.0";; + 1.67.*) electronversion="17.4.1"; nodeversion="16.13.0";; *) nodeversion="--lts";; esac diff --git a/setup-development/windows/upgrade-windows.ps1 b/setup-development/windows/upgrade-windows.ps1 index 9778fe7..ea1d534 100644 --- a/setup-development/windows/upgrade-windows.ps1 +++ b/setup-development/windows/upgrade-windows.ps1 @@ -49,9 +49,9 @@ Allow script to be run as Administrator param ( [switch]$AllowAdministrator, # Force allow installation as administrator - [switch]$NoPrompt, # Disable the 3-second wait and press-any-key prompt - [switch]$Install, # Perform all installations, even when commands are present - [switch]$DryRun, # Run script without installing + [switch]$NoPrompt, # Disable the 3-second wait and press-any-key prompt + [switch]$Install, # Perform all installations, even when commands are present + [switch]$DryRun, # Run script without installing [switch]$NoWinget # Don't update dependdencies with winget ) @@ -84,7 +84,7 @@ function Invoke-Dryrun { function Reset-Path { Write-Output "Reloading Path..." #* This code was created by user [mpen](https://stackoverflow.com/users/65387/mpen) on [StackOverflow](https://stackoverflow.com/a/31845512) and is used in accordance with Creative Commons CC BY-SA 3.0 - $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") + $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") } @@ -114,7 +114,8 @@ if ( ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5 Write-Host "Press any key to continue... " [void][Console]::ReadKey(1) # Equivalent to Command Prompt's `pause` command } - } else { + } + else { # Throw a fatal errorOccurred if the user tries to run as administrator. Throw "Script must be run as a normal user." } @@ -158,7 +159,8 @@ function EnsureNodePackageInstalled { if ( -not (Get-CommandAvailable $command[0])) { Throw "$command failed to install. Aborting." } - } else { + } + else { Write-Host "`n$($command[0]) already installed." -ForegroundColor green } } @@ -182,28 +184,27 @@ Invoke-Dryrun "npm audit fix" # if we're on a known VSCode version, go ahead and run electron-rebuild switch -Regex (code --version) { -<# "1\.6[7-9]\.[0-9]+" { - #?: Do we update this in the future, or stop maintaining it and remove this entire switch block? - } #> - "1\.66\.[0-9]+" { # 1.66 - Write-Host "`nRebuilding Electron for your version of VSCode..." - Invoke-Dryrun 'electron-rebuild --version="17.2.0"' - Write-Host "Done!" -ForegroundColor green - break - } - "\d+\.\d+\.\d+" { # Anything else - Write-Host "`nOpen Visual Studio Code, select the `"Help`" tab in the Toolbar, and go to `"About`".`nYou should see a page that looks like the following:" -ForegroundColor darkcyan + #?: Do we update this in the future, or stop maintaining it and remove this entire switch block? + "1\.67\.\d+" { $electronversion = "17.4.1"; break } # April 2022 update + "1\.66\.\d+" { $electronversion = "17.2.0"; break } # March 2022 update + default { $electronversion = $false } # Unknown update +} - Write-Host " `(i`) Visual Studio Code`n`n Version: 1.66.2 `(user setup`)`n Commit: [Commit ID]`n Date: 2022-04-11T07:46:01.075Z`n Electron: 17.2.0`n [ ... ]" -ForegroundColor White +if ( $electronversion ) { + Write-Host "`nRebuilding Electron for your version of VSCode..." + Invoke-Dryrun "electron-rebuild --version='$electronversion'" + Write-Host "Done!" -ForegroundColor green +} +else { + Write-Host "`nOpen Visual Studio Code, select the `"Help`" tab in the Toolbar, and go to `"About`".`nYou should see a page that looks like the following:" -ForegroundColor darkcyan - Write-Host "Note the Electron version `(17.2.0 in the above example`)." -ForegroundColor darkcyan + Write-Host " `(i`) Visual Studio Code`n`n Version: 1.66.2 `(user setup`)`n Commit: [Commit ID]`n Date: 2022-04-11T07:46:01.075Z`n Electron: 17.2.0`n [ ... ]" -ForegroundColor White - Write-Host "Run the command " -NoNewLine - Write-Host "electron-rebuild --version ELECTRON_VERSION" -NoNewLine -ForegroundColor green - Write-Host " in Mind-Reader`'s root folder.`n" - break # Don't process the next items in the collection. - } - default { } # Leave blank + Write-Host "Note the Electron version `(17.2.0 in the above example`)." -ForegroundColor darkcyan + + Write-Host "Run the command " -NoNewLine + Write-Host "electron-rebuild --version ELECTRON_VERSION" -NoNewLine -ForegroundColor green + Write-Host " in Mind-Reader`'s root folder.`n" } # Return from whence we came From 57b0d6b97e9f4f86f981a19702a80a55c8282b76 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 17:08:48 -0500 Subject: [PATCH 69/78] Don't reinstall w/ pacman --- setup-development/linux/upgrade-linux.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index 87ca655..6ae3764 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -64,9 +64,9 @@ esac if which pacman; then # Install dependencies with pacman printf "Installing dependencies with pacman...\n" - cat ./package-managers/pacman.dependencies | dryrun $ELEVATE pacman -S - + cat ./package-managers/pacman.dependencies | dryrun $ELEVATE pacman -S --needed - # If not in Windows Subsystem for Linux, install vscode - [[ !(getwsl) ]] && dryrun $ELEVATE pacman -S code + [[ !(getwsl) ]] && dryrun $ELEVATE pacman -S --needed code # Install Node Version Manager installnvm From 75d9762f41a4012bdc8c147a6c5d72e014a40316 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 18:44:50 -0500 Subject: [PATCH 70/78] Improve github actions CI --- .github/workflows/vscode-test.yaml | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/vscode-test.yaml b/.github/workflows/vscode-test.yaml index 3e11b5e..143c952 100644 --- a/.github/workflows/vscode-test.yaml +++ b/.github/workflows/vscode-test.yaml @@ -10,15 +10,22 @@ jobs: build: strategy: matrix: - os: [macos-11, ubuntu-latest, windows-latest] + os: + - macos-11 + - ubuntu-latest + - windows-latest + node_version: + - 16 runs-on: ${{ matrix.os }} steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Install Node.js - uses: actions/setup-node@v1 + uses: actions/setup-node@v3 with: - node-version: 10.x + node-version: ${{ matrix.node_version }} + cache: 'npm' + cache-dependency-path: '**/package-lock.json' - run: npm ci - run: xvfb-run -a npm test if: runner.os == 'Linux' From 3bffd6a9fda5125199c73d3390ff1bf71676abd0 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 20:49:15 -0500 Subject: [PATCH 71/78] mindReader -> mind-reader --- package.json | 6 +++--- src/commands/hub.ts | 2 +- src/commands/text.ts | 4 ++-- src/extension.ts | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index b019f0c..7410f44 100644 --- a/package.json +++ b/package.json @@ -244,17 +244,17 @@ { "command": "editor.action.fontZoomOut", "key": "Shift+Alt+z -", - "when": "editorTextFocus && config.mindReader.reader.screenReader != JAWS" + "when": "editorTextFocus && config.mind-reader.reader.screenReader != JAWS" }, { "command": "editor.action.fontZoomIn", "key": "Shift+Alt+z =", - "when": "editorTextFocus && config.mindReader.reader.screenReader != JAWS" + "when": "editorTextFocus && config.mind-reader.reader.screenReader != JAWS" }, { "command": "editor.action.fontZoomReset", "key": "Shift+Alt+z 0", - "when": "editorTextFocus && config.mindReader.reader.screenReader != JAWS" + "when": "editorTextFocus && config.mind-reader.reader.screenReader != JAWS" }, { "command": "mind-reader.getIndent", diff --git a/src/commands/hub.ts b/src/commands/hub.ts index 55c9c3a..1b4ae63 100755 --- a/src/commands/hub.ts +++ b/src/commands/hub.ts @@ -65,7 +65,7 @@ async function connectHub(): Promise { return; } - let portPath: string | undefined = vscode.workspace.getConfiguration('mindReader.connection').get('portPath'); + let portPath: string | undefined = vscode.workspace.getConfiguration('mind-reader.connection').get('portPath'); if (!portPath) { let slots: vscode.QuickPickItem[] = []; diff --git a/src/commands/text.ts b/src/commands/text.ts index 15006a1..791f3cb 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -316,7 +316,7 @@ function createContextString(context: pl.LexNode[], line: number): string { /* * find up to `n` words around the cursor, where `n` is - * the value of `#mindReader.reader.contextWindow` + * the value of `#mind-reader.reader.contextWindow` */ function runCursorContext(): void { const editor: TextEditor | undefined = window.activeTextEditor; @@ -328,7 +328,7 @@ function runCursorContext(): void { const cursorPos : Position = editor.selection.active; const text : string = editor.document.lineAt(cursorPos).text; - const windowSize : any = workspace.getConfiguration('mindReader').get('reader.contextWindow'); + const windowSize : any = workspace.getConfiguration('mind-reader').get('reader.contextWindow'); let trimmedText: string = text.trimStart(); // trim leading whitespace const leadingWS : number = text.length - trimmedText.length; // # of characters of leading whitespace let pos : number = leadingWS; diff --git a/src/extension.ts b/src/extension.ts index fcc634a..18c2158 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -7,7 +7,7 @@ import { lineHighlighter } from "./lineHi import { accessCommands, hubCommands, navCommands, textCommands } from "./commands"; // Output Logger -const product: string = vscode.workspace.getConfiguration("mindReader").get("productType")!; +const product: string = vscode.workspace.getConfiguration("mind-reader").get("productType")!; const outputChannel = vscode.window.createOutputChannel(product + " Output"); export const logger = new Logger(outputChannel); From 8456f57b84c7d7a3e37f6a227e913f4e4a7d1f20 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 20:56:10 -0500 Subject: [PATCH 72/78] Mind_Reader -> Mind Reader (except in URLs and critical identifiers) --- README.md | 12 ++++++------ media/html/main.html | 2 +- setup-development/linux/upgrade-linux.sh | 2 +- setup-development/windows/install-windows.ps1 | 6 +++--- setup-development/windows/upgrade-windows.ps1 | 6 +++--- src/commands/nav.ts | 2 +- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 2239951..504d36e 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Mind Reader Logo

-

Mind_Reader

+

Mind Reader

@@ -42,7 +42,7 @@ Python programming with LEGO Mindstorms. Our goal is to: tools for native modules page with tool installation checked

-If the compiled serial port version is incompatible, you may see no options presented in the Mind_Reader actions panel: +If the compiled serial port version is incompatible, you may see no options presented in the Mind Reader actions panel:

mind reader actions panel with no items: @@ -73,7 +73,7 @@ The electron version should be listed, e.g.: `Electron: 13.5.2` vscode information

-### 3 Finding the Mind_Reader extension directory +### 3 Finding the Mind Reader extension directory On MacOS and Linux this is `~/.vscode/extensions`. On Windows this is `C:\\.vscode\extensions\`. However, in Git Bash, it will appear like on MacOS and Linux @@ -81,7 +81,7 @@ e.g.: `~/.vscode/extensions`. --- -Find the Mind_Reader extension folder, this should look like `xxx.mind-reader-x.x.x`. +Find the Mind Reader extension folder, this should look like `xxx.mind-reader-x.x.x`. Navigate to the found folder in the terminal. @@ -102,8 +102,8 @@ $ electron-rebuild --version=ELECTRON_VERSION Use the following to set up the extension for development. ```console -$ git clone https://github.com/SingleSemesterSnobs/Mind_Reader.git -$ cd Mind_Reader +$ git clone https://github.com/SingleSemesterSnobs/Mind Reader.git +$ cd Mind Reader $ npm install ``` diff --git a/media/html/main.html b/media/html/main.html index afd1508..27fe0e6 100644 --- a/media/html/main.html +++ b/media/html/main.html @@ -8,7 +8,7 @@

-

Welcome to Mind_Reader!

+

Welcome to Mind Reader!

We are the Single Semester Snobs and this is our tool to Help Blind Students Program Lego Mindstorms Robots in Python.

  • diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh index 6ae3764..1cfa484 100644 --- a/setup-development/linux/upgrade-linux.sh +++ b/setup-development/linux/upgrade-linux.sh @@ -1,6 +1,6 @@ #!/bin/bash -#* linux-update.sh: Install and update dependencies of Mind_Reader, on linux. +#* linux-update.sh: Install and update dependencies of Mind Reader, on linux. #* Heads-up, this expects to be run from Mind_Reader/setup-development/linux. # If run with bash -vx, print useful information instead of just a + sign diff --git a/setup-development/windows/install-windows.ps1 b/setup-development/windows/install-windows.ps1 index 3b48a01..dba9613 100644 --- a/setup-development/windows/install-windows.ps1 +++ b/setup-development/windows/install-windows.ps1 @@ -1,10 +1,10 @@ <# .synopsis -Dependency installer for Mind-Reader on Windows. +Dependency installer for Mind Reader on Windows. This sets up a development environment from a BARE windows install. .description -Install Git for Windows, clone the Mind-Reader repository, and install all dependencies. +Install Git for Windows, clone the Mind Reader repository, and install all dependencies. The script uses winget (A.K.A. "App Installer") to download and install the latest versions of each dependency, defined in winget/dependencies.json @@ -32,7 +32,7 @@ Perform a "dry run" of the script, changing directories and running commands, bu .example ./install-windows.ps1 -Perform a default upgrade of all Mind_Reader dependencies +Perform a default upgrade of all Mind Reader dependencies .example ./install-windows.ps1 -DryRun diff --git a/setup-development/windows/upgrade-windows.ps1 b/setup-development/windows/upgrade-windows.ps1 index ea1d534..0e7a549 100644 --- a/setup-development/windows/upgrade-windows.ps1 +++ b/setup-development/windows/upgrade-windows.ps1 @@ -1,6 +1,6 @@ <# .synopsis -Dependency updater for Mind-Reader on Windows. +Dependency updater for Mind Reader on Windows. This script expects to be run from Mind_Reader/setup-development .description @@ -32,7 +32,7 @@ Perform a "dry run" of the script, changing directories and running commands, bu .example ./upgrade-windows.ps1 -Perform a default upgrade of all Mind_Reader dependencies +Perform a default upgrade of all Mind Reader dependencies .example ./upgrade-windows.ps1 -DryRun @@ -204,7 +204,7 @@ else { Write-Host "Run the command " -NoNewLine Write-Host "electron-rebuild --version ELECTRON_VERSION" -NoNewLine -ForegroundColor green - Write-Host " in Mind-Reader`'s root folder.`n" + Write-Host " in Mind Reader`'s root folder.`n" } # Return from whence we came diff --git a/src/commands/nav.ts b/src/commands/nav.ts index 57f8ef7..e211f97 100755 --- a/src/commands/nav.ts +++ b/src/commands/nav.ts @@ -98,7 +98,7 @@ function getWebviewContent() {

    -

    Welcome to Mind_Reader!

    +

    Welcome to Mind Reader!

    We are the Single Semester Snobs and this is our tool to Help Blind Students Program Lego Mindstorms Robots in Python.

    • From 7c985b38179cc4ed85c48c53a77e8b18c2aefae3 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 21:13:18 -0500 Subject: [PATCH 73/78] Stop forciby reselecting the document Forcibly reselecting the document made using keyboard navigation inconvenient --- src/commands/text.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index 791f3cb..d314152 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -121,7 +121,6 @@ function getNumberOfSelectedLines(): void { (numberOfSelectedLines !== 1) ? window.showInformationMessage(`${numberOfSelectedLines.toString()} Lines Selected`) : window.showInformationMessage(`${numberOfSelectedLines.toString()} Line Selected`); - window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted } else { window.showErrorMessage('No document currently active'); @@ -139,7 +138,6 @@ function getLineNumber(): void { const lineNum: number = fetchLineNumber(editor); window.showInformationMessage(`Line ${lineNum.toString()}`); - window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted } else { window.showErrorMessage('No document currently active'); @@ -172,7 +170,6 @@ function getIndent(): void { ? window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indents`) : window.showInformationMessage(`Line ${lineNum.toString()}: ${i.toString()} indent`); } - window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted } else { window.showErrorMessage('No document currently active'); @@ -201,7 +198,6 @@ function getLeadingSpaces(): void { ? window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces`) : window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space`); } - window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted } else { window.showErrorMessage('No document currently active'); @@ -239,8 +235,9 @@ function selectLeadingWhitespace(): void { else { window.showErrorMessage(`Line ${lineNum.toString()}: No leading spaces to select!`); // No whitespace to select } - window.showTextDocument(editor.document); // After the selection is made, the editor loses focus. We need to re-focus the editor so typing isn't interrupted - } + // Move the cursor to the new selection + window.showTextDocument(editor.document); + } else { window.showErrorMessage('No document currently active'); // No active document } From 7e001ee50c9494a2d423049d287440427825e143 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 May 2022 22:06:24 -0500 Subject: [PATCH 74/78] Only return cursor to editor when selection succeeds --- src/commands/text.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/commands/text.ts b/src/commands/text.ts index d314152..b0b8b15 100755 --- a/src/commands/text.ts +++ b/src/commands/text.ts @@ -231,12 +231,13 @@ function selectLeadingWhitespace(): void { (numSpaces !== 1) ? window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} spaces selected`) : window.showInformationMessage(`Line ${lineNum.toString()}: ${numSpaces.toString()} space selected`); + + // Move the cursor to the new selection + window.showTextDocument(editor.document); } else { window.showErrorMessage(`Line ${lineNum.toString()}: No leading spaces to select!`); // No whitespace to select } - // Move the cursor to the new selection - window.showTextDocument(editor.document); } else { window.showErrorMessage('No document currently active'); // No active document From 3790d6c3a82f459d82913ce363d7e90653c5d00e Mon Sep 17 00:00:00 2001 From: John Date: Sat, 7 May 2022 13:19:57 -0500 Subject: [PATCH 75/78] JSON booleans are not strings --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 7410f44..67996e2 100644 --- a/package.json +++ b/package.json @@ -430,13 +430,13 @@ "order": 4, "type": "boolean", "markdownDescription": "Enable/Disable the line highlighter.\n\n\n* `Enabled (our default)`: Checked: Line Highlighter is turned `ON`\n* `Disabled`: Unchecked: Line Highlighter is turned `OFF`\n\n### `NOTE`: You Must Close Settings And RESTART Visual Studio Code For The Line Highlighter To Function\n#### Even If No Changes Were Made", - "default": "true" + "default": true }, "mind-reader.lineHighlighter.multiLineIsEnabled": { "order": 5, "type": "boolean", "markdownDescription": "Temporarily Disable highlighting when highlighting multiple lines.\n\n\n* `Enabled`: Checked: Multiline Highlighting is turned `ON`:\n* * When you click and drag line highlights will be applied to all lines\n* `Disabled (our default)`: Unchecked: Multiline Highlighting is turned `OFF`:\n* * When you click and drag the line highlighter will disable itself then re-enable itself when you click onto a single line.", - "default": "false" + "default": false }, "mind-reader.lineHighlighter.backgroundColor": { "order": 6, From e7bdd356e3e6007c373857f9c71201510ade225b Mon Sep 17 00:00:00 2001 From: John Date: Sat, 7 May 2022 13:24:46 -0500 Subject: [PATCH 76/78] Update permissions on install scripts, for linux. --- setup-development/linux/install-linux.sh | 0 setup-development/linux/upgrade-linux.sh | 0 2 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 setup-development/linux/install-linux.sh mode change 100644 => 100755 setup-development/linux/upgrade-linux.sh diff --git a/setup-development/linux/install-linux.sh b/setup-development/linux/install-linux.sh old mode 100644 new mode 100755 diff --git a/setup-development/linux/upgrade-linux.sh b/setup-development/linux/upgrade-linux.sh old mode 100644 new mode 100755 From 5131db0a8a065670d1d480ea4251acc2db0a46f4 Mon Sep 17 00:00:00 2001 From: tel0065 <77864718+tel0065@users.noreply.github.com> Date: Sat, 7 May 2022 13:31:34 -0500 Subject: [PATCH 77/78] added setup instructions Added instructions as to how to setup for the first time to the comments section, added 2 more TODO items. --- src/lineHighlighter.ts | 55 +++++++++++++++++++++++++++++++++++------- 1 file changed, 46 insertions(+), 9 deletions(-) diff --git a/src/lineHighlighter.ts b/src/lineHighlighter.ts index e8ebc13..149c86c 100644 --- a/src/lineHighlighter.ts +++ b/src/lineHighlighter.ts @@ -5,7 +5,44 @@ * ? ██╔══██║██║██║ ██║██╔══██║██║ ██║██║ ██║██╔══██║ ██║ ╚════╝██║ ██║ * ? ██║ ██║██║╚██████╔╝██║ ██║███████╗██║╚██████╔╝██║ ██║ ██║ ██║ ██║ * ? ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ -* TODO: Add ability for user to change options through a command pallette configurator +* ! Initial Setup: +* ! Open settings.json (ctrl+shift+p type 'settings' choose: 'Preferences: Open Settings (JSON)) +* ! Add the following to the bottom (may have to add a comma to the line above if it's not there, also remove the *s): +* "mind-reader.lineHighlighter.isEnabled" : true, +* "mind-reader.lineHighlighter.multiLineIsEnabled" : false, +* +* "mind-reader.lineHighlighter.backgroundColor" : "#232C5C", + +* "mind-reader.lineHighlighter.outlineColor" : "#4866FE", +* "mind-reader.lineHighlighter.outlineWidth" : "1px", +* "mind-reader.lineHighlighter.outlineStyle" : "solid", +* +* "mind-reader.lineHighlighter.borderColorTop" : "#FFFFFF", +* "mind-reader.lineHighlighter.borderColorRight" : "#FFFFFF", +* "mind-reader.lineHighlighter.borderColorBottom" : "#FFFFFF", +* "mind-reader.lineHighlighter.borderColorLeft" : "#FFFFFF", +* +* "mind-reader.lineHighlighter.borderWidthTop" : "1px", +* "mind-reader.lineHighlighter.borderWidthRight" : "16px", +* "mind-reader.lineHighlighter.borderWidthBottom" : "1px", +* "mind-reader.lineHighlighter.borderWidthLeft" : "1px", +* +* "mind-reader.lineHighlighter.borderStyleTop" : "solid", +* "mind-reader.lineHighlighter.borderStyleRight" : "solid", +* "mind-reader.lineHighlighter.borderStyleBottom" : "solid", +* "mind-reader.lineHighlighter.borderStyleLeft" : "solid", +* +* "mind-reader.lineHighlighter.fontStyle" : "normal", +* "mind-reader.lineHighlighter.fontWeight" : "bolder", +* "mind-reader.lineHighlighter.textColor" : "#FFFFFF", +* +* ! Restart VSCode for changes to take effect (if they didn't automatically) +* ! Afterwards you can now edit using the settings window, or manually edit them +* ! directly in settings.json by editing the values. +* +* TODO: FEATURE: Add ability for user to change options through a command pallette configurator +* TODO: FEATURE: Add hotkey to toggle linehighlighter on/off +* TODO: BUG: Adding the settings configurator made default settings break (if no values are found in settings.json) **/ 'use strict'; import { Position, window, workspace, TextEditorDecorationType, TextEditor, WorkspaceConfiguration, Range } from 'vscode'; @@ -233,14 +270,14 @@ function lineHighlighter(): void { let enabledStatus: boolean | undefined; /*** - * if "isEnabled" is missing from the settings (aka undefined) + * if 'isEnabled' is missing from the settings (aka undefined) * - set our variable to true (default) - * otherwise, "isEnabled" is listed in the settings + * otherwise, 'isEnabled' is listed in the settings * - so we just pull its value */ - (workspace.getConfiguration("mind-reader.lineHighlighter").get("isEnabled") === undefined) + (workspace.getConfiguration('mind-reader.lineHighlighter').get('isEnabled') === undefined) ? (enabledStatus = true) - : (enabledStatus = workspace.getConfiguration("mind-reader.lineHighlighter").get("isEnabled")); + : (enabledStatus = workspace.getConfiguration('mind-reader.lineHighlighter').get('isEnabled')); // return the enabledStatus return enabledStatus; @@ -251,14 +288,14 @@ function lineHighlighter(): void { let multiLineIsEnabled: boolean | undefined; /*** - * if "isEnabled" is missing from the settings (aka undefined) + * if 'isEnabled' is missing from the settings (aka undefined) * - set our variable to true (default) - * otherwise, "isEnabled" is listed in the settings + * otherwise, 'isEnabled' is listed in the settings * - so we just pull its value */ - (workspace.getConfiguration("mind-reader.lineHighlighter").get("multiLineIsEnabled") === undefined) + (workspace.getConfiguration('mind-reader.lineHighlighter').get('multiLineIsEnabled') === undefined) ? (multiLineIsEnabled = true) - : (multiLineIsEnabled = workspace.getConfiguration("mind-reader.lineHighlighter").get("multiLineIsEnabled")); + : (multiLineIsEnabled = workspace.getConfiguration('mind-reader.lineHighlighter').get('multiLineIsEnabled')); // return the enabledStatus return multiLineIsEnabled; From 84f8e41737e6afe3dc1f1207bfe985d8d1d2549a Mon Sep 17 00:00:00 2001 From: John Date: Sat, 7 May 2022 20:34:47 -0500 Subject: [PATCH 78/78] Update Mind Reader dependencies --- package-lock.json | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/package-lock.json b/package-lock.json index e3d6f86..77d24c7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "mind-reader", - "version": "1.0.0", + "version": "2.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "mind-reader", - "version": "1.0.0", + "version": "2.0.0", "dependencies": { "serialport": "^9.2.5" }, @@ -26,7 +26,7 @@ "vscode-test": "^1.5.2" }, "engines": { - "vscode": "^1.60.0" + "vscode": "^1.66.0" } }, "node_modules/@babel/code-frame": { @@ -2101,9 +2101,9 @@ } }, "node_modules/minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" }, "node_modules/mkdirp": { "version": "0.5.5", @@ -2817,9 +2817,9 @@ ] }, "node_modules/simple-get": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.0.tgz", - "integrity": "sha512-bCR6cP+aTdScaQCnQKbPKtJOKDp/hj9EDLJo3Nw4y1QksqaovlW/bnptB6/c1e+qmNIDHRK+oXFDdEqBT8WzUA==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.1.tgz", + "integrity": "sha512-CQ5LTKGfCpvE1K0n2us+kuMPbk/q0EKl82s4aheV9oXjFEz6W/Y7oQFVJuU6QG77hRT4Ghb5RURteF5vnWjupA==", "dependencies": { "decompress-response": "^4.2.0", "once": "^1.3.1", @@ -3205,9 +3205,9 @@ } }, "node_modules/wide-align/node_modules/ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz", + "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", "engines": { "node": ">=4" } @@ -4896,9 +4896,9 @@ } }, "minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" }, "mkdirp": { "version": "0.5.5", @@ -5405,9 +5405,9 @@ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==" }, "simple-get": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.0.tgz", - "integrity": "sha512-bCR6cP+aTdScaQCnQKbPKtJOKDp/hj9EDLJo3Nw4y1QksqaovlW/bnptB6/c1e+qmNIDHRK+oXFDdEqBT8WzUA==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.1.tgz", + "integrity": "sha512-CQ5LTKGfCpvE1K0n2us+kuMPbk/q0EKl82s4aheV9oXjFEz6W/Y7oQFVJuU6QG77hRT4Ghb5RURteF5vnWjupA==", "requires": { "decompress-response": "^4.2.0", "once": "^1.3.1", @@ -5715,9 +5715,9 @@ }, "dependencies": { "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz", + "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==" }, "is-fullwidth-code-point": { "version": "2.0.0",