Skip to content

Instantly share code, notes, and snippets.

@zeffii
Forked from anonymous/notations.py
Last active December 27, 2015 14:49
Show Gist options
  • Save zeffii/7342902 to your computer and use it in GitHub Desktop.
Save zeffii/7342902 to your computer and use it in GitHub Desktop.
it works!
'''
// this does not work in st3
author: Dealga McArdle, 2013.
http://www.sublimetext.com/docs/2/api_reference.html
Installation
- place iteration_notation.py in Data/Packages/User
- place dictionary entry in Keybindings, User
{ "keys": ["ctrl+shift+["], "command": "iternotate" }
Usage
highlight:
for i in iterable: (inluding the whitespace, it it's there)
press ctrl+shift+[, the plugin will output
for(0 => int i; i<iterable.cap(); i++){
iterable[i];
}
'''
import sublime, sublime_plugin
def check_is_loopform(istr):
# returns non None only if everything seems ok.
# does not support tabs, but could. I don't use tabs so meh.
# some preprocessing, count spaces to the left, store this
restr = istr.lstrip()
spaces = len(istr) - len(restr)
restr = restr.strip()
# python 2.6 has no 'startswith'
if (not restr[:4] == "for "):
print("must start with keyword for")
return
# explicitly split on space
elements = restr.split(" ")
if (not len(elements) == 4):
print("must take form: for i in some_array:")
# print("got: {0} instead".format(restr))
return
if (not elements[2] == "in"):
print("missing the in keyword")
return
if (not restr[-1] ==":"):
print("must end with colon")
return
return [spaces, elements]
def perform_replacement(istr):
content = check_is_loopform(istr)
if not content:
print("stuff here")
return
ostr = """\
{0}for(0 => int {1}; {1}<{2}.cap(); {1}++){{
{0} {2}[{1}];\n{0}}}"""
amount_space = " "*content[0]
print(repr(amount_space))
a = ostr.format(amount_space, content[1][1], content[1][3][:-1])
print(a)
return a
def nothing_selected():
sublime.status_message('nothing selected, fool')
class Iternotate(sublime_plugin.TextCommand):
def run(self, edit):
if not self.enabled():
nothing_selected()
return
# sublime.status_message('here too')
view = self.view
sel = view.sel()[0]
# just selected region
selection = view.substr(sel)
final = perform_replacement(selection)
if not final:
return
edit = view.begin_edit() # stick onto undo stack
view.replace(edit, sel, final)
# finalize this edit, use as one undo level
view.end_edit(edit)
def enabled(self):
'''only allow 1 selection for version 0.1'''
sels = self.view.sel() # lists regions,
nsels = len(sels) # dir(sels[0]) for methods
fsel = sels[0] # first selection
if nsels == 1 and not fsel.empty():
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment