GithubHelp home page GithubHelp logo

draivin / hsnips Goto Github PK

View Code? Open in Web Editor NEW
148.0 4.0 23.0 248 KB

HyperSnips: a powerful snippet engine for VS Code, inspired by vim's UltiSnips

License: MIT License

TypeScript 98.83% JavaScript 1.17%

hsnips's Introduction

HyperSnips

HyperSnips is a snippet engine for vscode heavily inspired by vim's UltiSnips.

Usage

To use HyperSnips you create .hsnips files on a directory which depends on your platform:

  • Windows: %APPDATA%\Code\User\globalStorage\draivin.hsnips\hsnips\(language).hsnips
  • Mac: $HOME/Library/Application Support/Code/User/globalStorage/draivin.hsnips/hsnips/(language).hsnips
  • Linux: $HOME/.config/Code/User/globalStorage/draivin.hsnips/hsnips/(language).hsnips

You can open this directory by running the command HyperSnips: Open snippets directory. This directory may be customized by changing the setting hsnips.hsnipsPath. If this setting starts with ~ or ${workspaceFolder}, then it will be replaced with your home directory or the current workspace folder, respectively.

The file should be named based on the language the snippets are meant for (e.g. latex.hsnips for snippets which will be available for LaTeX files). Additionally, you can create an all.hsnips file for snippets that should be available on all languages.

Snippets file

A snippets file is a file with the .hsnips extension, the file is composed of two types of blocks: global blocks and snippet blocks.

Global blocks are JavaScript code blocks with code that is shared between all the snippets defined in the current file. They are defined with the global keyword, as follows:

global
// JavaScript code
endglobal

Snippet blocks are snippet definitions. They are defined with the snippet keyword, as follows:

context expression
snippet trigger "description" flags
body
endsnippet

where the trigger field is required and the fields description and flags are optional.

Trigger

A trigger can be any sequence of characters which does not contain a space, or a regular expression surrounded by backticks (`).

Flags

The flags field is a sequence of characters which modify the behavior of the snippet, the available flags are the following:

  • A: Automatic snippet expansion - Usually snippets are activated when the tab key is pressed, with the A flag snippets will activate as soon as their trigger matches, it is specially useful for regex snippets.

  • i: In-word expansion* - By default, a snippet trigger will only match when the trigger is preceded by whitespace characters. A snippet with this option is triggered regardless of the preceding character, for example, a snippet can be triggered in the middle of a word.

  • w: Word boundary* - With this option the snippet trigger will match when the trigger is a word boundary character. Use this option, for example, to permit expansion where the trigger follows punctuation without expanding suffixes of larger words.

  • b: Beginning of line expansion* - A snippet with this option is expanded only if the tab trigger is the first word on the line. In other words, if only whitespace precedes the tab trigger, expand.

  • M: Multi-line mode - By default, regex matches will only match content on the current line, when this option is enabled the last hsnips.multiLineContext lines will be available for matching.

*: This flag will only affect snippets which have non-regex triggers.

Snippet body

The body is the text that will replace the trigger when the snippet is expanded, as in usual snippets, the tab stops $1, $2, etc. are available.

The full power of HyperSnips comes when using JavaScript interpolation: you can have code blocks inside your snippet delimited by two backticks (``) that will run when the snippet is expanded, and every time the text in one of the tab stops is changed.

Code interpolation

Inside the code interpolation, you have access to a few special variables:

  • rv: The return value of your code block, the value of this variable will replace the code block when the snippet is expanded.
  • t: An array containing the text within the tab stops, in the same order as the tab stops are defined in the snippet block. You can use it to dynamically change the snippet content.
  • m: An array containing the match groups of your regular expression trigger, or an empty array if the trigger is not a regular expression.
  • w: A URI string of the currently opened workspace, or an empty string if no workspace is open.
  • path: A URI string of the current document. (untitled documents have the scheme untitled)

Additionally, every variable defined in one code block will be available in all the subsequent code blocks in the snippet.

The require function can also be used to import NodeJS modules.

Context matching

Optionally, you can have a context line before the snippet block, it is followed by any javascript expression, and the snippet is only available if the context expression evaluates to true.

Inside the context expression you can use the context variable, which has the following type:

interface Context {
  scopes: string[];
}

Here, scopes stands for the TextMate scopes at the current cursor position, which can be viewed by running the Developer: Inspect Editor Tokens and Scopes command in vscode.

As an example, here is an automatic LaTeX snippet that only expands when inside a math block:

global
function math(context) {
    return context.scopes.some(s => s.startsWith("meta.math"));
}
endglobal

context math(context)
snippet inv "inverse" Ai
^{-1}
endsnippet

Examples

  • Simple snippet which greets you with the current date and time
snippet dategreeting "Gives you the current date!"
Hello from your hsnip at ``rv = new Date().toDateString()``!
endsnippet
  • Box snippet as shown in the gif above
snippet box "Box" A
``rv = '' + ''.repeat(t[0].length + 2) + ''``
│ $1``rv = '' + ''.repeat(t[0].length + 2) + ''``
endsnippet
  • Snippet to insert the current filename
snippet filename "Current Filename"
``rv = require('path').basename(path)``
endsnippet

hsnips's People

Contributors

alan-liang avatar dependabot[bot] avatar draivin avatar eytienne avatar hinell avatar itswin avatar jovvik avatar logerfo avatar mfederczuk avatar orangex4 avatar rioj7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

hsnips's Issues

Quotes " sign

hi,

is it somehow possible to use " in snippets? In the extension's code, the " is replaced.

Snippets with tab completion don't work (regex)

global
function math(context) {
    return context.scopes.some(s => s.startsWith("meta.math"));
}
endglobal

context math(context)
snippet `(?<!\\)(sin|cos|arccot|arccos|arcsin|sinh|cosh|cot|csc|ln|log|exp|star|perp)` "ln" 
\\``rv = m[1]``
endsnippet

This snippet only works when adding the flag A, however, I don't want it to expand instantly but when hitting tab, why?
This problem also occurs for many other snippets which I want to expand with tab.

Feature request: new `e` flag for exact match

Hello, I have an issue that could be solved with a new flag. When the i flag is used (for in-word expansion), the snippet will be triggered even if the trigger was not fully input by the user. The VSCode suggestion box comes up and tries to autocomplete the trigger that you started to input which can lead to unexpected behavior.

Consider the following hyper-snippet:

snippet xx "Cross" i
\\times
endsnippet

When typing the word latex in a document, the VSCode suggestion dropdown comes up and tries to autocomplete the trigger xx. If I press the trigger key, the snippet will expand (even though I did not typed xx) resulting in late\times.
(On top of that undoing with ctrl+z will show latexx as if I had typed xx, that really confused me at first xD)

We could use the e flag, standing for "exact", in the snippet definition that will solve this issue. A snippet that has this flag would be shown (and triggered) only if the exact match is typed by the user.

(latex<tab> would not trigger the snippet but latexx<tab> will)

Return value from code interpolation replaces placeholder text

The following snippet contains two placeholders: $1 on the first line, and $2 on the last one. Between $1 and $2 there is a dynamic code that prints 'c' if the first character typed in $2 is '-', and 'd' otherwise.

snippet mm "test" A
\$$1\$
``if (t[1] && t[1][0] == '-') { rv = 'c' } else { rv = 'd' }``
$2
endsnippet

If $1, $2 and the code interpolation are all on different lines, the snippet works as expected. However, if line breaks are removed, like in the following:

snippet mm "test" A
\$$1\$``if (t[1] && t[1][0] == '-') { rv = 'c' } else { rv = 'd' }``$2
endsnippet

then, the return value rv interferes with $1 and $2, and the snippet does not work anymore.

This snippet actually comes by adapting code from a UltiSnips snippet:

snippet mk "Math" wA
$${1}$`!p
if t[2] and t[2][0] not in [',', '.', '?', '-', ' ']:
    snip.rv = ' '
else:
    snip.rv = ''
`$2
endsnippet

which is used in https://castel.dev/post/lecture-notes-1/ and works as expected in Vim. Is it possible to replicate this behavior in Visual Studio Code?

How does one use the matching regex?

I have a snippet defined as follows:

context math(context)
snippet `vec([a-zA-Z])` "bold vector" iA
``rv = \textbf{m[1]}`` $0
endsnippet

How can I use the captured group from the snippet trigger word, e.g. if I type veca it should become \textbf{a}

Feature request: priority of snippets

It would be useful to assign a priority value to snippets, determining their order of evaluation, like in UltiSnips:

priority 10
snippet test "Just a test"
Hello!
endsnippet

So that snippets with higher priority are evaluated before others, and snippets with the same priority are evaluated in the order they appear in code. This could be especially useful to control "snippet cascades", where the output of a higher priority snippet triggers another lower priority snippet.

Expose More Variables

Hi. First of all, I love UltiSnips, when seeing your snippet engine, I'm excited VSCode potentially can have snippet engine as powerful as UltiSnips can be. Anyway, Can you add more variables to expose?

There's some things I want to access:

  1. Current Buffer text (The whole document), as string or array of lines if possible (It may be slow, but it's friendly). Nice to have both (2 different variables).
  2. The line index number where the snippet trigger.
  3. The column index number where the snippet trigger.

Something nice to have:

  1. Tab stop line number
  2. Tab stop column line number

The purpose, if not obvious, is to have context around the snippet's trigger location.

Like for example in golang (basically ultisnips example):

file, err := os.Open("file.go")

by writing if in the next line, I get snippet that will expand to:

if err != nil {
	$0
}

but if there's no err := in the previous line, by writing if I get snippet that will expand to:

if $1 {
  $0
}

I can easily do so by using line number where the snippet trigger as the index of Buffer Text document and use regex match on that index - 1 (previous line).

Can't use regex with normal completion

I recognised that regex expressions don't seem to work with normal tab completion. Whenever I use regex in a snippet without adding the A flag, which I don't want because I need tab completion, it doesn't work.

Is python support possible ?

I have to say I find this extension god-send really. The only problem is I have never used Javascript before. I'm already familiar with Python. I know that browsers can run Javascript code directly, but is there a possibility we can use Python instead of Javascript ?

Suggestion: Remove `triggerCharacters` that passed to registerCompletionItemProvider

When setting "editor.suggestOnTriggerCharacters": true in vscode, and enable hsnips. I encounter a strange problem, vscode IntelliSense (TS/JS code suggestion) won't show, only snippets shown in completion suggestions.

Quoted vscode documentation on registerCompletionItemProvider:

When trigger characters are being typed, completions are requested but only from providers that registered the typed character

Setting trigger character within the alphabet may block other completion item provider's results.

With triggerCharacters removed, multiple completion item providers can work together nicely.

Hypersnips disables quicksuggestions

Hi,

When the extension is disabled, vscode gives me pop-up suggestions as I type.
However, when hypersnips is enabled, this no longer occurs and only hyper snippets show up; I have to press ctrl+space to see the regular suggestions

Implement end to end testing of the extension

As said in the title, to do so would require for us to somehow simulate entering one key at a time inside vscode, and triggering auto completion when those keys are pressed.

We also would need to parse the input to detect sequences like <tab> so we could accept the best auto completion at that position.

Expanding snippet inside another snippet interrupts code interpolation

I have two snippets: the first one inserts a math block ($$), followed by a space if the first character in the last placeholder is not in some set of characters.

snippet mk "inline math" A
\$$1\$``if (t[1] && ",-.? ".indexOf(t[1][0]) >= 0) { rv = '' } else { rv = ' ' }``$2
endsnippet

The second snippet formats every string of an alphabetical character followed by a number in the following way: a2 => a_{2}

snippet `([a-zA-Z])([0-9]+)` "underset" A
``rv = m[1] + '_{' + m[2] + '} '``
endsnippet

Both snippets work fine on their own. However, if I use one "inside" the other, for example by typing mka2<Tab>? the return value of the "outer" code interpolation (i.e. the "inline math" one) gets interrupted. In this case I expect to get "$a_{2}$?" (without the space), but I get "$a_{2}$ ?" (with the space).

This is more easy to see by typing "a2" inside the "box" snippet reported in the examples:

snippet box "Box" A
``rv = '┌' + '─'.repeat(t[0].length + 2) + '┐'``
│ $1 │
``rv = '└' + '─'.repeat(t[0].length + 2) + '┘'``
endsnippet

The problem persists even if the "inner" snippet is not dynamic (it is without the "A" in the definition, requiring to expand), or it doesn't contain any code interpolation. Note that using a usual VS code snippet inside an hsnips snippet works as expected, without any problem.

Flags i

In the Ultisnips for vim, there are flags 'A' and 'i'
this extension have flag A
but I think 'i' is also a useful flag
such as using latex in markdown
$if I use snips here$
the snips won't trigger,because it is next to '$'
I have to print space twice
$ $
then back to the middle, to print

How to end snippets?

The following snippet replaces the text you type with a lowercase version with spaces replaced with -. However, pressing tab doesn't seem to "end" the snippet - subsequent typing still gets .toLowerCase() and .replace(/ /g, '-') applied.

snippet slug "Markdown Slug"
$0``rv = t[0].toLowerCase().replace(/ /g, '-')``
endsnippet

I feel like pressing tab should always end the snippet capture if the last input ($0) is selected.

Comment shortcut not working in `.hsnips` grammar

The Ctrl+/ shortcut to comment the selected code block seems not to be working when editing .hsnips files, even though JavaScript style // comments do comment the line and are colour-coded in the editor.

This might be an issue with the language grammar.

how to define context of snippets?

如果hsnip可以定义上下文环境,那么这将是完美的!参考这篇文章

https://castel.dev/post/lecture-notes-1/#context

他通过代码突出显示提取出了公式环境,而这在VSCode中理论上可以实现。。各种VSCode主题也是这样做的

另外可以通过 inspectTMScopes 得到当前环境(scope):

image

而Vsnips插件似乎也可以做到这一点:

image

是否可以通过某些手段,实现对上下文的支持?

Feature request: open snippets file inside VSCode

Right now there is only a command to open the snippets directory, however it would be useful for quick fixes to snippets while working if there was a way to open the .hsnips file directly in VSCode from the command palette, as is the case with regular VSCode snippets files with the command Preferences: configure user snippets.

Fast typing breaks code evaluation

This is a minor bug, as it happens rarely, and in very specific situations.
It can happen with any kind of snippet with code interpolation. For example, by using the box snippet reported in the examples, and holding down the character 'a', evaluation quickly stops, leading to a result like this:
quick_typing
The same thing happens by repeating different keys (like 'jk', instead of 'a') really fast.
I tested this on VS Code 1.39.1, using HyperSnips 0.0.15. It is not a matter of interference with other snippets, as I tested it by leaving only the code for box in the .hsnips file.

Snippet expanding in-word when it shouldn't

According to your notes, "a snippet trigger will only match when the trigger is preceded by whitespace characters" unless the "i" flag is used.

The code below should expand for a1 as a_1 but shouldn't expand for item1 since the trigger is not preceded by whitespace characters.

snippet `[A-Za-z])(\d)` "auto subscript" A
``rv = m[1] + '_' + m[2]``
endsnip

It's quite easy to fix (as shown below), but I don't know this is correct behaviour ?

snippet `(?<= )([A-Za-z])(\d)` "auto subscript" A
``rv = m[1] + '_' + m[2]``
endsnip

Restricting snippets to contexts

I'm just wondering if it is possible to make some snippets expand only inside certain contexts. For example, if I type "ahat" inside an equation block or inside $ $, I want it to become \hat{a} but if I type "that" anywhere outside an equation block, I don't want it to become \hat{t} but stay as it is. Is something like this possible?

Here's a page where someone does something like this, but in vim: https://castel.dev/post/lecture-notes-1/#context

Can't use dynamic imports in code interpolation.

Context: I'm trying to get math expression evaluation working through snippets using the mathjs library (Particularly the evaluate function from mathjs).

Here's the snippet I'm using to test. I've verified the JS works on my machine.

snippet import "import test"
``
function load() {
  import('mathjs')
  .then(module => {
    console.log("Successful load");
    console.log(module.default.evaluate("sqrt(3^2+4^2)"));
  })
}

load();
``
endsnippet

I get the error

rejected promise not handled within 1 second: Error: Not supported
extensionHostProcess.js:1048
stack trace: Error: Not supported
	at load (eval at parse (c:\Users\Win33\Documents\Programming\hsnips\out\parser.js:115:22), <anonymous>:216:1)
	at HSnippet.eval [as generator] (eval at parse (c:\Users\Win33\Documents\Programming\hsnips\out\parser.js:115:22), <anonymous>:223:1)
	at new HSnippetInstance (c:\Users\Win33\Documents\Programming\hsnips\out\hsnippetInstance.js:39:36)
	at expandSnippet (c:\Users\Win33\Documents\Programming\hsnips\out\extension.js:61:27)
	at c:\Users\Win33\Documents\Programming\hsnips\out\extension.js:110:9
	at c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:977:271
	at Object.edit (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:630:242)
	at c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:977:260
	at _executeContributedCommand (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:675:513)
	at _doExecuteCommand (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:674:689)
	at _.executeCommand (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:674:595)
	at b._executeConvertedCommand (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:677:381)
	at _executeContributedCommand (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:675:513)
	at _.$executeContributedCommand (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:675:888)
	at g._doInvokeHandler (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:860:464)
	at g._invokeHandler (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:860:156)
	at g._receiveRequest (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:858:817)
	at g._receiveOneMessage (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:857:623)
	at c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:855:691
	at l.fire (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:46:475)
	at v.fire (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:256:381)
	at c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:1047:649
	at l.fire (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:46:475)
	at v.fire (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:256:381)
	at Object._receiveMessage (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:261:451)
	at c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:258:489
	at l.fire (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:46:475)
	at p.acceptChunk (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:253:851)
	at c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:253:203
	at Socket.t (c:\Users\Win33\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\services\extensions\node\extensionHostProcess.js:263:54)
	at Socket.emit (events.js:223:5)
	at addChunk (_stream_readable.js:309:12)
	at readableAddChunk (_stream_readable.js:290:11)
	at Socket.push (_stream_readable.js:224:10)
	at Pipe.onStreamRead (internal/stream_base_commons.js:181:23)

Not sure why this really happens. Maybe VSCode doesn't like/allow dynamic imports?

Bug: trigger not working if ending with some characters

I found a weird behavior in the new version:

For some reasons, this is not working anymore:

snippet a1 "Issue 1" A
Not working
endsnippet

snippet `a2` "Issue 2" A
Not working
endsnippet

snippet `a\/` "Issue 3" A
Not working
endsnippet

If the trigger is not ending with a [A-Za-z\#\>] character, it will not work.

This only occurs in math center mode, with line breaks:

\[
    a1
\]
$$
a1
$$

Wrong directory in usage docs

$HOME/Library/Application Support/Code/User/snippets/(language).hsnips should be:
$HOME/Library/Application Support/Code/User/hsnips/(language).hsnips

Snippet in Snippet

Hello, there is a problem that I have encountered that is starting to give many problems.
When I try to expand one snippet into another, I can't, unless the latter is an automatic snippet (iA, wA, bA ...).
When I try to activate a snippet (which requires the tabulator) inside another snippet, the latter will not be able to operate.
Please solve the problem.

Thanks in advance.

Untitled.Project.Made.with.Clipchamp.mp4

Regular expression cannot match line break

image

I want to match a\nb\nc\n\d.change

image

I tried these two kinds of measure (.|\n) and [\s\S].
but both of them doesn't work

image

it can only match when they are written in one line

Trigger A leaves me in visual mode, I want it to leave me in insert mode instead

Hi, I really love the extension, there is one issue for me. I am not sure whether it is caused by hsnips or by my vscode-vim settings somehow.

I have a snippet like:

snippet eq "Equation" b
\begin{equation}
$1
\end{equation}
$0
endsnippet

which works exactly as expected, places the cursor in position $1 and vim is in insert mode. However, if I use an automatic trigger like

snippet eq "Equation" bA
\begin{equation}
$1
\end{equation}
$0
endsnippet

the snippet still expands as before however vim is in visual mode and the cursor is placed just somewhere. Then to proceed, I shall navigate with hjkl to the place $1, press ECS to enter normal mode, then press i to enter insert mode and only then the snippet works as expected.

So my question is where are the settings that tell vscode-vim in which mode to be after the snippet is expanded?

Snippets won't expand at all

I have installed the plugin and placed a tex.hsnips file in the respective directory (opening with the command HyperSnips: Open Snippets Directory but the snippets don't expand. The file contents:

snippet norm "norm" Ai
\|$1\| $0
endsnippet

What am I doing wrong?

Add "context" by regex

my friend from NJU gives a method to add math context. He uses regex to achieve that.

https://github.com/OrangeX4/hsnips

He add this code into extension.ts:

function isMathEnvironment(editor: vscode.TextEditor) {
        let text = editor.document.getText(new vscode.Range(new vscode.Position(0, 0), editor.selection.start))
        const reg = /(\\begin\{equation\}[^\$]*?\\end\{equation\})|(\\begin\{equation\*\}[^\$]*?\\end\{equation\*\})|(\\\[[^\$]*?\\\])|(\\\([^\$]*?\\\))|(\$\$[^\$]+\$\$)|(\$[^\$]+?\$)/g
        text = text.replace(reg, '')
        if (text.indexOf('$') == -1 && text.indexOf('\\(') == -1 && text.indexOf('\\[') == -1 && text.indexOf('\\begin{equation}') == -1 && text.indexOf('\\begin{equation\*}') == -1) {
            return false
        } else {
            return true
        }
    }

and changes something in other files. You can add a flag m add use that, like:

snippet inv "inv" iAm
^{-1}
endsnippet

we can find the extension "hypersnips for math" in VSCode market.

(I 'm not so familiar with Enelish🤣🤣🤣)

How to make it work with Latex workshop ?

Hello,

I've been playing with this extension and seems to work as described. I created a tex.hsnips file but it doesn't seem to be detected inside a tex document. The all.hsnips gets detected fine. I am using Latex workshop to parse the tex documents. How can I get this extension to work if I don't want to put all the code inside the all.snippets?

Random Snippets don't work

I have a couple of snippets, those who are automatically expanded still work but after adding global context for math environments in latex, all of non automatic ones have stopped working. I have started at the file hard and failed to find any problem with it so it must be Hsnips fault, or I am missing something again, in which case I would like some guidance on how to solve this problem.

Update: Even making them automatic doesn't make them work.

how to get previous line text?

take restructured text for example, I need to dynamically insert headline directive under a line after typing the texts:

HEADLINE TEXT
<trigger the hysnips here>

expecting result:

HEADLINE TEXT
=============

the number of '=' exactly equals to the calculated length of the 'HEADLINE TEXT'(in CJK environment, the length is another complex thing, and I will write a function to do that in 'global' blocks)

Triggers Won't Fire

Installed hypersnips 0.1.0 in Visual Studio Code:
Version: 1.46.1
Commit: cd9ea6488829f560dc949a8b2fb789f3cdc05f5d
Date: 2020-06-17T21:13:08.304Z
Electron: 7.3.1
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Linux x64 4.15.0-106-generic

VS Code reports that Hypersnips 0.1.0 is enabled globally.

I defined a file all.hsnips in $HOME/.config/Code/User/hsnips/all.hsnips
and copied the code examples from the README.md file.

I then exited out of VS Code and restarted it. I created a file named junk.js. I typed the command box, pressed tab nothing happened. I pressed the period and nothing happened. I did the same with dategreeting .

In the command Palette I see 3 commands related to Hypersnips but when I run Hypersnips: Open Snippets Directory I get the following error:
Command 'HyperSnips: Open Snippets Directory' resulted in an error (command 'hsnips.openSnippetsDir' not found) and corresponding errors for the other Hypersnips commands.

What can I do to determine why these triggers aren't firing?

Thanks,

there is something wrong with vim extension for vscode

after they publish 1.17.x version, until now 1.18.5
after hypersnips triggers the snippets, vim will change to Visual mode, which should normally keep insert mode

image

image
In fact, the previous version 17 had this problem with vscode's own block engine, too , but it was fixed in version 18

Question: with VIM mode , is there a way to use javascript?

Hi,

I am using vim mode in VSCode and try to use hsnips extension as well.
Apparently, I can use simple snippets without problem but I cannot use javascript inside the snippet. Is this known limitation or maybe I am doing something wrong?

Subtle context matching

Hello, I am currently testing the new context matching support and I found something that can be annoying for LaTeX users:

In math mode, the math scope is still active inside \text{} command...
If I need to write a small text while writing an equation, all my snippets will automatically trigger.

I don't know if this can be solved or not as it has to do with TextMate scopes. If not, could we find a workaround ?

You can take a look at the Context § in https://castel.dev/post/lecture-notes-1.

Consistency in using \

There seems to some inconsistency in the use of \.

For example, consider the code below:

snippet floor "floor" iA
\left\lfloor $1 \right\rfloor$0
endsnippet

Triggering the snippet only prints the first \.

So, I changed every single \ into \\. Triggering the snippet returns the first \ as \\ while the other ones as \.

It seems to get the expected result, one needs to write things as shown below. While this is a trivial issue, it seems inconsistent.

snippet floor "floor" iA
\left\\lfloor $1 \\right\\rfloor$0
endsnippet

Also, how can I return \\. In Javascript, one would simple write it as \\\\. This doesn't seem to work here.

Undo (Ctrl+Z) triggers automatic snippet expansion

Occasionally I want to revert the automatic snippet expansion using Ctrl+Z, but it won't work if the trigger contains regex or if it is with A flag. For example, consider the snippet

snippet `([a-zA-Z])td` "superscript" iA
``rv = m[1] + '^{$1}'``$0
endsnippet

which expands atd to a^{}.

Expected behavior

If I press Ctrl+Z, a^{} reverts back to atd.

Actual behavior

If I press Ctrl+Z, first a^{} reverts back to atd but then is immediately and automatically converted to a^{} again.
So effectively Ctrl+Z achieves nothing.

Additional Context

  1. Undo works well if the snippet body has multiple lines:
snippet `([a-zA-Z])td` "superscript" iA
newline
``rv = m[1] + '^{$1}'``$0
endsnippet

In this case Undo properly reverts the snippet expansion.

  1. Even if the trigger does not contain regex, a similar problem exists.
snippet invs "inverse" A
^{-1}
endsnippet

invs is expanded to ^{-1}. Pressing Ctrl+Z once converts it to invs^{-1}, and pressing Ctrl+Z once again reverts back to invs.

Overall, the interaction between Undo and automatic snippet expansion by hsnips is quite inconsistent.

`<tab>` does not trigger expansion of nested snippets

Related to this VSCode issue.

When the HyperSnips extension is enabled, it becomes impossible to use nested completion: completion while being inside a snippet placeholder.

This is a bit frustrating as it is preventing snippet nesting (not only for .hsnips snippets but for any VSCode snippets)

Steps to reproduce

(Don't forget to add the setting "editor.suggest.snippetsPreventQuickSuggestions": false)

Create a simple VSCode snippet:

"Dash": {
    "prefix": "dash",
    "body": [
        "$1-$0"
    ]
}

(| is a future snippet placeholder, <cursor> is the current cursor position)

Without the HyperSnips extension, the behavior is as intended:
Typing dash<tab>dash<tab> is nesting the two snippets resulting in <cursor>-|-|.

With the HyperSnips extension enabled:
Typing dash<tab>dash<tab> results in dash-<cursor>.

Compatibility with Settings Sync

First of all, thank you for developing this amazing extension! It has saved me a lot of time.

I recently cleaned up and reinstalled my macOS and just found out that I did not backup my list of snippets... Would it be possible to include .hsnips files in the new Settings Sync feature of VSCode? That would be beneficial for people with multiple workstations and prevent such disaster from happening again.

Thank you!

how to change this snippet for Hypersnips

Good morning, I used to use this snippet in Macvim, I have taken this snippet from github (Ultisnips), but now, when I try to insert this snippet in Hypersnips, it doesn't work, could You help me??
this is the snippet:

global !p
def create_matrix_placeholders(snip):
# Create anonymous snippet body
anon_snippet_body = ""

# Get start and end line number of expanded snippet
start = snip.snippet_start[0]
end = snip.snippet_end[0]

Append current line into anonymous snippet

for i in range(start, end + 1):
	anon_snippet_body += snip.buffer[i]
	anon_snippet_body += "" if i == end else "\n"

# Delete expanded snippet line till second to last line
for i in range(start, end):
	del snip.buffer[start]

# Empty last expanded snippet line while preserving the line
snip.buffer[start] = ''

# Expand anonymous snippet
snip.expand_anon(anon_snippet_body)

def create_matrix(cols, rows, sep, start, end):
res = ""
placeholder = 1
for _ in range(0, int(rows)):
res += start + f"${placeholder} "
placeholder += 1
for _ in range(0, int(cols) - 1):
res += sep + f" ${placeholder} "
placeholder += 1
res += end
return res[:-1]
endglobal

post_jump "create_matrix_placeholders(snip)"
snippet 'arr(\d+),(\d+)' "LaTeX array" br
\begin{array}{!p orient = "" for _ in range(0, int(match.group(1))): orient += "l" snip.rv = orient}
!p snip.rv = create_matrix(match.group(1), match.group(2), "&", "\t", "\\\\\\\\\n") $0
\end{array}
endsnippet

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.