This is what I'd like to achieve (t is selected in editor):
Before snippet:
var t = 'Foobar';
After snippet:
var t = 'Foobar';
console.log('t', t);
How can I do that?
Here is what I tried to do:
"log_selection": {
"prefix": "cls",
"body": [
"console.log('$TM_SELECTED_TEXT', $TM_SELECTED_TEXT);"
],
"description": "Logs selected text"
}
But this just replace selected text with snippet. I think that I could use TM_CURRENT_LINE here but I have no idea what to do with remaining text in the line.
Do you have any idea for this? Maybe it's impossible with snippet? If so, how can I achieve desired effect?
Thank you.
Extension macros (executing multiple commands in 1 keybinding).
settings.json:
"macros": {
"snippetWithDescription": [
"editor.action.clipboardCopyAction",
"editor.action.insertLineAfter",
{
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "console.log('$CLIPBOARD', $CLIPBOARD)$0"
}
}
]
}
keybindings.json:
{
"key": "ctrl+shift+;",
"command": "macros.snippetWithDescription"
}
P.S. you can even omit the selection part if you add another command at the beginning of snippetWithDescription: "editor.action.addSelectionToNextFindMatch",. Just place cursor beside the word and hit hotkey.
I came to this question looking for a solution other than installing a macro extension. Yours can be done with a snippet though as long as the cursor is at the end of your var declaration line. The snippet would use regex:
"log_selection": {
"prefix": "cls",
"body": [
"",
"console.log('${TM_CURRENT_LINE/var (.+?) =.*$/$1', $1/});"
],
"description": "Logs selected text"
}
The capturing group (.+?) holds your variable name and is placed in $1. I've tested it (and a good thing, because it took a lot of edits to get a working regex). You'd probably want to set up a key binding in your settings to trigger the snippet (but it also works typing the snippet prefix):
"key": "alt+c alt+l", // some key combo
"command": "editor.action.insertSnippet",
"when": "editorTextFocus && !editorHasSelection",
"args": {
"langId": "js", // ?? optional?
"name": "log_selection" // your snippet name
}
Unfortunately, in my case I'm trying to alter the current line so it seems I may need a macro to select the line so that it is replaced.
this worked for me:
"macros": {
"logCurrentVariable": [
"editor.action.addSelectionToNextFindMatch",
"problems.action.copy",
"editor.action.clipboardCopyAction",
{
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "console.log('$CLIPBOARD', $CLIPBOARD)$0"
}
}
]
},
from https://medium.com/#copperfox777/how-to-console-log-variable-under-the-cursor-in-visual-studio-code-ba25feadb00a
Related
I have JS as defined below (JS File). On push to a repo I want to statically validate things defined below (Validate This). I've been researching this and my first idea is to validate items 1-4 using https://www.npmjs.com/package/espree. Appreciate it if someone can confirm if this would do the job (be the best method) and if so an example validating the returned AST.
Validating item 5 is a little more interesting I need to extract the contents that w.abc.myobj is set which will effectively always equate to JSON and validate it's contents against rules using something like https://www.npmjs.com/package/ajv. Appreciate any insights on how best to do this as well especially the extraction of the JSON from the static code file.
Validate This
/*
1. Is the first statement a try/catch block
2. Is the first statement within the try/catch block an anonymous function with a "w" arg
3. Is the second statement what is shown
4. Is the anonymous function called with the window object
5. Next i'd like to grab w.abc.myobj and validate it using schema validation.
*/
JS File
try {
(function (w) {
w.abc = w.abc || {};
w.abc.myobj = {
"prop1": {
"enabled": true,
"type": "non-fiction",
"params: {
"serverInfo": {
"url": "{arg} ? https://www.url1.com : https://www.url2.com",
"path": "/some/directory"
},
"accountInfo: {
"user": "someUser1"
}
}
},
"prop2: {
"enabled": true,
"type": "fiction",
"params": {
"serverInfo": {
"url": "https://www.url2.com",
"path": "/some/directory"
},
"accountInfo: {
"user": "someUser2"
}
}
}
};
})(window);
} catch (e) { /* do nothing */ }
EsLint is built on top of the packages you mention, so you could make your life easier by writing an eslint plugin for each of your tests.
I'm building a little web-app to practice and learn Vue.js and working with APIs.
For a particular problem I want to solve, I would like to return the object that has the matching uuid that I request.
With my current knowledge, I understand I can do this by implementing some sorts and loops logic.
However I'm still new with JS, Vue.js, so I'm not sure if there is a better way to approach this.
Is there a built in function, or some form of "best practice" to approach this?
methods: {
fetchItem(row) {
// row.target_uuid -- this is the UUID I want
// this.$props.todoItems; -- this contains the json objects
// return this.$props.todoItems[i] where this.$props.todoItems[i]['uuid'] == row.target_uuid
},
This is a snippet of my $props.todoItems for context
[
{
"title": "Install Maris",
"uuid": "9ec9ea6b-0efc-4f6a-be2e-143be5748d3a",
"field_completed": "False"
},
{
"title": "Figure out why VS Code sucks",
"uuid": "85120da5-ee59-4947-a40f-648699365c73",
"field_completed": "False"
},
{
"title": "Start designing portfolio",
"uuid": "243c1960-7ade-4a68-9a74-0ccc4afa3e36",
"field_completed": "False"
},
{
"title": "Meal Prep",
"uuid": "85b64b18-9110-44d8-bd2d-8f818b0a810f",
"field_completed": "False"
},
{
"title": "Sharpen knives",
"uuid": "8a7ac5f6-8180-4f20-b886-628fd3bcfc85",
"field_completed": "False"
},
{
"title": "Set up SSH keys",
"uuid": "f879c441-8c05-4f24-9226-125c62576297",
"field_completed": "False"
}
]
If you know you're looking for exactly one item (or the first item that matches) you should take a closer look at the Array.find() method provided by JS. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
Also take a look at all the other methods the Array prototype provides, most of them are fairly descriptive and solve most of the basic problems you'll encounter.
To use this in your Vue app you can either have a method that returns your todo based on a provided uid like this
todoByUid(uidToFind) {
return this.todos.find(todo => todo.uid == uidToFind)
}
If you only care about a currently selected item a computed value as Jacob mentioned is the way to go:
computed() {
selectedTodo() {
return this.todos.find(todo => todo.uid == this.selectedUid)
}
}
Trying to add hovers to add hovers to my VS Code extension. I was able to syntax highlighting and commands to work, but stuck on adding this hover feature.
I think my blocker is how to properly implement the HoverProvider API. I'm doing a simple test below for a hover provider that activates when a series of tokens are recognized as the keyword HELLO. The hover I've implemented in my testing. I'm using vsce package to package and test my extension locally.
My command for the extension works, but when I hover over the word "HELLO", my hover does not appear.
./client/extension.js
const vscode = require('vscode');
function activate(context) {
console.log('Congratulations, your extension "star-rod" is now active!');
let disposable = vscode.commands.registerCommand('extension.mamar', () => {
vscode.window.showInformationMessage("The Star Rod... is powerful beyond belief. It can grant any wish. For as long as we can remember, Bowser has been making wishes like, for instance... 'I'd like to trounce Mario' or 'I want Princess Peach to like me.' Of course, Stars ignore such selfish wishes. As a result, his wishes were never granted.");
});
context.subscriptions.push(disposable);
vscode.languages.registerHoverProvider('javascript', {
provideHover(document, position, token) {
const range = document.getWordRangeAtPosition(position);
const word = document.getText(range);
if (word == "HELLO") {
return new vscode.Hover({
language: "Hello language",
value: "Hello Value"
});
}
}
});
}
function deactivate() { }
module.exports = {
activate,
deactivate
}
./package.json
{
"name": "star-rod-script",
"publisher": "sonicspiral",
"displayName": "Star Rod Script",
"description": "Syntax highlighting for Paper Mario 64 ROM patching tool",
"version": "1.0.1",
"repository": {
"type": "git",
"url": "https://github.com/gregdegruy/star-rod.git"
},
"categories": [
"Programming Languages"
],
"activationEvents": [
"onCommand:extension.mamar",
"onLanguage:star-rod-script"
],
"engines": {
"vscode": "^1.31.0"
},
"main": "./client/extension.js",
"contributes": {
"capabilities": {
"hoverProvider": "true"
},
"commands": [
{
"command": "extension.mamar",
"title": "Mamar"
}
],
"languages": [
{
"id": "star-rod-script",
"extensions": [
".bpat",
".bscr",
".mpat",
".mscr"
],
"aliases": [
"Star Rod Script",
"mscr"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "star-rod-script",
"scopeName": "source.mscr",
"path": "./syntaxes/mscr.tmLanguage.json"
}
]
},
"devDependencies": {
"js-yaml": "^3.12.1",
"vscode": "^1.1.29"
}
}
Your code allowed me to get Hovers working in my first extension. I think your mistake is having javascript as the selector: vscode.DocumentSelector. Is that there from code you copied? That should probably be set to star-rod-script for your extension.
I also don't have "capabilities": {"hoverProvider": "true"} in mine. I changed your code to:
disposable = vscode.languages.registerHoverProvider('star-rod-script', { // or 'star rod script'
//....
});
context.subscriptions.push(disposable);
I don't know the nuances of how you apply your extension to certain documents, but it doesn't look like you're trying to apply the hover to javascript docs. You need the selector to include the docs your extension works with. In my case that's covered by my extension name which is the language mode that shows up in the vscode status bar. More info on document-selectors.
Not sure if it's needed, but I also took the return and pushed it onto the subscriptions array. Works without that, but I think that's proper??
Your package.json looks a bit odd. I bet your extension is not activated. The "contributes/capabilites" value is something I haven't seen before. Remove that and instead change your activationEvents to:
"activationEvents": [
"onLanguage:star-rod-script"
],
(Sorry if the title doesn't make much sense, I had no idea how to word the question right and that was the best way I could think of)
So I have an API (the steam API) that returns something like this:
{
"playerstats": {
"steamID": "76561197962837077",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 3255
},
{
"name": "total_deaths",
"value": 4816
},
...
{
"name": "total_shots_hit",
"value": 3642
}
{
"name": "total_shots_fired",
"value": 4572
}
...
],
}
}
So I want to get the value for total_shots_hit and total_shots_fired, but it's in a different order for different people so I was wondering how I would get the value depending on the name in each of the sections? The way I'm doing it right now is by doing statsResponse.playerstats.stats[39].value, but it's not in the 39th spot for everyone, so I was wondering how I would get it? I'm using JavaScript/jQuery if that helps at all.
Any help is appreciated :)
EDIT: Figured out how to do it, I used a for loop to go through every response until it found the item I wanted, then used that number to find the same value
You can use Array.find() to find an object in an array by one of its properties.
var o = stats.find(function(item) {
return item.name === 'total_shots_hit';
}
console.log(o.value) // value property, e.g. 3642
Can you guys teach me on how to use jsoniq to display both of the book name which is robin cruose and tom jones? i've gone through some research but no matter how i do, it's always wrong.
{
"books": {
"reader": {
"Read": {
"book": {
"name": "Robinson Crusoe",
"author": "Daniel Defoe"
}
},
"HaventRead": {
"book": {
"name": " Tom Jones",
"author": "Henry Fielding "
}
},
"_type": "Ken Rawing"
}
}
}
This is how i did in zorba.io and it got lots of error, i am very sure the way i did is totally wrong. Please teach me
for $reader in collection("books"),
$read in collection("books"),
$book in collection ("books")
where $reader.type eq "Ken Rawing"
return $book
Getting some leaf values from a JSON document is done with the navigation syntax, which is the . notation.
It doesn't need a for clause, as iteration is implicit with the ..
Assuming the object is stored in the variable $content, $content.books.reader navigates to the object with the fields Read and HaventRead. Calling jnlib:values() then gets the two objects in there, and then one continues all the way to the name with .book.name.
The query is like so (most of it is actually the input document itself, which is typically stored in a file or a data store instead):
jsoniq version "1.0";
import module namespace jnlib = "http://jsoniq.org/function-library";
(: That's the input document, stored in a global variable :)
declare variable $content := {
"books": {
"reader": {
"Read": {
"book": {
"name": "Robinson Crusoe",
"author": "Daniel Defoe"
}
},
"HaventRead": {
"book": {
"name": " Tom Jones",
"author": "Henry Fielding "
}
},
"_type": "Ken Rawing"
}
}
};
(: That's the query :)
jnlib:values($content.books.reader).book.name
Mind the jsoniq version="1.0";, which activates the native JSONiq parser (the default parser on try.zorba.io is XQuery).
It can also be tested in zorba.io
Note
JSONiq also exists as an extension to XQuery, in which case navigation is done with function calls, as the . is a valid character in XML names. However, it is not recommended to use this unless you have XML to deal with as well.
jnlib:values($content("books")("reader"))("book")("name")