Sublime How to set new shortcut for a specific feature - sublimetext

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.

Related

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\""

VSCode not respecting tab size when formatting a Dart file

I want VSCode on my Mac to use 4 spaces instead of 2 when I select Format Document. This is what I have on my User Settings:
{
"editor.fontFamily": "Andale Mono",
"editor.fontSize": 13,
"editor.renderWhitespace": "all",
"editor.tabSize": 4,
"[dart]": {
"editor.tabSize": 4,
"editor.detectIndentation": false
},
"workbench.colorTheme": "Material Theme",
"materialTheme.fixIconsRunning": false,
"workbench.iconTheme": "eq-material-theme-icons"
}
However when I format the document, it does not respect the 4 spaces tab. It uses 2.
This is a limitation of the Dart plugin for VS Code. It uses the official dart_style formatter which only supports formatting with spaces (the same as running dartfmt).
If you'd like to see a more flexible formatter, please put a ThumbsUp on this GitHub issue:
https://github.com/Dart-Code/Dart-Code/issues/914

Automatically add spaces around "=>"

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.

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" }

Customizing Mathematica shortcuts

Is there a place I can view/change global shortcut options like Command + 9 (turn into Input style)?
In particular, I need a faster way of creating bulleted lists. It's the style "Item" in the Cell context menu which doesn't have its own shortcut.
Here is a nice article.
Also, FROM HERE (unchecked)
Question:
How do I modify the front end to add new keyboard shortcuts?
Answer:
(mathgroup May 2005, trevor baca:)
I've been mucking around in KeyEventTranslations.tr setting up keyboard shortcuts recently and i've learned that front end tokens are pretty cool. this wolfram page gives pretty good docs.
Anyway, here are three that i had to work a little to get going (with good help from the mathgroup, as always).
for a quit kernel keyboard shortcut, add the following to KeyEventTranslations.tr:
Item[KeyEvent["q", Modifiers -> {Control, Option}],
FrontEndExecute[
FrontEndToken[
SelectedNotebook[ ],
"EvaluatorQuit",
Automatic
]
]
]
for an initialization cell toggle keyboard shortcut (repeated from previous thread), add the following to KeyEventTranslations.tr:
Item[KeyEvent["i", Modifiers -> {Command, Control}],
FrontEndExecute[
FrontEndToken[
SelectedNotebook[ ],
"InitializationCell",
"Toggle"
]
]
]
for a save as package keyboard shortcut, add the following to KeyEventTranslations.tr:
Item[KeyEvent["k", Modifiers -> {Control, Option}],
SaveRenameSpecial["Package"]]
Edit
I found a full list of the (undocumented) front-end tokens. Hope you'll understand that these are unsupported!
{"AllWindowsFront", "BackgroundDialog", "Balance", "BringToFront",
"CellContextDialog", "CellGroup", "CellLabelsToTags", "CellMerge",
"CellSplit", "CellTagsEditDialog", "CellTagsEmpty", "CellTagsFind",
"CellUngroup", "Clear", "ClearCellOptions", "ClearNoAutoScroll",
"Close", "CloseAll", "CloseMain", "ColorSelectorDialog",
"ColorsPanel", "CompleteSelection", "Copy", "CopyCell",
"CopySpecial", "CreateCounterBoxDialog", "CreateGridBoxDialog",
"CreateHyperlinkDialog", "CreateInlineCell", "CreateValueBoxDialog",
"Cut", "CycleNotebooksBackward", "CycleNotebooksForward",
"DebuggerAbort", "DebuggerClearAllBreakpoints", "DebuggerContinue",
"DebuggerContinueToSelection", "DebuggerFinish",
"DebuggerResetProfile", "DebuggerShowProfile", "DebuggerStep",
"DebuggerStepIn", "DebuggerStepInBody", "DebuggerStepOut",
"DebuggerToggleBreakpoint", "DebuggerToggleWatchpoint",
"DeleteGeneratedCells", "DeleteIndent", "DeleteInvisible",
"DuplicatePreviousInput", "DuplicatePreviousOutput",
"EditStyleDefinitions", "EnterSubsession", "Evaluate",
"EvaluateCells", "EvaluateInitialization", "EvaluateNextCell",
"EvaluateNotebook", "EvaluatorAbort", "EvaluatorHalt",
"EvaluatorInterrupt", "EvaluatorQuit", "EvaluatorStart",
"ExitSubsession", "ExpirationDialog", "ExplainBeepDialog",
"ExplainColoringDialog", "ExpressionLinewrap", "FileNameDialog",
"FindDialog", "FindEvaluatingCell", "FindNextMisspelling",
"FindNextWarningColor", "FinishNesting", "FixCellHeight",
"FixCellWidth", "FontColorDialog", "FontFamilyB", "FontPanel",
"FontSizeDialog", "FrontEndHide", "FrontEndQuit",
"FrontEndQuitNonInteractive", "GenerateImageCaches",
"GenerateNotebook", "GeneratePalette", "GraphicsAlign",
"GraphicsCoordinatesDialog", "GraphicsOriginalSize",
"GraphicsPlotRangeAll", "GraphicsPlotRangeAutomatic",
"GraphicsPlotRangeFixed", "GraphicsRender", "Group",
"HandleShiftReturn", "HeadersFootersDialog", "HelpDialog",
"HyperlinkGo", "HyperlinkGoBack", "HyperlinkGoForward", "Import",
"ImportPictures", "ImportStyleDefinitions", "Indent",
"InsertClipPlane", "InsertMatchingBraces", "InsertMatchingBrackets",
"InsertMatchingParentheses", "InsertNewGraphic", "InsertObject",
"InsertRawExpression", "InsertSoftReturn", "LicAuthFailureDialog",
"MacintoshOpenDeskAccessory", "MenuListBoxFormFormatTypes",
"MenuListCellEvaluators", "MenuListCellTags",
"MenuListCommonDefaultFormatTypesInput",
"MenuListCommonDefaultFormatTypesInputInline",
"MenuListCommonDefaultFormatTypesOutput",
"MenuListCommonDefaultFormatTypesOutputInline",
"MenuListCommonDefaultFormatTypesText",
"MenuListCommonDefaultFormatTypesTextInline",
"MenuListConvertFormatTypes", "MenuListDisplayAsFormatTypes",
"MenuListExportClipboardSpecial", "MenuListFonts",
"MenuListFontSubstitutions", "MenuListGlobalEvaluators",
"MenuListHelpWindows", "MenuListNotebookEvaluators",
"MenuListNotebooksMenu", "MenuListPackageWindows",
"MenuListPalettesMenu", "MenuListPaletteWindows",
"MenuListPlayerWindows", "MenuListPlugInCommands",
"MenuListPrintingStyleEnvironments", "MenuListQuitEvaluators",
"MenuListRelatedFilesMenu", "MenuListSaveClipboardSpecial",
"MenuListScreenStyleEnvironments", "MenuListStartEvaluators",
"MenuListStyleDefinitions", "MenuListStyles",
"MenuListStylesheetWindows", "MenuListTextWindows",
"MenuListWindows", "ModifyBoxFormFormatTypes",
"ModifyDefaultFontProperties", "ModifyEvaluatorNames",
"ModifyFontSubstitutions", "ModifyNotebooksMenu",
"ModifyRelatedFiles", "MoveBackward", "MoveForward", "MoveToBack",
"MoveToFront", "New", "NewPackage", "NewText",
"NextFunctionTemplate", "NotebookMail", "NotebookMailSelection",
"NotebookOneNote", "NotebookOneNoteSelection",
"NotebookStatisticsDialog", "Open", "OpenCloseGroup",
"OpenFromNotebooksMenu", "OpenFromNotebooksMenuEmpty",
"OpenFromPalettesMenu", "OpenFromRelatedFilesMenu", "OpenHelpLink",
"OpenSelection", "OpenSelectionParents", "OpenURL", "OptionsDialog",
"PasswordDialog", "Paste", "PasteApply", "PasteApplyNoAutoScroll",
"PasteDiscard", "PasteDiscardNoAutoScroll", "PasteSpecial",
"PlainFont", "PreferencesDialog", "PreviousFunctionTemplate",
"PrintDialog", "PrintOptionsDialog", "PrintSelectionDialog",
"PublishToPlayer", "RebuildHelpIndex", "RecordSoundDialog",
"RefreshDynamicObjects", "RelatedFilesMenu",
"RemoveFromEvaluationQueue", "Replace", "ReplaceAll", "ReplaceFind",
"ReplaceParent", "Revert", "RunColorDialog", "RunEdgeColorDialog",
"RunFaceColorDialog", "Save", "SaveRename", "SaveRenameSpecial",
"ScrollLineDown", "ScrollLineUp", "ScrollNotebookEnd",
"ScrollNotebookStart", "ScrollPageBottom", "ScrollPageDown",
"ScrollPageFirst", "ScrollPageLast", "ScrollPageNext",
"ScrollPagePrevious", "ScrollPageTop", "ScrollPageUp",
"SelectGeneratedCells", "SelectionAnimate", "SelectionBrace",
"SelectionBracket", "SelectionCloseAllGroups",
"SelectionCloseUnselectedCells", "SelectionConvert",
"SelectionConvertB", "SelectionDisplayAs", "SelectionDisplayAsB",
"SelectionHelpDialog", "SelectionOpenAllGroups",
"SelectionParenthesize", "SelectionSaveSpecial", "SelectionScroll",
"SelectionSetFind", "SelectionSpeak", "SelectionSpeakSummary",
"SelectionUnbracket", "SelectNotebookWindow", "SetDefaultGraphic",
"SimilarCellBelow", "SoundPlay", "SpellCheckerDialog",
"StackWindows", "Style", "StyleDefinitionsOther", "StyleOther",
"SubsessionEvaluateCells", "SystemPrintOptionsDialog",
"TemplateSelection", "TestEvaluateNotebook", "TileWindowsTall",
"TileWindowsWide", "ToggleDebugFlag", "ToggleDynamicUpdating",
"ToggleGrayBox", "ToggleOptionListElement", "ToggleShowExpression",
"ToggleTestingFlag", "TrustNotebook", "Undo", "Ungroup",
"WindowMiniaturize", "XInfoDialog", "ZoomWindow"}
The shortcuts for different types of cells are stored in the Stylesheet.
Choose the style you want and change the MenuKeyCommand MenuCommandKey value.
The dropdown options in the Option Inspector only allow you to use 1-9, but I tested it with "`" and "=" and they worked fine. Sometimes its easier to modify the Stylesheet using the Show Expression (Ctrl-Shift-E) rather than the Option Inspector.

Resources