Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix \ and $ escape error in VSCode snippet #22

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "npm run dev",
"dev": "webpack-dev-server --mode development --open",
"build": "rm -rf dist && webpack --mode production"
},
Expand Down
23 changes: 11 additions & 12 deletions src/components/VSCode.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,22 @@ import React from 'react';
import { html } from 'common-tags';
import { Consumer } from './Context';

const renderSnippet = (snippet, tabtrigger, description) => {

// escape " with \"
// split lines by line-break
const separatedSnippet = snippet.replace(/"/g, '\\"').split('\n');
const separatedSnippetLength = separatedSnippet.length;

// add double quotes around each line apart from the last one
const newSnippet = separatedSnippet.map((line, index) => {
return index === separatedSnippetLength - 1 ? `"${line}"` : `"${line}",`;
});
const formatSnippet = snippet => (
snippet
.replace(/\\/g, '\\\\\\\\') /* escape `\`: in JSON, `\\` or `\\\\` escape one `\` */
.replace(/"/g, '\\"') /* escape quotes */
.replace(/\$/g, '\\\\$') /* escape `$`: VSCode use `$` as placeholder*/
.split('\n') /* split lines */
.map(line => `"${line}"`) /* add quotes to lines */
.join(',\n')
);

const renderSnippet = (snippet, tabtrigger, description) => {
return html`
"${description}": {
"prefix": "${tabtrigger}",
"body": [
${newSnippet.join('\n')}
${formatSnippet(snippet)}
],
"description": "${description}"
}
Expand Down