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

Add code block support in markdown #11

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,24 @@

All notable changes to the "neo4j-vscode" extension will be documented in this file.

## [0.1.9]

- Automatically selects the text within code block(s) when running a query if no selection is made, based on cursor position(s)

Example:

The following will execute the queries separately

```cypher
match (n) return n limit 1 // A cursor is here
```

```cypher
match (n) return n limit 10 // A cursor is here
```

- Added support for Cypher code blocks in Markdown files [Reference](https://stackoverflow.com/a/76239666/3876654)

## [0.1.8]

- Applied case insensitivity to parameter commands
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 24 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"type": "git",
"url": "https://github.com/adam-cowley/neo4j-vscode"
},
"version": "0.1.8",
"version": "0.1.9",
"engines": {
"vscode": "^1.74.0"
},
Expand All @@ -27,12 +27,32 @@
],
"main": "./out/extension.js",
"activationEvents": [],
"markdown.codeLanguages": [
{
"id": "cypher",
"aliases": [
"cypher",
"Cypher Query Language"
]
}
],
"contributes": {
"grammars": [
{
"language": "cypher",
"scopeName": "source.cypher",
"path": "./cypher/cypher.tmLanguage"
},
{
"language": "cypher-markdown-injection",
"scopeName": "markdown.cypher.codeblock",
"path": "./syntaxes/cypher-markdown-injection.json",
"injectTo": [
"text.html.markdown"
],
"embeddedLanguages": {
"meta.embedded.block.cypher": "cypher"
}
}
],
"viewsContainers": {
Expand Down Expand Up @@ -187,6 +207,9 @@
}
],
"languages": [
{
"id": "cypher-markdown-injection"
},
{
"id": "cypher",
"aliases": [
Expand Down
111 changes: 107 additions & 4 deletions src/commands/cypher/run-cypher.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,95 @@
import { window } from 'vscode'
import { TextEditor, window } from 'vscode'
import ConnectionManager from '../../connections/connection-manager.class'
import { Method } from '../../constants'
import CypherRunner from '../../cypher/runner'

type CodeBlockErrors = {
notInsideCodeBlock: number[];
emptyCodeBlock: number[];
}

function showBlockError(message: string, lines: number[]) {
window.showErrorMessage(`${message} at line${
lines.length > 1 ? 's' : ''
}: ${lines.join(', ')}`)
}

/**
* Handle errors for code blocks
* @param errors The potential errors to handle
* @returns Boolean indicating if there were errors
*/
function handleCodeBlockErrors({
notInsideCodeBlock, emptyCodeBlock
}: CodeBlockErrors) {
if (notInsideCodeBlock.length > 0) {
showBlockError(`Cursor is not inside a code block`, notInsideCodeBlock)
return true
}

if (emptyCodeBlock.length > 0) {
showBlockError(`Empty code block`, emptyCodeBlock)
return true
}
}

/**
* Get code blocks from markdown based on cursor position(s)
* Informs the user if there are any errors
* @param editor The text editor to get code blocks from
* @returns The code blocks if no errors, else undefined
*/
function getCodeBlocks(editor: TextEditor): string[] | undefined {
const markdown = editor.document.getText()

const codeBlockRegex = /(```|~~~)+\s*cypher\s*\n([\s\S]*?)\n\1/g

// Sorting and filtering prevents errors in code block matching
const selections = [...editor.selections]
.sort((a, b) => a.active.line - b.active.line)
// Remove duplicate selections that share the same line
.filter((selection, index, selections) =>
selection.active.line !== selections[index - 1]?.active.line)

const initialAccumulator = {
codeBlocks: [] as string[],
errors: {notInsideCodeBlock: [] as number[], emptyCodeBlock: [] as number[]}
}

// Get code blocks from markdown based on cursor position(s)
const {codeBlocks, errors} = selections.reduce(({codeBlocks, errors}, selection) => {
const cursorPosition = selection.active
let match: RegExpExecArray | null

// Find all code blocks
while ((match = codeBlockRegex.exec(markdown)) !== null) {
const codeBlockStart = editor.document.positionAt(match.index)
const codeBlockEnd = editor.document.positionAt(match.index + match[0].length)

// Check if cursor is inside code block
if (cursorPosition.isAfterOrEqual(codeBlockStart)
&& cursorPosition.isBeforeOrEqual(codeBlockEnd)) {
const text = match[2].trim()
if (text.length === 0) {
errors.emptyCodeBlock.push(codeBlockStart.line + 1)
} else {
codeBlocks.push(text)
return {codeBlocks, errors}
}
}
}

errors.notInsideCodeBlock.push(cursorPosition.line + 1)
return {codeBlocks, errors}
}, initialAccumulator)

if (handleCodeBlockErrors(errors)) {
return
}

return codeBlocks
}

export default async function runCypher(
connections: ConnectionManager,
cypherRunner: CypherRunner,
Expand All @@ -27,11 +114,27 @@ export default async function runCypher(
&& editor.document.getText(selection)
)

// Attempt to run entire file
// Attempt to run entire file or code block(s) if no selection
if (selections.length === 0) {
const documentText = editor.document.getText()
const isMarkdown = editor.document.languageId === 'markdown'

if (isMarkdown) {
const codeBlocks = getCodeBlocks(editor)
if (!codeBlocks) {
return
}
await Promise.all(codeBlocks.map((codeBlock) =>
cypherRunner.run(activeConnection, codeBlock, method)
))
} else {
const documentText = editor.document.getText()
if (!documentText) {
window.showErrorMessage(`No text in document`)
return
}
await cypherRunner.run(activeConnection, documentText, method)
}

await cypherRunner.run(activeConnection, documentText, method)

return
}
Expand Down
45 changes: 45 additions & 0 deletions syntaxes/cypher-markdown-injection.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"fileTypes": [],
"injectionSelector": "L:text.html.markdown",
"patterns": [
{
"include": "#cypher-code-block"
}
],
"repository": {
"cypher-code-block": {
"begin": "(^|\\G)(\\s*)(\\`{3,}|~{3,})\\s*(?i:(cypher)(\\s+[^`~]*)?$)",
"name": "markup.fenced_code.block.markdown",
"end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
"beginCaptures": {
"3": {
"name": "punctuation.definition.markdown"
},
"4": {
"name": "fenced_code.block.language.markdown"
},
"5": {
"name": "fenced_code.block.language.attributes.markdown"
}
},
"endCaptures": {
"3": {
"name": "punctuation.definition.markdown"
}
},
"patterns": [
{
"begin": "(^|\\G)(\\s*)(.*)",
"while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)",
"contentName": "meta.embedded.block.cypher",
"patterns": [
{
"include": "source.cypher"
}
]
}
]
}
},
"scopeName": "markdown.cypher.codeblock"
}