Automatically add spaces around "=>" - sublimetext

On SublimeText 3 I try to automatically add spaces before and after "=>"
I try to add this in User Keybinding:
{ "keys": ["equals,>"], "command": "insert_snippet", "args": { "name": "Packages/User/spacer.sublime-snippet" } }
And this is my snippet:
<snippet>
<content><![CDATA[ => ]]></content>
</snippet>
But it's not working.

Console says Unknown key equals,>
equals is redundant. So correct settings:
{ "keys": [">"], "command": "insert_snippet", "args": { "name": "Packages/User/spacer.sublime-snippet" } }
Next time please look for errors in the console first.
UPDATE
I want it matchs on "=>".
["=",">"] should be used in this case
{ "keys": ["=",">"], "command": "insert_snippet", "args": { "name": "Packages/User/spacer.sublime-snippet" } }

When I read the question I realized that I frequently insert spaces on both sides of something, so I knocked up the Sublime Text plugin below for my own use and, as an afterthought, decided to post it here.
This plugin adds a single space both before and after any selected text, e.g. "Sel" --> " Sel ". Multiple selections are, of course, handled. Single cursors are ignored otherwise you'd just be adding two spaces. It is compatible with both Sublime Text v.2 and v.3.
Save the following code in a file called AddSpacesAroundSelection.py and place the file somewhere in your Sublime Text Packages folder. e.g. ~/.config/sublime-text-3/Packages/User/
# File: AddSpacesAroundSelection.py
# Command: add_spaces_around_selection
# Keys: { "keys": ["ctrl+space"], "command": "add_spaces_around_selection" }
import sublime, sublime_plugin
class AddSpacesAroundSelectionCommand(sublime_plugin.TextCommand):
"""
The AddSpacesAroundSelectionCommand class is a Sublime Text plugin which
adds a single space on both sides of each selection. e.g. "Sel" -> " Sel "
"""
def run(self, edit):
""" run() is called when the command is run. """
space_char = " "
# Loop through all the selections.
for sel in self.view.sel():
# If something is actually selected (i.e. not just a cursor) then
# insert a space on both sides of the selected text.
if sel.size() > 0:
# Insert the space at the end of the selection before the
# beginning of it or the insertion position will be wrong.
self.view.insert(edit, sel.end(), space_char)
self.view.insert(edit, sel.begin(), space_char)
# End of def run()
# End of class AddSpacesAroundSelectionCommand()
Add a key binding to your user .sublime-keymap file. On my system the ctrl+space key bindings were not in use and they seemed appropriate to use.
{ "keys": ["ctrl+space"], "command": "add_spaces_around_selection" },
Hope this helps.

Related

VSCode keybinding that inputs large amount of code (Python: Visual Studio Code)

I'm currently trying to add a keybinding in Vscode that inputs multiple lines of code. Below is my current attempt at doing that – but it's not working due to some syntaxical errors. Would anyone know how I'm supposed to format this?
{
"key": "ctrl+y",
"command" : "type",
"args": {
"text": "
leave1 = False
while(leave1 == False):
try:
driver.find_element(By.XPATH, '')
except Exception:
time.sleep(0.5)
else:
leave1 = True
"
}
}

Passing spaces in arguments for Visual Studio Pro 2019

I am trying to debug a command line program inside Visual Studio. I am sharing my configuration with another machine using Box. The paths I am passing have spaces in them and I haven't been successful in escaping the spaces so that instead of 3 arguments I get 9. This is the relevant section from the original launch.vs.json.
{
"type": "default",
"project": "CMakeLists.txt",
"projectTarget": "dispatcher.exe (src\\dispatcher\\dispatcher.exe)",
"name": "dispatcher.exe (src\\dispatcher\\dispatcher.exe)",
"args": [
"C:\\Users\\212434537\\Box Sync\\Edge Agent\\srasku-windows.json",
"C:\\Users\\212434537\\Box Sync\\Edge Agent\\static.json",
"C:\\Users\\212434537\\Box Sync\\Edge Agent\\dynamic.json"
]
}
None of these work.
"\"C:\\Users\\212434537\\Box Sync\\Edge Agent\\srasku-windows.json\""
"\\"C:\\Users\\212434537\\Box Sync\\Edge Agent\\srasku-windows.json\\""
"\\\"C:\\Users\\212434537\\Box Sync\\Edge Agent\\srasku-windows.json\\\""
"\\\\"C:\\Users\\212434537\\Box Sync\\Edge Agent\\srasku-windows.json\\\\""
How can I escape my spaces so that each argument is passed as a single argument instead of three. Note: I saw this question but it didn't solve my problem.
It turns out you need to surround the spaces with singly-escaped double-quotes:
Here is the resultant section:
{
"type": "default",
"project": "CMakeLists.txt",
"projectTarget": "dispatcher.exe (src\\dispatcher\\dispatcher.exe)",
"name": "dispatcher.exe (src\\dispatcher\\dispatcher.exe)",
"currentDir": "C:\\Users\\212434537\\source\\Edge-Agent",
"args": [
"C:\\Users\\212434537\\Box\" \"Sync\\Edge\" \"Agent\\srasku-windows.json",
"C:\\Users\\212434537\\Box\" \"Sync\\Edge\" \"Agent\\static.json",
"C:\\Users\\212434537\\Box\" \"Sync\\Edge\" \"Agent\\dynamic.json"
]
}
A simple workaround for this, is just to include the entire path in quotes, such as:
"C:\Users\212434537\Box Sync\Edge Agent\dynamic.json"
So, the escaped json becomes:
"\"C:\\Users\\212434537\\Box Sync\\Edge Agent\\dynamic.json\""

How to make "todo" in markdown in sublime text?

I am migrating to sublime text with markdownediting from emacs orgmode. With the help of markdownediting, sublime is fine with markdown. But I haven't figure out how to make TODO list, and toggle between TODO and DONE. Is there a way to do it? or any plugin works well with markdownediting?
I installed the mdTodo plugin for Sublime text.
It works but the TODO list displayed as bulletin list (in html) on GitHub, which looks not so good.
I found that GitHub supports the orgmode-style TODO list:
https://github.com/blog/1375-task-lists-in-gfm-issues-pulls-comments
https://github.com/blog/1825-task-lists-in-all-markdown-documents
Solar System Exploration, 1950s – 1960s
[ ] Mercury
[x] Venus
[x] Earth (Orbit/Moon)
[x] Mars
[ ] Jupiter
[ ] Saturn
[ ] Uranus
[ ] Neptune
[ ] Comet Haley
So I modified the mdTodo source code, makes it works on orgmode-style TODO list.
Here is my modification: (mdTodo.py in the package folder)
import sublime, sublime_plugin
from datetime import datetime
class ItodoBase(sublime_plugin.TextCommand):
def run(self, edit):
filename = self.view.file_name()
# list of allowed filetypes
allowed_filetypes = ('.md', '.markdown', '.mdown')
if filename is None or not filename.endswith(allowed_filetypes):
return False
self.runCommand(edit)
class NewCommand(ItodoBase):
def runCommand(self, edit):
for region in self.view.sel():
lines = self.view.lines(region)
lines.reverse()
for line in lines:
# don't add a newline when creating new item with cursor is at an empty line
if not line:
line_contents = '-'
self.view.insert(edit, line.begin(), line_contents)
# add a newline when creating new item when cursor is at another line
else:
line_contents = self.view.substr(line) + '\n-'
self.view.replace(edit, line, line_contents)
class CompleteCommand(ItodoBase):
def runCommand(self, edit):
for region in self.view.sel():
lines = self.view.lines(region)
lines.reverse()
for line in lines:
line_head = self.view.find("- \[[x ]\]", line.begin())
line_contents = self.view.substr(line).strip()
# prepend #done if item is ongoing
if line_contents.startswith("- [ ]"):
self.view.insert(edit, line.end(), " #done (%s)" % datetime.now().strftime("%Y-%m-%d %H:%M"))
self.view.replace(edit, line_head, "- [x]")
# undo #todo
elif line_contents.startswith('- [x]'):
subfix = self.view.find('(\s)*#done(.)+\)$', line.begin())
self.view.erase(edit, subfix)
self.view.replace(edit, line_head, "- [ ]")
I hope this would be helpful to those migrated to Sublime text from Emacs (org-mode).
Update
The default shortcut ctrl+shift+d conflicts with the default duplicate line command.
Solution:
path_to_sublime\Sublime Text 3\Packages\mdTodo\Default (Windows).sublime-keymap
Comment out this line
[ // iTodo plugin
{ "keys": ["ctrl+shift+d"], "command": "complete" }
]
and change it in the user keybinds file.
I binded it to:
{ "keys": ["ctrl+alt+d"], "command": "complete" }

Sublime How to set new shortcut for a specific feature

In sublime I want to add a feature that if I enter a key combination. I want that combination to produce the following result:
SHIFT+Ctrl+ALT+ENTER : put a semicolon at the end of the line and create a new line and put the cursor there.
How to do it?
The process is quite straightforward. First, create a new file with these contents:
[
{
"command": "move_to",
"args":
{
"to": "eol"
}
},
{
"command": "insert",
"args":
{
"characters": ";\n"
}
}
]
and save it as Packages/User/semicolon-newline.sublime-macro where Packages is the directory opened when you select Preferences -> Browse Packages....
Next, go to Preferences -> Key Bindings-User and add the following:
{ "keys": ["ctrl+alt+shift+enter"], "command": "run_macro_file", "args": {"file": "Packages/User/semicolon-newline.sublime-macro"} }
This file is JSON-formatted, so if it doesn't have any contents when you open it, surround the line above with square brackets [ ]. If there are already entries in it, place the line above at the top (after the opening [) and add a comma , at the end, after the final closing curly brace }.
Save the keybindings file, and you should be all set. This should work with both Sublime Text 2 and 3, on any platform.

how to use `NSScriptCommandDescription initWithSuiteName:commandName:dictionary:`

I want to know how to use
NSScriptCommandDescription initWithSuiteName:commandName:dictionary:, esp. how the dictionary is supposed to look like.
It would be nice to see a simple example for a command with a single parameter of type NSString and a return value of type NSString.
I think the documentation about how the dictionary should look like can be found here, esp in "Table B-8, Command dictionary".
However, I am trying with this example and it doesn't work (returns nil):
cmdDesc = NSScriptCommandDescription.alloc().initWithSuiteName_commandName_dictionary_(
"Standard Suite",
"execPython",
{
"CommandClass": "NSScriptCommand", # default behavior
"AppleEventCode": "expy", # 4-char code
"Type": "text", # return-type
"ResultAppleEventCode": "NSString", # return-type
"Arguments": [{
"Type": "NSString",
"AppleEventCode": "data"
}]
}
)
(Note: I really want to know exactly that here; I don't want to know how to register scripting definitions or do other stuff with this question.)
I know this is a VERY old questions but I have stumble upon this and it seems that the this statckoverflow question is the most common result when doing a google search on how to use the NSScriptCommandDescription with arguments.
The code from the accepted answer is correct EXCEPT on how the arguments value is created. The arguments value must be a dictionary that maps argument names with argument descriptions. Using the accepted answer code as an example, in order to pass arguments, our dictionary should look as follows:
cmdDesc = NSScriptCommandDescription.alloc().initWithSuiteName_commandName_dictionary_(
"Chromium Suite",
"exec Python",
{
"Name": "exec Python",
"CommandClass": "NSScriptCommand", # default behavior
"AppleEventCode": "ExPy", # 4-char code
"AppleEventClassCode": "CrSu",
"Type": "NSString", # return-type
"ResultAppleEventCode": "ctxt", # return-type
"Arguments": {
"firstArg": {
"Type": "NSString",
"AppleEventCode": "comm"
}
}
}
)
The above dictionary works on ObjectC (I don't know if the python code does work).
The only thing I can see there that disagrees with the documentation is your value for "Type"; while the documentation doesn't show an example for "Type" in the context of a command, its value in the documentation's examples for other contexts is "NSString", not "text". So, try the Cocoa class name instead of the AppleScript class name.
The "Arguments" section still doesn't really work correct for me (I got strange crashs) but I can also just omit that and still get an argument passed at runtime.
This is the code:
import objc
NSObject = objc.lookUpClass("NSObject")
sharedScriptSuiteReg = objc.lookUpClass("NSScriptSuiteRegistry").sharedScriptSuiteRegistry()
NSScriptCommandDescription = objc.lookUpClass("NSScriptCommandDescription")
sharedAppleEventMgr = objc.lookUpClass("NSAppleEventManager").sharedAppleEventManager()
NSAppleEventDescriptor = objc.lookUpClass("NSAppleEventDescriptor")
from PyObjCTools.TestSupport import fourcc
def register_scripting():
cmdDesc = NSScriptCommandDescription.alloc().initWithSuiteName_commandName_dictionary_(
"Chromium Suite",
"exec Python",
{
"Name": "exec Python",
"CommandClass": "NSScriptCommand", # default behavior
"AppleEventCode": "ExPy", # 4-char code
"AppleEventClassCode": "CrSu",
"Type": "NSString", # return-type
"ResultAppleEventCode": "ctxt", # return-type
"Arguments": {
#"----": {
# "Type": "NSString",
# "AppleEventCode": "comm"
#}
}
}
)
assert cmdDesc is not None
sharedScriptSuiteReg.registerCommandDescription_(cmdDesc)
sharedAppleEventMgr.setEventHandler_andSelector_forEventClass_andEventID_(
appScriptHandler, appScriptHandler.handleExecPy,
fourcc("CrSu"), fourcc("ExPy"))
def handleExecPy(self, ev, replyEv):
print "execPython called,",
cmd = ev.descriptorForKeyword_(fourcc("comm")).stringValue()
print "cmd:", repr(cmd)
res = eval(cmd)
res = unicode(res)
replyEv.setDescriptor_forKeyword_(NSAppleEventDescriptor.descriptorWithString_(res), fourcc("----"))
return True
try:
class AppScriptHandler(NSObject):
def handleExecPy(self, ev, replyEv):
try: return handleExecPy(self, ev, replyEv)
except: traceback.print_exc()
return
except:
AppScriptHandler = objc.lookUpClass("AppScriptHandler")
appScriptHandler = AppScriptHandler.alloc().init()
This works together with this simple client demo:
#!/usr/bin/python
import aem
fullpath = aem.findapp.byname("Google Chrome")
app = aem.Application(fullpath)
def execPy(cmd):
return app.event("CrSuExPy", {"comm": cmd}).send()
print execPy("app.bundle()")
def simple_shell():
import sys
try: import readline
except: pass # ignore
while True:
try:
s = raw_input("> ")
except:
print "breaked debug shell:", sys.exc_info()[0].__name__
break
s = s.strip()
if s: print execPy(s)
simple_shell()
The full code can be seen here and in action here.

Resources