Skip to content

Commit

Permalink
Merge pull request #33 from guicassolato/feature/append-terminal-output
Browse files Browse the repository at this point in the history
Append output to preview
  • Loading branch information
guicassolato authored Jan 8, 2023
2 parents 4fe4748 + d3c0ec5 commit 76b1959
Show file tree
Hide file tree
Showing 10 changed files with 178 additions and 29 deletions.
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ This file is structured according to the [Keep a Changelog](http://keepachangelo

## [Unreleased]

### Added

- Option to default to running code blocks in a separate shell in the background instead of the in the integrated terminal. Output is appended to the preview. (Closes https://github.com/guicassolato/tothom/issues/6)
- Option to save env variables to temporary file when running code blocks in a separate shell in the background
- New command <kbd>⇧ ⌘ P</kbd> _Tothom: Clear terminal selection_ - removes the binding between the activate preview and a terminal

## [v0.3.0] - 2022-01-05

### Added
Expand All @@ -22,7 +28,7 @@ This file is structured according to the [Keep a Changelog](http://keepachangelo

### Fixed

- 'Tothom preview not found' message shown whenever the text editor changes (#27)
- 'Tothom preview not found' message shown whenever the text editor changes. (Closes https://github.com/guicassolato/tothom/issues/27)

## [v0.3.0] - 2022-01-04

Expand Down
31 changes: 25 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ that gives you nice <kbd>▶️</kbd> _Run in terminal_ buttons for your code bl

- Markdown preview (<kbd>⇧ ⌘ P</kbd></kbd> _Tothom: Markdown Preview_)
- <kbd>▶️</kbd> _Run in terminal_ actions for code blocks (auto-generated)
- Alternative to run code blocks in a separate shell in the background (output appended to the preview)
- GitHub styling
- Syntax highlight for code blocks
- Dark/light mode
Expand Down Expand Up @@ -38,21 +39,39 @@ For more examples with more markdown syntax, check the [samples](samples/tothom.

### Re-use a terminal

Tothom binds each preview window to a terminal. When a terminal does not exist, Tothom creates a dedicated one at the time when the first <kbd>▶️</kbd> _Run in terminal_ action is executed.
Tothom binds each preview window to an integrated Visual Studio terminal.
When a terminal does not exist, Tothom creates a dedicated one at the time when the first <kbd>▶️</kbd> _Run in terminal_ action is executed.

To bind a new preview window to an existing terminal, use the command <kbd>⇧ ⌘ P</kbd> _Tothom: Markdown Preview (existing terminal)_.

To re-bind a preview window to an existing terminal, activate the preview and execute the command <kbd>⇧ ⌘ P</kbd> _Tothom: Select terminal_.

These options allow to share a terminal across multiple preview windows.

To clear the current binding of a preview to a terminal, activate the preview window and execute the command <kbd>⇧ ⌘ P</kbd> _Tothom: Clear terminal selection_.

### Run in a separate shell in the background (output appended to the preview)

Alternatively to running a code block in an integrated Visual Studio terminal, enable the option in the settings to default to running in a separate shell in the background (`tothom.runInBackgroundByDefault`).
New preview windows and preview windows not yet bound to a terminal will execute code blocks in the background and the output of the executions appended to the preview window.

![Run in background](./resources/run-in-background.gif)

Keep in mind that, with this option enabled, each execution of a code block will run in an independent shell (separate child process).
To set and re-use environment variable values across multiple code blocks, enable the `tothom.saveEnvToTmp` configuration option.

This option is ignored if the preview is currently bound to a terminal (e.g. by using the 'Select terminal' command).
If needed, clear the current binding of a preview to a terminal after enabling this option by activating the preview window and executing the command <kbd>⇧ ⌘ P</kbd> _Tothom: Clear terminal selection_.

## Extension Settings

| Setting | Description | Options/Default |
|-----------------------------|--------------------------------------------------------------|-----------------------------------|
| `tothom.bracketedPasteMode` | Apply bracketed paste sequences on commands sent to terminal | `true` (default), `false` |
| `tothom.colorScheme` | Color scheme of the preview panel | `auto` (default), `light`, `dark` |
| `tothom.runInTerminalLabel` | Label of the _Run in terminal_ button | Default: `▶️` |
| Setting | Description | Options/Default |
|-----------------------------------|-----------------------------------------------------------------------------------------------------------------|-----------------------------------|
| `tothom.bracketedPasteMode` | Apply bracketed paste sequences on commands sent to terminal | `true` (default), `false` |
| `tothom.colorScheme` | Color scheme of the preview panel | `auto` (default), `light`, `dark` |
| `tothom.runInTerminalLabel` | Label of the _Run in terminal_ button | Default: `▶️` |
| `tothom.runInBackgroundByDefault` | Default to running code blocks in a separate child process in the background instead of the integrated terminal | `true`, `false` (default) |
| `tothom.saveEnvToTmp` | Save and restore environment variables to temporary files around each code block execution | `true`, `false` (default) |

## Limitations

Expand Down
25 changes: 23 additions & 2 deletions media/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
// This script will be run within the webview itself
(
function () {

//connect to the vscode api
const vscode = acquireVsCodeApi();

Expand All @@ -45,4 +44,26 @@
node = node.parentNode;
}
}, true);
}());

window.addEventListener('message', event => {
const message = event.data; // The JSON data our extension sent

switch (message.command) {
case 'tothom.terminalOutput':
const id = message.data.codeId;
const el = document.getElementById(id);
if (!el) {
return;
}
const out = document.getElementById(`${id}-out`);
const html = `<code>${message.data.text}</code>`;
if (out) {
out.innerHTML = html;
} else {
el.insertAdjacentHTML('afterend', `<p>Output:</p><pre class="tothom-code-output" id="${id}-out">${html}</pre>`);
}
break;
}
});
}()
);
26 changes: 23 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
"tothom.bracketedPasteMode": {
"description": "Apply bracketed paste sequences on commands sent to terminal",
"type": "boolean",
"default": true
"default": true,
"order": 30
},
"tothom.colorScheme": {
"description": "Color scheme of the preview panel",
Expand All @@ -56,17 +57,36 @@
"Uses the default color scheme set for the context",
"Light color scheme",
"Dark color scheme"
]
],
"order": 10
},
"tothom.runInBackgroundByDefault": {
"markdownDescription": "Default to running code blocks in a separate shell in the background instead of in an integrated terminal window. Outputs of the executions are appended to the preview window.\n\nThis setting is ignored if the preview is bound to a terminal (e.g. by using the 'Select terminal' command).\n\nTo be able to set and re-use environment variables across code blocks when this option is active, activate as well `#tothom.saveEnvToTmp#`.",
"type": "boolean",
"default": false,
"order": 40
},
"tothom.runInTerminalLabel": {
"description": "Label of the 'Run in terminal' button",
"type": "string",
"default": "▶️"
"default": "▶️",
"order": 20
},
"tothom.saveEnvToTmp": {
"markdownDescription": "Save and restore environment variables to temporary files (`/tmp/tothom-*.env`) around each code block execution. Only applies when `#tothom.runInBackgroundByDefault#` is enabled.",
"type": "boolean",
"default": false,
"order": 50
}
}
}
],
"commands": [
{
"command": "tothom.clearTerminalSelection",
"title": "Clear terminal selection",
"category": "Tothom"
},
{
"command": "tothom.markdownPreview",
"title": "Markdown Preview",
Expand Down
Binary file added resources/run-in-background.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified resources/usage.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
33 changes: 23 additions & 10 deletions samples/tothom.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

- [Code blocks](#code-blocks)
- [Executable](#executable)
- [Non-executable](#non-executable)
- [Interpolation](#interpolation)
- [Multiline](#multiline)
- [Non-executable](#non-executable)
- [Carrying values](#carrying-values)
- [Compatibility](#compatibility)
- [Formatting](#formatting)
- [Attributes](#attributes)
Expand All @@ -28,6 +29,18 @@
echo 'Hello World!'
```

### Non-executable

```yaml
obj:
arr:
- item 1
- item 2
str: value
num: 1
bool: true
```
### Interpolation
```sh
Expand All @@ -44,18 +57,18 @@ code block
EOF
```

### Non-executable
### Carrying values

```yaml
obj:
arr:
- item 1
- item 2
str: value
num: 1
bool: true
```sh
TIME="$(date)"
```

```sh
echo "Time was: $TIME\nTime now is: $(date)"
```

> **Note:** `$TIME` above will be undefined when running the blocks in separate shells in the background and the `tothom.saveEnvToTmp` setting is disabled.
## Compatibility

### Formatting
Expand Down
7 changes: 5 additions & 2 deletions src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export class Engine {
private _engine: any;
private _originalImageFunc: RendererRuleFunc;
private _originalHeadingOpenFunc: RendererRuleFunc;
private _nonce: number = 0;

constructor(private options?: EngineOptions) {
this._engine = engine({
Expand Down Expand Up @@ -55,20 +56,22 @@ export class Engine {
private runInTerminalTitle = (): string => this.options?.runInTerminalTitle || defaultRunInTerminalTitle;

private renderCodeBlock = (code: string, language: string): string => {
const id = `code-${this._nonce++}`;
const codeAttrs = (language !== "") ? ` class="language-${language}"` : '';

let link = "";
switch (language) {
case 'bash':
case 'sh':
case 'zsh':
link = `<a href="tothom://?p=${terminal.encodeTerminalCommand(code, true)}" class="tothom-code-action" title="${this.runInTerminalTitle()}">${this.runInTerminalLabel()}</a>`;
const href = `tothom://?p=${terminal.encodeTerminalCommand(code, true)}&id=${id}`;
link = `<a href="${href}" class="tothom-code-action" title="${this.runInTerminalTitle()}">${this.runInTerminalLabel()}</a>`;
break;
default:
break;
}

return `<pre class="hljs"><code${codeAttrs}>${this.syntaxHighlight(code, language)}</code>${link}</pre>`;
return `<pre class="tothom-code hljs" id="${id}"><code${codeAttrs}>${this.syntaxHighlight(code, language)}</code>${link}</pre>`;
};

private syntaxHighlight = (code: string, language: string): string => {
Expand Down
6 changes: 5 additions & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const TOTHOM_MARKDOWN_PREVIEW = 'tothom.markdownPreview';
const TOTHOM_MARKDOWN_PREVIEW_EXISTING_TERMINAL = 'tothom.markdownPreviewWithExistingTerminal';
const TOTHOM_RELOAD_PREVIEW = 'tothom.reloadPreview';
const TOTHOM_SELECT_TERMINAL = 'tothom.selectTerminal';
const TOTHOM_CLEAR_TERMINAL_SELECTION = 'tothom.clearTerminalSelection';

const tothomOptions = (): TothomOptions => {
const config = vscode.workspace.getConfiguration('tothom');
Expand All @@ -16,7 +17,9 @@ const tothomOptions = (): TothomOptions => {
bracketedPasteMode: config.get('bracketedPasteMode'),
engineOptions: {
runInTerminalLabel: config.get('runInTerminalLabel')
}
},
runInBackgroundByDefault: config.get('runInBackgroundByDefault'),
saveEnvToTmp: config.get('saveEnvToTmp')
};
};

Expand All @@ -27,6 +30,7 @@ export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand(TOTHOM_MARKDOWN_PREVIEW_EXISTING_TERMINAL, (uri: vscode.Uri) => selectTerminal().then(term => tothom.openPreview(uri, { terminal: term }))));
context.subscriptions.push(vscode.commands.registerCommand(TOTHOM_RELOAD_PREVIEW, tothom.reloadPreview));
context.subscriptions.push(vscode.commands.registerCommand(TOTHOM_SELECT_TERMINAL, (uri: vscode.Uri) => selectTerminal().then(term => tothom.bindTerminal(uri, term))));
context.subscriptions.push(vscode.commands.registerCommand(TOTHOM_CLEAR_TERMINAL_SELECTION, tothom.clearTerminalSelection));

vscode.workspace.onDidChangeTextDocument(event => tothom.reloadPreview(event.document.uri, { reveal: false }));
vscode.workspace.onDidChangeConfiguration(() => tothom.setOptions(tothomOptions()));
Expand Down
Loading

0 comments on commit 76b1959

Please sign in to comment.