Sublime Text 3 sublime_plugin.WindowCommand - plugins

I have a sublime text window open which contains many 'files'
I would like to be able to run a plugin I have written which does some checks on the contents of each file.
I can't get started with the sublime_plugin.WindowCommand.
Here is the start of my efforts. It does not return any errors, but does not return anything.
import sublime, sublime_plugin
class StuffCommand(sublime_plugin.WindowCommand):
def run(self):
my_views = self.window.views()
for a_view in my_views:
file = a_view.file_name()
print(file)
print("Finished")

OdatNurd is on the right track.
I was entering a view.run_command in the console.
I created a key binding so that I was able to execute the code whilst the window containing the files was the focus, and it worked okay.

Related

How do I edit a jupyter notebook cell's tags in visual studio code?

I am editing a .ipynb file in Visual Studio Code, with the file open in VS code's Jupyter Notebook editor.
When I edit this notebook in the Jupyter Notebook App (i.e. if I were not using VS code, instead using the interface described here), I could add tags to cells by clicking View > Cell Toolbar > Tags, and then entering tags into the UI that comes up.
Is there an equivalent way to do this in VS Code?
I am aware I can reopen the file in a text editor view and edit the JSON directly. But I am looking for something a bit more user friendly than this.
Try installing this jupyter on vs code.
On my old windows 7 I used to use this. It has the same interface as when you open Jupiter in your browser but you don't need to load a bunch of stuff to open jupyter. You can open it in one single click like changing text file while writing code inside vc code.
Also you need to install one library to use it but unfortunately I can't remember the library as I don't use python or Jupiter anymore.
In the documentation is a python code cell which enables to change all the cell tags.
import nbformat as nbf
from glob import glob
# Collect a list of all notebooks in the content folder
notebooks = glob("**/*.ipynb", recursive=True)
notebooks_windows = []
for i in notebooks:
j = i.replace("\\", "/")
notebooks_windows.append(j)
notebooks_windows
# Text to look for in adding tags
text_search_dict = {
"# HIDDEN": "remove-cell", # Remove the whole cell
"# NO CODE": "remove-input", # Remove only the input
"# HIDE CODE": "hide-input" # Hide the input w/ a button to show
}
# Search through each notebook and look for the text, add a tag if necessary
for ipath in notebooks_windows:
ntbk = nbf.read(ipath, nbf.NO_CONVERT)
for cell in ntbk.cells:
cell_tags = cell.get('metadata', {}).get('tags', [])
for key, val in text_search_dict.items():
if key in cell['source']:
if val not in cell_tags:
cell_tags.append(val)
if len(cell_tags) > 0:
cell['metadata']['tags'] = cell_tags
Microsoft have finally released an extra extension to support this.
ms-toolsai.vscode-jupyter-cell-tags
See this long running github.com/microsoft/vscode-jupyter issue #1182 and comment recently closing the issue.
Be ware however, that while you can set tags, e.g. raises-exception, which is meant to make the runtime expect and ignore the exception and keep on running more cells, but the vscode-jupyter extension that runs the cells does not always honor tag features the same way that the standard Jupyter notebook runtime does, and so, disappointingly, it's still difficult to demo common mistakes or what not to do (exceptions).
Just copy everything in .py file with the unremovable tags, paste that into a plaintext file. The tags are now just editable text. Remove them, Save As or copy/paste back to the .py file.

Is it possible to write script plugins for VSCode similar to Sublime Text?

Sublime Text allowed writing python scripts which, upon placing within the IDE folders, were available as internal commands that could then be placed in menu, bound to a key, etc. https://www.sublimetext.com/docs/plugin-basics
Is there something similar for VSCode?
For example, this file, when placed in ST3\Data\Packages\User would add a duplicate command.
<binding key="ctrl+alt+d" command="duplicate"/>
or with view.runCommand('duplicate') in the console
import sublime, sublimeplugin
class DuplicateCommand(sublimeplugin.TextCommand):
def run(self, view, args):
for region in view.sel():
if region.empty():
line = view.line(region)
lineContents = view.substr(line) + '\n'
view.insert(line.begin(), lineContents)

Automatically select pasted text in Sublime Text 3

Is there any way, plugin, macro or something to make Sublime Text 3 automatically select the text that was just pasted?
I need to copy and paste some JSON data, but the pasted text is never in line with the surrounding text. Paste and indent -feature does not work properly for this.
What does work is the reindent feature, but it requires me to select a block of text and pressing a hotkey. So after pasting I would benefit for having the just pasted block of text being automatically selected, so I can just press the reindent hotkey to properly indent what I pasted.
Furthermore, it would be even better if I could bind the whole process to a hotkey, so:
Select text
Copy
Press some self defined hotkey to run a macro(?)
This macro the pastes the text, selects the pasted text and runs the reindent hotkey (*)
*So basically I would like to make a keybinding, say, ctrl+shift+b to do the following:
ctrl+v
Somehow select pasted text
ctrl+shift+f
You can create a plugin to do this, and execute it with a keybinding:
from the Tools menu -> Developer -> New Plugin...
select all and replace with the following
import sublime
import sublime_plugin
class PasteAndReindentCommand(sublime_plugin.TextCommand):
def run(self, edit):
before_selections = [sel for sel in self.view.sel()]
self.view.run_command('paste')
after_selections = [sel for sel in self.view.sel()]
new_selections = list()
delta = 0
for before, after in zip(before_selections, after_selections):
new = sublime.Region(before.begin() + delta, after.end())
delta = after.end() - before.end()
new_selections.append(new)
self.view.sel().clear()
self.view.sel().add_all(new_selections)
self.view.run_command('reindent')
save it, in the folder ST suggests (Packages/User/) as something like paste_and_reindent.py
add the following to your User keybindings { "keys": ["ctrl+shift+b"], "command": "paste_and_reindent" },
Note that Ctrl+Shift+B will replace the default binding for "Build With".
How it works:
when the keybinding is pressed, it runs the new command created in the plugin
this stores the current text selection positions
then it performs the paste operation
then it gets the new text caret positions
then it compares the old positions to the new ones, and selects the text that was pasted
then it runs the reindent command
You could get it to clear the selections again afterwards (by repositioning the text carets to the end of the selections - i.e. the default behavior after pasting) by doing another comparison of the selections before and after the reindentation.
On MacOS you can add:
"find_selected_text": true
to Sublime Text->Preferences->Settings (User Settings View)

How to create macro in sublime text 3 with saveAs and close file command?

I need to change encoding of a lot of html files to UTF8 (from Windows 1252). I´m using Sublime text 3 on Windows 8. So I think creating macro will be very efficient, I need just two commands in that macro "Save with Encoding - UTF8" and "Close file". But when I´m trying to record macro these commands are not recorded. So I need to manually create json file with macro command but I don´t know how.
I'm not sure that this can be done with a macro maybe these commands are out of scope for a macro (eg a window command not a view command?), but I managed to make it work as a plugin…
Save the following as $PATH_TO_SUBLIME_DATA/Packages/SaveAs-UTF8.py
import sublime, sublime_plugin
class SaveAsUtf8Command(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command("save", {"encoding": "utf-8" })
self.window.run_command("close")
To trigger the command with 'Command Option Shift 8', add the following to your Sublime Text > Preferences > Keybindings - User file:
[
{ "keys": ["super+option+shift+8"], "command": "save_as_utf8"}
]
I've saved this as a gist if you prefer: https://gist.github.com/9505499

Sublime text 2 - find file by class name in Zend Framework

When you press Ctrl+p Sublime will open popup when you can easily find the file. Sublime auto detect the file location in both situation when you press / or space between file path parts.
In Zend Framework all classes has name within follow template: Namespace_Module_Other_Part_Of_Class_Location, how can I make Sublime understand the _ as a path separator when I press Ctrl+p and copy past the class name there?
So the above class should be recognized on location: Project/Namespace/Module/Other/Part/Of/Class/Location.php
I'm still looking for the solution of it. Even if the file search is hard-coded in Sublime 3, and you have a workaround to make it works, maybe to write some plugin? you are welcome.
Thank you.
You can do this with a simple plugin and key binding. Select Tools -> New Plugin... and replace the contents with the following:
import sublime
import sublime_plugin
class UnderscoreToSpaceCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.run_command('copy')
clipboard = sublime.get_clipboard()
clipboard = clipboard.replace('_', ' ')
sublime.set_clipboard(clipboard)
Save the file as Packages/User/underscore_to_space.py where Packages is the folder opened when clicking on Preferences -> Browse Packages....
Next, create a custom key binding for the command. Select Preferences -> Key Bindings-User and add the following:
{ "keys": ["ctrl+shift+c"], "command": "underscore_to_space" }
If the file is empty when you open it, surround the above line with square brackets [ ]. Save the file (it will automatically save to the correct location), and you're all set.
Now, all you need to do is select the text you want to convert, and hit CtrlShiftC. This will copy the text to the clipboard, replace the underscores with spaces, and put the modified text back in the clipboard. You can now hit CtrlP to open Goto Anything... and paste in the modified text with CtrlV.
If you prefer to have the underscores replaces with forward slashes /, just change the clipboard.replace() arguments from ('_', ' ') to ('_', '/').
To get to the class definition you are looking for there exist several plugins doing "code intelligence". The plugins are language specific.
The most popular is SublimeCodeIntel which provides Jump to symbol definition functionality. SublimeCodeIntel claims to do this for PHP too. However, who to setup this for your project should be another question.
Some more options for possible source code static analysis in Sublime Text 2 in this blog post: