[Idle-dev] Smart Templates
carvalho joao
jngscarvalho@yahoo.com
Tue, 6 Nov 2001 10:14:32 -0800 (PST)
--0-114468734-1005070472=:51324
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Hi,
my name is Joao Nuno and this is my first Python
program, if you see flowes, please email me.
I made Smart Templates expansion to IDLE,
i don't now if you can add it to IDLE, but i send the
code has an attachment.
I got the last version of IDLE from VPython, it works
with there version of IDLE, i hope it works with
yours.
To work on IDLE VPython i just add "[SmartTemplates]"
on config.txt and copy the file to same directorie.
waiting comments.
Best regards,
Joao Nuno
__________________________________________________
Do You Yahoo!?
Find a job, post your resume.
http://careers.yahoo.com
--0-114468734-1005070472=:51324
Content-Type: text/plain; name="SmartTemplates.py"
Content-Description: SmartTemplates.py
Content-Disposition: inline; filename="SmartTemplates.py"
## Smart templates was made by Joao Nuno G. S. Carvalho 2001 V1.0
## It's a extension to IDLE IDE.
import string
import re
import sys
class SmartTemplates:
version = 1.0
menudefs = [
('windows', [
(),
('_Smart Templates', '<<smart-templates>>'),
('_Smart Templates Next', '<<smart-templates-next>>')
])
]
windows_keydefs = {
'<<smart-templates>>': ['<Alt-j>'],
'<<smart-templates-next>>': ['<Alt-h>'],
}
unix_keydefs = {
'<<smart-templates>>': ['<Control-x><Control-z>'],
}
wordchars = string.letters + string.digits + "_"
dic_im =("import ?", "")
dic_fr = ("from ? import ?", "")
dic_fra = ("from ? import ? as ?", "")
dic_cl = ("class ?:", "\t?",
"\tdef __init__(self ?):",
"\t\t?\n")
dic_clm = ("class ?:",
"\t?",
"\tdef __init__(self ?):",
"\t\t?",
"\tdef ?(self ?):",
"\t\t#?",
"\t\t?")
dic_d = ("def ?(self?):",
"\t#?",
"\t?")
dic_de = ("def ?(?):",
"\t#?",
"\t?")
dic_for = ("for i in ?:",
"\t?" )
dic_try = ("try:",
"\t?",
"except ?, e:",
"\t?" )
dic_tryf = ("try:",
"\t?",
"finally:",
"\t?" )
dic_ife = ("if ?:",
"\t?",
"else:",
"\t?")
dic_ifn = ("if not ?:",
"\t?",
"else:",
"\t?")
dic_ifei = ("if ?:",
"\t?",
"elif ?:",
"\t?")
dic_ifeie = ("if ?:",
"\t?",
"elif ?:",
"\t?",
"else:",
"\t?")
dic_main = ("# Check if running as a program.",
"if __name__ == '__main__':",
"\t# Yes",
"\t?",
"else:",
"\t# No, I must have been imported as a module.",
"\t?")
dic_p = ("print ?", "")
dic_s = ("self.?", "")
dic_ss = ("\" + ? + \"", "")
dic_g = ("global ? \t# \"?\" is in global namespace ", "")
dic_comment = ("##################################################",
"# ?",
"##################################################")
dic_cardinal = ("### ? ###", "")
dic_help = ("\"This expansion print all templates.\"", "")
dic = {
"im" : dic_im, # colocar aqui as restantes variaveis.
"fr" : dic_fr,
"fra" : dic_fra,
"cl" : dic_cl,
"clm" : dic_clm,
"d" : dic_d,
"de" : dic_de,
"for" : dic_for,
"try" : dic_try,
"tryf" : dic_tryf,
"ife" : dic_ife,
"ifn" : dic_ifn,
"ifei" : dic_ifei,
"ifeie" : dic_ifeie,
"main" : dic_main,
"p" : dic_p,
"s" : dic_s,
"ss" : dic_ss,
"g" : dic_g,
"c#" : dic_comment,
"#" : dic_cardinal,
"help": dic_help
}
tabSpace = 4
curStr = "?"
def __init__(self, editwin):
self.text = editwin.text
## self.state = None
def hasMacro(self, abrev):
if self.dic.has_key(abrev):
return 1
else:
return 0
def macroExpand(self, abrev):
if self.dic.has_key(abrev):
return self.dic[abrev]
def smart_templates_event(self, event):
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
word = self.getprevword()
f = open("c:\jerros.txt", "w")
print >>f, word
f.close()
word = string.join(word, "")
if not self.hasMacro(word):
## print "There is no macro for that abrev."
return "break"
self.text.delete("insert - %d chars" % len(word), "insert")
if word == "help":
self.writeHelp()
else:
self.writeTemplate(word)
self.text.mark_set("insert", curinsert) #Put the cursor at the beginning of the template.
self.next() #Jumps to the next tamplate cursoe position.
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
return "break"
def getprevword(self):
# If text is selected, we use it has keyword, so we can expand without the space.
if self.text.tag_ranges("sel"):
return self.text.get("sel.first", "sel.last")
line = self.text.get("insert linestart", "insert")
i = len(line)
while i > 0 and line[i-1] in self.wordchars:
i = i-1
return line[i:]
def next(self):
#search for the string that marks the insersion, "?", search from current pos to end and from init to cur pos.
where = self.text.search(self.curStr, "insert", "end") # INSERT , END
if not where:
where = self.text.search(self.curStr, "1.0", "insert")
if not where:
pass
## print "Nao existe next. Para baixo!"
else:
#Select the "|" simbol or the regular expression defined in the beginning of this class. "|num:num|"
pastkey = where + '+%dc' % len(self.curStr)
self.text.tag_remove("sel", '1.0', "end") # END
self.text.tag_add("sel", where, pastkey)
self.text.mark_set("insert", pastkey)
self.text.see(where)
def writeTemplate(self, word):
newword = self.macroExpand(word)
#calculate the number of spaces for identation.
line = self.text.get("insert linestart", "insert")
identSpace = len(line)
self.text.insert("insert", newword[0])
#apply the identation to each line of the template. Starting at the second line if multiline.
for i in newword[1:]:
i = i.replace('\t', ' ' * self.tabSpace )
i = "\n" + ( " " * len(line) ) + i
self.text.insert("insert", i )
def writeHelp(self):
# Print help.
helpStr = "\n\n#####\n## ___________________________"
helpStr += "\n## | |"
helpStr += "\n## | Smart Templates |"
helpStr += "\n## |___________________________|"
helpStr += "\n##\n## Welcome to the help of Smart Templates."
helpStr += "\n##\n## Author: Joao Nuno Carvalho. mail: jngscarvalho@yahoo.com"
helpStr += "\n## Version:" + str(self.version)
helpStr += "\n##\n## Below are the current templates that you can expand, but you\n## can add more, just edit the file SmartTemplates.py"
helpStr += "\n##\n## Create a new \"dic_???\" and insert it in \"dic\", restart IDLE\n## so it reload the class and there you go."
helpStr += "\n##\n## You can alter the tabSpace just change the variable \"tabSpace = 4\"."
helpStr += "\n## If you add more general purpose tamplates please email me so\n## i can add to the next version."
helpStr += "\n## If you don't agree with key bindings and/or tamplate bindings tell me."
helpStr += "\n## This is my first Python program if you think this is usefull\n## please say so i can know and implement crazy ideas in SmartTemplates."
helpStr += "\n##\n## I would like you to tell me what are your most used expansions,\n## so i can write small and meanfull names for those expansion."
helpStr += "\n#####\n\n"
self.text.insert("insert", helpStr)
# Print all templates
sortKeys = self.dic.keys()
sortKeys.sort()
for i in sortKeys:
i_str = " " + i + " ---> "
self.text.insert("insert", i_str )
self.writeTemplate(i)
self.text.insert("insert", "\n\n" )
def smart_templates_next_event(self, event):
#call the next funtion.
self.next()
return "break"
########################################
## Falta:
## -Se a expansao contem mais do que um pipe entao manter estado entre invocações. (problema: invocacoes aninhadas, tem de se poder permitir)
##
## -Ler e escrever para um ficheiro os diferentes templates.
## -Criar a janela para configurar o Smart Template Extension.
##
## -Criar uma janela para a lista de opcoes possiveis no contexto de cada pipe (next).
## -Criar a janela anterior mas com uma view de texto associada a cada opcao.
##
## -Colocar dois numeros entre cada pipe, |1;3| O primeiro indica o numero da expansao e segundo indica dentro
## da expansao, o numero de ordem do pipe. A cada um destes pares e mantido uma lista associada de opcoes e suas descricoes.
## Num dicionario/hash table. Quando se cria uma nova expansao todos as chaves deste dicionario sao validadas,
## por forma a retirar do dicionario as que ja nao estiverem no ficheiro.
##
--0-114468734-1005070472=:51324--