gecrit-2.8.4/data/plugins/AbbreviationCompletion.py000777 000000 000000 00000016046 12051462410 022374 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx, os import yapsy.IPlugin from data.plugins.categories import General class AbbreviationSettingsWin(wx.Frame): def __init__(self, parent): self.parent = parent self.config_path = self.parent.HOMEDIR+"/.gEcrit/AbbreviationCompletion.conf" wx.Frame.__init__(self,self.parent, -1,"Abbreviation Editor" , size = (500,300)) self.main_panel = wx.Panel(self) self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.abbr_ctrl_sizer = wx.BoxSizer(wx.VERTICAL) self.bt_sizer = wx.BoxSizer(wx.HORIZONTAL) self.abbr_list = wx.ListCtrl(self.main_panel,style=wx.LC_REPORT) self.abbr_list.InsertColumn(0, "Abbreviaton") self.abbr_list.SetColumnWidth(0, 150) self.abbr_list.InsertColumn(1, "Value") self.abbr_list.SetColumnWidth(1, 350) self.abbreviations = [] self.selected_abbr = None self.abbr_list.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelect) self.abbr_list.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnSelect) self.add_abbr_bt = wx.Button(self.main_panel, -1, "Add") self.add_abbr_bt.Bind(wx.EVT_BUTTON, self.OnAddAbbreviation) self.remove_abbr_bt = wx.Button(self.main_panel, -1, "Remove") self.remove_abbr_bt.Bind(wx.EVT_BUTTON, self.OnRemoveAbbreviation) self.new_abbr_txt_lbl = wx.StaticText(self.main_panel,-1,"Abbreviation:") self.new_abbr_txt = wx.TextCtrl(self.main_panel, -1) self.new_abbr_val_txt_lbl = wx.StaticText(self.main_panel,-1,"Abbreviation Value:") self.new_abbr_val_txt = wx.TextCtrl(self.main_panel, -1) self.abbr_ctrl_sizer.AddSpacer(5) self.abbr_ctrl_sizer.Add(self.new_abbr_txt_lbl,0) self.abbr_ctrl_sizer.AddSpacer(5) self.abbr_ctrl_sizer.Add(self.new_abbr_txt, 0 , wx.EXPAND) self.abbr_ctrl_sizer.AddSpacer(5) self.abbr_ctrl_sizer.Add(self.new_abbr_val_txt_lbl, 0) self.abbr_ctrl_sizer.AddSpacer(5) self.abbr_ctrl_sizer.Add(self.new_abbr_val_txt, 0 , wx.EXPAND) self.bt_sizer.Add(self.add_abbr_bt, 0) self.bt_sizer.AddSpacer(5) self.bt_sizer.Add(self.remove_abbr_bt, 0) self.main_sizer.Add(self.abbr_list, 1, wx.EXPAND) self.main_sizer.Add(self.abbr_ctrl_sizer, 0 , wx.EXPAND) self.main_sizer.AddSpacer(10) self.main_sizer.Add(self.bt_sizer, 0) self.main_panel.SetSizer(self.main_sizer) self.main_panel.Fit() self.Populate() self.Bind(wx.EVT_CLOSE, self.HideMe) self.Hide() def Populate(self): self.abbr_list.DeleteAllItems() self.ReadAbbrConfig() for a in self.abbreviations: self.abbr_list.Append(a) def ReadAbbrConfig(self): if os.path.exists(self.config_path): cfg_fl = open(self.config_path,"r") self.abbreviations = eval(cfg_fl.read()) else: cfg_fl = open(self.config_path,"w") cfg_fl.write(str([])) cfg_fl.close() def SaveAbbrConfig(self): cfg_fl = open(self.config_path,"w") cfg_fl.write(str(self.abbreviations)) cfg_fl.close() def OnAddAbbreviation(self, event): abbr = self.new_abbr_txt.GetValue() abbr_val = self.new_abbr_val_txt.GetValue() if not abbr.isspace() and not abbr_val.isspace(): self.abbreviations.append([abbr,abbr_val]) self.abbr_list.Append([abbr,abbr_val]) self.SaveAbbrConfig() def OnSelect(self, event): self.selected_abbr = event.GetSelection() def OnDeselect(self, event): self.selected_abbr = None def OnRemoveAbbreviation(self, event): if self.selected_abbr == None: return self.abbr_list.DeleteItem(self.selected_abbr) items = self.abbr_list.GetItemCount() if items == 0: self.abbreviations = [] for i in xrange(0, items): txt = self.abbr_list.GetItemText(i) k = 0 v = False for j in self.abbreviations: if txt == j[0]: v = True ;break k += 1 if v: self.abbreviations.pop(k) self.SaveAbbrConfig() def ShowMe(self, event): self.Show() def HideMe(self,event): self.Hide() class AbbreviationCompletion(yapsy.IPlugin.IPlugin, General): def __init__(self): self.name = "Abbreviation Completion" def Init(self, parent): self.parent = parent self.pref_win = AbbreviationSettingsWin(self.parent) self.current_doc = None #creating plugin menu entry self.plugins_menu = wx.Menu() edit_entry = self.plugins_menu.Append(-1,"Edit Abbreviations") self.menu_item = self.parent.AddToMenuBar("Abbreviation Completion", self.plugins_menu) self.parent.BindMenubarEvent(edit_entry, self.pref_win.ShowMe) def NotifyDocumentOpened(self): self.current_doc = self.parent.GetCurrentDocument() self.current_doc.Bind(wx.stc.EVT_STC_CHARADDED, self.OnEditorChar) def NotifyTabChanged(self): self.current_doc = self.parent.GetCurrentDocument() def NotifyNewTabOpened(self): self.NotifyDocumentOpened() def ReplaceAbbr(self): abbr_found = False abbr_val = None st = self.current_doc.WordStartPosition(self.current_doc.GetCurrentPos()-1, False) end = self.current_doc.WordEndPosition(self.current_doc.GetCurrentPos()-1, False) word = self.current_doc.GetTextRange(st, end) for a in self.pref_win.abbreviations: if word.rstrip() == a[0].rstrip(): abbr_found = True abbr_val = a[1] break if abbr_found: self.current_doc.SetTargetStart(st) self.current_doc.SetTargetEnd(end) self.current_doc.ReplaceTarget(abbr_val) self.current_doc.WordRight() return True return False def OnEditorChar(self, event): key = event.GetKey() if chr(key).isspace(): if self.ReplaceAbbr(): self.current_doc.InsertText(self.current_doc.GetCurrentPos(),chr(key)) self.current_doc.CharRight() event.Skip() def Stop(self): self.parent.RemoveFromMenubar(self.menu_item) self.pref_win.Destroy() gecrit-2.8.4/data/plugins/ClassHierarchyWin.yapsy-plugin000777 000000 000000 00000000325 12051462410 023321 0ustar00rootroot000000 000000 [Core] Name = Class Hierarchy Tree Module = ClassHierarchyWin [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Provides a class hierarchy tree. gecrit-2.8.4/data/plugins/SyntaxChecker.yapsy-plugin000777 000000 000000 00000000340 12051462410 022507 0ustar00rootroot000000 000000 [Core] Name = Python Syntax Doctor Module = SyntaxChecker [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Provides syntax checking facilities for python. gecrit-2.8.4/data/plugins/WordCounter.yapsy-plugin000777 000000 000000 00000000303 12051462410 022206 0ustar00rootroot000000 000000 [Core] Name = Word Counter Module = WordCounter [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Counts occurences of a word. gecrit-2.8.4/data/plugins/ClassHierarchyWin.py000777 000000 000000 00000017172 12051462410 021320 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx import yapsy.IPlugin from data.plugins.categories import General class HierarchyCtrl(wx.TreeCtrl): """ HierarchyCtrl Manages data colection, processing and displaying of python classes from a source of files. Creates hierarchies of them in tree. """ class Class(): def __init__(self, name = "", bases = []): self.name = name self.bases = bases self.children = [] self.tree_ctrl_root = None def __init__(self,parent = None, id = wx.ID_ANY, pos = (10,10), size=(-1,-1)): """ __inti__ Initializes the wx.TreeCtrl object, creates a tree root and the environment. """ wx.TreeCtrl.__init__(self, parent, id,pos,size,style = wx.TR_HIDE_ROOT | wx.TR_HAS_BUTTONS | wx.TR_HAS_VARIABLE_ROW_HEIGHT) self.root = self.AddRoot("Top") self.classes = [] def GenerateHierarchies(self,docs): """ GenerateHierarchies Gathers data using helper functions and organizes it on the tree. First clears the tree with the help of the helper function and then populates it. """ file_list = self.GetFileList(docs) for fl in file_list: self.GetClassesFromFile(fl) # base attributes are nothing but strings now. replace them with real Class objects for cl in self.classes: bases = [] for c in self.classes: if c.name in cl.bases: bases.append(c) cl.bases = bases # get list of children to_be_removed = [] for cl in self.classes: for c in self.classes: if cl in c.bases: cl.children.append(c) to_be_removed.append(c) self.classes = [ c for c in self.classes if not c in to_be_removed ] def WalkAndAddTree(node,root): node.tree_ctrl_root = self.AppendItem(root, node.name) for child in node.children: child.tree_ctrl_root = self.AppendItem(node.tree_ctrl_root, child.name) if child.children: WalkAndAddTree(child, child.tree_ctrl_root) for cls in self.classes: cls.tree_ctrl_root = self.AppendItem(self.root, cls.name) for child in cls.children: WalkAndAddTree(child,cls.tree_ctrl_root) self.classes = [] def FindChilds(self,cls): """ FindChilds Finds the child classes of the suplied argument cls. Uses a helper class to check inheritance. Return the list of childs. """ childs = [] for c in self.classes: if cls.name in c.bases: childs.append(c) return childs def GetClassesFromFile(self,file_path): """ GetClassesFromFile Reads and collects the class statements from the suplied file_path argument. Creates a list of found classes and returns it if not empty. """ with open(file_path,"r") as fl: for line in fl: if "class" in line and ":" in line: name = line.lstrip("class").split("(")[0].rstrip(":").strip() # extract class name bases = line.split("(")[1].split(")")[0].split(",") # extract bases bases = [ b.strip() for b in bases] # remove whitespace self.classes.append(HierarchyCtrl.Class(name,bases)) def GetFileList(self,docs): """ GetFileList Iterates through all the editor objects, retrieves their file paths, gathers them into a list and returns it. If none Found, return False. """ file_list = [] for d in docs: file_name = d.GetFilePath() if file_name != "": file_list.append(file_name) return file_list def Refresh(self,docs): """ Refresh Rebuild the class hierarchy tree. """ self.DeleteChildren(self.root) self.GenerateHierarchies(docs) class ClassHierarchyWin(wx.Frame, General,yapsy.IPlugin.IPlugin): """ HierarchyFrame Provides a display space and controls for the ClassHierarchyCtrl object. """ def __init__(self): self.name = "Class Hierarchy Tree" def Init(self,parent = None,id = wx.ID_ANY): """ Init Build the frame GUI components and initializes the wx.Frame object. Initializes the ClassHierarchyCtrl object. """ self.parent = parent wx.Frame.__init__(self, parent,id,"Class Hierarchies",size=(300,500)) self.panel = wx.Panel(self) panel_sizer = wx.BoxSizer(wx.VERTICAL) self.tree_ctrl = HierarchyCtrl(self.panel) self.button_sizer = wx.BoxSizer(wx.HORIZONTAL) self.refresh = wx.Button(self.panel,-1,"Refresh", pos=(200,400), size=(-1,-1)) self.close = wx.Button(self.panel,-1, "Close", pos = (250,400), size=(-1,-1)) self.button_sizer.Add(self.refresh,0) self.button_sizer.Add(self.close,0) panel_sizer.Add(self.tree_ctrl,1,wx.EXPAND) panel_sizer.Add(self.button_sizer,0) self.panel.SetSizer(panel_sizer) self.panel.Fit() self.Hide() self.Bind(wx.EVT_CLOSE, self.HideMe) self.refresh.Bind(wx.EVT_BUTTON, self.OnRefresh) self.close.Bind(wx.EVT_BUTTON, self.HideMe) #creating plugin menu entry self.plugins_menu = wx.Menu() show_entry = self.plugins_menu.Append(-1,"Show Tree") self.menu_item = self.parent.AddToMenuBar("Class Hiererchy Tree", self.plugins_menu) self.parent.BindMenubarEvent(show_entry, self.ShowMe) def ShowMe(self,event): """ ShowMe Makes window visible and refreshes the class hierarchy tree. """ self.documents = self.parent.GetAllDocuments() self.tree_ctrl.Refresh(self.documents) self.Show() def HideMe(self,event): """ HideMe Hides the window. """ self.Hide() def OnRefresh(self,event): """ OnRefresh Calls the ClassHierarchyCtrl's function Refresh. """ self.tree_ctrl.Refresh(self.documents) def NotifyTabChanged(self): self.Notify() def NotifyDocumentOpened(self): self.Notify() def NotifyDocumentSaved(self): self.Notify() def Notify(self): try:#the tab change event is produced prematurely self.documents = self.parent.GetAllDocuments() except: pass def Stop(self): self.parent.RemoveFromMenubar(self.menu_item) self.Destroy() gecrit-2.8.4/Logger.py000777 000000 000000 00000004170 12051462410 014555 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import time from Configuration import * class Logger: """ Logger Provides function to record applications activity, view the log, and erasing it. """ def __init__(self): self.__HOMEDIR = os.path.expanduser('~') self.log_path = os.path.join(self.__HOMEDIR, ".gEcrit", "gEcrit.log") def AddLogEntry(self, entry): """ AddLogEntry Opens the log file and appends a string with the format date,time : string to it. The string is received from its argument. """ if Config.GetOption("ActLog"): log_file = open(self.log_path, "a") log_file.write("\n") log_file.write(time.ctime() + " : "+ entry) log_file.close() def EraseLog(self, event): """ EraseLog Opens the log file and erases its contents. """ log_file = open(self.log_path, "w") log_file.write("") log_file.close() def ReadLog(self): """ ReadLog Reads the log file and returns a string with its contents. """ log_file = open(self.log_path, "r") logcontent = "" try: for line in log_file.readlines(): logcontent += line except: logcontent = "" finally: log_file.close() return logcontent Log = Logger() gecrit-2.8.4/gEcrit_es_utf.po000777 000000 000000 00000031746 12051462407 016125 0ustar00rootroot000000 000000 # SOME DESCRIPTIVE TITLE. # Copyright (C) 211 Anna Groza # This file is distributed under the same license as gEcrit. # FIRST AUTHOR anna.balerina@yahoo.com, 2011. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION" "Report-Msgid-Bugs-To: " "POT-Creation-Date: 2011-05-05 22:11-0400" "PO-Revision-Date: 2011-05-07 11:23-0500" "Last-Translator: Anna Groza anna.balerina@yahoo.com" "Language-Team: LANGUAGE " "Language: Spanish" "MIME-Version: 1.0" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit" #: editorClass.py:324 msgid "Session file loaded." msgstr "Sesión archivo cargado." #: editorClass.py:342 msgid "Session saved." msgstr "Sesión guardada" #: editorClass.py:381 msgid "" "Could not load file.\n" "The file " msgstr "No se pudo cargar el archivo.\n" "El archivo." #: editorClass.py:381 msgid " does not exists." msgstr "no existe." #: editorClass.py:381 msgid "Input Error." msgstr "Error de entrada" #: editorClass.py:486 msgid "" "Please make sure that your data is saved.\n" "Are you sure you want to quit?" msgstr "" "Por favor, asegúrese de que sus datos se guardan.\n" "Está seguro que quiere dejar?" #: editorClass.py:488 msgid "Are you sure?" msgstr "Estás seguro?" #: editorClass.py:530 msgid "The file " msgstr "El archivo" #: editorClass.py:531 msgid "" " is not saved.\n" "Do you wish to save it?" msgstr "" "no se guarda.\n" "Desea guardar esto?" #: editorClass.py:593 #: editorClass.py:597 msgid "Opened file " msgstr "Archivo abierto" #: FindReplaceText.py:39 msgid "Find" msgstr "Buscar" #: FindReplaceText.py:101 #: FindReplaceText.py:105 msgid "Search and Replace" msgstr "Buscar y Reemplazar" #: FindReplaceText.py:181 msgid "" "The end of file was reached!\n" "Nothing to replace." msgstr "El final del archivo se alcanzado!\n" "No hay nada de sustituir." #: Menu.py:47 msgid "&New Tab\tCtrl+N" msgstr "&Nuevo Documento\tCtrl+N" #: Menu.py:47 #: Toolbar.py:40 msgid "Open a new tab." msgstr "Abrir un nuevo documento." #: Menu.py:48 msgid "&Open\tCtrl+O" msgstr "&Abrir\tCtrl+O" #: Menu.py:48 #: Toolbar.py:42 msgid "Open a new document." msgstr "Abrir un nuevo documento" #: Menu.py:49 msgid "&Save\tCtrl+S" msgstr "&Guarde\tCtrl+S" #: Menu.py:49 msgid "Save the document." msgstr "Guarde el documento" #: Menu.py:50 #: Toolbar.py:45 msgid "Save As" msgstr "Guarde como" #: Menu.py:51 msgid "Save the document under a different name." msgstr "Guarde el documento con otro nombre." #: Menu.py:52 msgid "Save All" msgstr "Guarde Todo" #: Menu.py:53 msgid "Saves all the open documents that have a path." msgstr "Guarda todos los documentos abiertos que tienen una ruta de acceso." #: Menu.py:54 msgid "Reload\tCtrl+R" msgstr "Actualizar\tCtrl+R" #: Menu.py:54 msgid "Reload the current file from disk." msgstr "Actualizar el archivo actual de disco." #: Menu.py:55 msgid "&Print\tCtrl+P" msgstr "&Imprimir\tCtrl+P" #: Menu.py:55 #: Toolbar.py:54 msgid "Print the current document." msgstr "Imprimir el documento actual." #: Menu.py:56 msgid "Close &Tab\tCtrl+W" msgstr "Cerrar &Documento\tCtrl+W" #: Menu.py:56 msgid "Close the current tab." msgstr "Cerrar la documento actual." #: Menu.py:64 msgid "Recent files\tShow the last opened files." msgstr "Archivos recientes\tMostrar los últimos archivos abiertos" #: Menu.py:66 msgid "&Quit\tCtrl+Q" msgstr "&Salir\tCtrl+Q" #: Menu.py:66 msgid "Quit gEcrit." msgstr "Salga de la gEcrit." #: Menu.py:70 msgid "&Undo\tCtrl+Z" msgstr "&Undo\tCtrl+Z" #: Menu.py:70 msgid "Cancel the last action." msgstr "Canclearla última acción." #: Menu.py:71 msgid "&Redo\tCtrl+Y" msgstr "&Rehace\tCtrl+Y" #: Menu.py:71 msgid "Bring back the last action." msgstr "Traer de vuelta la última acción." #: Menu.py:73 msgid "&Cut\tCtrl+X" msgstr "&Corta\tCtrl+X" #: Menu.py:73 msgid "Cut the selection." msgstr "Cortar la selección." #: Menu.py:74 msgid "&Copy\tCtrl+C" msgstr "&Copio\tCtrl+C" #: Menu.py:74 msgid "Copy the selection." msgstr "Copio la selección." #: Menu.py:75 msgid "&Paste\tCtrl+V" msgstr "&Paste\tCtrl+V" #: Menu.py:75 msgid "Paste the selection." msgstr "Paste la selección." #: Menu.py:77 msgid "Select All\tCtrl+A" msgstr "Seleccionar todo\tCtrl+A" #: Menu.py:78 msgid "Select all the document." msgstr "Seleccionar todo los documentos" #: Menu.py:79 msgid "Select Code Block\tCtrl+Shift+A" msgstr "Seleccionar el bloque de código" #: Menu.py:80 msgid "Select all the current code block." msgstr "" #: Menu.py:82 msgid "Indent\tCtrl+K" msgstr "Indent\tCtrl+K" #: Menu.py:82 msgid "Indent the selected lines." msgstr "Indent las líneas seleccionadas." #: Menu.py:83 msgid "Dedent\tCtrl+J" msgstr "Dedent\tCtrl+J" #: Menu.py:83 msgid "Dedent the selected lines." msgstr "Dedent l" #: Menu.py:85 msgid "Comment Lines\tCtrl+Shift+C" msgstr "Las líneas de comentario\tCtrl+Shift+C" #: Menu.py:85 msgid "Comment the selected lines." msgstr "Comentar las líneas seleccionadas." #: Menu.py:86 msgid "Uncomment Lines\tCtrl+Shift+X" msgstr "Elimine el comentarios de las líneas\tCtrl+Shift+X" #: Menu.py:86 msgid "Uncomment the selected lines." msgstr "Elimine el comentarios de las líneas seleccionadas." #: Menu.py:89 msgid "Insert date" msgstr "Inserte la fecha" #: Menu.py:90 msgid "Insert the date at cursor position." msgstr "Inserte la fecha en la posición del cursor." #: Menu.py:92 msgid "Preferences\tCtrl+E" msgstr "Preferencias\tCtrl+E" #: Menu.py:93 #: Toolbar.py:48 msgid "Open the configuration window." msgstr "Abra la ventana de configuración." #: Menu.py:95 msgid "Find\tCtrl+F" msgstr "Buscar\tCtrl+F" #: Menu.py:96 msgid "Search text in the current document." msgstr "Busca el texto en el documento actual." #: Menu.py:97 msgid "Find and Replace\tCtrl+H" msgstr "Busca y reemplazar" #: Menu.py:98 msgid "Search and replace text in the current document." msgstr "Busca y reemplazar texto en el documento actual." #: Menu.py:100 msgid "Regex Search\tCtrl+Shift+F" msgstr "Regex Busca\tCtrl+Shift+F" #: Menu.py:100 msgid "Find text using a regular expression." msgstr "Búsca de texto utilizando una expresión regular." #: Menu.py:101 msgid "Regex Search and Replace\tCtrl+Shift+H" msgstr "Regex busca y reemplazar\tCtrl+Shift+H" #: Menu.py:101 msgid "Find and replace text using a regular expression." msgstr "Busca y reemplazar texto usando una expresión regular." #: Menu.py:103 msgid "Zoom In\tCtrl++" msgstr "Zoom In\tCtrl++" #: Menu.py:104 msgid "Increase the size of the text." msgstr "Aumenta el tamaño del texto." #: Menu.py:105 msgid "Zoom Out\tCtrl+-" msgstr "Zoom Out\tCtrl+-" #: Menu.py:106 msgid "Decrease the size of the text." msgstr "Disminuir el tamaño del texto." #: Menu.py:107 msgid "Normal Size\tCtrl+0" msgstr "Normal Tamaño\tCtrl+0" #: Menu.py:108 msgid "Set the size of the text to normal." msgstr "Establece el tamaño del texto a la normalidad." #: Menu.py:110 msgid "Line Numbers" msgstr "Números de línea" #: Menu.py:111 msgid "Show/Hide line numbers." msgstr "Mostrar / Ocultar Números de Línea." #: Menu.py:112 msgid "Fold Marks" msgstr "Fold Marks(Doble Marcas)" #: Menu.py:112 msgid "Show/Hide fold marks." msgstr "Mostrar / Ocultar fold marks(Doble Marcas)." #: Menu.py:113 msgid "White Space" msgstr "Espacio en Blanco" #: Menu.py:114 msgid "Show/Hide white spaces." msgstr "Mostrar / Ocultar espacio en blanco." #: Menu.py:115 msgid "Indentation Guides" msgstr "Sangría Guías" #: Menu.py:116 msgid "Show/Hide indentation guides." msgstr "Mostrar / Ocultar sangría guías" #: Menu.py:117 msgid "Edge Line" msgstr "Edge Line" #: Menu.py:118 msgid "Show/Hide the edge line." msgstr "Mostrar / Ocultar la edge line." #: Menu.py:119 msgid "Syntax Highlight" msgstr "Resaltado de Sintaxis(Syntax Highlight)" #: Menu.py:120 msgid "Enable/Disable Syntax Highlight." msgstr "Activar / Desactivar resaltado de sintaxis(Syntax Highlight)." #: Menu.py:122 msgid "Python Shell" msgstr "Python proyectil" #: Menu.py:123 msgid "Stop/Start a python shell." msgstr "Stop / Start un proyectil de Python." #: Menu.py:124 msgid "OS Shell" msgstr "OS proyectil" #: Menu.py:124 msgid "Stop/Start an OS shell." msgstr "Stop / Start OS un proyectil." #: Menu.py:126 msgid "Statusbar" msgstr "Barra de Estado." #: Menu.py:126 msgid "Show/Hide statusbar." msgstr "Mostrar / Ocultar barra de estado." #: Menu.py:127 msgid "Fullscreen\tF11" msgstr "Pantalla completa\tF11" #: Menu.py:127 msgid "Toggle Fullscreen mode." msgstr "Activar el modo de pantalla completa." #: Menu.py:128 msgid "Toggle Toolbox" msgstr "Activar Caja de herramientas" #: Menu.py:128 msgid "Show/Hide Toolbox window." msgstr "Mostrar / Ocultar ventana Caja de herramientas." #: Menu.py:129 msgid "Toggle Assistants" msgstr "Activar Asistentes" #: Menu.py:129 msgid "Show/Hide Assistants window." msgstr "Mostrar / Ocultar ventana de asistentes." #: Menu.py:131 msgid "Remove Trailing Spaces" msgstr "Eliminar (Trailing) espacios al final" #: Menu.py:131 msgid "Remove spaces at the end of the line." msgstr "Elimine espacios al final de la línea." #: Menu.py:132 msgid "Run File\tF5" msgstr "Ejecute Archivo\tF5" #: Menu.py:132 msgid "Run the current document.(python only)" msgstr "Ejecute el documento actual.(python sólo)" #: Menu.py:133 msgid "Tabify" msgstr "Tabify" #: Menu.py:133 msgid "Replace spaces by tabs." msgstr "Vuelva a colocar etiquetas con espacios." #: Menu.py:134 msgid "Untabify" msgstr "Untabify" #: Menu.py:134 msgid "Replace tabs by spaces." msgstr "Vuelva a colocar etiquetas con espacios." #: Menu.py:136 msgid "Enable Session" msgstr "Active Sesión" #: Menu.py:136 msgid "Enable/Disable Session support." msgstr "Activar / Desactivar soporte de Sesión ." #: Menu.py:137 msgid "Save Session" msgstr "Guarda Sesión" #: Menu.py:137 msgid "Save the current application state." msgstr "Guarda el aplicación actual de estado." #: Menu.py:138 msgid "Delete Session" msgstr "Elimina Sesión" #: Menu.py:138 msgid "Delete the saved session file." msgstr "Elimina el archivo de sesión guardada." #: Menu.py:140 msgid "Plugin Manager" msgstr "Plugin Administrador" #: Menu.py:140 msgid "Manage gEcrit Plugins." msgstr "Administrar gEcrit Plugins." #: Menu.py:142 msgid "About" msgstr "Casi" #: Menu.py:142 msgid "Open the about window." msgstr "Abre sobre la ventana." #: Menu.py:144 msgid "&File" msgstr "&Archivo" #: Menu.py:145 msgid "&Edit" msgstr "&Editar" #: Menu.py:146 msgid "&Search" msgstr "&Busca" #: Menu.py:147 msgid "&View" msgstr "&Ver" #: Menu.py:148 msgid "&Document" msgstr "&Documento" #: Menu.py:149 msgid "&Session" msgstr "&Sesiones" #: Menu.py:150 msgid "&Plugins" msgstr "&Plugins" #: Menu.py:151 msgid "&Help" msgstr "&Ayudar" #: Toolbar.py:39 msgid "New" msgstr "Nuevo" #: Toolbar.py:41 msgid "Open" msgstr "Abierto" #: Toolbar.py:43 msgid "Save" msgstr "Guardar" #: Toolbar.py:44 msgid "Save the current document." msgstr "Guardar el documento actual" #: Toolbar.py:46 msgid "Save the current document under a differend name." msgstr "Guardar el documento actual con un nombre diferente." #: Toolbar.py:47 msgid "Settings" msgstr "Configuración" #: Toolbar.py:50 msgid "Quit" msgstr "Salir" #: Toolbar.py:50 msgid "Quit gEcrit" msgstr "Salga de la gEcrit" #: Toolbar.py:53 msgid "Print" msgstr "Imprimir" #: Toolbar.py:56 msgid "Run the current file.(Python only)" msgstr "Ejecute el archivo actual.(Python sólo)" msgid "Autocomplete Braces" msgstr "Autocompleta Tirantes" msgid "Show Line Numbers" msgstr "Mostra números de línea" msgid "Autoindentation" msgstr "Auto indentación" msgid "Backspace to Unindent" msgstr "Retroceso para Unindent" msgid "Use Tabs" msgstr "Utilice los Documentos" msgid "Show Whitespace" msgstr "Mostrar espacios en blanco" msgid "Edge Line Position:" msgstr "Ponga el borde de línea:" msgid "Enable Autosave" msgstr "Activar el guardado automático" msgid "Save data each # of characters:" msgstr "Guardar los datos de cada # de caracteres:" msgid "Strip Trailing Spaces On Save" msgstr "Strip Trailing(Franja de arrastre)Espacios al guardar" msgid "Status Bar" msgstr "Barra de estado" msgid "Enable Log" msgstr "Activar la entrada" msgid "Colour Palette" msgstr "Paleta de color" msgid "View Log" msgstr "Ver el Entrada " msgid "Erase Log" msgstr "Eliminar Entrada" msgid "OK" msgstr "Bien" msgid "Toolbox" msgstr "Caja de herramientas" msgid "Assistants and others" msgstr "Asistentes y otros" msgid "Remove" msgstr "Quitar" msgid "Author: " msgstr "Autor:" msgid "Version: " msgstr "Versión:" msgid "Website: " msgstr "Página web:" msgid "Description: " msgstr "Descripción:" msgid "Keywords" msgstr "Clave Palabras" msgid "Strings" msgstr "Strings" msgid "Triple Quotes" msgstr "Triple Cotizaciones" msgid "Integers" msgstr "Enteros" msgid "Comments" msgstr "Comentarios" msgid "Brackets" msgstr "Paréntesis" msgid "Bad EOL" msgstr "Mal EOL" msgid "Method Names" msgstr "Método Nombres" msgid "Operators" msgstr "Operadores" msgid "Identifiers" msgstr "Identificadores" msgid "Plugins:" msgstr "Plugins:" gecrit-2.8.4/data/plugins/SpellChecker.py000777 000000 000000 00000011613 12051462410 020274 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- #!/usr/bin/python # -*- coding: utf-8 -*- import wx from data.plugins.categories import General import yapsy.IPlugin try: import enchant import enchant.checker.wxSpellCheckerDialog except: print "Spell checker pyenchant is not available." class SpellCheckDialog(enchant.checker.wxSpellCheckerDialog.wxSpellCheckerDialog): def __init__(self, parent): self.parent = parent enchant.checker.wxSpellCheckerDialog.wxSpellCheckerDialog.__init__(self,self.parent, -1, title = "Spell Checker") class SpellChecker(General, yapsy.IPlugin.IPlugin): """ Provides the necessary functions for spellchecking. Uses the enchant module. """ def __init__(self): """ __init__ Initializes the enchant module, sets the language dictionary. """ self.name = "Spell Checker" try: self.dictionary = enchant.Dict() except enchant.Error: print "The Dictionary could not be identified.\n Falling back to English." self.dictionary = enchant.Dict("en_US") self.spell_checker = enchant.checker.SpellChecker(self.dictionary.tag) def Init(self, parent): self.parent = parent self.current_doc = None self.last_word = "" self.plugins_menu = wx.Menu() edit_entry = self.plugins_menu.Append(-1,"Show Spell Checker") self.menu_item = self.parent.AddToMenuBar("Spell Checker", self.plugins_menu) self.parent.BindMenubarEvent(edit_entry, self.ShowMe) self.spell_dlg = SpellCheckDialog(self.parent) self.spell_dlg.SetSpellChecker(self.spell_checker) self.spell_dlg.Bind(wx.EVT_CLOSE, self.HideMe) def CheckWord(self, word): """ CheckWord Calls enchant to check the suplied argument word. """ return self.dictionary.check(word) def GetSuggestion(self, word): """ GetSuggestion Calls the enchant library to generate spelling suggestion for the suplied argument word. """ return self.dictionary.suggest(word) def ShowSpellDialog(self, event): """" ShowSpellDialog not implemented """ pass def SpellCheck(self, event): """ OnSpellCheck Delivers the data to the spell checker, and manages the underlineing and clearing of the text. """ st = self.current_doc.WordStartPosition(self.current_doc.GetCurrentPos(), False) end = self.current_doc.WordEndPosition(self.current_doc.GetCurrentPos(), False) word = self.current_doc.GetTextRange(st, end) self.last_word = word spelled_ok = self.CheckWord(word) if not spelled_ok: self.current_doc.StartStyling(st, wx.stc.STC_INDIC0_MASK) self.current_doc.SetStyling(end - st, wx.stc.STC_INDIC0_MASK) else: self.current_doc.StartStyling(st, wx.stc.STC_INDIC0_MASK) self.current_doc.SetStyling(end - st, 0) self.current_doc.spell_error = False event.Skip() def NotifyDocumentOpened(self): self.current_doc = self.parent.GetCurrentDocument() self.current_doc.Bind(wx.stc.EVT_STC_CHARADDED, self.SpellCheck) self.current_doc.IndicatorSetStyle(0, wx.stc.STC_INDIC_SQUIGGLE) self.current_doc.IndicatorSetForeground(0, wx.RED) def NotifyNewTabOpened(self): self.current_doc = self.parent.GetCurrentDocument() self.current_doc.Bind(wx.stc.EVT_STC_CHARADDED, self.SpellCheck) self.current_doc.IndicatorSetStyle(0, wx.stc.STC_INDIC_SQUIGGLE) self.current_doc.IndicatorSetForeground(0, wx.RED) def NotifyTabChanged(self): self.current_doc = self.parent.GetCurrentDocument() self.last_word = "" def HideMe(self, event): self.spell_dlg.Hide() def ShowMe(self, event): rng = self.current_doc.GetSelection() self.spell_checker.set_text(self.current_doc.GetTextRange(rng[0],rng[1])) self.spell_dlg.SetSpellChecker(self.spell_checker) self.spell_dlg.Show() gecrit-2.8.4/pyctags/000777 000000 000000 00000000000 12051462410 014431 5ustar00rootroot000000 000000 gecrit-2.8.4/data/plugins/categories.py000777 000000 000000 00000004673 12051462410 020065 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- class Passive(object): """ Passive The plugins that inherit from this interface do not interact with the application. """ def __init__(): self.name = "No Name" def Init(self, parent): """ Init Build the plugin gui and bind its events. """ pass def Stop(self): """ Stop This method is called at application exit. You are asked to stop your plugin and save the necessary data. """ pass class General(object): """ Gadget Plugins of this class are notified at each event listed below. The plugin then takes its action when notified. """ def __init__(self): self.name = "No Name" def Init(self, parent): """ Init Build the plugin gui and bind its events. """ pass def NotifyTabChanged(self): """ NotifyTabChanged This method is called whenever the current tab is changed. """ pass def NotifyDocumentOpened(self): """ NotifyDocumentOpened This method is called whenver the user opens a new document. """ pass def NotifyNewTabOpened(self): """ NotifyNewTabOpened This method is called whenever the user opens an empty tab. """ pass def NotifyDocumentSaved(self): """ NotifyDocumentSaved This method is called whenever the user saves the current document. """ pass def Stop(self): """ Stop This method is called at application exit. You are asked to stop your plugin and save the necessary data. """ pass gecrit-2.8.4/icons/000777 000000 000000 00000000000 12051462410 014072 5ustar00rootroot000000 000000 gecrit-2.8.4/data/plugins/ClipboardViewer.py000777 000000 000000 00000006614 12051462410 021016 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- from data.plugins.categories import Passive import yapsy.IPlugin import wx class ClipboardViewer(wx.Frame, Passive, yapsy.IPlugin.IPlugin): def __init__(self): self.name = "Clipboard Viewer" def Init(self, parent): self.parent = parent wx.Frame.__init__(self, self.parent) self.main_panel = wx.Panel(self) self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.button_sizer = wx.BoxSizer(wx.HORIZONTAL) self.clip_view_descr = wx.StaticText(self.main_panel, -1, "Clipboard Contents:", size = (-1, -1)) self.clip_view = wx.TextCtrl(self.main_panel, -1, style = wx.TE_MULTILINE) self.update_clp = wx.Button(self.main_panel, -1, "Update Clipboard") self.refresh_view = wx.Button(self.main_panel, -1, "Refresh") self.update_clp.Bind(wx.EVT_BUTTON, self.OnUpdate) self.refresh_view.Bind(wx.EVT_BUTTON, self.OnRefresh) self.plugins_menu = wx.Menu() show_entry = self.plugins_menu.Append(-1,"Show Clipboard") self.menu_item = self.parent.AddToMenuBar("Clipboard Viewer", self.plugins_menu) self.parent.BindMenubarEvent(show_entry, self.ShowMe) self.button_sizer.Add(self.update_clp) self.button_sizer.AddSpacer(5) self.button_sizer.Add(self.refresh_view) self.main_sizer.Add(self.clip_view_descr) self.main_sizer.AddSpacer(10) self.main_sizer.Add(self.clip_view, 1, wx.EXPAND) self.main_sizer.Add(self.button_sizer) self.main_panel.SetSizerAndFit(self.main_sizer) self.Bind(wx.EVT_CLOSE, self.HideMe) self.Hide() def ReadClipboard(self): #opening the clipboard if not wx.TheClipboard.IsOpened(): wx.TheClipboard.Open() #reading the clipboard txt = wx.TextDataObject() success = wx.TheClipboard.GetData(txt) #loading the text to the clip_view if success: self.clip_view.SetValue( txt.GetText() ) def OnRefresh(self, event): self.ReadClipboard() def OnUpdate(self, event): #creating the data object data = wx.TextDataObject() #settinc the data object value data.SetText(self.clip_view.GetValue()) #writing the data object to clipboard if not wx.TheClipboard.IsOpened(): wx.TheClipboard.Open() wx.TheClipboard.SetData(data) wx.TheClipboard.Close() def HideMe(self, event): self.Hide() def ShowMe(self, event): self.ReadClipboard() self.Show() gecrit-2.8.4/data/plugins/StampIt.yapsy-plugin000777 000000 000000 00000000330 12051462410 021314 0ustar00rootroot000000 000000 [Core] Name = StampIt Module = StampIt [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Automatically inserts text into a newlly created document. gecrit-2.8.4/AuiNoteBook.py000777 000000 000000 00000005006 12051462410 015514 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import wx.aui class AuiNoteBook(wx.aui.AuiNotebook): def __init__(self, parent): """ __init__ Basic constructor. """ self.parent = parent wx.aui.AuiNotebook.__init__(self, self.parent, -1 ,style=wx.aui.AUI_NB_TOP|wx.BORDER_SUNKEN|wx.aui.AUI_NB_TAB_SPLIT|wx.aui.AUI_NB_TAB_MOVE|wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB|wx.aui.AUI_NB_SCROLL_BUTTONS ) self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnChangeTab) self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, lambda event: self.parent.ManageCloseTab(event,self.parent.id_range[self.GetSelection()])) self.Bind(wx.aui.EVT_AUINOTEBOOK_BEGIN_DRAG, self.OnBeginDrag) self.Bind(wx.aui.EVT_AUINOTEBOOK_END_DRAG, self.OnEndDrag) self.SetId(900) #Needed in StcControl.py self.__dragged_doc = None def OnChangeTab(self, event): """ OnChangeTab Alerts the plugins of the current document change. """ wx.FindWindowById((self.parent.id_range)[self.GetSelection()]).SetStatusFileMode() for g in self.parent.general_plugins: self.parent.general_plugins[g].NotifyTabChanged() #tells the plugins the document # has changed. def OnBeginDrag(self, event): """ OnBeginDrag Updates the internal representation of the tabs. You should have nothing to do with this method. """ self.__dragged_doc = self.parent.id_range.pop(self.GetSelection()) event.Skip() def OnEndDrag(self, event): """ OnEndDrag Updates the internal representation of the tabs. You should have nothing to do with this method. """ self.parent.id_range.insert(self.GetSelection(),self.__dragged_doc) event.Skip() gecrit-2.8.4/data/plugins/PyTidyFormatter.py000777 000000 000000 00000434350 12051462410 021045 0ustar00rootroot000000 000000 from __future__ import division import yapsy.IPlugin import shutil, os, wx from data.plugins.categories import General DEBUG = False PERSONAL = False VERSION = '1.20' # 2010 Mar 10 import sys import codecs import StringIO import re import textwrap # 2007 May 25 if DEBUG: import token import doctest import tokenize import compiler #!/usr/bin/python # -*- coding: utf-8 -*- # PythonTidy.py # 2006 Oct 27 . ccr '''PythonTidy.py cleans up, regularizes, and reformats the text of Python scripts. =========================================== Copyright 2006 Charles Curtis Rhode =========================================== This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. =========================================== Charles Curtis Rhode, 1518 N 3rd, Sheboygan, WI 53081 mailto:CRhode@LacusVeris.com?subject=PythonTidy =========================================== This script reads Python code from standard input and writes a revised version to standard output. Alternatively, it may be invoked with file names as arguments: o python PythonTidy.py input output Suffice it to say that *input* defaults to \'-\', the standard input, and *output* defaults to \'-\', the standard output. It means to encapsulate the wisdom revealed in: o Rossum, Guido van, and Barry Warsaw. "PEP 8: Style Guide for Python Code." 23 Mar. 2006. Python.org. 28 Nov. 2006 . Python scripts are usually so good looking that no beautification is required. However, from time to time, it may be necessary to alter the style to conform to changing standards. This script converts programs in a consistent way. It abstracts the pretty presentation of the symbolic code from the humdrum[1] process of writing it and getting it to work. This script assumes that the input Python code is well-formed and works to begin with. It doesn\'t check. If all goes well, the output Python code will work, too. Of course, you are advised to test it fully to be sure. This script should be run only by python.2.5 (and perhaps higher) on scripts written for that version (and perhaps lower) because of its limited knowledge of and expectations for the abstract syntax tree node classes returned by the *compiler* module. It wouldn\'t hurt much to try it from (and on) other versions, though, and it might actually work. Search this script for "Python Version Dependency." Most of the Python 2.5 test suite passes through PythonTidy.py unimpaired. I ran the Python regression tests for 2.5.2 which is the version supported by Debian 5.0 "Lenny." On my system these tests fail before tidying: o test_imageop o test_pyclbr o test_sys 282 tests succeed after tidying with the default PythonTidy global settings, but these tests fail: *test_grammar* exposes bug 6978 in the *compiler* module. Tuples are immutable and hashable and thus suitable as dict indices. Whereas a singleton tuple literal (x,) is valid as an index, the *compiler* module parses it as x when it appears. *test_dis* compares "disassembled" Python byte code to what is expected. While byte code for a tidied script should be functionally equivalent to the untidied version, it will not necessarily be identical. *test_trace* compares the line numbers in a functional trace of a running script with those expected. A statement in a tidied script will generally have a line number slightly different from the same statement in the untidied version. *test_doctest* is an extensive suite of tests of the *doctest* module, which itself is used to document test code within doc strings and at need to compare instant results against those expected. One of the tests in *test_doctest* appears to require line numbers consistent with expectations, but tidied scripts generally violate such conditions as explained above. The more esoteric capabilities of PythonTidy.py had to be turned off to avoid corrupting the test-suite code. In practice, you\'ll want to run with PERSONAL = True (See, below.) to use all the functionality, and of course you\'ll have the good taste to find and patch all the glitches it introduces. [1] "Humdrum: A low cart with three wheels, drawn by one horse." The Collaborative International Dictionary of English v.0.48. ''' # 2010 Mar 10 . v1.20 . ccr . For Kuang-che Wu: # # o Optionally preserve unassigned constants so that code to be tidied # may contain blocks of commented-out lines that have been no-op'ed # with leading and trailing triple quotes. Python scripts may declare # constants without assigning them to a variables, but PythonTidy # considers this wasteful and normally elides them. # # o Generalize an earlier exception made for PythonDoc sentinels so # that the COMMENT_PREFIX is not inserted before any comments that # start with doubled number-signs. # # o Optionally omit parentheses around tuples, which are superfluous # after all. Normal PythonTidy behavior will be still to include them # as a sort of tuple display analogous to list displays, dict # displays, and yet-to-come set displays. # # o Kuang-che Wu has provided code that removes superfluous parens in # complex algebraic and logical expressions, which PythonTidy used to # interpolate to make operator precedence explicit. From now on # PythonTidy will rely upon default operator precedence and insert # parens only to enforce order of evaluation that is not default. # This should make tidied code more succinct, which usually results in # improved legibility. This fixes a PythonTidy bug noticed by # Kuang-che Wu having to do with order of evaluation of comparisons. # # o As a matter of style per PEP 308, parentheses are preferred around # conditional expressions. # # o Give the bitwise invert operator the same precedence as unary plus # and unary minus. # # I am making other changes to PythonTidy so that a few more of the # examples from the Python *test* module will pass: # # o Index literal pool by type. (Use *repr*.) # # o Never append a trailing comma to starred or double-starred # arguments. # 2009 Jun 29 . v1.19 . ccr . For Daniel G. Siegel at # http://home.cs.tum.edu, *python* 2.6 tokenizer returns newlines # separate from comments, so, though it may be necessary to save # newlines, it won't do for them to overlay comments. # 2009 Feb 05 . v1.18 . ccr . For Massimo Di Pierro at # http://mdp.cti.depaul.edu/, do not break up raw literals. # 2008 Jan 30 . v1.17 . ccr . This fixes regression in newline support # introduced at v1.11, which was first reported by Dr0id. # 2008 Jan 06 . v1.16 . ccr . John Machin demonstrates that hex values # are not in fact stored in the literal pool. They should always have # been and should always be. # Apparently, doubled number-signs in columns one and two are # sacrosanct sentinels in Fredrik Lundh's PythonDoc documentation # generator and must not therefore be disturbed. # Fix a crash caused by indents' crossing the centerline. # 2007 May 25 . v1.15 . ccr . Don't split lines in the middle of # function-parameter assignment. # Optionally wrap doc strings and comments to COL_LIMIT. # 2007 May 01, 23, 24 . v1.14 . ccr . Gaetan de Menten at # http://openhex.org points out that a null statement is generated by # a trailing semicolon. This has been fixed. He has been helpful by, # among other things, insisting that I clean up the rendering of doc # strings and comments. # Forcing string-literal delimiters to quotes or apostrophes (if # required) is now done before storing them to the literal pool. # Wrap chunks of code whose successors cannot be wrapped. # Don't elide leading tabs in comments and doc strings. Instead # substitute DOC_TAB_REPLACEMENT so they can be edited out manually. # Split long string literals at spaces when CAN_SPLIT_STRINGS is True. # String literals with attributes are no longer parenthesized. # For Francois Pinard, wrap before operators. # Subscripted class attributes are no longer parenthesized. # Differentiate MAX_SEPS for different situations. # 2007 Mar 06 . v1.12 . ccr . The requests of Aaron Bingham: Specify # boilerplate to be inserted after the module doc string. Optionally # split wide string literals at the column limit. Force trailing # newline. # 2007 Jan 22 . v1.11 . ccr . This update implements a couple of # well-taken user requests: # Jens Diemer wants a module-level function, *tidy_up*, to accept file # names or file-like objects. # Wolfgang Grafen wants trailing spaces eliminated to avoid spurious # differences with pre-tidied code. # 2007 Jan 14 . v1.10 . ccr . There was a big problem with earlier # versions: Canonical values were substituted for strings and numbers. # For example, decimal integers were substituted for hexadecimal, and # escaped strings for raw strings. Authors of Python scripts usually # use peculiar notations for peculiar purposes, and doing away with # them negatively impacts the readability of the code. # This version preserves the original constants (parsed by *tokenize*) # in a literal pool indexed by the value they evaluate to. The # canonical values (output by *compiler*) are then translated back # (when possible) to the original constants by looking them up in the # literal pool. # 2006 Dec 19 . v1.9 . ccr . If class name is a string, pass it to # personal substitutions routine to distinguish module globals like # gtk.VBox from class attributes like gtk.Dialog.vbox. # 2006 Dec 17 . v1.8 . ccr . Trailing comma in function parameter list # is not allowed in all cases. Catch substitutions that collide with # built-ins. # 2006 Dec 14 . v1.7 . ccr . Track line numbers on output. # Write a "Name Substitutions Report" on stderr. # 2006 Dec 13 . v1.6 . ccr . A *yield* may appear in parens when it is # the subject of an assignment; otherwise, not. # 2006 Dec 05 . v1.5 . ccr . Strings default to single quotes when # DOUBLE_QUOTED_STRINGS = False. Pass the newline convention from # input to output (transparently :-) ). # 2006 Dec 01 . v1.4 . ccr . Tighten qualifications for in-line # comments. Decode string nodes. Enclose doc strings in double # quotes. Allow file-name arguments. # 2006 Nov 30 . v1.3 . ccr . Safe check against names of *compiler* . # abstract syntax tree nodes rather than their classes to step around # one Python Version Dependency. ZERO = 0 SPACE = ' ' NULL = '' NA = -1 APOST = "'" # Old code is parsed. New code is generated from the parsed version, # using these literals: COL_LIMIT = 72 INDENTATION = ' ' ASSIGNMENT = ' = ' FUNCTION_PARAM_ASSIGNMENT = '=' FUNCTION_PARAM_SEP = ', ' LIST_SEP = ', ' SUBSCRIPT_SEP = ', ' DICT_COLON = ': ' SLICE_COLON = ':' COMMENT_PREFIX = '# ' # 2007 May 25 SHEBANG = '#!/usr/bin/python' CODING = 'utf-8' CODING_SPEC = '# -*- coding: %s -*-' % CODING BOILERPLATE = NULL # 2007 Mar 06 BLANK_LINE = NULL KEEP_BLANK_LINES = True ADD_BLANK_LINES_AROUND_COMMENTS = True MAX_SEPS_FUNC_DEF = 3 # 2007 May 24 MAX_SEPS_FUNC_REF = 5 # 2007 May 24 MAX_SEPS_SERIES = 5 # 2007 May 24 MAX_SEPS_DICT = 3 # 2007 May 24 MAX_LINES_BEFORE_SPLIT_LIT = 2 LEFT_MARGIN = NULL LEFTJUST_DOC_STRINGS = False WRAP_DOC_STRINGS = False # 2007 May 25 DOUBLE_QUOTED_STRINGS = False # 2006 Dec 05 SINGLE_QUOTED_STRINGS = False # 2007 May 01 RECODE_STRINGS = False # 2006 Dec 01 OVERRIDE_NEWLINE = '\n' # 2006 Dec 05 CAN_SPLIT_STRINGS = False # 2007 Mar 06 DOC_TAB_REPLACEMENT = '....' # 2007 May 24 KEEP_UNASSIGNED_CONSTANTS = False # 2010 Mar 10 PARENTHESIZE_TUPLE_DISPLAY = True # 2010 Mar 10 # Repertoire of name-transformation functions: def all_lower_case(str, **attribs): return str.lower() def all_upper_case(str, **attribs): return str.upper() def title_case(str, **attribs): return str.title() def strip_underscores(str, **attribs): return str.replace('_', NULL) def insert_underscores(str, **attribs): return UNDERSCORE_PATTERN.sub('_\\1', str) def is_magic(str): return str in ['self', 'cls'] or str.startswith('__') and str.endswith('__') def underscore_to_camel_case(str, **attribs): if is_magic(str): return str else: return strip_underscores(title_case(camel_case_to_underscore(str))) def camel_case_to_underscore(str, **attribs): if is_magic(str): return str else: return all_lower_case(insert_underscores(str)) def unmangle(str, **attribs): if str.startswith('__'): str = str[2:] return str def munge(str, **attribs): """Create an unparsable name. """ return '<*%s*>' % str def substitutions(str, **attribs): result = SUBSTITUTE_FOR.get(str, str) module = attribs.get('module') # 2006 Dec 19 if module is None: pass else: result = SUBSTITUTE_FOR.get('%s.%s' % (module, str), result) return result def elide_c(str, **attribs): return ELIDE_C_PATTERN.sub('\\1', str) def elide_a(str, **attribs): return ELIDE_A_PATTERN.sub('\\1', str) def elide_f(str, **attribs): return ELIDE_F_PATTERN.sub('\\1', str) # Name-transformation scripts: LOCAL_NAME_SCRIPT = [] GLOBAL_NAME_SCRIPT = [] CLASS_NAME_SCRIPT = [] FUNCTION_NAME_SCRIPT = [] # It is not wise to monkey with the # spelling of function names (methods) # where they are defined unless you are # willing to change their spelling where # they are referred to as class # attributes, too. FORMAL_PARAM_NAME_SCRIPT = [] # It is not wise to monkey with the # spelling of formal parameters for fear # of changing those of functions # (methods) defined in other modules. ATTR_NAME_SCRIPT = [] # It is not wise to monkey with the # spelling of attributes (methods) for # fear of changing those of classes # defined in other modules. # Author's preferences: if PERSONAL: LEFTJUST_DOC_STRINGS = True LOCAL_NAME_SCRIPT.extend([unmangle, camel_case_to_underscore]) GLOBAL_NAME_SCRIPT.extend([unmangle, camel_case_to_underscore, all_upper_case]) CLASS_NAME_SCRIPT.extend([elide_c, underscore_to_camel_case]) FUNCTION_NAME_SCRIPT.extend([camel_case_to_underscore]) FORMAL_PARAM_NAME_SCRIPT.extend([elide_a, camel_case_to_underscore]) ATTR_NAME_SCRIPT.extend([elide_f, camel_case_to_underscore, substitutions]) # Other global constants: UNDERSCORE_PATTERN = re.compile('(?<=[a-z])([A-Z])') COMMENT_PATTERN = re.compile('([^#]*?)#\s?') # 2007 May 25 SHEBANG_PATTERN = re.compile('#!') CODING_PATTERN = re.compile('coding[=:]\\s*([.\\w\\-_]+)') NEW_LINE_PATTERN = re.compile(r'(?>> force_quote("See the cat.", quoted=False) '"See the cat."' >>> force_quote("'See the cat.'") '"See the cat."' >>> force_quote("'See the cat.'", double=False) "'See the cat.'" >>> force_quote('"See the cat."') '"See the cat."' >>> force_quote('"See the cat."', double=False) "'See the cat.'" >>> force_quote('"\"That\'s that,\" said the cat."') '"\\"That\'s that,\\" said the cat."' >>> force_quote('"\"That\'s that,\" said the cat."', double=False) '\'"That\\\'s that," said the cat.\'' >>> force_quote("'\"That\'s that,\" said the cat.'") '"\\"That\'s that,\\" said the cat."' >>> force_quote("ru'ick'") 'ru"ick"' >>> force_quote("ru'ick'", double=False) "ru'ick'" >>> force_quote('ru"ick"') 'ru"ick"' >>> force_quote('ru"ick"', double=False) "ru'ick'" >>> force_quote("'''ick'''", double=False) "'''ick'''" """ if quoted: # 2007 May 23 match = QUOTE_PATTERN.match(encoded) if match is None: # 2008 Jan 06 prefix = NULL size = 1 else: (prefix, quote_old) = match.group(1, 2) encoded = QUOTE_PATTERN.sub(NULL, encoded, 1) size = len(quote_old) assert encoded[-size:] == quote_old encoded = encoded[:-size] else: prefix = NULL size = 1 double_backslash_delimited_substrings = encoded.split(r'\\') for (ndx, substring) in enumerate(double_backslash_delimited_substrings): substring = substring.replace(r'\"','"').replace(r"\'","'") if double: substring = substring.replace('"',r'\"') else: substring = substring.replace("'",r"\'") double_backslash_delimited_substrings[ndx] = substring encoded = r'\\'.join(double_backslash_delimited_substrings) if double: quote_new = '"' * size else: quote_new = "'" * size result = NULL.join([prefix, quote_new, encoded, quote_new]) return result def wrap_lines(lines, width=COL_LIMIT, initial_indent=NULL, subsequent_indent=NULL): # 2007 May 25 """Wrap lines of text, preserving blank lines. Lines is a Python list of strings *without* new-line terminators. Initial_indent is a string that will be prepended to the first line of wrapped output. Subsequent_indent is a string that will be prepended to all lines of wrapped output except the first. The result is a Python list of strings *without* new-Line terminators. >>> print '\\n'.join(wrap_lines('''Now is the time ... for every good man ... to come to the aid of his party. ... ... ... Don't pass the buck ... but give your buck ... to the party of your choice.'''.splitlines(), width=40)) Now is the time for every good man to come to the aid of his party. Don't pass the buck but give your buck to the party of your choice. """ DOC_WRAPPER.width = width DOC_WRAPPER.initial_indent = initial_indent DOC_WRAPPER.subsequent_indent = subsequent_indent result = [line.strip() for line in lines] result = '\n'.join(result) pgraphs = PGRAPH_PATTERN.split(result) result = [] while pgraphs: pgraph = DOC_WRAPPER.fill(pgraphs.pop(ZERO)) result.extend(pgraph.splitlines()) if pgraphs: result.append(NULL) return result def leftjust_lines(lines): # 2007 May 25 """Left justify lines of text. Lines is a Python list of strings *without* new-line terminators. The result is a Python list of strings *without* new-Line terminators. """ result = [line.strip() for line in lines] return result class InputUnit(object): """File-buffered wrapper for sys.stdin. """ def __init__(self, file_in): object.__init__(self) self.is_file_like = hasattr(file_in, 'read') # 2007 Jan 22 if self.is_file_like: buffer = file_in.read() # 2006 Dec 05 else: unit = open(os.path.expanduser(file_in), 'rb') buffer = unit.read() # 2006 Dec 05 unit.close() self.lines = UNIVERSAL_NEW_LINE_PATTERN.split(buffer) # 2006 Dec 05 if len(self.lines) > 2: if OVERRIDE_NEWLINE is None: self.newline = self.lines[1] # ... the first delimiter. else: self.newline = OVERRIDE_NEWLINE look_ahead = '\n'.join([self.lines[ZERO],self.lines[2]]) else: self.newline = '\n' look_ahead = NULL match = CODING_PATTERN.search(look_ahead) if match is None: self.coding = 'ascii' else: self.coding = match.group(1) self.rewind() # 2006 Dec 05 return def rewind(self): # 2006 Dec 05 self.ndx = ZERO self.end = len(self.lines) - 1 return self def next(self): # 2006 Dec 05 if self.ndx > self.end: raise StopIteration elif self.ndx == self.end: result = self.lines[self.ndx] else: result = self.lines[self.ndx] + '\n' self.ndx += 2 return result def __iter__(self): # 2006 Dec 05 return self def readline(self): # 2006 Dec 05 try: result = self.next() except StopIteration: result = NULL return result def readlines(self): # 2006 Dec 05 self.rewind() return [line for line in self] def __str__(self): # 2006 Dec 05 result = self.readlines() while result[:-1] == NULL: result.pop(-1) last_line = result[-1] if last_line[:-1] == '\n': # 2007 Mar 07 pass else: last_line += '\n' result[-1] = last_line return NULL.join(result) def decode(self, str): return str # It will not do to feed Unicode to *compiler.parse*. class OutputUnit(object): """Line-buffered wrapper for sys.stdout. """ def __init__(self, file_out): object.__init__(self) self.is_file_like = hasattr(file_out, 'write') # 2007 Jan 22 if self.is_file_like: self.unit = codecs.getwriter(CODING)(file_out) else: self.unit = codecs.open(os.path.expanduser(file_out), 'wb', CODING) self.blank_line_count = 1 self.margin = LEFT_MARGIN self.newline = INPUT.newline # 2006 Dec 05 self.lineno = ZERO # 2006 Dec 14 self.buffer = NULL self.chunks = None # 2009 Oct 26 return def close(self): # 2006 Dec 01 self.unit.write(self.buffer) # 2007 Jan 22 if self.is_file_like: pass else: self.unit.close() return self def line_init(self, indent=ZERO, lineno=ZERO): self.blank_line_count = ZERO self.col = ZERO if DEBUG: margin = '%5i %s' % (lineno, INDENTATION * indent) else: margin = self.margin + INDENTATION * indent self.tab_stack = [] self.tab_set(len(margin) + len(INDENTATION)) self.chunks = [] self.line_more(margin) return self def line_more( self, chunk=NULL, tab_set=False, tab_clear=False, can_split_str=False, can_split_after=False, can_break_after=False, ): # 2007 Mar 06 self.chunks.append([ chunk, tab_set, tab_clear, can_split_str, can_split_after, can_break_after, ]) self.col += len(chunk) return self def line_term(self, pause=False): # 2007 May 25 def is_split_needed(cumulative_width): pos = self.pos return ((pos + cumulative_width) > COL_LIMIT) and (pos > ZERO) # 2007 May 01 def drop_word(chunk, can_split_after): # 2007 May 23 result = COL_LIMIT - self.pos if can_split_after: result -= 1 else: result -= 2 ndx = result - 1 while (ndx >= 20) and ((result - ndx) <= 20): if chunk[ndx] in [SPACE]: result = ndx + 1 break ndx -= 1 return result self.pos = ZERO can_split_before = False can_break_before = False cumulative_width = ZERO chunk_lengths = [] self.chunks.reverse() for ( chunk, tab_set, tab_clear, can_split_str, can_split_after, can_break_after, ) in self.chunks: # 2007 May 01 if can_split_after or can_break_after: cumulative_width = ZERO cumulative_width += len(chunk) chunk_lengths.insert(ZERO, [ chunk, cumulative_width, tab_set, tab_clear, can_split_str, can_split_after, can_break_after, ]) for ( chunk, cumulative_width, tab_set, tab_clear, can_split_str, can_split_after, can_break_after, ) in chunk_lengths: # 2007 May 01 if is_split_needed(cumulative_width): if can_split_before: self.line_split() elif can_break_before: self.line_break() if can_split_str: # 2007 Mar 06 quote = chunk[:1] while is_split_needed(len(chunk)): take = drop_word(chunk, can_split_after) # 2007 May 23 if take < 20: break self.put(chunk[:take] + quote) chunk = quote + chunk[take:] if can_split_after: self.line_split() else: self.line_break() self.put(chunk) else: self.put(chunk) # 2006 Dec 14 self.pos += len(chunk) if tab_set: self.tab_set(self.pos) if tab_clear: self.tab_clear() can_split_before = can_split_after can_break_before = can_break_after if pause: # 2007 May 25 pass else: self.put(self.newline) # 2006 Dec 05 return self def line_split(self): self.put(self.newline) # 2006 Dec 05 self.pos = self.tab_forward() return self def line_break(self): self.put('\\%s' % self.newline) # 2006 Dec 14 self.pos = self.tab_forward() return self def tab_forward(self): if len(self.tab_stack) > 1: col = (self.tab_stack)[1] else: col = (self.tab_stack)[ZERO] self.put(SPACE * col) # 2006 Dec 14 return col def put(self, text): # 2006 Dec 14 self.lineno += text.count(self.newline) self.buffer += text # 2007 Jan 22 if self.buffer.endswith('\n') or self.buffer.endswith('\r'): # 2008 Jan 30 self.unit.write(self.buffer.rstrip()) self.unit.write(self.newline) # 2008 Jan 30 self.buffer = NULL return self def put_blank_line(self, trace, count=1): count -= self.blank_line_count while count > ZERO: self.put(BLANK_LINE) # 2006 Dec 14 self.put(self.newline) # 2006 Dec 05 if DEBUG: self.put('blank(%s)' % str(trace)) # 2006 Dec 14 self.blank_line_count += 1 count -= 1 return self def tab_set(self, col): if col > COL_LIMIT / 2: if self.tab_stack: # 2008 Jan 06 col = (self.tab_stack)[-1] + 4 else: col = 4 self.tab_stack.append(col) return self def tab_clear(self): if len(self.tab_stack) > 1: result = self.tab_stack.pop() else: result = None return result def inc_margin(self): self.margin += INDENTATION return self def dec_margin(self): self.margin = (self.margin)[:-len(INDENTATION)] return self class Comments(dict): """Collection of comments (blank lines) parsed out of the input Python code and indexed by line number. """ def __init__(self): def quote_original(token_type, original): # 2007 May 01 if token_type in [tokenize.STRING]: if DOUBLE_QUOTED_STRINGS: result = force_quote(original, double=True) elif SINGLE_QUOTED_STRINGS: result = force_quote(original, double=False) else: result = original else: result = original return result def compensate_for_tabs(line, scol): # 2007 May 25 match = COMMENT_PATTERN.match(line) if match is None: pass else: margin = match.group(1) tab_count = margin.count('\t') scol += (len(INDENTATION) - 1) * tab_count return scol self.literal_pool = {} # 2007 Jan 14 lines = tokenize.generate_tokens(INPUT.readline) for (token_type, token_string, start, end, line) in lines: if DEBUG: print (token.tok_name)[token_type], token_string, start, \ end, line (self.max_lineno, scol) = start (erow, ecol) = end if token_type in [tokenize.COMMENT, tokenize.NL]: original = token_string original = original.decode(INPUT.coding) original = original.replace('\t', DOC_TAB_REPLACEMENT) # 2007 May 24 original = original.strip() if SHEBANG_PATTERN.match(original) is not None: pass elif CODING_PATTERN.search(original) is not None and \ self.max_lineno <= 2: pass else: scol = compensate_for_tabs(line, scol) # 2007 May 25 original = COMMENT_PATTERN.sub(NULL, original, 1) # 2007 May 25 if (token_type in [tokenize.COMMENT]) and (original in [NULL]): original = SPACE if self.max_lineno in self: # 2009 Jun 29 pass else: self[self.max_lineno] = [scol, original] elif token_type in [tokenize.NUMBER, tokenize.STRING]: # 2007 Jan 14 try: original = token_string.strip().decode(INPUT.coding, 'backslashreplace') decoded = eval(original) # 2007 May 01 encoded = repr(decoded) if (encoded == original) or (encoded == force_quote(original, double=False)): pass else: original = quote_original(token_type, original) # 2007 May 01 original_values = \ self.literal_pool.setdefault(encoded, []) # 2010 Mar 10 for (tok, lineno) in original_values: # 2007 Jan 17 if tok == original: break else: original_values.append([original, self.max_lineno]) except: pass self.prev_lineno = -2 # 2010 Mar 10 self[self.prev_lineno] = (NA, SHEBANG) # 2007 May 25 self[NA] = (NA, CODING_SPEC) # 2007 May 25 return def merge(self, lineno=None, fin=False): def is_blank(): return token_string in [NULL, BLANK_LINE] def is_blank_line_needed(): return ADD_BLANK_LINES_AROUND_COMMENTS and not (is_blank() and KEEP_BLANK_LINES) def margin(scol): (quotient, remainder) = divmod(scol, len(INDENTATION)) result = INDENTATION * quotient + SPACE * remainder + COMMENT_PREFIX return result def strip_blank_lines(text_lines): first = NA last = NA is_first_blank = False is_last_blank = False if text_lines: first = ZERO (scol, line) = text_lines[first] is_first_blank = (scol == NA) if is_first_blank: first += 1 last = len(text_lines) (scol, line) = text_lines[last - 1] is_last_blank = (scol == NA) if is_last_blank: last -= 1 return (first, last, is_first_blank, is_last_blank) if fin: lineno = self.max_lineno + 1 on1 = True text=[] # 2007 May 25 while self.prev_lineno < lineno: if self.prev_lineno in self: (scol, token_string) = self[self.prev_lineno] if on1 and is_blank_line_needed(): OUTPUT.put_blank_line(1) if is_blank(): if KEEP_BLANK_LINES: # OUTPUT.put_blank_line(2) text.append([NA, NULL]) # 2007 May 25 else: if scol == NA: # 2007 May 25 # Output the Shebang and Coding-Spec. OUTPUT.line_init().line_more(token_string).line_term() else: text.append([scol, token_string]) # 2007 May 25 on1 = False self.prev_lineno += 1 if text and LEFTJUST_DOC_STRINGS: # 2007 May 25 (first, last, is_first_blank, is_last_blank) = strip_blank_lines(text) lines = [line for (scol, line) in text[first: last]] lines = leftjust_lines(lines) text = [(ZERO, line) for line in lines] if is_first_blank: text.insert(ZERO, [NA, NULL]) if is_last_blank: text.append([NA, NULL]) if text and WRAP_DOC_STRINGS: # 2007 May 25 (first, last, is_first_blank, is_last_blank) = strip_blank_lines(text) text = text[first: last] if text: (save_col, line) = text[ZERO] lines = [line for (scol, line) in text] line_length = COL_LIMIT - (save_col + len(COMMENT_PREFIX)) line_length = max(line_length, 20) lines = wrap_lines(lines, width=line_length) text = [(save_col, line) for line in lines] if is_first_blank: text.insert(ZERO, [NA, NULL]) if is_last_blank: text.append([NA, NULL]) for (scol, line) in text: # 2007 May 25 if scol == NA: OUTPUT.put_blank_line(2) else: OUTPUT.line_init() margin_string = margin(scol) if (margin_string == '# ') and (line.startswith('#')): # 2010 Mar 10 OUTPUT.line_more('#') # 2010 Mar 10 else: OUTPUT.line_more(margin(scol)) OUTPUT.line_more(line) OUTPUT.line_term() if text and is_blank_line_needed() and not fin: OUTPUT.put_blank_line(3) return self def put_inline(self, lineno): def margin(scol): result = SPACE * scol + COMMENT_PREFIX return result def new_line(): OUTPUT.put(OUTPUT.newline) return text=[] # 2007 May 25 while self.prev_lineno <= lineno: if self.prev_lineno in self: (scol, token_string) = self[self.prev_lineno] if token_string in [NULL]: pass else: text.append(token_string) # 2007 May 25 self.prev_lineno += 1 OUTPUT.line_term(pause=True) # 2007 May 25 col = OUTPUT.pos + 2 if WRAP_DOC_STRINGS: line_length = COL_LIMIT - (col + len(COMMENT_PREFIX)) line_length = max(line_length, 20) text = wrap_lines(text, width=line_length) for line in text[:1]: OUTPUT.put(SPACE * 2) OUTPUT.put(COMMENT_PREFIX) OUTPUT.put(line) new_line() for line in text[1:]: OUTPUT.line_init() OUTPUT.line_more(margin(col)) OUTPUT.line_more(line) OUTPUT.line_term() if text: pass else: new_line() return self class Name(list): # 2006 Dec 14 """Maps new name to old names. """ def __init__(self, new): self.new = new self.is_reported = False return def append(self, item): if item in self: pass else: list.append(self, item) return def rept_collision(self, key): self.append(key) # 2006 Dec 17 if len(self) == 1: pass elif self.is_reported: pass else: sys.stderr.write("Error: %s ambiguously replaced by '%s' at line %i.\n" % \ (str(self), self.new, OUTPUT.lineno + 1)) self.is_reported = True return self def rept_external(self, expr): if isinstance(expr, NodeName): expr = expr.name.str else: expr = str(expr) if expr in ['self','cls']: pass elif self.new == self[ZERO]: pass else: sys.stderr.write("Warning: '%s.%s,' defined elsewhere, replaced by '.%s' at line %i.\n" % \ (expr, self[ZERO], self.new, OUTPUT.lineno + 1)) return self class NameSpace(list): """Dictionary of names (variables). Actually a list of dictionaries. The current scope is the top one (ZEROth member). """ def push_scope(self): self.insert(ZERO, {}) return self def pop_scope(self): return self.pop(ZERO) def make_name(self, name, rules): name = name.get_as_str() key = name for rule in rules: name = rule(name) name = self[ZERO].setdefault(name,Name(name)) # 2006 Dec 14 self[ZERO].setdefault(key,name) name.append(key) return name def make_local_name(self, name): if self.is_global(): result = self.make_global_name(name) else: result = self.make_name(name, LOCAL_NAME_SCRIPT) return result def make_global_name(self, name): return self.make_name(name, GLOBAL_NAME_SCRIPT) def make_class_name(self, name): return self.make_name(name, CLASS_NAME_SCRIPT) def make_function_name(self, name): return self.make_name(name, FUNCTION_NAME_SCRIPT) def make_formal_param_name(self, name): return self.make_name(name, FORMAL_PARAM_NAME_SCRIPT) def make_imported_name(self, name): return self.make_name(name, []) def make_attr_name(self, expr, name): if isinstance(expr, NodeName): # 2006 Dec 19 module = expr.name.str else: module = None name = name.get_as_str() key = name for rule in ATTR_NAME_SCRIPT: name = rule(name, module=module) # 2006 Dec 19 name = Name(name) # 2006 Dec 14 name.append(key) name.rept_external(expr) return name.new def make_keyword_name(self, name): name = name.get_as_str() key = name for rule in FORMAL_PARAM_NAME_SCRIPT: name = rule(name) name = Name(name) # 2006 Dec 14 name.append(key) return name.new def get_name(self, node): name = key = node.get_as_str() # 2006 Dec 17 for scope in self: if key in scope: name = scope[key] name.rept_collision(key) # 2006 Dec 14 name = name.new break return name def has_name(self, node): name = node.get_as_str() return name in self[ZERO] def is_global(self): return len(self) == 1 def transform(indent, lineno, node): """Convert the nodes in the abstract syntax tree returned by the *compiler* module to objects with *put* methods. The kinds of nodes are a Python Version Dependency. """ def isinstance_(node, class_name): # 2006 Nov 30 """Safe check against name of a node class rather than the class itself, which may or may not be supported at the current Python version. """ class_ = getattr(compiler.ast, class_name, None) if class_ is None: result = False else: result = isinstance(node, class_) return result if isinstance_(node, 'Node') and node.lineno is not None: lineno = node.lineno if isinstance_(node, 'Add'): result = NodeAdd(indent, lineno, node.left, node.right) elif isinstance_(node, 'And'): result = NodeAnd(indent, lineno, node.nodes) elif isinstance_(node, 'AssAttr'): result = NodeAsgAttr(indent, lineno, node.expr, node.attrname, node.flags) elif isinstance_(node, 'AssList'): result = NodeAsgList(indent, lineno, node.nodes) elif isinstance_(node, 'AssName'): result = NodeAsgName(indent, lineno, node.name, node.flags) elif isinstance_(node, 'AssTuple'): result = NodeAsgTuple(indent, lineno, node.nodes) elif isinstance_(node, 'Assert'): result = NodeAssert(indent, lineno, node.test, node.fail) elif isinstance_(node, 'Assign'): result = NodeAssign(indent, lineno, node.nodes, node.expr) elif isinstance_(node, 'AugAssign'): result = NodeAugAssign(indent, lineno, node.node, node.op, node.expr) elif isinstance_(node, 'Backquote'): result = NodeBackquote(indent, lineno, node.expr) elif isinstance_(node, 'Bitand'): result = NodeBitAnd(indent, lineno, node.nodes) elif isinstance_(node, 'Bitor'): result = NodeBitOr(indent, lineno, node.nodes) elif isinstance_(node, 'Bitxor'): result = NodeBitXor(indent, lineno, node.nodes) elif isinstance_(node, 'Break'): result = NodeBreak(indent, lineno) elif isinstance_(node, 'CallFunc'): result = NodeCallFunc(indent, lineno, node.node, node.args, node.star_args, node.dstar_args) elif isinstance_(node, 'Class'): result = NodeClass(indent, lineno, node.name, node.bases, node.doc, node.code) elif isinstance_(node, 'Compare'): result = NodeCompare(indent, lineno, node.expr, node.ops) elif isinstance_(node, 'Const'): result = NodeConst(indent, lineno, node.value) elif isinstance_(node, 'Continue'): result = NodeContinue(indent, lineno) elif isinstance_(node, 'Decorators'): result = NodeDecorators(indent, lineno, node.nodes) elif isinstance_(node, 'Dict'): result = NodeDict(indent, lineno, node.items) elif isinstance_(node, 'Discard'): result = NodeDiscard(indent, lineno, node.expr) elif isinstance_(node, 'Div'): result = NodeDiv(indent, lineno, node.left, node.right) elif isinstance_(node, 'Ellipsis'): result = NodeEllipsis(indent, lineno) elif isinstance_(node, 'Exec'): result = NodeExec(indent, lineno, node.expr, node.locals, node.globals) elif isinstance_(node, 'FloorDiv'): result = NodeFloorDiv(indent, lineno, node.left, node.right) elif isinstance_(node, 'For'): result = NodeFor(indent, lineno, node.assign, node.list, node.body, node.else_) elif isinstance_(node, 'From'): result = NodeFrom(indent, lineno, node.modname, node.names) elif isinstance_(node, 'Function'): result = NodeFunction( indent, lineno, getattr(node, 'decorators', None), node.name, node.argnames, node.defaults, node.flags, node.doc, node.code, ) elif isinstance_(node, 'GenExpr'): result = NodeGenExpr(indent, lineno, node.code) elif isinstance_(node, 'GenExprFor'): result = NodeGenExprFor(indent, lineno, node.assign, node.iter, node.ifs) elif isinstance_(node, 'GenExprIf'): result = NodeGenExprIf(indent, lineno, node.test) elif isinstance_(node, 'GenExprInner'): result = NodeGenExprInner(indent, lineno, node.expr, node.quals) elif isinstance_(node, 'Getattr'): result = NodeGetAttr(indent, lineno, node.expr, node.attrname) elif isinstance_(node, 'Global'): result = NodeGlobal(indent, lineno, node.names) elif isinstance_(node, 'If'): result = NodeIf(indent, lineno, node.tests, node.else_) elif isinstance_(node, 'IfExp'): result = NodeIfExp(indent, lineno, node.test, node.then, node.else_) elif isinstance_(node, 'Import'): result = NodeImport(indent, lineno, node.names) elif isinstance_(node, 'Invert'): result = NodeInvert(indent, lineno, node.expr) elif isinstance_(node, 'Keyword'): result = NodeKeyword(indent, lineno, node.name, node.expr) elif isinstance_(node, 'Lambda'): result = NodeLambda(indent, lineno, node.argnames, node.defaults, node.flags, node.code) elif isinstance_(node, 'LeftShift'): result = NodeLeftShift(indent, lineno, node.left, node.right) elif isinstance_(node, 'List'): result = NodeList(indent, lineno, node.nodes) elif isinstance_(node, 'ListComp'): result = NodeListComp(indent, lineno, node.expr, node.quals) elif isinstance_(node, 'ListCompFor'): result = NodeListCompFor(indent, lineno, node.assign, node.list, node.ifs) elif isinstance_(node, 'ListCompIf'): result = NodeListCompIf(indent, lineno, node.test) elif isinstance_(node, 'Mod'): result = NodeMod(indent, lineno, node.left, node.right) elif isinstance_(node, 'Module'): result = NodeModule(indent, lineno, node.doc, node.node) elif isinstance_(node, 'Mul'): result = NodeMul(indent, lineno, node.left, node.right) elif isinstance_(node, 'Name'): result = NodeName(indent, lineno, node.name) elif isinstance_(node, 'Not'): result = NodeNot(indent, lineno, node.expr) elif isinstance_(node, 'Or'): result = NodeOr(indent, lineno, node.nodes) elif isinstance_(node, 'Pass'): result = NodePass(indent, lineno) elif isinstance_(node, 'Power'): result = NodePower(indent, lineno, node.left, node.right) elif isinstance_(node, 'Print'): result = NodePrint(indent, lineno, node.nodes, node.dest) elif isinstance_(node, 'Printnl'): result = NodePrintnl(indent, lineno, node.nodes, node.dest) elif isinstance_(node, 'Raise'): result = NodeRaise(indent, lineno, node.expr1, node.expr2, node.expr3) elif isinstance_(node, 'Return'): result = NodeReturn(indent, lineno, node.value) elif isinstance_(node, 'RightShift'): result = NodeRightShift(indent, lineno, node.left, node.right) elif isinstance_(node, 'Slice'): result = NodeSlice(indent, lineno, node.expr, node.flags, node.lower, node.upper) elif isinstance_(node, 'Sliceobj'): result = NodeSliceobj(indent, lineno, node.nodes) elif isinstance_(node, 'Stmt'): result = NodeStmt(indent, lineno, node.nodes) elif isinstance_(node, 'Sub'): result = NodeSub(indent, lineno, node.left, node.right) elif isinstance_(node, 'Subscript'): result = NodeSubscript(indent, lineno, node.expr, node.flags, node.subs) elif isinstance_(node, 'TryExcept'): result = NodeTryExcept(indent, lineno, node.body, node.handlers, node.else_) elif isinstance_(node, 'TryFinally'): result = NodeTryFinally(indent, lineno, node.body, node.final) elif isinstance_(node, 'Tuple'): result = NodeTuple(indent, lineno, node.nodes) elif isinstance_(node, 'UnaryAdd'): result = NodeUnaryAdd(indent, lineno, node.expr) elif isinstance_(node, 'UnarySub'): result = NodeUnarySub(indent, lineno, node.expr) elif isinstance_(node, 'While'): result = NodeWhile(indent, lineno, node.test, node.body, node.else_) elif isinstance_(node, 'With'): result = NodeWith(indent, lineno, node.expr, node.vars, node.body) elif isinstance_(node, 'Yield'): result = NodeYield(indent, lineno, node.value) elif isinstance(node, basestring): result = NodeStr(indent, lineno, node) elif isinstance(node, int): result = NodeInt(indent, lineno, node) else: result = node return result class Node(object): """Parent of parsed tokens. """ tag = 'Generic node' def __init__(self, indent, lineno): object.__init__(self) self.indent = indent self.lineno = lineno if DEBUG: sys.stderr.write('%5i %s\n' % (self.lineno, self.tag)) return def line_init(self, need_blank_line=ZERO): COMMENTS.merge(self.get_lineno()) OUTPUT.put_blank_line(4, count=need_blank_line) OUTPUT.line_init(self.indent, self.get_lineno()) return self def line_more( self, chunk=NULL, tab_set=False, tab_clear=False, can_split_str=False, can_split_after=False, can_break_after=False, ): OUTPUT.line_more( chunk, tab_set, tab_clear, can_split_str, can_split_after, can_break_after, ) return self def line_term(self, lineno=ZERO): lineno = max(self.get_hi_lineno(), self.get_lineno()) # , lineno) # 2006 Dec 01 COMMENTS.put_inline(lineno) return self def put(self, can_split=False): '''Place self on output. For the "Generic" node, this is abstract. A Generic node *is* instantiated for nodes of unrecognized type, and we don\'t know what to do for them, so we just place a string on output that should force an error when Python is used to interpret the result. ''' self.line_more(' /* %s at line %i */ ' % (self.tag, self.get_lineno())) return self def get_lineno(self): return self.lineno def get_hi_lineno(self): return self.get_lineno() def inc_margin(self): OUTPUT.inc_margin() return self def dec_margin(self): OUTPUT.dec_margin() return self def marshal_names(self): return self def make_local_name(self): return self class NodeOpr(Node): # 2010 Mar 10 tag = 'Opr' def put_expr(self, node, can_split=False, pos=None): if self.is_paren_needed(node, pos): self.line_more('(', tab_set=True) node.put(can_split=True) self.line_more(')', tab_clear=True) else: node.put(can_split=can_split) return self def is_paren_needed(self, node, pos): return type(node) in OPERATOR_TRUMPS[type(self)] class NodeOprAssoc(NodeOpr): # 2010 Mar 10 tag = 'A_Opr' class NodeOprNotAssoc(NodeOpr): # 2010 Mar 10 tag = 'NA_Opr' def is_paren_needed(self, node, pos): if NodeOpr.is_paren_needed(self, node, pos): result = True elif type(node) in OPERATOR_LEVEL[type(self)]: result = True else: result = False return result class NodeOprLeftAssoc(NodeOpr): # 2010 Mar 10 """Left-associative operator. """ tag = 'LA_Opr' def is_paren_needed(self, node, pos): if NodeOpr.is_paren_needed(self, node, pos): result = True elif type(node) in OPERATOR_LEVEL[type(self)]: result = not (pos == 'left') else: result = False return result class NodeOprRightAssoc(NodeOpr): # 2010 Mar 10 """Right-associative operator. """ tag = 'RA_Opr' def is_paren_needed(self, node, pos): if NodeOpr.is_paren_needed(self, node, pos): if type(node) in [NodeUnaryAdd, NodeUnarySub]: result = not (pos == 'right') else: result = True elif type(node) in OPERATOR_LEVEL[type(self)]: result = not (pos == 'right') else: result = False return result class NodeStr(Node): """String value. """ tag = 'Str' def __init__(self, indent, lineno, str): Node.__init__(self, indent, lineno) self.set_as_str(str) return def put(self, can_split=False): self.line_more(self.get_as_str()) return self def get_as_str(self): return self.str def set_as_str(self, str_): self.str = str_ if isinstance(self.str, unicode): pass elif not RECODE_STRINGS: # 2006 Dec 01 pass else: try: self.str = self.str.decode(INPUT.coding) except UnicodeError: pass try: self.str = str(self.str) except UnicodeError: pass return self def get_as_repr(self): # 2007 May 01 original_values = COMMENTS.literal_pool.get(repr(self.get_as_str()), []) # 2010 Mar 10 if len(original_values) == 1: (result, lineno) = original_values[ZERO] else: result = repr(self.get_as_str()) if DOUBLE_QUOTED_STRINGS: result = force_quote(result, double=True) elif SINGLE_QUOTED_STRINGS: result = force_quote(result, double=False) return result def put_doc(self, need_blank_line=ZERO): def fix_newlines(text): # 2010 Mar 10 lines = text.splitlines() result = OUTPUT.newline.join(lines) # 2006 Dec 05 return result doc = self.get_as_repr() # 2010 Mar 10 doc = doc.replace('\t', DOC_TAB_REPLACEMENT) # 2007 May 24 if LEFTJUST_DOC_STRINGS: lines = leftjust_lines(doc.strip().splitlines()) # 2007 May 25 lines.extend([NULL, NULL]) margin = '%s%s' % (OUTPUT.newline, INDENTATION * self.indent) # 2006 Dec 05 doc = margin.join(lines) if WRAP_DOC_STRINGS: # 2007 May 25 margin = '%s%s' % (OUTPUT.newline, INDENTATION * self.indent) # 2006 Dec 05 line_length = COL_LIMIT - (len(INDENTATION) * self.indent) line_length = max(line_length, 20) lines = wrap_lines(doc.strip().splitlines(), width=line_length) lines.extend([NULL, NULL]) doc = margin.join(lines) self.line_init(need_blank_line=need_blank_line) # 2006 Dec 01 doc = fix_newlines(doc) # 2010 Mar 10 self.put_multi_line(doc) self.line_term() OUTPUT.put_blank_line(5) return self def put_lit(self, can_split=False): lit = self.get_as_repr() # 2007 May 01 match = QUOTE_PATTERN.match(lit) # 2009 Feb 05 (prefix, quote) = match.group(1, 2) if ('r' in prefix.lower()): # 2009 Feb 05 self.line_more(lit, can_split_str=CAN_SPLIT_STRINGS, can_split_after=can_split) else: lines = NEW_LINE_PATTERN.split(lit) if len(lines) > MAX_LINES_BEFORE_SPLIT_LIT: lit = OUTPUT.newline.join(lines) # 2006 Dec 05 self.put_multi_line(lit) else: self.line_more(lit, can_split_str=CAN_SPLIT_STRINGS, can_split_after=can_split) return self def put_multi_line(self, lit): # 2006 Dec 01 match = QUOTE_PATTERN.match(lit) (prefix, quote) = match.group(1, 2) # 2007 May 01 if len(quote) == 3: # 2006 Jan 14 head = prefix + quote tail = NULL else: head = prefix + quote * 3 tail = quote * 2 lit = QUOTE_PATTERN.sub(head, lit, 1) + tail self.line_more(lit, can_split_str=False) # 2007 May 23 return self class NodeInt(Node): """Integer value. """ tag = 'Int' def __init__(self, indent, lineno, int): Node.__init__(self, indent, lineno) self.int = int return def put(self, can_split=False): self.line_more(self.get_as_repr()) return self def get_as_repr(self): original_values = COMMENTS.literal_pool.get(repr(self.int), []) # 2010 Mar 10 if len(original_values) == 1: (result, lineno) = original_values[ZERO] else: result = repr(self.int) return result class NodeAdd(NodeOprAssoc): # 2010 Mar 10 """Add operation. """ tag = 'Add' def __init__(self, indent, lineno, left, right): Node.__init__(self, indent, lineno) self.left = transform(indent, lineno, left) self.right = transform(indent, lineno, right) return def put(self, can_split=False): self.put_expr(self.left, can_split=can_split) self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('+ ') self.put_expr(self.right, can_split=can_split) return self def get_hi_lineno(self): return self.right.get_hi_lineno() class NodeAnd(NodeOprAssoc): # 2010 Mar 10 '''Logical "and" operation. ''' tag = 'And' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False): for node in (self.nodes)[:1]: self.put_expr(node, can_split=can_split) for node in (self.nodes)[1:]: self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('and ') self.put_expr(node, can_split=can_split) return self def get_hi_lineno(self): return (self.nodes)[-1].get_hi_lineno() class NodeAsgAttr(NodeOpr): """Assignment to a class attribute. """ tag = 'AsgAttr' def __init__(self, indent, lineno, expr, attrname, flags): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) self.attrname = transform(indent, lineno, attrname) self.flags = transform(indent, lineno, flags) return def put(self, can_split=False): is_del = self.flags.get_as_str() in ['OP_DELETE'] if is_del: self.line_init() self.line_more('del ') if isinstance(self.expr, NodeConst): if self.expr.is_str(): # 2007 May 01 self.expr.put() else: self.line_more('(') self.expr.put(can_split=True) self.line_more(')') else: self.put_expr(self.expr, can_split=can_split) self.line_more('.') self.line_more(NAME_SPACE.make_attr_name(self.expr, self.attrname)) if DEBUG: self.line_more(' /* AsgAttr flags: ') self.flags.put() self.line_more(' */ ') if is_del: self.line_term() return self def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeAsgList(Node): """A list as a destination of an assignment operation. """ tag = 'AsgList' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False): self.line_more('[', tab_set=True) if len(self.nodes) > MAX_SEPS_SERIES: # 2007 May 24 self.line_term() self.inc_margin() for node in self.nodes: self.line_init() node.put(can_split=True) self.line_more(LIST_SEP) self.line_term() self.line_init() self.dec_margin() else: for node in (self.nodes)[:1]: node.put(can_split=True) self.line_more(LIST_SEP, can_split_after=True) for node in (self.nodes)[1:2]: node.put(can_split=True) for node in (self.nodes)[2:]: self.line_more(LIST_SEP, can_split_after=True) node.put(can_split=True) self.line_more(']', tab_clear=True) return self def make_local_name(self): for node in self.nodes: node.make_local_name() return self def get_hi_lineno(self): return node[-1].get_hi_lineno() class NodeAsgName(Node): """Destination of an assignment operation. """ tag = 'AsgName' def __init__(self, indent, lineno, name, flags): Node.__init__(self, indent, lineno) self.name = transform(indent, lineno, name) self.flags = transform(indent, lineno, flags) return def put(self, can_split=False): is_del = self.flags.get_as_str() in ['OP_DELETE'] if is_del: self.line_init() self.line_more('del ') self.line_more(NAME_SPACE.get_name(self.name)) if DEBUG: self.line_more(' /* AsgName flags: ') self.flags.put() self.line_more(' */ ') if is_del: self.line_term() return self def make_local_name(self): if NAME_SPACE.has_name(self.name): pass else: NAME_SPACE.make_local_name(self.name) return self def get_hi_lineno(self): return self.name.get_hi_lineno() class NodeAsgTuple(Node): """A tuple as a destination of an assignment operation. """ tag = 'AsgTuple' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False, is_paren_required=True): # 2010 Mar 10 if len(self.nodes) > MAX_SEPS_SERIES: # 2007 May 24 self.line_more('(', tab_set=True) # 2010 Mar 10 self.line_term() self.inc_margin() for node in self.nodes: self.line_init() node.put(can_split=True) self.line_more(LIST_SEP) self.line_term() self.line_init() self.dec_margin() self.line_more(')', tab_clear=True) # 2010 Mar 10 elif is_paren_required or PARENTHESIZE_TUPLE_DISPLAY: # 2010 Mar 10 self.line_more('(', tab_set=True) # 2010 Mar 10 for node in (self.nodes)[:1]: node.put(can_split=True) self.line_more(LIST_SEP, can_split_after=True) for node in (self.nodes)[1:2]: node.put(can_split=True) for node in (self.nodes)[2:]: self.line_more(LIST_SEP, can_split_after=True) node.put(can_split=True) self.line_more(')', tab_clear=True) # 2010 Mar 10 else: for node in (self.nodes)[:1]: node.put() self.line_more(LIST_SEP, can_break_after=True) # 2010 Mar 10 for node in (self.nodes)[1:2]: node.put() for node in (self.nodes)[2:]: self.line_more(LIST_SEP, can_break_after=True) # 2010 Mar 10 node.put() return self def make_local_name(self): for node in self.nodes: node.make_local_name() return self def get_hi_lineno(self): return (self.nodes)[-1].get_hi_lineno() class NodeAssert(Node): """Assertion. """ tag = 'Assert' def __init__(self, indent, lineno, test, fail): Node.__init__(self, indent, lineno) self.test = transform(indent, lineno, test) self.fail = transform(indent, lineno, fail) return def put(self, can_split=False): self.line_init() self.line_more('assert ') self.test.put(can_split=can_split) if self.fail is None: pass else: self.line_more(LIST_SEP, can_break_after=True) self.fail.put() self.line_term() return self def get_hi_lineno(self): lineno = self.test.get_hi_lineno() if self.fail is None: pass else: lineno = self.fail.get_hi_lineno() return lineno class NodeAssign(Node): """Set one or more destinations to the value of the expression. """ tag = 'Assign' def __init__(self, indent, lineno, nodes, expr): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] self.expr = transform(indent, lineno, expr) return def put(self, can_split=False): self.line_init() for node in self.nodes: if isinstance(node, NodeAsgTuple): node.put(can_split=can_split, is_paren_required=False) # 2010 Mar 10 else: node.put(can_split=can_split) self.line_more(ASSIGNMENT, can_break_after=True) if isinstance(self.expr, NodeYield): # 2006 Dec 13 self.line_more('(') self.expr.put(can_split=True) self.line_more(')') elif isinstance(self.expr, NodeTuple): self.expr.put(can_split=can_split, is_paren_required=False) # 2010 Mar 10 else: self.expr.put(can_split=can_split) self.line_term() return self def marshal_names(self): for node in self.nodes: node.make_local_name() return self def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeAugAssign(Node): """Augment the destination by the value of the expression. """ tag = 'AugAssign' def __init__(self, indent, lineno, node, op, expr): Node.__init__(self, indent, lineno) self.node = transform(indent, lineno, node) self.op = transform(indent, lineno, op) self.expr = transform(indent, lineno, expr) return def put(self, can_split=False): self.line_init() self.node.put(can_split=can_split) op = ASSIGNMENT.replace('=', self.op.get_as_str()) self.line_more(op, can_break_after=True) self.expr.put(can_split=can_split) self.line_term() return self def marshal_names(self): self.node.make_local_name() return self def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeBackquote(Node): """String conversion a'la *repr*. """ tag = 'Backquote' def __init__(self, indent, lineno, expr): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) return def put(self, can_split=False): self.line_more('`') self.expr.put(can_split=can_split) self.line_more('`') return self def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeBitAnd(NodeOprAssoc): # 2010 Mar 10 '''Bitwise "and" operation (set union). ''' tag = 'BitAnd' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False): for node in (self.nodes)[:1]: self.put_expr(node, can_split=can_split) for node in (self.nodes)[1:]: self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('& ') self.put_expr(node, can_split=can_split) return self def get_hi_lineno(self): return (self.nodes)[-1].get_hi_lineno() class NodeBitOr(NodeOprAssoc): # 2010 Mar 01 '''Bitwise "or" operation (set intersection). ''' tag = 'BitOr' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False): for node in (self.nodes)[:1]: self.put_expr(node, can_split=can_split) for node in (self.nodes)[1:]: self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('| ') self.put_expr(node, can_split=can_split) return self def get_hi_lineno(self): return (self.nodes)[-1].get_hi_lineno() class NodeBitXor(NodeOprAssoc): # 2010 Mar 01 '''Bitwise "xor" operation. ''' tag = 'BitXor' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False): for node in (self.nodes)[:1]: self.put_expr(node, can_split=can_split) for node in (self.nodes)[1:]: self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('^ ') self.put_expr(node, can_split=can_split) return self def get_hi_lineno(self): return (self.nodes)[-1].get_hi_lineno() class NodeBreak(Node): """Escape from a loop. """ tag = 'Break' def __init__(self, indent, lineno): Node.__init__(self, indent, lineno) return def put(self, can_split=False): self.line_init() self.line_more('break') self.line_term() return self class NodeCallFunc(Node): """Function invocation. """ tag = 'CallFunc' def __init__(self, indent, lineno, node, args, star_args, dstar_args): Node.__init__(self, indent, lineno) self.node = transform(indent, lineno, node) self.args = [transform(indent, lineno, arg) for arg in args] self.star_args = transform(indent, lineno, star_args) self.dstar_args = transform(indent, lineno, dstar_args) if len(self.args) == 1: arg = (self.args)[ZERO] if isinstance(arg, NodeGenExpr): arg.need_parens = False return def put(self, can_split=False): def count_seps(): result = len(self.args) if self.star_args is None: pass else: result += 1 if self.dstar_args is None: pass else: result += 1 return result if isinstance(self.node, NodeLambda): self.line_more('(') self.node.put(can_split=True) self.line_more(')') else: self.node.put(can_split=can_split) self.line_more('(', tab_set=True) if count_seps() > MAX_SEPS_FUNC_REF: # 2007 May 24 self.line_term() self.inc_margin() arg_list = [(NULL, arg) for arg in self.args] # 2010 Mar 10 has_stars = False # 2010 Mar 10 if self.star_args is None: pass else: arg_list.append(('*', self.star_args)) has_stars = True if self.dstar_args is None: pass else: arg_list.append(('**', self.dstar_args)) has_stars = True for (sentinel, arg) in arg_list[:-1]: # 2010 Mar 10 self.line_init() self.line_more(sentinel) arg.put(can_split=True) self.line_more(LIST_SEP) self.line_term() for (sentinel, arg) in arg_list[-1:]: # 2010 Mar 10 self.line_init() self.line_more(sentinel) arg.put(can_split=True) if has_stars: pass else: self.line_more(LIST_SEP) self.line_term() self.line_init() self.dec_margin() else: for arg in (self.args)[:-1]: arg.put(can_split=True) self.line_more(FUNCTION_PARAM_SEP, can_split_after=True) for arg in (self.args)[-1:]: arg.put(can_split=True) if self.star_args is None and self.dstar_args is None: pass else: self.line_more(FUNCTION_PARAM_SEP, can_split_after=True) if self.star_args is None: pass else: self.line_more('*') self.star_args.put(can_split=True) if self.dstar_args is None: pass else: self.line_more(FUNCTION_PARAM_SEP, can_split_after=True) if self.dstar_args is None: pass else: self.line_more('**') self.dstar_args.put(can_split=True) self.line_more(')', tab_clear=True) return self def get_lineno(self): return self.node.get_lineno() def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) if self.args: lineno = (self.args)[-1].get_hi_lineno() if self.star_args is None: pass else: lineno = self.star_args.get_hi_lineno() if self.dstar_args is None: pass else: lineno = self.dstar_args.get_hi_lineno() return lineno class NodeClass(Node): """Class declaration. """ tag = 'Class' def __init__(self, indent, lineno, name, bases, doc, code): Node.__init__(self, indent, lineno) self.name = transform(indent, lineno, name) self.bases = [transform(indent, lineno, base) for base in bases] self.doc = transform(indent + 1, lineno, doc) self.code = transform(indent + 1, lineno, code) return def put(self, can_split=False): self.line_init(need_blank_line=2) self.line_more('class ') self.line_more(NAME_SPACE.get_name(self.name)) if self.bases: self.line_more('(') for base in (self.bases)[:1]: base.put(can_split=True) for base in (self.bases)[1:]: self.line_more(LIST_SEP, can_split_after=True) base.put(can_split=True) self.line_more(')') self.line_more(':') self.line_term(self.code.get_lineno() - 1) if self.doc is None: pass else: self.doc.put_doc(need_blank_line=1) OUTPUT.put_blank_line(6) self.push_scope() self.code.marshal_names() self.code.put() self.pop_scope() OUTPUT.put_blank_line(7, count=2) return self def push_scope(self): NAME_SPACE.push_scope() return self def pop_scope(self): NAME_SPACE.pop_scope() return self def marshal_names(self): NAME_SPACE.make_class_name(self.name) return self def get_hi_lineno(self): lineno = self.name.get_hi_lineno() if self.bases: lineno = (self.bases)[-1].get_hi_lineno() return lineno class NodeCompare(NodeOprNotAssoc): """Logical comparison. """ tag = 'Compare' def __init__(self, indent, lineno, expr, ops): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) self.ops = [(op, transform(indent, lineno, ex)) for (op, ex) in ops] return def put(self, can_split=False): self.put_expr(self.expr, can_split=can_split) for (op, ex) in self.ops: self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('%s ' % op) self.put_expr(ex, can_split=can_split) return self def get_hi_lineno(self): (op, ex) = (self.ops)[-1] return ex.get_hi_lineno() class NodeConst(Node): """Literal or expression. """ tag = 'Const' def __init__(self, indent, lineno, value): Node.__init__(self, indent, lineno) self.value = transform(indent, lineno, value) return def put(self, can_split=False): if self.is_str(): # 2007 May 01 self.value.put_lit(can_split=can_split) elif isinstance(self.value, Node): self.value.put(can_split=can_split) else: self.line_more(self.get_as_repr()) # 2007 May 01 return self def is_none(self): return self.value is None def is_str(self): # 2007 May 01 return isinstance(self.value, NodeStr) def get_as_repr(self): # 2007 May 01 original_values = COMMENTS.literal_pool.get(repr(self.value), []) # 2010 Mar 10 if len(original_values) == 1: (result, lineno) = original_values[ZERO] else: result = repr(self.value) return result class NodeContinue(Node): """Start a new trip through a loop. """ tag = 'Continue' def __init__(self, indent, lineno): Node.__init__(self, indent, lineno) return def put(self, can_split=False): self.line_init() self.line_more('continue') self.line_term() return self class NodeDecorators(Node): """Functions that take a class method (the next) and a return callable object, e.g., *classmethod*. """ def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, spacing=ZERO, can_split=False): for node in self.nodes: self.line_init(need_blank_line=spacing) self.line_more('@') node.put(can_split=can_split) self.line_term() spacing = ZERO return self def get_hi_lineno(self): return (self.nodes)[-1].get_hi_lineno() class NodeDict(Node): """Declaration of a map (dictionary). """ tag = 'Dict' def __init__(self, indent, lineno, items): Node.__init__(self, indent, lineno) self.items = [(transform(indent, lineno, key), transform(indent, lineno, value)) for (key, value) in items] return def put(self, can_split=False): def put_item(): key.put(can_split=can_split) self.line_more(DICT_COLON) value.put(can_split=can_split) return self.line_more('{', tab_set=True) if len(self.items) > MAX_SEPS_DICT: # 2007 May 24 self.line_term() self.inc_margin() for (key, value) in self.items: self.line_init() put_item() self.line_more(LIST_SEP) self.line_term() self.line_init() self.dec_margin() else: for (key, value) in (self.items)[:1]: put_item() for (key, value) in (self.items)[1:]: self.line_more(LIST_SEP, can_split_after=True) put_item() self.line_more('}', tab_clear=True) return self def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) if self.items: (key, value) = (self.items)[-1] lineno = value.get_hi_lineno() return lineno class NodeDiscard(Node): """Evaluate an expression (function) without saving the result. """ tag = 'Discard' def __init__(self, indent, lineno, expr): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) return def put(self, can_split=False): if isinstance(self.expr, NodeConst) and (not KEEP_UNASSIGNED_CONSTANTS): # 2010 Mar 10 pass else: self.line_init() self.expr.put(can_split=can_split) self.line_term() return self def marshal_names(self): self.expr.marshal_names() return self def get_lineno(self): return self.expr.get_lineno() def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeDiv(NodeOprLeftAssoc): # 2010 Mar 10 """Division operation. """ tag = 'Div' def __init__(self, indent, lineno, left, right): Node.__init__(self, indent, lineno) self.left = transform(indent, lineno, left) self.right = transform(indent, lineno, right) return def put(self, can_split=False): self.put_expr(self.left, can_split=can_split, pos='left') # 2010 Mar 10 self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('/ ') self.put_expr(self.right, can_split=can_split, pos='right') # 2010 Mar 10 return self def get_hi_lineno(self): return self.right.get_hi_lineno() class NodeEllipsis(Node): tag = 'Ellipsis' def __init__(self, indent, lineno): Node.__init__(self, indent, lineno) return def put(self, can_split=False): self.line_more('...') return self class NodeExec(Node): """Execute a given string of Python code in a specified namespace. """ tag = 'Exec' def __init__(self, indent, lineno, expr, locals, globals): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) self.locals = transform(indent, lineno, locals) self.globals = transform(indent, lineno, globals) return def put(self, can_split=False): self.line_init() self.line_more('exec ') self.expr.put(can_split=can_split) if self.locals is None: pass else: self.line_more(' in ', can_break_after=True) self.locals.put(can_split=can_split) if self.globals is None: pass else: self.line_more(LIST_SEP, can_break_after=True) self.globals.put(can_split=can_split) self.line_term() return self def get_hi_lineno(self): lineno = self.expr.get_hi_lineno() if self.locals is None: pass else: lineno = self.locals.get_hi_lineno() if self.globals is None: pass else: lineno = self.globals.get_hi_lineno() return lineno class NodeFor(Node): """For loop. """ tag = 'For' def __init__(self, indent, lineno, assign, list, body, else_): Node.__init__(self, indent, lineno) self.assign = transform(indent, lineno, assign) self.list = transform(indent, lineno, list) self.body = transform(indent + 1, lineno, body) self.else_ = transform(indent + 1, lineno, else_) return def put(self, can_split=False): self.line_init() self.line_more('for ') if isinstance(self.assign, NodeAsgTuple): self.assign.put(can_split=can_split, is_paren_required=False) # 2010 Mar 10 else: self.assign.put(can_split=can_split) self.line_more(' in ', can_break_after=True) if isinstance(self.list, NodeTuple): self.list.put(can_split=can_split, is_paren_required=False) # 2010 Mar 10 else: self.list.put(can_split=can_split) self.line_more(':') self.line_term(self.body.get_lineno() - 1) self.body.put() if self.else_ is None: pass else: self.line_init() self.line_more('else:') self.line_term(self.else_.get_lineno() - 1) self.else_.put() return self def marshal_names(self): self.assign.make_local_name() self.body.marshal_names() if self.else_ is None: pass else: self.else_.marshal_names() return self def get_hi_lineno(self): return self.list.get_hi_lineno() class NodeFloorDiv(NodeOprLeftAssoc): # 2010 Mar 10 """Floor division operation. """ tag = 'FloorDiv' def __init__(self, indent, lineno, left, right): Node.__init__(self, indent, lineno) self.left = transform(indent, lineno, left) self.right = transform(indent, lineno, right) return def put(self, can_split=False): self.put_expr(self.left, can_split=can_split, pos='left') # 2010 Mar 10 self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('// ') self.put_expr(self.right, can_split=can_split, pos='right') # 2010 Mar 10 return self def get_hi_lineno(self): return self.right.get_hi_lineno() class NodeFrom(Node): """Import a name space. """ tag = 'From' def __init__(self, indent, lineno, modname, names): Node.__init__(self, indent, lineno) self.modname = transform(indent, lineno, modname) self.names = [(transform(indent, lineno, identifier), transform(indent, lineno, name)) for (identifier, name) in names] return def put(self, can_split=False): def put_name(): identifier.put(can_split=can_split) if name is None: pass else: self.line_more(' as ') name.put(can_split=can_split) return self.line_init() self.line_more('from ') self.modname.put(can_split=can_split) self.line_more(' import ') for (identifier, name) in (self.names)[:-1]: put_name() self.line_more(LIST_SEP, can_break_after=True) for (identifier, name) in (self.names)[-1:]: put_name() self.line_term() return self def marshal_names(self): for (identifier, name) in self.names: if name is None: NAME_SPACE.make_imported_name(identifier) else: NAME_SPACE.make_local_name(name) return self def get_hi_lineno(self): (identifier, name) = (self.names)[-1] lineno = identifier.get_hi_lineno() if name is None: pass else: lineno = name.get_hi_lineno() return lineno class NodeFunction(Node): """Function declaration. """ tag = 'Function' def __init__( self, indent, lineno, decorators, name, argnames, defaults, flags, doc, code, ): Node.__init__(self, indent, lineno) self.decorators = transform(indent, lineno, decorators) self.name = transform(indent, lineno, name) self.argnames = self.walk(argnames, self.xform) self.defaults = [transform(indent, lineno, default) for default in defaults] self.flags = transform(indent, lineno, flags) self.doc = transform(indent + 1, lineno, doc) self.code = transform(indent + 1, lineno, code) return def walk(self, tuple_, func, need_tuple=False): if isinstance(tuple_, tuple) or isinstance(tuple_, list): result = [self.walk(item, func, need_tuple) for item in tuple_] if need_tuple: result = tuple(result) else: result = func(tuple_) return result def xform(self, node): result = transform(self.indent, self.lineno, node) return result def pair_up(self, args, defaults): args = args[:] # This function manipulates its arguments defaults = defaults[:] # destructively, so make copies first. stars = [] args.reverse() defaults.reverse() is_excess_positionals = self.flags.int & 4 is_excess_keywords = self.flags.int & 8 if is_excess_positionals == ZERO: pass else: stars.insert(ZERO, '*') defaults.insert(ZERO, None) if is_excess_keywords == ZERO: pass else: stars.insert(ZERO, '**') defaults.insert(ZERO, None) result = map(None, args, defaults, stars) result.reverse() return result def put_parm(self, arg, default, stars, can_split=True): if stars is None: pass else: self.line_more(stars) tuple_ = self.walk(arg, NAME_SPACE.get_name, need_tuple=True) tuple_ = str(tuple_) tuple_ = tuple_.replace("'", NULL).replace(',)', ', )') self.line_more(tuple_) if default is None: pass else: self.line_more(FUNCTION_PARAM_ASSIGNMENT) default.put(can_split=can_split) return def put(self, can_split=False): if NAME_SPACE.is_global(): spacing = 2 else: spacing = 1 if self.decorators is None: pass else: self.decorators.put(spacing) spacing = ZERO self.line_init(need_blank_line=spacing) self.line_more('def ') self.line_more(NAME_SPACE.get_name(self.name)) self.push_scope() parms = self.pair_up(self.argnames, self.defaults) for (arg, default, stars) in parms: self.walk(arg, NAME_SPACE.make_formal_param_name) self.code.marshal_names() self.line_more('(', tab_set=True) if len(parms) > MAX_SEPS_FUNC_DEF: # 2007 May 24 self.line_term() self.inc_margin() for (arg, default, stars) in parms[:-1]: self.line_init() self.put_parm(arg, default, stars) self.line_more(FUNCTION_PARAM_SEP) self.line_term() for (arg, default, stars) in parms[-1:]: self.line_init() self.put_parm(arg, default, stars) if stars is None: # 2006 Dec 17 self.line_more(FUNCTION_PARAM_SEP) self.line_term() self.line_init() self.dec_margin() else: for (arg, default, stars) in parms[:1]: self.put_parm(arg, default, stars) for (arg, default, stars) in parms[1:]: self.line_more(FUNCTION_PARAM_SEP, can_split_after=True) self.put_parm(arg, default, stars) self.line_more('):', tab_clear=True) if DEBUG: self.line_more(' /* Function flags: ') self.flags.put() self.line_more(' */ ') self.line_term(self.code.get_lineno() - 1) if self.doc is None: pass else: self.doc.put_doc() self.code.put() self.pop_scope() OUTPUT.put_blank_line(8, count=spacing) return self def push_scope(self): NAME_SPACE.push_scope() return self def pop_scope(self): NAME_SPACE.pop_scope() return self def marshal_names(self): NAME_SPACE.make_function_name(self.name) return self class NodeLambda(NodeFunction): tag = 'Lambda' def __init__(self, indent, lineno, argnames, defaults, flags, code): NodeFunction.__init__( self, indent, lineno, None, None, argnames, defaults, flags, None, code, ) return def put(self, can_split=False): self.line_more('lambda ') self.push_scope() parms = self.pair_up(self.argnames, self.defaults) for (arg, default, stars) in parms: self.walk(arg, NAME_SPACE.make_formal_param_name) for (arg, default, stars) in parms[:1]: self.put_parm(arg, default, stars, can_split=False) for (arg, default, stars) in parms[1:]: self.line_more(FUNCTION_PARAM_SEP, can_break_after=True) self.put_parm(arg, default, stars, can_split=False) self.line_more(': ', can_break_after=True) if DEBUG: self.line_more(' /* Function flags: ') self.flags.put() self.line_more(' */ ') self.code.put() self.pop_scope() return self def get_hi_lineno(self): return self.code.get_hi_lineno() def marshal_names(self): return self class NodeGenExpr(Node): """Generator expression, which needs its own parentheses. """ tag = 'GenExpr' def __init__(self, indent, lineno, code): Node.__init__(self, indent, lineno) self.code = transform(indent, lineno, code) self.need_parens = True return def put(self, can_split=False): if self.need_parens: self.line_more('(') self.code.put(can_split=True) if self.need_parens: self.line_more(')') return self def get_hi_lineno(self): return self.code.get_hi_lineno() class NodeGenExprInner(Node): """Generator expression inside parentheses. """ tag = 'GenExprInner' def __init__(self, indent, lineno, expr, quals): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) self.quals = [transform(indent, lineno, qual) for qual in quals] return def put(self, can_split=False): self.push_scope() self.marshal_names() self.expr.put(can_split=can_split) for qual in self.quals: qual.put(can_split=can_split) self.pop_scope() return self def push_scope(self): NAME_SPACE.push_scope() return self def pop_scope(self): NAME_SPACE.pop_scope() return self def marshal_names(self): for qual in self.quals: qual.marshal_names() return self def get_hi_lineno(self): lineno = (self.quals)[-1].get_hi_lineno() return lineno class NodeGenExprFor(Node): '''"For" of a generator expression. ''' tag = 'GenExprFor' def __init__(self, indent, lineno, assign, list, ifs): Node.__init__(self, indent, lineno) self.assign = transform(indent, lineno, assign) self.list = transform(indent, lineno, list) self.ifs = [transform(indent, lineno, if_) for if_ in ifs] return def put(self, can_split=False): self.line_more(SPACE, can_split_after=True) self.line_more('for ') self.assign.put(can_split=can_split) self.line_more(' in ', can_split_after=True) self.list.put(can_split=can_split) for if_ in self.ifs: if_.put(can_split=can_split) return self def marshal_names(self): self.assign.make_local_name() return self def get_hi_lineno(self): lineno = self.list.get_hi_lineno() if self.ifs: lineno = (self.ifs)[-1].get_hi_lineno() return lineno class NodeGenExprIf(Node): '''"If" of a generator expression. ''' tag = 'GenExprIf' def __init__(self, indent, lineno, test): Node.__init__(self, indent, lineno) self.test = transform(indent, lineno, test) return def put(self, can_split=False): self.line_more(SPACE, can_split_after=True) self.line_more('if ') self.test.put(can_split=can_split) return self def get_hi_lineno(self): return self.test.get_hi_lineno() class NodeGetAttr(NodeOpr): """Class attribute (method). """ tag = 'GetAttr' def __init__(self, indent, lineno, expr, attrname): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) self.attrname = transform(indent, lineno, attrname) return def put(self, can_split=False): if isinstance(self.expr, NodeConst): if self.expr.is_str(): # 2007 May 01 self.expr.put() else: self.line_more('(') self.expr.put(can_split=True) self.line_more(')') else: self.put_expr(self.expr, can_split=can_split) self.line_more('.') self.line_more(NAME_SPACE.make_attr_name(self.expr, self.attrname)) return self def get_hi_lineno(self): return self.attrname.get_hi_lineno() class NodeGlobal(Node): tag = 'Global' def __init__(self, indent, lineno, names): Node.__init__(self, indent, lineno) self.names = [transform(indent, lineno, name) for name in names] return def put(self, can_split=False): self.line_init() self.line_more('global ') for name in (self.names)[:1]: self.line_more(NAME_SPACE.get_name(name)) for name in (self.names)[1:]: self.line_more(LIST_SEP, can_break_after=True) self.line_more(NAME_SPACE.get_name(name)) self.line_term() return self def marshal_names(self): for name in self.names: NAME_SPACE.make_global_name(name) return self def get_hi_lineno(self): return (self.names)[-1].get_hi_lineno() class NodeIf(Node): """True/False test. """ tag = 'If' def __init__(self, indent, lineno, tests, else_): Node.__init__(self, indent, lineno) self.tests = [(transform(indent, lineno, expr), transform(indent + 1, lineno, stmt)) for (expr, stmt) in tests] self.else_ = transform(indent + 1, lineno, else_) return def put(self, can_split=False): for (expr, stmt) in (self.tests)[:1]: self.line_init() self.line_more('if ') expr.put(can_split=can_split) self.line_more(':') self.line_term(stmt.get_lineno() - 1) stmt.put() for (expr, stmt) in (self.tests)[1:]: self.line_init() self.line_more('elif ') expr.put(can_split=can_split) self.line_more(':') self.line_term(stmt.get_lineno() - 1) stmt.put() if self.else_ is None: pass else: self.line_init() self.line_more('else:') self.line_term(self.else_.get_lineno() - 1) self.else_.put() return self def marshal_names(self): for (expr, stmt) in self.tests: stmt.marshal_names() if self.else_ is None: pass else: self.else_.marshal_names() return self def get_hi_lineno(self): (expr, stmt) = (self.tests)[ZERO] return expr.get_hi_lineno() class NodeIfExp(Node): """Conditional assignment. (Ternary expression.) """ tag = 'IfExp' def __init__(self, indent, lineno, test, then, else_): Node.__init__(self, indent, lineno) self.test = transform(indent, lineno, test) self.then = transform(indent, lineno, then) self.else_ = transform(indent, lineno, else_) return def put(self, can_split=False): self.line_more('(', tab_set=True) # 2010 Mar 10 self.then.put(can_split=True) # 2010 Mar 10 self.line_more(' if ') self.test.put(can_split=True) # 2010 Mar 10 self.line_more(' else ') self.else_.put(can_split=True) # 2010 Mar 10 self.line_more(')', tab_clear=True) # 2010 Mar 10 return self def get_hi_lineno(self): return self.else_.get_hi_lineno() class NodeImport(Node): tag = 'Import' def __init__(self, indent, lineno, names): Node.__init__(self, indent, lineno) self.names = [(transform(indent, lineno, identifier), transform(indent, lineno, name)) for (identifier, name) in names] return def put(self, can_split=False): def put_name(): identifier.put(can_split=can_split) if name is None: pass else: self.line_more(' as ') name.put(can_split=can_split) return for (identifier, name) in self.names: self.line_init() self.line_more('import ') put_name() self.line_term() return self def marshal_names(self): for (identifier, name) in self.names: if name is None: pass else: NAME_SPACE.make_local_name(name) return self def get_hi_lineno(self): (identifier, name) = (self.names)[-1] lineno = identifier.get_hi_lineno() if name is None: pass else: lineno = name.get_hi_lineno() return lineno class NodeInvert(NodeOpr): """Unary bitwise complement. """ tag = 'Invert' def __init__(self, indent, lineno, expr): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) return def put(self, can_split=False): self.line_more('~') self.put_expr(self.expr, can_split=can_split) return self def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeKeyword(Node): """Formal parameter on a function invocation. """ tag = 'Keyword' def __init__(self, indent, lineno, name, expr): Node.__init__(self, indent, lineno) self.name = transform(indent, lineno, name) self.expr = transform(indent, lineno, expr) return def put(self, can_split=False): self.line_more(NAME_SPACE.make_keyword_name(self.name)) self.line_more(FUNCTION_PARAM_ASSIGNMENT) # 2007 May 25 self.expr.put(can_split=can_split) return self def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeLeftShift(NodeOprLeftAssoc): # 2010 Mar 01 """Bitwise shift left. """ tag = 'LeftShift' def __init__(self, indent, lineno, left, right): Node.__init__(self, indent, lineno) self.left = transform(indent, lineno, left) self.right = transform(indent, lineno, right) return def put(self, can_split=False): self.put_expr(self.left, can_split=can_split, pos='left') # 2010 Mar 10 self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('<< ') self.put_expr(self.right, can_split=can_split, pos='right') # 2010 Mar 10 return self def get_hi_lineno(self): return self.right.get_hi_lineno() class NodeList(Node): """Declaration of a mutable list. """ tag = 'List' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False): self.line_more('[', tab_set=True) if len(self.nodes) > MAX_SEPS_SERIES: # 2007 May 24 self.line_term() self.inc_margin() for node in self.nodes: self.line_init() node.put(can_split=True) self.line_more(LIST_SEP) self.line_term() self.line_init() self.dec_margin() else: for node in (self.nodes)[:1]: node.put(can_split=True) for node in (self.nodes)[1:]: self.line_more(LIST_SEP, can_split_after=True) node.put(can_split=True) self.line_more(']', tab_clear=True) return self def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) if self.nodes: lineno = (self.nodes)[-1].get_hi_lineno() return lineno class NodeListComp(Node): """List comprehension. """ tag = 'ListComp' def __init__(self, indent, lineno, expr, quals): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) self.quals = [transform(indent, lineno, qual) for qual in quals] return def put(self, can_split=False): self.push_scope() self.marshal_names() self.line_more('[', tab_set=True) self.expr.put(can_split=True) for qual in self.quals: qual.put(can_split=True) self.line_more(']', tab_clear=True) self.pop_scope() return self def push_scope(self): NAME_SPACE.push_scope() return self def pop_scope(self): NAME_SPACE.pop_scope() return self def marshal_names(self): for qual in self.quals: qual.marshal_names() return self def get_hi_lineno(self): lineno = (self.quals)[-1].get_hi_lineno() return lineno class NodeListCompFor(Node): '''"For" of a list comprehension. ''' tag = 'ListCompFor' def __init__(self, indent, lineno, assign, list, ifs): Node.__init__(self, indent, lineno) self.assign = transform(indent, lineno, assign) self.list = transform(indent, lineno, list) self.ifs = [transform(indent, lineno, if_) for if_ in ifs] return def put(self, can_split=False): self.line_more(SPACE, can_split_after=True) self.line_more('for ') self.assign.put(can_split=can_split) self.line_more(' in ', can_split_after=True) self.list.put(can_split=can_split) for if_ in self.ifs: if_.put(can_split=can_split) return self def marshal_names(self): self.assign.make_local_name() return self def get_hi_lineno(self): lineno = self.list.get_hi_lineno() if self.ifs: lineno = (self.ifs)[-1].get_hi_lineno() return lineno class NodeListCompIf(Node): '''"If" of a list comprehension. ''' tag = 'ListCompIf' def __init__(self, indent, lineno, test): Node.__init__(self, indent, lineno) self.test = transform(indent, lineno, test) return def put(self, can_split=False): self.line_more(SPACE, can_split_after=True) self.line_more('if ') self.test.put(can_split=can_split) return self def get_hi_lineno(self): return self.test.get_hi_lineno() class NodeMod(NodeOprLeftAssoc): # 2010 Mar 10 """Modulus (string formatting) operation. """ tag = 'Mod' def __init__(self, indent, lineno, left, right): Node.__init__(self, indent, lineno) self.left = transform(indent, lineno, left) self.right = transform(indent, lineno, right) return def put(self, can_split=False): self.put_expr(self.left, can_split=can_split, pos='left') # 2010 Mar 10 self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('% ') self.put_expr(self.right, can_split=can_split, pos='right') # 2010 Mar 10 return self def get_hi_lineno(self): return self.right.get_hi_lineno() class NodeModule(Node): """A whole script. Contains a doc string and a statement. """ tag = 'Module' def __init__(self, indent, lineno, doc, node): Node.__init__(self, indent, lineno) self.doc = transform(indent, lineno, doc) self.node = transform(indent, lineno, node) return def put(self, can_split=False): if self.doc is None: pass else: self.doc.lineno = self.get_lineno() self.doc.put_doc() if BOILERPLATE == NULL: # 2007 Mar 06 pass else: self.line_init() self.line_more(BOILERPLATE) self.line_term() self.node.put() return self def push_scope(self): NAME_SPACE.push_scope() return self def pop_scope(self): NAME_SPACE.pop_scope() return self def marshal_names(self): self.node.marshal_names() return self def get_lineno(self): return self.node.get_lineno() class NodeMul(NodeOprLeftAssoc): # 2010 Mar 10 """Multiply operation. """ tag = 'Mul' def __init__(self, indent, lineno, left, right): Node.__init__(self, indent, lineno) self.left = transform(indent, lineno, left) self.right = transform(indent, lineno, right) return def put(self, can_split=False): self.put_expr(self.left, can_split=can_split, pos='left') # 2010 Mar 10 self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('* ') self.put_expr(self.right, can_split=can_split, pos='right') # 2010 Mar 10 return self def get_hi_lineno(self): return self.right.get_hi_lineno() class NodeName(Node): """Variable. """ tag = 'Name' def __init__(self, indent, lineno, name): Node.__init__(self, indent, lineno) self.name = transform(indent, lineno, name) return def put(self, can_split=False): self.line_more(NAME_SPACE.get_name(self.name)) return self def make_local_name(self): if NAME_SPACE.has_name(self.name): pass else: NAME_SPACE.make_local_name(self.name) return self def get_hi_lineno(self): return self.name.get_hi_lineno() class NodeNot(NodeOpr): """Logical negation. """ tag = 'Not' def __init__(self, indent, lineno, expr): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) return def put(self, can_split=False): self.line_more('not ') self.put_expr(self.expr, can_split=can_split) return self def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeOr(NodeOprAssoc): # 2010 Mar 10 '''Logical "or" operation. ''' tag = 'Or' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False): for node in (self.nodes)[:1]: self.put_expr(node, can_split=can_split) for node in (self.nodes)[1:]: self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('or ') self.put_expr(node, can_split=can_split) return self def get_hi_lineno(self): return (self.nodes)[-1].get_hi_lineno() class NodePass(Node): """No-op. """ tag = 'Pass' def __init__(self, indent, lineno): Node.__init__(self, indent, lineno) return def put(self, can_split=False): self.line_init() self.line_more('pass') self.line_term() return self class NodePower(NodeOprRightAssoc): # 2010 Mar 10 """Exponentiation. """ tag = 'Power' def __init__(self, indent, lineno, left, right): Node.__init__(self, indent, lineno) self.left = transform(indent, lineno, left) self.right = transform(indent, lineno, right) return def put(self, can_split=False): self.put_expr(self.left, can_split=can_split, pos='left') # 2010 Mar 10 self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('** ') self.put_expr(self.right, can_split=can_split, pos='right') # 2010 Mar 10 return self def get_hi_lineno(self): return self.right.get_hi_lineno() class NodePrint(Node): """The print statement with optional chevron and trailing comma. """ tag = 'Print' def __init__(self, indent, lineno, nodes, dest): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] self.dest = transform(indent, lineno, dest) return def put(self, can_split=False): self.line_init() self.line_more('print ') if self.dest is None: pass else: self.line_more('>> ') self.dest.put(can_split=can_split) if self.nodes: self.line_more(LIST_SEP, can_break_after=True) for node in self.nodes: node.put(can_split=can_split) self.line_more(LIST_SEP, can_break_after=True) self.line_term() return self def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) if self.dest is None: pass else: lineno = self.dest.get_hi_lineno() if self.nodes: lineno = (self.nodes)[-1].get_hi_lineno() return lineno class NodePrintnl(Node): """The print statement with optional chevron and without trailing comma. """ tag = 'Printnl' def __init__(self, indent, lineno, nodes, dest): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] self.dest = transform(indent, lineno, dest) return def put(self, can_split=False): self.line_init() self.line_more('print ') if self.dest is None: pass else: self.line_more('>> ') self.dest.put(can_split=can_split) if self.nodes: self.line_more(LIST_SEP, can_break_after=True) for node in (self.nodes)[:-1]: node.put(can_split=can_split) self.line_more(LIST_SEP, can_break_after=True) for node in (self.nodes)[-1:]: node.put(can_split=can_split) self.line_term() return self def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) if self.dest is None: pass else: lineno = self.dest.get_hi_lineno() if self.nodes: lineno = (self.nodes)[-1].get_hi_lineno() return lineno class NodeRaise(Node): """Raise an exception. """ tag = 'Raise' def __init__(self, indent, lineno, expr1, expr2, expr3): Node.__init__(self, indent, lineno) self.expr1 = transform(indent, lineno, expr1) self.expr2 = transform(indent, lineno, expr2) self.expr3 = transform(indent, lineno, expr3) return def put(self, can_split=False): self.line_init() self.line_more('raise ') if self.expr1 is None: pass else: self.expr1.put(can_split=can_split) if self.expr2 is None: pass else: self.line_more(LIST_SEP, can_break_after=True) self.expr2.put(can_split=can_split) if self.expr3 is None: pass else: self.line_more(LIST_SEP, can_break_after=True) self.expr3.put(can_split=can_split) self.line_term() return self def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) if self.expr1 is None: pass else: lineno = self.expr1.get_hi_lineno() if self.expr2 is None: pass else: lineno = self.expr2.get_hi_lineno() if self.expr3 is None: pass else: lineno = self.expr3.get_hi_lineno() return lineno class NodeReturn(Node): """Return a value from a function. """ tag = 'Return' def __init__(self, indent, lineno, value): Node.__init__(self, indent, lineno) self.value = transform(indent, lineno, value) return def has_value(self): return not (isinstance(self.value, NodeConst) and self.value.is_none()) def put(self, can_split=False): self.line_init() self.line_more('return ') if self.has_value(): if isinstance(self.value, NodeTuple): self.value.put(can_split=can_split, is_paren_required=False) # 2010 Mar 10 else: self.value.put(can_split=can_split) self.line_term() return self def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) if self.has_value: lineno = self.value.get_hi_lineno() return lineno class NodeRightShift(NodeOprLeftAssoc): # 2010 Mar 10 """Bitwise shift right. """ tag = 'RightShift' def __init__(self, indent, lineno, left, right): Node.__init__(self, indent, lineno) self.left = transform(indent, lineno, left) self.right = transform(indent, lineno, right) return def put(self, can_split=False): self.put_expr(self.left, can_split=can_split, pos='left') # 2010 Mar 10 self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('>> ') self.put_expr(self.right, can_split=can_split, pos='right') # 2010 Mar 10 return self def get_hi_lineno(self): return self.right.get_hi_lineno() class NodeSlice(NodeOpr): """A slice of a series. """ tag = 'Slice' def __init__(self, indent, lineno, expr, flags, lower, upper): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) self.flags = transform(indent, lineno, flags) self.lower = transform(indent, lineno, lower) self.upper = transform(indent, lineno, upper) return def has_value(self, node): return not (node is None or isinstance(node, NodeConst) and node.is_none()) def put(self, can_split=False): is_del = self.flags.get_as_str() in ['OP_DELETE'] if is_del: self.line_init() self.line_more('del ') if (isinstance(self.expr, NodeGetAttr) or isinstance(self.expr, NodeAsgAttr)): # 2007 May 23 self.expr.put(can_split=can_split) else: self.put_expr(self.expr, can_split=can_split) self.line_more('[') if self.has_value(self.lower): self.lower.put(can_split=True) self.line_more(SLICE_COLON) if self.has_value(self.upper): self.upper.put(can_split=True) self.line_more(']') if DEBUG: self.line_more(' /* Subscript flags: ') self.flags.put() self.line_more(' */ ') if is_del: self.line_term() return self def make_local_name(self): self.expr.make_local_name() return self def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) if self.has_value(self.lower): lineno = self.lower.get_hi_lineno() if self.has_value(self.upper): lineno = self.upper.get_hi_lineno() return lineno class NodeSliceobj(Node): """A subscript range. This is used for multi-dimensioned arrays. """ tag = 'Sliceobj' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def has_value(self, node): return not (node is None or isinstance(node, NodeConst) and node.is_none()) def put(self, can_split=False): for node in (self.nodes)[:1]: if self.has_value(node): node.put(can_split=can_split) for node in (self.nodes)[1:]: self.line_more(SLICE_COLON, can_split_after=True) if self.has_value(node): node.put(can_split=can_split) return self def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) for node in self.nodes: if self.has_value(node): lineno = node.get_hi_lineno() return lineno class NodeStmt(Node): """A list of nodes.. """ tag = 'Stmt' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False): for node in self.nodes: node.put() return self def get_lineno(self): for node in self.nodes: result = node.get_lineno() if result == ZERO: pass else: return result return ZERO def marshal_names(self): for node in self.nodes: node.marshal_names() return self class NodeSub(NodeOprLeftAssoc): # 2010 Mar 10 """Subtract operation. """ tag = 'Sub' def __init__(self, indent, lineno, left, right): Node.__init__(self, indent, lineno) self.left = transform(indent, lineno, left) self.right = transform(indent, lineno, right) return def put(self, can_split=False): self.put_expr(self.left, can_split=can_split, pos='left') # 2010 Mar 10 self.line_more(SPACE, can_split_after=can_split, can_break_after=True) # 2007 May 23 self.line_more('- ') self.put_expr(self.right, can_split=can_split, pos='right') # 2010 Mar 10 return self def get_hi_lineno(self): return self.right.get_hi_lineno() class NodeSubscript(NodeOpr): """A subscripted sequence. """ tag = 'Subscript' def __init__(self, indent, lineno, expr, flags, subs): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) self.flags = transform(indent, lineno, flags) self.subs = [transform(indent, lineno, sub) for sub in subs] return def put(self, can_split=False): is_del = self.flags.get_as_str() in ['OP_DELETE'] if is_del: self.line_init() self.line_more('del ') if (isinstance(self.expr, NodeGetAttr) or isinstance(self.expr, NodeAsgAttr)): # 2007 May 23 self.expr.put(can_split=can_split) else: self.put_expr(self.expr, can_split=can_split) if DEBUG: self.line_more(' /* Subscript flags: ') self.flags.put() self.line_more(' */ ') self.line_more('[', tab_set=True) for sub in (self.subs)[:1]: sub.put(can_split=True) for sub in (self.subs)[1:]: self.line_more(SUBSCRIPT_SEP, can_split_after=True) sub.put(can_split=True) self.line_more(']', tab_clear=True) if is_del: self.line_term() return self def make_local_name(self): self.expr.make_local_name() return self def get_hi_lineno(self): lineno = self.expr.get_hi_lineno() if self.subs: lineno = (self.subs)[-1].get_hi_lineno() return lineno class NodeTryExcept(Node): """Define exception handlers. """ tag = 'TryExcept' def __init__(self, indent, lineno, body, handlers, else_): Node.__init__(self, indent, lineno) self.body = transform(indent + 1, lineno, body) self.handlers = [(transform(indent, lineno, expr), transform(indent, lineno, target), transform(indent + 1, lineno, suite)) for (expr, target, suite) in handlers] self.else_ = transform(indent + 1, lineno, else_) self.has_finally = False return def put(self, can_split=False): if self.has_finally: pass else: self.line_init() self.line_more('try:') self.line_term(self.body.get_lineno() - 1) self.body.put() for (expr, target, suite) in self.handlers: self.line_init() self.line_more('except') if expr is None: pass else: self.line_more(SPACE) expr.put() if target is None: pass else: self.line_more(LIST_SEP, can_break_after=True) target.put() self.line_more(':') self.line_term(suite.get_lineno() - 1) suite.put() if self.else_ is None: pass else: self.line_init() self.line_more('else:') self.line_term(self.else_.get_lineno() - 1) self.else_.put() return self def marshal_names(self): self.body.marshal_names() for (expr, target, suite) in self.handlers: suite.marshal_names() if self.else_ is None: pass else: self.else_.marshal_names() return self class NodeTryFinally(Node): """Force housekeeping code to execute even after an unhandled except is raised and before the default handling takes care of it. """ tag = 'TryFinally' def __init__(self, indent, lineno, body, final): Node.__init__(self, indent, lineno) if isinstance(body, compiler.ast.TryExcept): self.body = transform(indent, lineno, body) self.body.has_finally = True else: self.body = transform(indent + 1, lineno, body) self.final = transform(indent + 1, lineno, final) return def put(self, can_split=False): self.line_init() self.line_more('try:') self.line_term(self.body.get_lineno() - 1) self.body.put() self.line_init() self.line_more('finally:') self.line_term(self.final.get_lineno() - 1) self.final.put() return self def marshal_names(self): self.body.marshal_names() self.final.marshal_names() return self class NodeTuple(Node): """Declaration of an immutable tuple. """ tag = 'Tuple' def __init__(self, indent, lineno, nodes): Node.__init__(self, indent, lineno) self.nodes = [transform(indent, lineno, node) for node in nodes] return def put(self, can_split=False, is_paren_required=True): # 2010 Mar 10 if len(self.nodes) > MAX_SEPS_SERIES: # 2007 May 24 self.line_more('(', tab_set=True) # 2010 Mar 10 self.line_term() self.inc_margin() for node in self.nodes: self.line_init() node.put(can_split=True) self.line_more(LIST_SEP) self.line_term() self.line_init() self.dec_margin() self.line_more(')', tab_clear=True) # 2010 Mar 10 elif ((len(self.nodes) == ZERO) or is_paren_required or PARENTHESIZE_TUPLE_DISPLAY): # 2010 Mar 10 self.line_more('(', tab_set=True) # 2010 Mar 10 for node in (self.nodes)[:1]: node.put(can_split=True) self.line_more(LIST_SEP, can_split_after=True) for node in (self.nodes)[1:2]: node.put(can_split=True) for node in (self.nodes)[2:]: self.line_more(LIST_SEP, can_split_after=True) node.put(can_split=True) self.line_more(')', tab_clear=True) # 2010 Mar 10 else: for node in (self.nodes)[:1]: node.put() self.line_more(LIST_SEP, can_break_after=True) # 2010 Mar 10 for node in (self.nodes)[1:2]: node.put() for node in (self.nodes)[2:]: self.line_more(LIST_SEP, can_break_after=True) # 2010 Mar 10 node.put() return self def get_hi_lineno(self): lineno = Node.get_hi_lineno(self) if self.nodes: lineno = (self.nodes)[-1].get_hi_lineno() return lineno class NodeUnaryAdd(NodeOpr): """Algebraic positive. """ tag = 'UnaryAdd' def __init__(self, indent, lineno, expr): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) return def put(self, can_split=False): self.line_more('+') self.put_expr(self.expr, can_split=can_split) return self def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeUnarySub(NodeOpr): """Algebraic negative. """ tag = 'UnarySub' def __init__(self, indent, lineno, expr): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) return def put(self, can_split=False): self.line_more('-') self.put_expr(self.expr, can_split=can_split) return self def get_hi_lineno(self): return self.expr.get_hi_lineno() class NodeWhile(Node): """While loop. """ tag = 'While' def __init__(self, indent, lineno, test, body, else_): Node.__init__(self, indent, lineno) self.test = transform(indent, lineno, test) self.body = transform(indent + 1, lineno, body) self.else_ = transform(indent + 1, lineno, else_) return def put(self, can_split=False): self.line_init() self.line_more('while ') self.test.put(can_split=can_split) self.line_more(':') self.line_term(self.body.get_lineno() - 1) self.body.put() if self.else_ is None: pass else: self.line_init() self.line_more('else:') self.line_term(self.else_.get_lineno() - 1) self.else_.put() return self def marshal_names(self): self.body.marshal_names() if self.else_ is None: pass else: self.else_.marshal_names() return def get_hi_lineno(self): return self.test.get_hi_lineno() class NodeWith(Node): """Context manager. """ tag = 'With' def __init__(self, indent, lineno, expr, vars, body): Node.__init__(self, indent, lineno) self.expr = transform(indent, lineno, expr) self.vars = transform(indent, lineno, vars) self.body = transform(indent + 1, lineno, body) return def put(self, can_split=False): self.line_init() self.line_more('with ') self.expr.put(can_split=can_split) if self.vars is None: pass else: self.line_more(' as ', can_break_after=True) self.vars.put(can_split=can_split) self.line_more(':') self.line_term(self.body.get_lineno() - 1) self.body.put() return self def marshal_names(self): if self.vars is None: pass else: self.vars.make_local_name() self.body.marshal_names() return self def get_hi_lineno(self): lineno = self.expr.get_hi_lineno() if self.vars is None: pass else: lineno = self.vars.get_hi_lineno() return lineno class NodeYield(Node): """Yield a generator value. """ tag = 'Yield' def __init__(self, indent, lineno, value): Node.__init__(self, indent, lineno) self.value = transform(indent, lineno, value) return def put(self, can_split=False): self.line_more('yield ') # 2006 Dec 13 self.value.put(can_split=can_split) return self def get_hi_lineno(self): return self.value.get_hi_lineno() # The abstract syntax tree returns the nodes of arithmetic and logical # expressions in the correct order for evaluation, but, to reconstruct # the specifying code in general and to output it correctly, we need # to insert parentheses to enforce the correct order. # This is a Python Version Dependency. OPERATOR_PRECEDENCE = [ (NodeIfExp, ), (NodeLambda, ), (NodeOr, ), (NodeAnd, ), (NodeNot, ), (NodeCompare, ), (NodeBitOr, ), (NodeBitXor, ), (NodeBitAnd, ), (NodeLeftShift, NodeRightShift), (NodeAdd, NodeSub), (NodeMul, NodeDiv, NodeFloorDiv, NodeMod), (NodeUnaryAdd, NodeUnarySub, NodeInvert, ), # 2010 Mar 10 (NodePower, ), (NodeAsgAttr, NodeGetAttr), (NodeSubscript, ), (NodeSlice, ), (NodeCallFunc, ), (NodeTuple, ), (NodeList, ), (NodeDict, ), (NodeBackquote, ), ] OPERATORS = [] OPERATOR_TRUMPS = {} OPERATOR_LEVEL = {} for LEVEL in OPERATOR_PRECEDENCE: for OPERATOR in LEVEL: OPERATOR_LEVEL[OPERATOR] = LEVEL OPERATOR_TRUMPS[OPERATOR] = OPERATORS[:] # a static copy. OPERATORS.extend(LEVEL) def tidy_up(file_in=sys.stdin, file_out=sys.stdout): # 2007 Jan 22 """Clean up, regularize, and reformat the text of a Python script. File_in is a file name or a file-like object with a *read* method, which contains the input script. File_out is a file name or a file-like object with a *write* method to contain the output script. """ global INPUT, OUTPUT, COMMENTS, NAME_SPACE, INPUT_CODING # 2007 May 23 INPUT = InputUnit(file_in) OUTPUT = OutputUnit(file_out) COMMENTS = Comments() NAME_SPACE = NameSpace() module = compiler.parse(str(INPUT)) module = transform(indent=ZERO, lineno=ZERO, node=module) INPUT_CODING = INPUT.coding # 2007 May 23 del INPUT module.push_scope().marshal_names().put().pop_scope() COMMENTS.merge(fin=True) OUTPUT.close() return # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- class PyTidyFormatter(wx.Frame, General ,yapsy.IPlugin.IPlugin): def __init__(self): self.name = "PyTidy" def Init(self, parent): self.parent = parent wx.Frame.__init__(self, self.parent,-1 ,"PyTidy Formatter",size = (500,150)) self.current_doc = None self.main_panel = wx.Panel(self) self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.file_lb = wx.StaticText(self, -1, "File to format: ", size = (400, -1)) self.fl_bk_lb = wx.StaticText(self, -1,"File Backup: ", size = (400, -1)) self.dont_backup = wx.CheckBox(self, -1, "Don't Backup") self.format_bt = wx.Button(self, -1, "Format File") self.format_bt.Bind(wx.EVT_BUTTON, self.OnFormatter) self.main_sizer.AddSpacer(20) self.main_sizer.Add(self.file_lb, 1 , wx.EXPAND) self.main_sizer.AddSpacer(10) self.main_sizer.Add(self.fl_bk_lb, 1 , wx.EXPAND) self.main_sizer.AddSpacer(10) self.main_sizer.Add(self.dont_backup, 1 , wx.EXPAND) self.main_sizer.AddSpacer(10) self.main_sizer.Add(self.format_bt, 1) self.SetSizer(self.main_sizer) self.main_panel.Fit() self.plugins_menu = wx.Menu() format_entry = self.plugins_menu.Append(-1,"Format File") self.menu_item = self.parent.AddToMenuBar("PyTidy",self.plugins_menu) self.parent.BindMenubarEvent(format_entry, self.ShowMe) self.Bind(wx.EVT_CLOSE, self.HideMe) self.Hide() def NotifyTabChanged(self): try: #premature event happening self.current_doc = self.parent.GetCurrentDocument() self.file_lb.SetLabel("File to format: "+self.current_doc.GetFilePath()) self.fl_bk_lb.SetLabel("File Backup: "+self.current_doc.GetFilePath()+".backup") except: pass def OnFormatter(self, event): if self.current_doc.GetFileExtension() not in ["py","pyw"]: self.BadSourceFileExt() return self.current_doc.Save(0) cur_path = self.current_doc.GetFilePath() if not self.dont_backup.GetValue(): shutil.copyfile(self.current_doc.GetFilePath(), os.path.join(os.path.split(self.current_doc.GetFilePath())[0], self.current_doc.GetFileName()+".backup")) temp = cur_path + ".temp" try: tidy_up(cur_path, cur_path + ".temp") self.current_doc.LoadFile(temp) self.current_doc.Save(0) os.remove(temp) except Exception as e: wx.MessageDialog(None, str(e), "Error" ,style = wx.OK).ShowModal() def BadSourceFileExt(self): warning = wx.MessageDialog(self, "The current buffer is not a python source file.\n","Invalid Source File", style = wx.OK | wx.ICON_EXCLAMATION) warning.ShowModal() def ShowMe(self, event): self.current_doc = self.parent.GetCurrentDocument() self.file_lb.SetLabel("File to format: "+self.current_doc.GetFilePath()) self.fl_bk_lb.SetLabel("File Backup: "+self.current_doc.GetFilePath()+".backup") self.Show() def HideMe(self, event): self.Hide() def Stop(self): self.parent.RemoveFromMenubar(self.menu_item) self.Destroy() gecrit-2.8.4/data/plugins/HtmlConverter.yapsy-plugin000777 000000 000000 00000000320 12051462410 022526 0ustar00rootroot000000 000000 [Core] Name = HTML Converter Module = HtmlConverter [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Converts text buffers te HTML format. gecrit-2.8.4/locale/ro/LC_MESSAGES/gEcrit.mo000777 000000 000000 00000025202 12051462410 020201 0ustar00rootroot000000 000000 T  & B NX^dj z      0@V^g  4Sf    #2 R s} 1%   $ CQl  #  !&;Kb   H/5 Q^ c o(|% "%5[s &" #$1Hz).0$Ej|"#(:Jg  (C[c0   #@^g pz  I %5 FPYai~   2: Saz  8 V`'u  .:K f r 7 (B k        !"!?! E!S!d!! !!!!!!!"""5" D"N"]"Yr"" "" "# (#5# <#J#0Z##,##'#$$$5$Z$x$$$$.$$ % %%"/%%R%-x%%'%%3&4&2I&$|&&"&&&''9'%J' p'|''''''(%(>(U(n(((((($() )5*) `)j){)))))) * * 1* <* J*W* j* x*^| Ak[a93Mjo_>q6/sJGD="fNVh-'We*(Kpt:$O)#8RZ0S1+yxPwlrn \5b F7L!X}vzg;{?%,Hu`2iEd<BYQ4&@TcI UC]~m. does not exists. is not saved. Do you wish to save it?&Cut Ctrl+X&Document&Edit&File&Help&New Tab Ctrl+N&Open Ctrl+O&Plugins&Print Ctrl+P&Quit Ctrl+Q&Redo Ctrl+Y&Save Ctrl+S&Search&Session&Undo Ctrl+Z&ViewAboutAre you sure?Assistants and othersAuthor: Autocomplete BracesAutoindentationBackspace to UnindentBad EOLBracketsBring back the last action.C&opy Ctrl+CCancel the last action.Close &Tab Ctrl+WClose the current tab.Colour PaletteComment Lines Ctrl+Shift+CComment the selected lines.CommentsCopy the selection.Could not load file. The file Cut the selection.Decrease the size of the text.Dedent Ctrl+JDedent the selected lines.Delete SessionDelete the saved session file.Description: Edge LineEdge Line Position:Enable AutosaveEnable LogEnable SessionEnable/Disable Session support.Enable/Disable Syntax Highlight.Erase LogFindFind Ctrl+FFind and Replace Ctrl+HFind and replace text using a regular expression.Find text using a regular expression.Fold MarksFullscreen F11IdentifiersIncrease the size of the text.Indent Ctrl+KIndent the selected lines.Indentation GuidesInput ErrorInsert dateInsert the date at cursor position.IntegersKeywordsLine NumbersManage gEcrit Plugins.Method NamesNewNormal Size Ctrl+0OKOS ShellOpenOpen a new document.Open a new tab.Open the about window.Open the configuration window.Opened file OperatorsP&aste Ctrl+VPaste the selection.Please make sure that your data is saved. Are you sure you want to quit?Plugin ManagerPlugins:Preferences Ctrl+EPrintPrint the current document.Python ShellQuitQuit gEcritQuit gEcrit.Recent files Show the last opened files.Regex Search Ctrl+Shift+FRegex Search and Replace Ctrl+Shift+HReload Ctrl+RReload the current file from disk.RemoveRemove Trailing SpacesRemove spaces at the end of the line.Replace spaces by tabs.Replace tabs by spaces.Run File F5Run the current document.(python only)Run the current file.(Python only)SaveSave AllSave AsSave SessionSave data each # of characters:Save the current application state.Save the current document under a differend name.Save the current document.Save the document under a different name.Save the document.Saves all the open documents that have a path.Search and ReplaceSearch and replace text in the current document.Search text in the current document.Select All Ctrl+ASelect Code Block Ctrl+Shift+ASelect all the current code block.Select all the document.Session file loaded.Session saved.Set the size of the text to normal.SettingsShow Line NumbersShow WhitespaceShow/Hide Assistants window.Show/Hide Toolbox window.Show/Hide fold marks.Show/Hide indentation guides.Show/Hide line numbers.Show/Hide statusbar.Show/Hide the edge line.Show/Hide white spaces.Status BarStatusbarStop/Start a python shell.Stop/Start an OS shell.StringsStrip Trailing Spaces On SaveSyntax HighlightTabifyThe end of file was reached! Nothing to replace.The file Toggle AssistantsToggle Fullscreen mode.Toggle ToolboxToolboxTriple QuotesUncomment Lines Ctrl+Shift+XUncomment the selected lines.UntabifyUse TabsVersion: View LogWebsite: White SpaceZoom In Ctrl++Zoom Out Ctrl+-Project-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: POT-Creation-Date: 2011-05-05 22:11-0400 PO-Revision-Date: 2011-05-07 11:23-0500 Last-Translator: Groza cristi Language-Team: LANGUAGE Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nu exista. Nu este salvat. Doriti sa il salvati?&Decupare Ctrl+X&Document&Editare&FisierA&jutor&Document Nou Ctrl+N&Deschidere Ctrl+OExtensiiIm&primare Ctrl+P&Inchide Ctrl+Q&Redo Ctrl+Y&Salvare Ctrl+S&Cautare&Sesiune&Undo Ctrl+Z&AfisareDespre gEcritSunteti sigur?Asistenti si alteleAutor: Autocompletare parantezeAutoindentareDedentare prin BackspaceLinii invalideParantezeReface ultima actiune.C&opiere Ctrl+CInchide ultima actiune.Inchidere &Document Ctrl+WInchide documentul selectat.Paleta de CuloriComentare Linii Ctrl+Shift+CComenteaza liniile selectate.ComentariCopiaza selectiunea.Imposibil de incarcat fisierul.FisierulDecupeaza Selectia.Micsoreaza dimensiunea textului.Dedentare Ctrl+JDedenteaza liniile selectate.Stergere SesiuneSterge fisierul de sesiune.Descriere: Linie de MarginaPositia Liniei de Margina:AutosalvareActivare LogActivare sesiuneActivare/Dezactivare sesiune.Comuta colorarea sintaxei. Stergere LogCautareCautare Ctrl+FCautare si Inlocuire Ctrl+HCauta si inlocuieste text folosind o expresie regulara.Cauta text folosind o expresie regulara.Marci de RestringereFullscreen F11IdentificatoriMareste dimensiunea textului.Identare Ctrl+KIndenteaza liniile selectate.Ghiduri de IndentareEroare IntrareInserare dataInsereaza data la pozitia actuala.CifreCuvinte cheieNumerotare LiniiGestioneaza extensiile gEcrit.Nume de metodeDocument NouDimensune Normala Ctrl+0OKShell OSDeschideDeschideti un document nou.Deschideti un fisier nou.Despre autori.Deschide fereastra de configurare.Fisier deschisOperatoriL&ipire Ctrl+VLipeste selectiunea.Va rugam sa fiti sigur daca informatia este salvata. Sunteti sigur ca vreti sa inchideti?Gestionar de ExtensiiExtensii:Preferinte Ctrl+EImprimareImprimeaza ducumentul selectat.Shell PhytonIesireIesire gEcritInchide gEcrit.Fisiere recente Arata ultimile fisiere deschise.Cautare prin Regex Ctrl+Shift+FCautare prin Regex si Inlocuire Ctrl+Shift+HReincarcare Ctrl+RReincarca fisierul selectat de pe disc.EliminaElimina Spatiile de CoadaElimina spatiile la sfirsitul linii.Substituire spatii cu taburi.Substituire taburi cu spatii.Executare Fisier F5Executa documentul selectat.(Python)Executa fisierul selectat.(Doar pentru Phyton)SalveazaSalvare totSalvare caSalvare sesiuneaSalvare la fiecare # de caractere:Salveaza starea actuala a aplicatiei.Salveaza documentul selectat sub un alt nume.Salzeaza documentul selectat.Salveaza documentu sub un nume diferit.Salvati documentul.Salveaza toate documentele deschise care au o cale.Cauta si InlocuiesteCauta si inlocueste textul in documentul selectat.Cauta textul in documentul selectat.Selectare Tot Ctrl+ASelectare bloc de cod Ctrl+Shift+ASelecteaza blocul de cod in intregime.Selecteaza tot documentul.Fisierul de sesiune incarcat.Sesiune salvata.Seteaza dimensiunea textului normala.ConfigurareNumerotare LiniiIndicare Spatiile AlbeComuta fereastra asistentilorComuta fereastra setului de intrumente.Comuta Mmrci de restringere.Comuta ghidurile de identare.Comuta numerotare linii.Comuta bara de status.Comuta Linia de margina.Comuta afisarea spatiului alb.Bara de StatutBara de StatusComuta shellul phyton.Comuta Shellul OS.Siruri de caractereElimina Spatiile de Coada la SalvareColorare SintaxaTabificareSfirsitul fisierului a fost atins! Nimic de inlocuit.Fisierul Comuta AsistentiComuta modul Fullscreen.Comuta Setul de InstrumenteSet de instrumenteGhilimele tripleDecomentare Linii Ctrl+Shift+XDecomenteaza liniile selectate.DetabificareFoloseste TaburiVersiune: Visionare LogPagina Web: Comuta Spatiul AlbMarire Ctrl++Micsoraregecrit-2.8.4/locale/es/LC_MESSAGES/000777 000000 000000 00000000000 12051462410 016412 5ustar00rootroot000000 000000 gecrit-2.8.4/FindReplaceText.py000777 000000 000000 00000017306 12051462410 016364 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx class SearchReplace: """ SearchReplace Provied the necessary dialogs and functions for the text search feature. """ def OnClose(self,event,widget): """ OnClose Destroys the suplied widet. """ widget.Destroy() def FindDocText(self, event, text_id, other_flags = 0): """ FindDocText Creates and initializes the neccesary dialog for text searching. Sets up the environment and the variables that indicate the position in the text document. """ self._ = wx.FindWindowById(text_id)._ self.min_text_range = 0 self.max_text_range = wx.FindWindowById(text_id).GetLength() #FindFrame = wx.Frame(None, -1, "Search", size=(200, 200)) find_data = wx.FindReplaceData() find_dlg = wx.FindReplaceDialog(None, find_data, self._("Find")) find_dlg.find_data = find_data # save a reference to it... find_dlg.Bind(wx.EVT_FIND_NEXT, lambda event: self.SearchWord(event, text_id, find_data, other_flags)) find_dlg.Bind(wx.EVT_FIND, lambda event: self.SearchWord(event, text_id, find_data, other_flags)) find_dlg.Show(True) find_dlg.Bind(wx.EVT_CLOSE,lambda event: self.OnClose(event,find_dlg)) find_dlg.Bind(wx.EVT_FIND_CLOSE, lambda event: self.OnClose(event,find_dlg)) def SearchWord(self, event, text_id, item, other_flags): """ SearchWord Searches the suplied string in the current document. Manages highlighting and scrolling to that position. Returns the text position if found and -1 if not found. When reaches end, resets the current postion in the document to 0. """ cur_doc = wx.FindWindowById(text_id) search_flags = item.GetFlags() word = item.GetFindString() max_pos = cur_doc.GetLength() if search_flags in [0, 2, 4, 6]: text_pos = cur_doc.FindText(self.max_text_range, self.min_text_range, word, search_flags | other_flags) if text_pos != -1: start_pos = text_pos end_pos = start_pos + len(word) self.max_text_range = text_pos - len(word) cur_doc.GotoPos(self.max_text_range) cur_doc.SetSelection(end_pos, start_pos) elif text_pos == -1: cur_doc.GotoPos(1) self.min_text_range = 0 else: text_pos = cur_doc.FindText(self.min_text_range, max_pos, word, search_flags|other_flags) start_pos = text_pos end_pos = text_pos + len(word) if text_pos != -1: cur_doc.GotoPos(text_pos) self.min_text_range = end_pos cur_doc.SetSelection(start_pos, end_pos) elif text_pos == -1: cur_doc.GotoPos(1) self.min_text_range = 0 def ReplaceDocText(self, event, text_id, other_flags = 0): """ ReplaceDocText Creates and initializes the neccesary dialog for text searching and replaceing. Sets up the environment and the variables that indicate the position in the text document. """ self._ = wx.FindWindowById(text_id)._ self.max_text_range = wx.FindWindowById(text_id).GetLength() self.min_text_range = 1 find_repl_frame = wx.Frame(None, -1, self._("Search and Replace"), size=(300, 300)) find_repl_data = wx.FindReplaceData() replace_dlg = wx.Findreplace_dlg(find_repl_frame, find_repl_data, self._("Search and Replace"), style=wx.FR_REPLACEDIALOG) replace_dlg.find_repl_data = find_repl_data replace_dlg.Bind(wx.EVT_FIND_NEXT, lambda event: self.SearchWord(event, text_id, find_repl_data, other_flags)) replace_dlg.Bind(wx.EVT_FIND, lambda event: self.SearchWord(event, text_id, find_repl_data, other_flags)) replace_dlg.Bind(wx.EVT_FIND_REPLACE, lambda event: self.ReplaceWord(event, text_id, find_repl_data, other_flags)) replace_dlg.Bind(wx.EVT_FIND_REPLACE_ALL, lambda event: self.ReplaceAllWords(event, text_id, find_repl_data, other_flags)) replace_dlg.Show(True) replace_dlg.Bind(wx.EVT_CLOSE,lambda event: self.OnClose(event,replace_dlg)) replace_dlg.Bind(wx.EVT_FIND_CLOSE, lambda event: self.OnClose(event,replace_dlg)) def ReplaceWord(self, event, text_id, item, other_flags): """ ReplaceWord Searches the suplied string in the current document and replaces it with the suplied replacement. Manages scrolling to that position. Returns the text position if found and -1 if not found. When reaches end, resets the current postion in the document to 0. """ cur_doc = wx.FindWindowById(text_id) max_pos = cur_doc.GetLength() op_flags = item.GetFlags() search_word = item.GetFindString() replace_word = item.GetReplaceString() if op_flags in [0, 2, 4, 6]: to_pos = cur_doc.FindText(self.max_text_range, self.min_text_range, search_word, op_flags|other_flags) from_pos = to_pos + len(search_word) cur_doc.SetTargetStart(to_pos) cur_doc.SetTargetEnd(from_pos) if from_pos != -1: cur_doc.ReplaceTarget(replace_word) self.max_text_range = to_pos cur_doc.GotoPos(to_pos) cur_doc.SetSelection(to_pos, from_pos) return to_pos elif from_pos == -1: self.max_text_range = cur_doc.GetLength() return -1 else: from_pos = cur_doc.FindText(self.min_text_range, max_pos, search_word, op_flags|other_flags) to_pos = from_pos + len(search_word) cur_doc.SetTargetStart(from_pos) cur_doc.SetTargetEnd(to_pos) if from_pos != -1: cur_doc.ReplaceTarget(replace_word) self.min_text_range = to_pos cur_doc.GotoPos(from_pos) cur_doc.SetSelection(to_pos, from_pos) return from_pos elif from_pos == -1: self.min_text_range = 0 return -1 def ReplaceAllWords(self, event, text_id, item, other_flags): """ ReplaceAllWords Replaces all the occurences of the suplied string with the suplie replacement. Promps user when end of file was reached. """ while self.ReplaceWord(0, text_id, item) != -1: self.ReplaceWord(0, text_id, item) EndReached = wx.MessageDialog(None, self._("The end of file was reached!\nNothing to replace."), "", style=wx.OK) EndReached.ShowModal() FindRepl = SearchReplace() gecrit-2.8.4/StcMode.py000777 000000 000000 00000012734 12051462410 014701 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import wx import wx.lib.inspection class StcMode(object): """ This class is an interface for all clases that want to implement a Mode for the StyledTextControl The children class must overwrite all the empty methods and all None instance variables. This class will be passed an wx.StyledTextCtrl and can have an enourmous amount of control over it. """ lexer = None # a lexer that will provide syntax highlight for the control. # Must be part of wx.stc.STC_LEX#### lang_name = "" # language name eg: python, ruby... file_extensions = [] # a list of file extensions that this mode is candidate for. (format: ["py","pyw"]) keywords = [] # a keyword list for this mode. (format: ["for","while"]) def __init__(self, stc_ctrl): self.stc_ctrl = stc_ctrl def CommentSelection(self, comment_string): """ This is a helper function for child classes. It appends @comment_string in front of every selected line. """ # from drPython source code selstart, selend = self.stc_ctrl.GetSelection() #From the start of the first line selected oldcursorpos = self.stc_ctrl.GetCurrentPos() startline = self.stc_ctrl.LineFromPosition(selstart) self.stc_ctrl.GotoLine(startline) start = self.stc_ctrl.GetCurrentPos() #To the end of the last line selected #Bugfix Chris Wilson #Edited by Dan (selend fix) if selend == selstart: tend = selend else: tend = selend - 1 docstring = comment_string end = self.stc_ctrl.GetLineEndPosition(self.stc_ctrl.LineFromPosition(tend)) #End Bugfix Chris Wilson eol = self.stc_ctrl.GetEndOfLineCharacter() corr = 0 l = len(self.stc_ctrl.GetText()) # if self.prefs.doccommentmode == 0: self.stc_ctrl.SetSelection(start, end) text = docstring + self.stc_ctrl.GetSelectedText() text = text.replace(eol, eol + docstring) self.stc_ctrl.ReplaceSelection(text) corr = len(self.stc_ctrl.GetText()) - l self.stc_ctrl.GotoPos(oldcursorpos + corr) def UnCommentSelection(self, comment_string): """ This is a helper function for child classes. It removes the leading @comment_string in selectod lines. """ #from drPython source code #franz: pos is not used selstart, selend = self.stc_ctrl.GetSelection() #From the start of the first line selected startline = self.stc_ctrl.LineFromPosition(selstart) oldcursorpos = self.stc_ctrl.GetCurrentPos() self.stc_ctrl.GotoLine(startline) start = self.stc_ctrl.GetCurrentPos() #To the end of the last line selected #Bugfix Chris Wilson #Edited by Dan (selend fix) if selend == selstart: tend = selend else: tend = selend - 1 end = self.stc_ctrl.GetLineEndPosition(self.stc_ctrl.LineFromPosition(tend)) #End Bugfix Chris Wilson mask = self.stc_ctrl.GetModEventMask() self.stc_ctrl.SetModEventMask(0) lpos = start newtext = "" l = len(self.stc_ctrl.GetText()) docstring = comment_string ldocstring = len(docstring) while lpos < end: lpos = self.stc_ctrl.PositionFromLine(startline) line = self.stc_ctrl.GetLine(startline) lc = line.find(docstring) if lc > -1: prestyle = self.stc_ctrl.GetStyleAt(lpos + lc - 1) style = self.stc_ctrl.GetStyleAt(lpos + lc) newtext += line[0:lc] + line[lc+ldocstring:] else: newtext += line startline += 1 lpos = self.stc_ctrl.PositionFromLine(startline) self.stc_ctrl.SetModEventMask(mask) self.stc_ctrl.SetSelection(start, end) self.stc_ctrl.ReplaceSelection(newtext.rstrip(self.stc_ctrl.GetEndOfLineCharacter())) corr = len(self.stc_ctrl.GetText()) - l self.stc_ctrl.GotoPos(oldcursorpos + corr) # every method will be passed the event argument. The method must not event.Skip() it. #interface functions def OnComment(self, event): """This method will mangage commenting selections of text.""" pass def OnUnComment(self, event): """ This method will manage uncommenting selections of text.""" pass def AutoIndent(self, event): """ This method will be called when the Enter key is pressed and autoindentation is enabled. This method must manage autoindentation. """ pass def OnSelectCodeBlock(self, event): """ This method manages selecting code blocks. """ pass gecrit-2.8.4/data/plugins/TaskKeeper.yapsy-plugin000777 000000 000000 00000000337 12051462410 022000 0ustar00rootroot000000 000000 [Core] Name = Task Keeper Module = TaskKeeper [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Collects annotated tasks from the files and displays them. gecrit-2.8.4/data/plugins/DocumentCloner.py000777 000000 000000 00000003053 12051462410 020650 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- from data.plugins.categories import General import yapsy.IPlugin import wx class DocumentCloner(General, yapsy.IPlugin.IPlugin): def __init__(self): self.name = "Document Cloner" def Init(self, parent): self.parent = parent self.plugins_menu = wx.Menu() clone_entry = self.plugins_menu.Append(-1,"Clone Current Document") self.menu_item = self.parent.AddToMenuBar("Document Cloner", self.plugins_menu) self.parent.BindMenubarEvent(clone_entry, self.OnClone) def OnClone(self, event): origin = self.parent.GetCurrentDocument() doc = self.parent.CreateNewDocument(self.parent.GetCurrentDocument ().GetFileName()+" -Clone") doc.SetText(origin.GetText()) gecrit-2.8.4/SyntaxHighlight.py000777 000000 000000 00000005644 12051462410 016463 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx import os class SyntaxHighlight: """ SyntaxColorizer Sets up the lexer for syntax highlighting. """ def __init__(self): """ __init__ Generates a default color dictionary. """ self.__default_color_dict = { "Integers": wx.Colour(181, 69, 166, 255), "Brackets": wx.Colour(25, 57, 185, 255), "Identifiers": wx.Colour(0, 0, 0, 255), "BadEOL": wx.Colour(231, 0, 255, 255), "Comments": wx.Colour(214, 214, 214, 255), "Strings": wx.Colour(255, 0, 22), "MethodNames": wx.Colour(0, 7, 255, 255), "Keywords": wx.Colour(26, 32, 189, 255), "Operators": wx.Colour(210, 147, 29, 255), "TripleQuotes": wx.Color(210, 149, 29, 255), "EdgeLine": wx.Color(255, 0, 22), } self.__color_dict = {} self.__HOMEDIR = os.path.expanduser('~') self.cfg_path = os.path.join(self.__HOMEDIR, ".gEcrit", ".gEcritColor") self.cfg_dir = os.path.join(self.__HOMEDIR, ".gEcrit") self.__color_dict = {} self.ReadColorFile() def GetColor(self, item): return self.__color_dict[item] def ReadColorFile(self): """ ReadColorFile Reads the configuration file and generates a color dictionary for the lexer. """ try: colour_file = open(self.cfg_path, "r") self.__color_dict = eval(colour_file.read()) except: if not os.path.exists(self.cfg_dir): os.mkdir(self.cfg_dir) self.__color_dict = self.__default_color_dict colour_file = open(self.cfg_path, "w") colour_file.write(str(self.__default_color_dict)) colour_file.close() def ChangeColorFile(self, item, newcolor): """ Changecolour_file Modifies the value of the suplied argument item with the suplied argument newcolor. Writes changes to file. """ self.__color_dict[item] = newcolor with open(self.cfg_path, "w") as colour_file: colour_file.write(str(self.__color_dict)) SyntCol = SyntaxHighlight() gecrit-2.8.4/doc/000777 000000 000000 00000000000 12051462410 013524 5ustar00rootroot000000 000000 gecrit-2.8.4/icons/save.bmp000777 000000 000000 00000006066 12051462410 015543 0ustar00rootroot000000 000000 BM6 6(    Š}}}~~x~}}|~|zpppHHH@@@999@@@&&&444***$$$'''%%%'''&&&$$$!!!"""! $&! )$,( 6&<*"/*"$/*10$9;777===:::pppAAAFFF@@@"""666111--->>>222666---...111---444---/..).3:.1;0- 0#J44eO*=/;1-?25"'>>>CCCFFFlllQQQFFF>>>111GGGkkkvvv...;;;eee```kkkPPPYYYOOOdedpvkoupYzg,|^}бV|gvmffMP4%*DDDFFF;;;oooHHHAAAJJJ)))2=??>>CCCCCCoooJJJBBBFFF222ȿøƺ¼YUWDDDCCCEEEoooJJJBBBEEE555¹ڷDACDDDCCCEEEnnnJJJDDDFFF///Ƚɦ///DDDCCCEEEnnnJJJDDDGGG+++渾031DCDCCCEEEnnnJJJDDDBBB666ҷĽºøĿ(+)DDDCCCEEEnnnJJJBBBJJJ777jjjϺпշ+1,DCDCCCDDDmmmJJJCCCGGG;;;OOOӢȷαմܨ)/*DDDCCCDDDmmmJJJDDDBBBBBB333֎ɻz}|bzlZzharkvlدڐ061DCDCCCDDDmmmJJJEEEAAADDD,,,՝£L{[s3]kzkÿ۟twu5;6DDDCCCDDDmmmJJJCCCFFFBBB***ڽˬfrkiא?rYrrӭORP7<8DDDCCCDDDmmmJJJBBBFFFCCC...Ƿvz^yT7j@p?lrӐPbӳҼԾE<>R:>CDCCCCDDDmmmJJJFFFHHHDDD222rƄ[}7c3c>jCj>k{erεԚ)%'MAFCDCCCCDDDmmmJJJCCCDDDGGG---лMh^?k6_:_>b6\>g/^%94<IFvKĶx.:1FD>CDDCCCDDDmmmJJJDDDBBBEEE>>>===qstgpvg~^msMc%D)G5FEI Pw֏KtJ{}~owv@NK5<8JIECCCCCCDDDmmmJJJCCCBBBGGG@@@===BACB9FD=B;A6-R.etC`/Q4ODRQT,MkAuC@M:;77?BNAFCDDCCCDDDmmmJJJEEEEEE???IIIDDDDCDHAHH?H>E>,X0Vf?[:\AaOaX^7RUfE|J7J6FIIA@J=>HACKKEJN@BCDCCCCDDDmmmJJJDDDCCCCCCCCCCCCADA:C@KASA=E/Y,TSCNFaSrXkY\EjOdNQ9J3C@=F@G?@I>BFBDBGD=CDDCCCDDDnnnIIIDDDDDDDDDDDDDDDBEBCKDJ>KD?F*S(HIEVSuX\zWjEe9M;x?8Q2DF>ECFABIBCGGDELDBBBBBBBCCCnnnKKKDDDDDDDDDDDDDDDBDABG>G;DLFI0S/5;EZadžehŽfƆPh.<+j.2P,AJA2=)7J'w13e27P2AJ. #!/usr/bin/python # -*- coding: utf-8 -*- import wx.html import wx class PrettyPrinter(wx.html.HtmlEasyPrinting): """ PrettyPrinter Provides the necessary functions for printing documents. Build the GUI and provides the appropriate controls. """ def __init__(self, parent=None): """ __init__ Initializes the HtmlEasyPrinting object. Creates the necessary dialogs. Retrieves the content to be printed. """ wx.html.HtmlEasyPrinting.__init__(self) self.parent = parent data = wx.PrintDialogData() data.EnableSelection(True) data.EnablePrintToFile(True) data.EnablePageNumbers(True) data.SetMinPage(1) data.SetMaxPage(5) data.SetAllPages(True) dlg = wx.PrintDialog(parent, data) dlg.Destroy() self.DoPrint() def DoPrint(self): """ DoPrint Sets the print hedear and calls the HTML generation function. Sends the output to HtmlEasyPrinting object for printing. """ filename = self.parent.GetCurrentDocument().GetFileName() self.SetHeader(filename) self.PrintText(self.ToHTML(), filename) def ToHTML(self): """ ToHTML Formats the document text to HTML form. Returns it. """ self.current_doc = self.parent.GetCurrentDocument() text = self.current_doc.GetText().replace('&', "&").replace('<', "<").replace('>', ">") if self.current_doc.GetLineCount(): text = "100000" + text.replace(' ', "  ") x = 0 l = len(text) line = 2 n = "" while x < l: if text[x] == "\n": n = n + "\n" + str(line) if line < 10: n = n + "00000" elif line < 100: n = n + "0000" elif line < 1000: n = n + "000" else: n = n + "00" line = line + 1 else: n = n + text[x] x = x + 1 text = n thehtml = \ "" + \ text.replace("\n", "\n
") + "" return thehtml gecrit-2.8.4/icons/close.png000777 000000 000000 00000010612 12051462410 015710 0ustar00rootroot000000 000000 PNG  IHDR szz OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3-bKGD pHYs  tIMEsNIDATXýkU{sΝ;s_ 30[bPDI4D6J~:om—"jR)&Z@-ҡ`0W?ǜXkܫhXbjU\-D("`myO?dT^-?h~[*Ofy-wԼ>,VʠVĖ٤jU݆u>%?űo<µ~0Kwgߠe*EkS.PI2rH8-dQpA.h p ɏ{=W@b9A"R&μfHwб2®rty+AP뾫 He!(/BrC(/:kg<]5ga6ϝC18"BXOk*YB%:2m] @4Tr,P,<3C\h$Mq'X;:4lsŧC,Nȇ9QN Bĵ$}U9m{pӚo_ev!@BrË~ClpHΚ0-JS(E* Ar>,{䪻D~wEt<ѥg2LX=\4QrB(^X, |[ μ/2^ϲr(Ȗw|P(ȊBݳlf!@P2X(vq$J@*r%KIa&/07xo]mcQh>zdYg BT",/;ƕ1\?4ĉm7`Pl ڦ+ VD7MRk>}7~Q|'ɐdH\SG~j`}ZQhFמB@Z-#.퀦 * ,xZDq{##5r2R8gHiM xDFUi \cp۞}SSrarE4F)6ݍU5@f5 e C=/gF'bctX"m-w&ܚ@2sڼs&$RDd<ł&Ѻ%ftUVT]5Ok$~իιYx2A2"OֱAK%ve@jiZ%KjuqqvV࿾ڰpS>v-{ gR 'KKe%0^<$ s d~ZDkwv0 ~VQ2|eq,()5h,ђ&y<8O>/~;;L&q=fa~(xp=ĢND3v,r"ZxXs  Ȝ<ɒtFyc?΅#G]VכhTOCK$Z߄"̍Cj]Ƹ98a3L*ViV m1i`D1-[pÖqaǓd'H%S _2?}(:uita+m_jƑ#/<|G&տHs3lRs=z#1n']0B·\I ,cp48 V8}>_H˾< rs*WXP +=uIENDB`gecrit-2.8.4/setup.py000777 000000 000000 00000002112 12051462410 014470 0ustar00rootroot000000 000000 from distutils.core import setup short_description = " gEcrit is a text editor used to write Python source code." long_descr = """ gEcrit is a text editor used to write Python source code. You can find all the common features that you may find in other editors. It features a plugin system that allows the application to be extended easily. It it comes with pulgins such as a terminal emulator, a source code refactoirng tool based on Pytidy etc. """ setup( name = "gEcrit", version = "2.8.2", description = short_description, long_description = long_descr, author = "Groza Cristian", author_email = "kristi9524@gmail.com", url = "http://sourceforge.net/projects/gecrit/", scripts = ["gecrit"], license = "GPL3", packages = ["gEcrit"], package_dir = {"gEcrit" : "."}, package_data = {"gEcrit" : ["yapsy/*", "pyctags/*" ,"data/__init__.py","data/plugins/*","icons/*", "locale/ro/LC_MESSAGES/*", "locale/es/LC_MESSAGES/*", "locale/pl/LC_MESSAGES/*", "runner.sh"]}, # py_modules = ["yapsy/*", "pyctags/*"] ) gecrit-2.8.4/locale/pl/LC_MESSAGES/gEcrit.mo000777 000000 000000 00000024666 12051462410 020211 0ustar00rootroot000000 000000 T  & B NX^dj z      0@V^g  4Sf    #2 R s} 1%   $ CQl  #  !&;Kb   H/5 Q^ c o(|% "%5[s &" #$1Hz).0$Ej|"#(:Jg  (C[c0   #@^g pz  I - > JT\ah{   &?$Ot|$ ?J"^   ) 3? O)p  D0 I e v      ' "!3! C!P! k!x!}!!!!!!!! " " !" /"L="""""" """"2#:#$T#y#$######$/'$)W$$$ $ $$ $,$!%!?%a%4r%%6%,%&5&&U&|&&&& &&&&'2'!P'r'''' ' '') (3(;(R(j(5q(((((((!);)X) a)m) u) ) )))^| Ak[a93Mjo_>q6/sJGD="fNVh-'We*(Kpt:$O)#8RZ0S1+yxPwlrn \5b F7L!X}vzg;{?%,Hu`2iEd<BYQ4&@TcI UC]~m. does not exists. is not saved. Do you wish to save it?&Cut Ctrl+X&Document&Edit&File&Help&New Tab Ctrl+N&Open Ctrl+O&Plugins&Print Ctrl+P&Quit Ctrl+Q&Redo Ctrl+Y&Save Ctrl+S&Search&Session&Undo Ctrl+Z&ViewAboutAre you sure?Assistants and othersAuthor: Autocomplete BracesAutoindentationBackspace to UnindentBad EOLBracketsBring back the last action.C&opy Ctrl+CCancel the last action.Close &Tab Ctrl+WClose the current tab.Colour PaletteComment Lines Ctrl+Shift+CComment the selected lines.CommentsCopy the selection.Could not load file. The file Cut the selection.Decrease the size of the text.Dedent Ctrl+JDedent the selected lines.Delete SessionDelete the saved session file.Description: Edge LineEdge Line Position:Enable AutosaveEnable LogEnable SessionEnable/Disable Session support.Enable/Disable Syntax Highlight.Erase LogFindFind Ctrl+FFind and Replace Ctrl+HFind and replace text using a regular expression.Find text using a regular expression.Fold MarksFullscreen F11IdentifiersIncrease the size of the text.Indent Ctrl+KIndent the selected lines.Indentation GuidesInput ErrorInsert dateInsert the date at cursor position.IntegersKeywordsLine NumbersManage gEcrit Plugins.Method NamesNewNormal Size Ctrl+0OKOS ShellOpenOpen a new document.Open a new tab.Open the about window.Open the configuration window.Opened file OperatorsP&aste Ctrl+VPaste the selection.Please make sure that your data is saved. Are you sure you want to quit?Plugin ManagerPlugins:Preferences Ctrl+EPrintPrint the current document.Python ShellQuitQuit gEcritQuit gEcrit.Recent files Show the last opened files.Regex Search Ctrl+Shift+FRegex Search and Replace Ctrl+Shift+HReload Ctrl+RReload the current file from disk.RemoveRemove Trailing SpacesRemove spaces at the end of the line.Replace spaces by tabs.Replace tabs by spaces.Run File F5Run the current document.(python only)Run the current file.(Python only)SaveSave AllSave AsSave SessionSave data each # of characters:Save the current application state.Save the current document under a differend name.Save the current document.Save the document under a different name.Save the document.Saves all the open documents that have a path.Search and ReplaceSearch and replace text in the current document.Search text in the current document.Select All Ctrl+ASelect Code Block Ctrl+Shift+ASelect all the current code block.Select all the document.Session file loaded.Session saved.Set the size of the text to normal.SettingsShow Line NumbersShow WhitespaceShow/Hide Assistants window.Show/Hide Toolbox window.Show/Hide fold marks.Show/Hide indentation guides.Show/Hide line numbers.Show/Hide statusbar.Show/Hide the edge line.Show/Hide white spaces.Status BarStatusbarStop/Start a python shell.Stop/Start an OS shell.StringsStrip Trailing Spaces On SaveSyntax HighlightTabifyThe end of file was reached! Nothing to replace.The file Toggle AssistantsToggle Fullscreen mode.Toggle ToolboxToolboxTriple QuotesUncomment Lines Ctrl+Shift+XUncomment the selected lines.UntabifyUse TabsVersion: View LogWebsite: White SpaceZoom In Ctrl++Zoom Out Ctrl+-Project-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: POT-Creation-Date: 2011-05-05 22:11-0400 PO-Revision-Date: 2011-05-07 11:23-0500 Last-Translator: Groza cristi Language-Team: LANGUAGE Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nie istnieje.Nie został zapisany. Czy chcesz go zapisać?&Cut Ctrl+X&Dokument&EdycjaPlik&PomocNowa karta Ctrl+NOpen Ctrl + O&Wtyczki& Drukuj Ctrl+PZakończ Ctrl + QRedo Ctrl+YZapisz Ctrl + S&Szukaj&Sesja& Undo Ctrl + Z&WidokOCzy na pewno?Asystentów i innychAutor:Autouzupełnianie SzelkiAutoindentationBackspace Usunięcie wcięcia tekstuBad EOLKlamryPrzywróć ostatnią akcję.&Kopiuj Ctrl+CAn&uluj ostatniej akcji.Zamknij & Tab Ctrl+WZamknij bieżącą kartę.Colour PaletteLines komentarz Ctrl+Shift+CKomentarz wybranych linii.KomentarzeKopiuj zaznaczenie.Nie można załadować pliku .PlikWytnij zaznaczenie.Zmniejsz rozmiar tekstu.Dedent Ctrl + JDedent wybranych linii.Usuń SessionUsuń zapisanego pliku sesji.Opis:Edge LineEdge Line stanowisko:AutozapisWłącz LogWłącz SessionWłącz/Wyłącz Obsługa sesji.Włącz/wyłącz podświetlanie składni.Usuń LogZnajdźPokaż Ctrl+FZnajdź i zamień Ctrl+HZnajdowanie i zastępowanie tekstu za pomocą wyrażeń regularnych.Znajdź tekst za pomocą wyrażenia regularnego.Pokaż/Ukryj krotnie marek.Pełny ekran F11IdentyfikatoryZwiększ rozmiar tekstu.Wcięcie Ctrl+Kwcięcie wybranych linii.Wcięcia przewodnikiBłąd wejściaData dodaniaNależy podać datę w pozycji kursora.Liczby naturalneSłowa kluczoweNumery liniiZarządzaj gEcrit Plugins.Metoda NamesNowyRozmiar normalny Ctrl+0OKOS ShellOpenOtwórz nowy dokument.Otwórz nową kartę.Otwórz okno o programie.Otwórz okno konfiguracji.Otwarty plikOperatorówP&aste Ctrl+VWklej wyboru.Proszę się upewnić, że dane są zapisywane. Czy na pewno chcesz wyjść?Plugin ManagerWtyczkiUstawienia Ctrl+EDrukujDrukuje bieżący dokument.Python ShellQuitZamknij gEcritZamknij gEcrit.Ostatnie files Show ostatnio otwieranych plików.Regex Search Ctrl+Shift+FRegex Znajdź i zamień Ctrl+ hift+HOdśwież Ctrl+ROdśwież bieżącego pliku z dysku.UsuńUsuń spacje na końcuUsuń spacje na końcu linii.Zamień spacje kart.Zamień karty spacjami.Uruchom File F5Uruchom w bieżącym dokumencie. (python tylko)Uruchom bieżącego pliku. (Python tylko)ZapiszZapisz wszystkieZapisz jakoZapisz sesjęZapisz dane każdego # znaków:Zapisz bieżący stan aplikacji.Zapisz bieżący dokument w differend imię.Zapisz bieżącego dokumentu.Zapisz dokument pod inną nazwą.Zapisz dokument.Zapisuje wszystkie otwarte dokumenty, które drogą.Znajdź i zamieńWyszukiwanie i zamiana tekstu w bieżącym dokumencie.Wyszukiwanie tekstu w bieżącym dokumencie.Zaznacz wszystko Ctrl+AWybierz Code Block Ctrl+Shift+AZaznacz wszystko do końca bloku kodu.Wybierz dokumentu.Sesja załadowana.zapisanej sesji.Ustaw rozmiar tekstu do normy.UstawieniaPokaż numery liniiSpacjaPokaż/Ukryj okno asystentów.Pokaż/Ukryj okno Toolbox.Pokaż/Ukryj krotnie znaków.Pokaż/Ukryj prowadnice wcięcia.Pokaż/Ukryj numery linii.Pokaż/Ukryj pasek stanu.Pokaż/Ukryj krawędzi.Pokaż/Ukryj spacji.Pasek stanuPasek stanuStop/Start powłoki Pythona.Stop/Start powłoki systemu operacyjnego.StringsStrip spacje na ZapiszPodświetlanie składniTabifyKoniec pliku został osiągnięty! Nic nie zastąpi.Plik Przełącz asystentówPrzełącz tryb pełnoekranowy.Przełącz ToolboxToolboxPotrójnych cudzysłowówOdkomentować linie Ctrl+Shift+XOdkomentować wybrane linie.UntabifyUżyj kartyWersja:Zobacz LogStrona WWWWhite SpaceZoom In Ctrl++Zoom Out Ctrl+-gecrit-2.8.4/icons/printer.bmp000777 000000 000000 00000006066 12051462410 016270 0ustar00rootroot000000 000000 BM6 6(  ޫqruKLP68<ՠjknOOQobK|EȘCf68<̔cdhVSQ~mPMثYȌ|:<@uvy͵{|}{|~_`d`[TzVWsԣwob"GIMabeLMQHIMϠ̌߸߿ױvkW!$(efiUVYNOSIJN^^bڷԫ͞ӸkugP-/4z|~stv]^aWX[PQUJKOPQUزݽְěz{af]NCA>35:9;?8:>7:=TVZŸghk_`cYZ]RSWLMQJKOހfeeoqiZOLH<=ACDH@BF>@D?ADBDHJLOXY\efhmopz{|ghjabdZ[^TUXNOR[\_ȀQRVJKOFGKDFJFHKLNQY[^fhjqrtyz{~uvxijlcdf\]`VWZPQT˸NPS[]_hikrsuy{|~opr\^`GJMPQTyz|tuwklnefh^_bXY\xy{egiRTV?AD+.2"!&cehǯtuvmnpghj`adnpq[]_HJM57;!$)  $ #(&)-,/346;;>BADHGIMUW[۠uvxoprijl|}qsu,/3! #"'IKO}~pqt:<@@CGFIMKNQORUSUYXZ][]`XZ]X[^XZ^WZ]~wxzqrt[^a),00378;??BFFHLKNQPRVTVZVY\[]`_adbdgefigikikmijlgikacePRVFIMACG;>Bޔyz|ŽRTXTVZWZ]Z\`]`cacfcehfgjhilijmhilfgjdehabe^`b[\_WY\SUXOQTHJM(+/#%*"&249ݠ۴`bfacghilijlgikefibdg_ad\^aXZ]UVZQRVLNRHJMCFI?AE;=A8:>58<57;!&Ę췸PRVRTWZ\_VX[RTWNOSIKOEGJ@BF<>B79=36:13702602613846:79=;<@>@D!$( 259037=?C8:>36:/26,.3*-1+.2249<>BGILSUXacflmpQRVIJNMORlnq %%','*.+-2HIMrsv}}tuwjkmmnpZ[^VW[opsijlnoqnoqopropropropropropropraceoproproproproproproproproprgikoproproproproproproproproprlmowxzoproproproproproproproprnoqdfioproproproproproproproproprPRUoproproproproproproproprXZ]noqoproprnoqoprpqsrsutuwhjlѻgecrit-2.8.4/data/plugins/Terminator.py000777 000000 000000 00000123554 12051462410 020064 0ustar00rootroot000000 000000 import os.path #!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import pty import select from array import * import threading import wx import fcntl try: import termios TERMIOS = True except: print "termios is not available. Terminator will not be available." TERMIOS = False import struct import tty import wx import yapsy.IPlugin from data.plugins.categories import Passive class V102Terminal: """ Emulator for VT100 terminal programs. This module provides terminal emulation for VT100 terminal programs. It handles V100 special characters and most important escape sequences. It also handles graphics rendition which specifies text style(i.e. bold, italics), foreground color and background color. The handled escape sequences are CUU, CUD, CUF, CUB, CHA, CUP, ED, EL, VPA and SGR. """ __ASCII_NUL = 0 # Null __ASCII_BEL = 7 # Bell __ASCII_BS = 8 # Backspace __ASCII_HT = 9 # Horizontal Tab __ASCII_LF = 10 # Line Feed __ASCII_VT = 11 # Vertical Tab __ASCII_FF = 12 # Form Feed __ASCII_CR = 13 # Carriage Return __ASCII_XON = 17 # Resume Transmission __ASCII_XOFF = 19 # Stop Transmission or Ignore Characters __ASCII_ESC = 27 # Escape __ASCII_SPACE = 32 # Space __ASCII_CSI = 153 # Control Sequence Introducer __ESCSEQ_CUU = 'A' # n A: Moves the cursor up n(default 1) times. __ESCSEQ_CUD = 'B' # n B: Moves the cursor down n(default 1) times. __ESCSEQ_CUF = 'C' # n C: Moves the cursor forward n(default 1) times. __ESCSEQ_CUB = 'D' # n D: Moves the cursor backward n(default 1) times. __ESCSEQ_CHA = 'G' # n G: Cursor horizontal absolute position. 'n' denotes __ESCSEQ_CUP = 'H' # n ; m H: Moves the cursor to row n, column m. __ESCSEQ_ED = 'J' # n J: Clears part of the screen. If n is zero __ESCSEQ_EL = 'K' # n K: Erases part of the line. If n is zero __ESCSEQ_VPA = 'd' # n d: Cursor vertical absolute position. 'n' denotes __ESCSEQ_SGR = 'm' # n [;k] m: Sets SGR (Select Graphic Rendition) RENDITION_STYLE_BOLD = 1 RENDITION_STYLE_DIM = 2 RENDITION_STYLE_ITALIC = 4 RENDITION_STYLE_UNDERLINE = 8 RENDITION_STYLE_SLOW_BLINK = 16 RENDITION_STYLE_FAST_BLINK = 32 RENDITION_STYLE_INVERSE = 64 RENDITION_STYLE_HIDDEN = 128 CALLBACK_SCROLL_UP_SCREEN = 1 CALLBACK_UPDATE_LINES = 2 CALLBACK_UPDATE_CURSOR_POS = 3 CALLBACK_UPDATE_WINDOW_TITLE = 4 CALLBACK_UNHANDLED_ESC_SEQ = 5 def __init__(self, rows, cols): """ Initializes the terminal with specified rows and columns. User can resize the terminal any time using Resize method. By default the screen is cleared(filled with blank spaces) and cursor positioned in the first row and first column. """ self.cols = cols self.rows = rows self.curX = 0 self.curY = 0 self.ignoreChars = False self.charHandlers = { self.__ASCII_NUL: self.__OnCharIgnore, self.__ASCII_BEL: self.__OnCharIgnore, self.__ASCII_BS: self.__OnCharBS, self.__ASCII_HT: self.__OnCharHT, self.__ASCII_LF: self.__OnCharLF, self.__ASCII_VT: self.__OnCharLF, self.__ASCII_FF: self.__OnCharLF, self.__ASCII_CR: self.__OnCharCR, self.__ASCII_XON: self.__OnCharXON, self.__ASCII_XOFF: self.__OnCharXOFF, self.__ASCII_ESC: self.__OnCharESC, self.__ASCII_CSI: self.__OnCharCSI, } self.escSeqHandlers = { self.__ESCSEQ_CUU: self.__OnEscSeqCUU, self.__ESCSEQ_CUD: self.__OnEscSeqCUD, self.__ESCSEQ_CUF: self.__OnEscSeqCUF, self.__ESCSEQ_CUB: self.__OnEscSeqCUB, self.__ESCSEQ_CHA: self.__OnEscSeqCHA, self.__ESCSEQ_CUP: self.__OnEscSeqCUP, self.__ESCSEQ_ED: self.__OnEscSeqED, self.__ESCSEQ_EL: self.__OnEscSeqEL, self.__ESCSEQ_VPA: self.__OnEscSeqVPA, self.__ESCSEQ_SGR: self.__OnEscSeqSGR, } self.printableChars = "0123456789" self.printableChars += "abcdefghijklmnopqrstuvwxyz" self.printableChars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ" self.printableChars += """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ """ self.printableChars += "\t" self.screen = [] self.scrRendition = [] self.curRendition = 0L self.isLineDirty = [] for i in range(rows): line = array('c') rendition = array('L') for j in range(cols): line.append(' ') rendition.append(0) self.screen.append(line) self.scrRendition.append(rendition) self.isLineDirty.append(False) self.callbacks = {self.CALLBACK_SCROLL_UP_SCREEN: None, self.CALLBACK_UPDATE_LINES: None, self.CALLBACK_UPDATE_CURSOR_POS: None, self.CALLBACK_UNHANDLED_ESC_SEQ: None, self.CALLBACK_UPDATE_WINDOW_TITLE: None} self.unparsedInput = None def GetRawScreen(self): """ Returns the screen as a list of strings. The list will have rows no. of strings and each string will have columns no. of characters. Blank space used represents no character. """ return self.screen def GetRawScreenRendition(self): """ Returns the screen as a list of array of long. The list will have rows no. of array and each array will have columns no. of longs. The first 8 bits of long represents rendition style like bold, italics and etc. The next 4 bits represents foreground color and next 4 bits for background color. """ return self.scrRendition def GetRows(self): """ Returns no. rows in the terminal """ return self.rows def GetCols(self): """ Returns no. cols in the terminal """ return self.cols def GetSize(self): """ Returns terminal rows and cols as tuple """ return (self.rows, self.cols) def Resize(self, rows, cols): """ Resizes the terminal to specified rows and cols. - If the new no. rows is less than existing no. rows then existing rows are deleted at top. - If the new no. rows is greater than existing no. rows then blank rows are added at bottom. - If the new no. cols is less than existing no. cols then existing cols are deleted at right. - If the new no. cols is greater than existing no. cols then new cols are added at right. """ if rows < self.rows: for i in range(self.rows - rows): self.isLineDirty.pop(0) self.screen.pop(0) self.scrRendition.pop(0) elif rows > self.rows: for i in range(rows - self.rows): line = array('c') rendition = array('L') for j in range(self.cols): line.append(' ') rendition.append(0) self.screen.append(line) self.scrRendition.append(rendition) self.isLineDirty.append(False) if cols < self.cols: for i in range(self.rows): (self.screen)[i] = ((self.screen)[i])[:cols - self.cols] for j in range(self.cols - cols): (self.scrRendition)[i].pop(len((self.scrRendition)[i]) - 1) elif cols > self.cols: for i in range(self.rows): for j in range(cols - self.cols): (self.screen)[i].append(' ') (self.scrRendition)[i].append(0) self.rows = rows self.cols = cols def GetCursorPos(self): """ Returns cursor position as tuple """ return (self.curY, self.curX) def Clear(self): """ Clears the entire terminal screen """ ClearRect(0, 0, self.rows - 1, self.cols - 1) def ClearRect(self, startRow, startCol, endRow, endCol): """ Clears the terminal screen starting from startRow and startCol to endRow and EndCol. """ if startRow < 0: startRow = 0 elif startRow >= self.rows: startRow = self.rows - 1 if startCol < 0: startCol = 0 elif startCol >= self.cols: startCol = self.cols - 1 if endRow < 0: endRow = 0 elif endRow >= self.rows: endRow = self.rows - 1 if endCol < 0: endCol = 0 elif endCol >= self.cols: endCol = self.cols - 1 if startRow > endRow: (startRow, endRow) = (endRow, startRow) if startCol > endCol: (startCol, endCol) = (endCol, startCol) for i in range(startRow, endRow + 1): start = 0 end = self.cols - 1 if i == startRow: start = startCol elif i == endRow: end = endCol for j in range(start, end + 1): (self.screen)[i][j] = ' ' (self.scrRendition)[i][j] = 0 if end + 1 > start: (self.isLineDirty)[i] = True def GetChar(self, row, col): ''' Returns the character at the location specified by row and col. The row and col should be in the range 0..rows - 1 and 0..cols - 1." ''' if row < 0 or row >= self.rows: return None if cols < 0 or col >= self.cols: return None return (self.screen)[row][col] def GetRendition(self, row, col): """ Returns the screen rendition at the location specified by row and col. The returned value is a long, the first 8 bits specifies the rendition style and next 4 bits for foreground and another 4 bits for background color. """ if row < 0 or row >= self.rows: return None if col < 0 or col >= self.cols: return None style = (self.scrRendition)[row][col] & 0x000000ff fgcolor = ((self.scrRendition)[row][col] & 0x00000f00) >> 8 bgcolor = ((self.scrRendition)[row][col] & 0x0000f000) >> 12 return (style, fgcolor, bgcolor) def GetLine(self, lineno): """ Returns the terminal screen line specified by lineno. The line is returned as string, blank space represents empty character. The lineno should be in the range 0..rows - 1 """ if lineno < 0 or lineno >= self.rows: return None return (self.screen)[lineno].tostring() def GetLines(self): """ Returns terminal screen lines as a list, same as GetScreen """ lines = [] for i in range(self.rows): lines.append((self.screen)[i].tostring()) return lines def GetLinesAsText(self): """ Returns the entire terminal screen as a single big string. Each row is seperated by \\n and blank space represents empty character. """ text = "" for i in range(self.rows): text += (self.screen)[i].tostring() text += "\n" text = text.rstrip("\n") # removes leading new lines return text def GetDirtyLines(self): """ Returns list of dirty lines(line nos) since last call to GetDirtyLines. The line no will be 0..rows - 1. """ dirtyLines = [] for i in range(self.rows): if (self.isLineDirty)[i]: dirtyLines.append(i) (self.isLineDirty)[i] = False return dirtyLines def SetCallback(self, event, func): """ Sets callback function for the specified event. The event should be any one of the following. None can be passed as callback function to reset the callback. CALLBACK_SCROLL_UP_SCREEN Called before scrolling up the terminal screen. CALLBACK_UPDATE_LINES Called when ever some lines need to be updated. Usually called before leaving ProcessInput and before scrolling up the terminal screen. CALLBACK_UPDATE_CURSOR_POS Called to update the cursor position. Usually called before leaving ProcessInput. CALLBACK_UPDATE_WINDOW_TITLE Called when ever a window title escape sequence encountered. The terminal window title will be passed as a string. CALLBACK_UNHANDLED_ESC_SEQ Called when ever a unsupported escape sequence encountered. The unhandled escape sequence(escape sequence character and it parameters) will be passed as a string. """ (self.callbacks)[event] = func def ProcessInput(self, text): """ Processes the given input text. It detects V100 escape sequences and handles it. Any partial unparsed escape sequences are stored internally and processed along with next input text. Before leaving, the function calls the callbacks CALLBACK_UPDATE_LINE and CALLBACK_UPDATE_CURSOR_POS to update the changed lines and cursor position respectively. """ if text == None: return if self.unparsedInput != None: text = self.unparsedInput + text self.unparsedInput = None textlen = len(text) index = 0 while index < textlen: ch = text[index] ascii = ord(ch) if self.ignoreChars: index += 1 continue if ascii in self.charHandlers.keys(): index = (self.charHandlers)[ascii](text, index) else: if ch in self.printableChars: self.__PushChar(ch) else: print "WARNING: Unsupported character %s:%d" % (ch, ascii) index += 1 if (self.callbacks)[self.CALLBACK_UPDATE_LINES] != None: (self.callbacks)[self.CALLBACK_UPDATE_LINES]() if (self.callbacks)[self.CALLBACK_UPDATE_CURSOR_POS] != None: (self.callbacks)[self.CALLBACK_UPDATE_CURSOR_POS]() def ScrollUp(self): """ Scrolls up the terminal screen by one line. The callbacks CALLBACK_UPDATE_LINES and CALLBACK_SCROLL_UP_SCREEN are called before scrolling the screen. """ if (self.callbacks)[self.CALLBACK_UPDATE_LINES] != None: (self.callbacks)[self.CALLBACK_UPDATE_LINES]() if (self.callbacks)[self.CALLBACK_SCROLL_UP_SCREEN] != None: (self.callbacks)[self.CALLBACK_SCROLL_UP_SCREEN]() line = self.screen.pop(0) for i in range(self.cols): line[i] = ' ' self.screen.append(line) rendition = self.scrRendition.pop(0) for i in range(self.cols): rendition[i] = 0 self.scrRendition.append(rendition) def Dump(self, file=sys.stdout): """ Dumps the entire terminal screen into the given file/stdout """ for i in range(self.rows): file.write((self.screen)[i].tostring()) file.write("\n") def __NewLine(self): """ Moves the cursor to the next line, if the cursor is already at the bottom row then scrolls up the screen. """ self.curX = 0 if self.curY + 1 < self.rows: self.curY += 1 else: self.ScrollUp() def __PushChar(self, ch): """ Writes the character(ch) into current cursor position and advances cursor position. """ if self.curX >= self.cols: self.__NewLine() (self.screen)[self.curY][self.curX] = ch (self.scrRendition)[self.curY][self.curX] = self.curRendition self.curX += 1 (self.isLineDirty)[self.curY] = True def __ParseEscSeq(self, text, index): """ Parses escape sequence from the input and returns the index after escape sequence, the escape sequence character and parameter for the escape sequence """ textlen = len(text) interChars = None while index < textlen: ch = text[index] ascii = ord(ch) if ascii >= 32 and ascii <= 63: if interChars == None: interChars = ch else: interChars += ch elif ascii >= 64 and ascii <= 125: return (index + 1, chr(ascii), interChars) else: print "Unexpected characters in escape sequence ", ch index += 1 return (index, '?', interChars) def __HandleEscSeq(self, text, index): """ Tries to parse escape sequence from input and if its not complete then puts it in unparsedInput and process it when the ProcessInput called next time. """ if text[index] == '[': index += 1 (index, finalChar, interChars) = self.__ParseEscSeq(text, index) if finalChar == '?': self.unparsedInput = "\033[" if interChars != None: self.unparsedInput += interChars elif finalChar in self.escSeqHandlers.keys(): (self.escSeqHandlers)[finalChar](interChars) else: escSeq = "" if interChars != None: escSeq += interChars escSeq += finalChar if (self.callbacks)[self.CALLBACK_UNHANDLED_ESC_SEQ] != \ None: (self.callbacks)[self.CALLBACK_UNHANDLED_ESC_SEQ](escSeq) elif text[index] == ']': textlen = len(text) if index + 2 < textlen: if text[index + 1] == '0' and text[index + 2] == ';': index += 3 # ignore '0' and ';' start = index while index < textlen: if ord(text[index]) == self.__ASCII_BEL: break index += 1 self.__OnEscSeqTitle(text[start:index]) return index def __OnCharBS(self, text, index): """ Handler for backspace character """ if self.curX > 0: self.curX -= 1 return index + 1 def __OnCharHT(self, text, index): """ Handler for horizontal tab character """ while True: self.curX += 1 if self.curX % 8 == 0: break return index + 1 def __OnCharLF(self, text, index): """ Handler for line feed character """ self.__NewLine() return index + 1 def __OnCharCR(self, text, index): """ Handler for carriage return character """ self.curX = 0 return index + 1 def __OnCharXON(self, text, index): """ Handler for XON character """ self.ignoreChars = False return index + 1 def __OnCharXOFF(self, text, index): """ Handler for XOFF character """ self.ignoreChars = True return index + 1 def __OnCharESC(self, text, index): """ Handler for escape character """ index += 1 if index < len(text): index = self.__HandleEscSeq(text, index) return index def __OnCharCSI(self, text, index): """ Handler for control sequence intruducer(CSI) character """ index += 1 index = self.__HandleEscSeq(text, index) return index def __OnCharIgnore(self, text, index): """ Dummy handler for unhandler characters """ return index + 1 def __OnEscSeqTitle(self, params): """ Handler for window title escape sequence """ if (self.callbacks)[self.CALLBACK_UPDATE_WINDOW_TITLE] != None: (self.callbacks)[self.CALLBACK_UPDATE_WINDOW_TITLE](params) def __OnEscSeqCUU(self, params): """ Handler for escape sequence CUU """ n = 1 if params != None: n = int(params) self.curY -= n None if self.curY < 0: self.curY = 0 def __OnEscSeqCUD(self, params): """ Handler for escape sequence CUD """ n = 1 if params != None: n = int(params) self.curY += n None if self.curY >= self.rows: self.curY = self.rows - 1 def __OnEscSeqCUF(self, params): """ Handler for escape sequence CUF """ n = 1 if params != None: n = int(params) self.curX += n None if self.curX >= self.cols: self.curX = self.cols - 1 def __OnEscSeqCUB(self, params): """ Handler for escape sequence CUB """ n = 1 if params != None: n = int(params) self.curX -= n None if self.curX < 0: self.curX = 0 def __OnEscSeqCHA(self, params): """ Handler for escape sequence CHA """ if params == None: print "WARNING: CHA without parameter" return col = int(params) col -= 1 if col >= 0 and col < self.cols: self.curX = col else: print "WARNING: CHA column out of boundary" def __OnEscSeqCUP(self, params): """ Handler for escape sequence CUP """ y = 0 x = 0 if params != None: values = params.split(';') if len(values) == 2: y = int(values[0]) - 1 x = int(values[1]) - 1 else: print "WARNING: escape sequence CUP has invalid parameters" return if x < 0: x = 0 elif x >= self.cols: x = self.cols - 1 if y < 0: y = 0 elif y >= self.rows: y = self.rows - 1 self.curX = x self.curY = y def __OnEscSeqED(self, params): """ Handler for escape sequence ED """ n = 0 if params != None: n = int(params) if n == 0: self.ClearRect(self.curY, self.curX, self.rows - 1, self.cols - 1) elif n == 1: self.ClearRect(0, 0, self.curY, self.curX) elif n == 2: self.ClearRect(0, 0, self.rows - 1, self.cols - 1) else: print "WARNING: escape sequence ED has invalid parameter" def __OnEscSeqEL(self, params): """ Handler for escape sequence EL """ n = 0 if params != None: n = int(params) if n == 0: self.ClearRect(self.curY, self.curX, self.curY, self.cols - 1) elif n == 1: self.ClearRect(self.curY, 0, self.curY, self.curX) elif n == 2: self.ClearRect(self.curY, 0, self.curY, self.cols - 1) else: print "WARNING: escape sequence EL has invalid parameter" def __OnEscSeqVPA(self, params): """ Handler for escape sequence VPA """ if params == None: print "WARNING: VPA without parameter" return row = int(params) row -= 1 if row >= 0 and row < self.rows: self.curY = row else: print "WARNING: VPA line no. out of boundary" def __OnEscSeqSGR(self, params): """ Handler for escape sequence SGR """ if params != None: renditions = params.split(';') for rendition in renditions: irendition = int(rendition) if irendition == 0: self.curRendition = 0L elif irendition > 0 and irendition < 9: self.curRendition |= 1 << irendition - 1 elif irendition >= 30 and irendition <= 37: self.curRendition |= irendition - 29 << 8 & \ 0x00000f00 elif irendition >= 40 and irendition <= 47: self.curRendition |= irendition - 39 << 12 & \ 0x0000f000 elif irendition == 27: self.curRendition &= 0xffffffbf elif irendition == 39: self.curRendition &= 0xfffff0ff elif irendition == 49: self.curRendition &= 0xffff0fff else: print "WARNING: Unsupported rendition", irendition else: self.curRendition = 0L class ShellEmulator(wx.TextCtrl): def __init__(self, parent, path_to_shell): self.parent = parent self.path_to_shell = path_to_shell wx.TextCtrl.__init__(self, parent, -1, pos=(0, 0), size= (100, 100), style=wx.TE_MULTILINE | wx.RESIZE_BORDER) ID_TERMINAL = self.GetId() font = wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTSTYLE_NORMAL, False) self.SetFont(font) self.Bind(wx.EVT_CHAR, self.OnTerminalChar, id=ID_TERMINAL) self.Bind(wx.EVT_KEY_DOWN, self.OnTerminalKeyDown, id= ID_TERMINAL) self.Bind(wx.EVT_KEY_UP, self.OnTerminalKeyUp, id=ID_TERMINAL) self.termRows = 24 self.termCols = 80 self.FillScreen() self.linesScrolledUp = 0 self.scrolledUpLinesLen = 0 self.termEmulator = V102Terminal(self.termRows, self.termCols) self.termEmulator.SetCallback(self.termEmulator.CALLBACK_SCROLL_UP_SCREEN, self.OnTermEmulatorScrollUpScreen) self.termEmulator.SetCallback(self.termEmulator.CALLBACK_UPDATE_LINES, self.OnTermEmulatorUpdateLines) self.termEmulator.SetCallback(self.termEmulator.CALLBACK_UPDATE_CURSOR_POS, self.OnTermEmulatorUpdateCursorPos) self.termEmulator.SetCallback(self.termEmulator.CALLBACK_UPDATE_WINDOW_TITLE, self.OnTermEmulatorUpdateWindowTitle) self.termEmulator.SetCallback(self.termEmulator.CALLBACK_UNHANDLED_ESC_SEQ, self.OnTermEmulatorUnhandledEscSeq) self.isRunning = False self.UpdateUI() def OnTerminalKeyDown(self, event): event.Skip() def OnTerminalKeyUp(self, event): event.Skip() def OnTerminalChar(self, event): if not self.isRunning: return ascii = event.GetKeyCode() keystrokes = None if ascii < 256: keystrokes = chr(ascii) elif ascii == wx.WXK_UP: keystrokes = "\033[A" elif ascii == wx.WXK_DOWN: keystrokes = "\033[B" elif ascii == wx.WXK_RIGHT: keystrokes = "\033[C" elif ascii == wx.WXK_LEFT: keystrokes = "\033[D" if keystrokes != None: os.write(self.processIO, keystrokes) def OnTermEmulatorScrollUpScreen(self): blankLine = "\n" for i in range(self.termEmulator.GetCols()): blankLine += ' ' lineLen = self.termCols self.AppendText(blankLine) self.linesScrolledUp += 1 self.scrolledUpLinesLen += lineLen + 1 def OnTermEmulatorUpdateLines(self): self.UpdateDirtyLines() wx.YieldIfNeeded() def OnTermEmulatorUpdateCursorPos(self): self.UpdateCursorPos() def OnTermEmulatorUpdateWindowTitle(self, title): pass def OnTermEmulatorUnhandledEscSeq(self, escSeq): print "Unhandled escape sequence: [" + escSeq def FillScreen(self): """ Fills the screen with blank lines so that we can update terminal dirty lines quickly. """ text = "" for i in range(self.termRows): for j in range(self.termCols): text += ' ' text += "\n" text = text.rstrip("\n") self.SetValue(text) def UpdateUI(self): self.Enable(self.isRunning) def OnRun(self): path = self.path_to_shell #self.tc1.GetValue() basename = os.path.expanduser('~') arglist = [basename] arguments = "" #self.tc2.GetValue() if arguments != "": for arg in arguments.split(' '): arglist.append(arg) self.termRows = 24 #int(self.tc3.GetValue()) self.termCols = 80 #int(self.tc4.GetValue()) (rows, cols) = self.termEmulator.GetSize() if rows != self.termRows or cols != self.termCols: self.termEmulator.Resize(self.termRows, self.termCols) (processPid, processIO) = pty.fork() if processPid == 0: # child process os.execl(path, basename) print "Child process pid", processPid fcntl.ioctl(processIO, termios.TIOCSWINSZ, struct.pack("hhhh", self.termRows, self.termCols, 0, 0)) tcattrib = termios.tcgetattr(processIO) tcattrib[3] = tcattrib[3] & ~termios.ICANON termios.tcsetattr(processIO, termios.TCSAFLUSH, tcattrib) self.processPid = processPid self.processIO = processIO self.processOutputNotifierThread = threading.Thread(target=self.__ProcessOuputNotifierRun) self.waitingForOutput = True self.stopOutputNotifier = False self.processOutputNotifierThread.start() self.isRunning = True self.UpdateUI() def __ProcessOuputNotifierRun(self): inpSet = [self.processIO] while not self.stopOutputNotifier and self.__ProcessIsAlive(): if self.waitingForOutput: (inpReady, outReady, errReady) = select.select(inpSet, [], [], 1) if self.processIO in inpReady: self.waitingForOutput = False wx.CallAfter(self.ReadProcessOutput) if not self.__ProcessIsAlive(): self.isRunning = False wx.CallAfter(self.ReadProcessOutput) wx.CallAfter(self.UpdateUI) print "Process exited" print "Notifier thread exited" def __ProcessIsAlive(self): try: (pid, status) = os.waitpid(self.processPid, os.WNOHANG) if pid == self.processPid and os.WIFEXITED(status): return False except: return False return True def ReadProcessOutput(self): output = "" try: while True: data = os.read(self.processIO, 512) datalen = len(data) output += data if datalen < 512: break except: output = "" self.termEmulator.ProcessInput(output) self.SetForegroundColour((0, 0, 0)) self.SetBackgroundColour((255, 255, 255)) self.waitingForOutput = True def UpdateDirtyLines(self, dirtyLines=None): text = "" curStyle = 0 curFgColor = 0 curBgColor = 0 self.SetTerminalRenditionForeground(curFgColor) self.SetTerminalRenditionBackground(curBgColor) screen = self.termEmulator.GetRawScreen() screenRows = self.termEmulator.GetRows() screenCols = self.termEmulator.GetCols() if dirtyLines == None: dirtyLines = self.termEmulator.GetDirtyLines() disableTextColoring = False #self.cb1.IsChecked() for row in dirtyLines: text = "" lineNo = self.linesScrolledUp + row lineStart = self.GetTextCtrlLineStart(lineNo) lineEnd = lineStart + self.termCols self.Replace(lineStart, lineEnd, "") self.SetInsertionPoint(lineStart) for col in range(screenCols): (style, fgcolor, bgcolor) = self.termEmulator.GetRendition(row, col) if not disableTextColoring and (curStyle != style or curFgColor != fgcolor or curBgColor != bgcolor): if text != "": self.WriteText(text) text = "" if curStyle != style: curStyle = style if style == 0: self.SetForegroundColour((0, 0, 0)) self.SetBackgroundColour((255, 255, 255)) elif style & self.termEmulator.RENDITION_STYLE_INVERSE: self.SetForegroundColour((255, 255, 255)) self.SetBackgroundColour((0, 0, 0)) else: pass if curFgColor != fgcolor: curFgColor = fgcolor self.SetTerminalRenditionForeground(curFgColor) if curBgColor != bgcolor: curBgColor = bgcolor self.SetTerminalRenditionBackground(curBgColor) text += screen[row][col] self.WriteText(text) def SetTerminalRenditionForeground(self, fgcolor): if fgcolor != 0: if fgcolor == 1: self.SetForegroundColour((0, 0, 0)) elif fgcolor == 2: self.SetForegroundColour((255, 0, 0)) elif fgcolor == 3: self.SetForegroundColour((0, 255, 0)) elif fgcolor == 4: self.SetForegroundColour((255, 255, 0)) elif fgcolor == 5: self.SetForegroundColour((0, 0, 255)) elif fgcolor == 6: self.SetForegroundColour((255, 0, 255)) elif fgcolor == 7: self.SetForegroundColour((0, 255, 255)) elif fgcolor == 8: self.SetForegroundColour((255, 255, 255)) else: self.SetForegroundColour((0, 0, 0)) def SetTerminalRenditionBackground(self, bgcolor): if bgcolor != 0: if bgcolor == 1: self.SetBackgroundColour((0, 0, 0)) elif bgcolor == 2: self.SetBackgroundColour((255, 0, 0)) elif bgcolor == 3: self.SetBackgroundColour((0, 255, 0)) elif bgcolor == 4: self.SetBackgroundColour((255, 255, 0)) elif bgcolor == 5: self.SetBackgroundColour((0, 0, 255)) elif bgcolor == 6: self.SetBackgroundColour((255, 0, 255)) elif bgcolor == 7: self.SetBackgroundColour((0, 255, 255)) elif bgcolor == 8: self.SetBackgroundColour((255, 255, 255)) else: self.SetBackgroundColour((255, 255, 255)) def GetTextCtrlLineStart(self, lineNo): lineStart = self.scrolledUpLinesLen lineStart += (self.termCols + 1) * (lineNo - self.linesScrolledUp) return lineStart def UpdateCursorPos(self): (row, col) = self.termEmulator.GetCursorPos() lineNo = self.linesScrolledUp + row insertionPoint = self.GetTextCtrlLineStart(lineNo) insertionPoint += col self.SetInsertionPoint(insertionPoint) def OnClose(self): if self.isRunning: self.stopOutputNotifier = True self.processOutputNotifierThread.join(None) self.UpdateUI() class Terminator(wx.Frame, Passive, yapsy.IPlugin.IPlugin): def __init__(self): self.name = "Terminator" self.terminal_index = { #name : path } self.active_shells = { #name : instance } def Init(self, parent): # if termios is not installed, abort. if not TERMIOS: return self.parent = parent self.__config_path = os.path.join(self.parent.HOMEDIR, ".gEcrit/Terminator.conf") wx.Frame.__init__(self, self.parent, size = (400,400)) self.main_panel = wx.Panel(self) self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.button_sizer = wx.BoxSizer(wx.HORIZONTAL) self.add_shell_bt = wx.Button(self.main_panel, -1, "Add Shell") self.add_shell_bt.Bind(wx.EVT_BUTTON, self.OnAddNewTerm) self.remove_shell_bt = wx.Button(self.main_panel, -1, "Remove Shell") self.remove_shell_bt.Bind(wx.EVT_BUTTON, self.OnRemoveTerm) self.restart_shell_bt = wx.Button(self.main_panel, -1, "Restart Shell") self.restart_shell_bt.Bind(wx.EVT_BUTTON, self.OnRestartTerm) self.close_bt = wx.Button(self.main_panel, -1, "Close") self.close_bt.Bind(wx.EVT_BUTTON, self.HideMe) self.button_sizer.Add(self.add_shell_bt, 0, wx.EXPAND) self.button_sizer.AddSpacer(10) self.button_sizer.Add(self.remove_shell_bt, 0, wx.EXPAND) self.button_sizer.AddSpacer(10) self.button_sizer.Add(self.restart_shell_bt, 0, wx.EXPAND) self.button_sizer.AddSpacer(10) self.button_sizer.Add(self.close_bt, 0, wx.EXPAND) self.shell_list = wx.ListCtrl(self.main_panel, style = wx.LC_REPORT|wx.LC_SINGLE_SEL ) self.shell_list.InsertColumn(0, "Shell") self.shell_list.SetColumnWidth(0,100) self.shell_list.InsertColumn(1, "Path") self.shell_list.SetColumnWidth(1,300) self.shell_name_txt = wx.TextCtrl(self.main_panel, -1, "[Name]") self.path_txt = wx.TextCtrl(self.main_panel, -1, "[Path]") self.main_sizer.Add(self.shell_list, 1, wx.EXPAND) self.main_sizer.Add(self.shell_name_txt, 0, wx.EXPAND) self.main_sizer.Add(self.path_txt, 0, wx.EXPAND) self.main_sizer.Add(self.button_sizer, 0, wx.EXPAND) self.main_panel.SetSizerAndFit(self.main_sizer) self.plugins_menu = wx.Menu() manage_entry = self.plugins_menu.Append(-1,"Manage Terminals") self.menu_item = self.parent.AddToMenuBar("Terminator", self.plugins_menu) self.parent.BindMenubarEvent(manage_entry, self.ShowMe) self.Bind(wx.EVT_CLOSE, self.HideMe) self.ReadConfigFile() self.InitShells() self.PopulateShellList() def AddTerminal(self, term_name): #taking bottom panel, it will the parent of the panel panel = wx.Panel(self.parent.GetBottomPanel()) #the shell parent #creating shell terminal = ShellEmulator(panel, self.terminal_index[term_name]) #sizer to keep it proprelly sized panel_sz = wx.BoxSizer(wx.HORIZONTAL) panel_sz.Add(terminal, 1, wx.EXPAND) terminal.OnRun() #starting shell panel.SetSizerAndFit(panel_sz) self.parent.AddToBottomPanel(panel, term_name) #add it to app bottom panel self.active_shells[term_name] = terminal #adding it to the active shells def RemoveTerminal(self, term_name): self.active_shells[term_name].OnClose() #closing shell self.parent.DeleteBottomPage(term_name) #removing from app bottom panel del self.active_shells[term_name] #delete it's entry from active shells del self.terminal_index[term_name] def ReadConfigFile(self): if os.path.exists(self.__config_path): #reading nd evaluating string conf = open(self.__config_path, "r") self.terminal_index = eval(conf.read()) conf.close() else: #create default conf if it does not exists conf = open(self.__config_path, "w") conf.write('{"Python":"/usr/bin/python","Bash":"/bin/bash"}\n') conf.close() def SaveConfig(self): conf = open(self.__config_path, "w") conf.write(str(self.terminal_index)) #writing the terminal index to file conf.close() def Stop(self): for i in self.active_shells: self.active_shells[i].OnClose() def InitShells(self): for i in self.terminal_index: self.AddTerminal(i) def OnAddNewTerm(self, event): path = self.path_txt.GetValue().rstrip() #striping whitespace name = self.shell_name_txt.GetValue().rstrip() if os.path.exists(path): if not name in self.terminal_index: self.terminal_index[name] = path self.shell_list.Append([name, path]) self.AddTerminal(name) self.SaveConfig() #updating config #shell name already exists else: wx.MessageDialog(self, "The entered name is already assigned.\n Please enter a valid name.", "Invalid Input", style = wx.OK).ShowModal() else: wx.MessageDialog(self, "The entered path does not exists.\n Please enter a valid path.", "Invalid Input", style = wx.OK).ShowModal() event.Skip() def OnRemoveTerm(self, event): start = -1 selected_item = self.shell_list.GetNextSelected(start) if selected_item != -1: term_name = self.shell_list.GetItemText(selected_item) #getting selected terminal name self.RemoveTerminal(term_name) #removing from app bottom panel self.shell_list.DeleteItem(selected_item) #removing from shell_list self.SaveConfig() #updatig config event.Skip() def OnRestartTerm(self, event): start = -1 selected_item = self.shell_list.GetNextSelected(start) if selected_item != -1: term_name = self.shell_list.GetItemText(selected_item) self.active_shells[term_name].OnClose() self.active_shells[term_name].OnRun() event.Skip() def ShowMe(self, event): self.Show() def HideMe(self, event): self.Hide() def PopulateShellList(self): #add all terminals to the shell_list for i in self.terminal_index: self.shell_list.Append([i, self.terminal_index[i]]) gecrit-2.8.4/data/__init__.py000777 000000 000000 00000000000 12051462410 015772 0ustar00rootroot000000 000000 gecrit-2.8.4/ColorPFrame.py000777 000000 000000 00000016057 12051462410 015516 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx, gettext from SyntaxHighlight import * import wx.lib.colourselect as csel class ColorPFrame(wx.Frame): """ ColorPFrame Provides the necessary function and control to modify the lexer styles. """ def __init__(self, parent=None): """ __init__ Makes its parent class global. """ self.parent = parent def CollorPaletteWindow(self, event, parent,id_range): """ CollorPaletteWindow Builds the GUI controls and binds the necessary binds to the corresponding functions. """ wx.Frame.__init__(self, self.parent, -1, "Colour Palette", size= (145, 530)) self._ = parent._ self.SetIcon(wx.Icon('icons/gEcrit.png', wx.BITMAP_TYPE_PNG)) cpalette_panel = wx.Panel(self) self.Bind(wx.EVT_CLOSE, self.HideMe) color_sizer = wx.BoxSizer(wx.VERTICAL) cpalette_panel.SetAutoLayout(True) mainSizer = wx.BoxSizer(wx.VERTICAL) cpalette_panel.SetSizer(mainSizer) keyword_sel = csel.ColourSelect(cpalette_panel, -1, self._("Keywords"), SyntCol.GetColor("Keywords"), pos=(10, 10), size=(121, 35)) keyword_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "Keywords")) strings_sel = csel.ColourSelect(cpalette_panel, -1, self._("Strings"), SyntCol.GetColor("Strings"), pos=(10, 50), size=(121, 35)) strings_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "Strings")) quote3_sel = csel.ColourSelect(cpalette_panel, -1, self._("Triple Quotes"), SyntCol.GetColor("TripleQuotes"), pos=(10, 90), size=(121, 35)) quote3_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "TripleQuotes")) int_sel = csel.ColourSelect(cpalette_panel, -1, self._("Integers"), SyntCol.GetColor("Integers"), pos=(10, 130), size=(121, 35)) int_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "Integers")) comments_sel = csel.ColourSelect(cpalette_panel, -1, self._("Comments"), SyntCol.GetColor("Comments"), pos=(10, 170), size=(121, 35)) comments_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "Comments")) brackets_sel = csel.ColourSelect(cpalette_panel, -1, self._("Brackets"), SyntCol.GetColor("Brackets"), pos=(10, 210), size=(121, 35)) brackets_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "Brackets")) bad_eol_sel = csel.ColourSelect(cpalette_panel, -1, self._("Bad EOL"), SyntCol.GetColor("BadEOL"), pos=(10, 250), size=(121, 35)) bad_eol_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "BadEOL")) function_sel = csel.ColourSelect(cpalette_panel, -1, self._("Method Names"), SyntCol.GetColor("MethodNames"), pos=(10, 290), size=(121, 35)) function_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "MethodNames")) operator_sel = csel.ColourSelect(cpalette_panel, -1, self._("Operators"), SyntCol.GetColor("Operators"), pos=(10, 330), size= (121, 35)) operator_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "Operators")) identifier_sel = csel.ColourSelect(cpalette_panel, -1, self._("Identifiers"), SyntCol.GetColor("Identifiers"), pos= (10, 370), size=(121, 35)) identifier_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "Identifiers")) edge_line_sel = csel.ColourSelect(cpalette_panel, -1, self._("Edge Line"), SyntCol.GetColor("EdgeLine"), pos=(10, 410), size=(121, 35)) edge_line_sel.Bind(csel.EVT_COLOURSELECT, lambda event: self.OnSelectColor(event, "EdgeLine")) ok_button = wx.Button(cpalette_panel, -1, self._("OK"), pos=(35, 455), size=(-1, -1)) ok_button.Bind(wx.EVT_BUTTON, lambda event: self.Close(True)) ok_button.Bind(wx.EVT_BUTTON, lambda event: self.RefreshLexer(event, id_range)) ok_button.Bind(wx.EVT_BUTTON, lambda event: self.RefreshLexer(event, id_range)) color_sizer.Add(keyword_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(strings_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(quote3_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(int_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(comments_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(brackets_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(bad_eol_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(function_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(operator_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(identifier_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(edge_line_sel, 0, wx.EXPAND | wx.ALL, 5) color_sizer.Add(ok_button, 0, wx.EXPAND | wx.ALL, 5) cpalette_panel.SetSizer(color_sizer) self.Hide() self.Centre() def HideMe(self, event): """ HideMe Hides the window. """ self.Hide() def ShowMe(self, event): """ ShowMe Makes window visible. """ self.Show() def OnSelectColor(self, event, item): """ OnSelectColor Helper function to call SyntCol.ChangeColorFile """ SyntCol.ChangeColorFile(item, event.GetValue()) def RefreshLexer(self, event, id_range): """ RefreshLexer Updates the lexer with the changes. """ for id in id_range: stc_control = wx.FindWindowById(id) stc_control.ActivateSyntaxHighLight() event.Skip() ColPal = ColorPFrame() gecrit-2.8.4/yapsy/PluginManager.py000777 000000 000000 00000057172 12051462410 017246 0ustar00rootroot000000 000000 #!/usr/bin/python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- """ Role ==== The ``PluginManager`` loads plugins that enforce the `Plugin Description Policy`_, and offers the most simple methods to activate and deactivate the plugins once they are loaded. .. note:: It may also classify the plugins in various categories, but this behaviour is optional and if not specified elseway all plugins are stored in the same default category. .. note:: It is often more useful to have the plugin manager behave like singleton, this functionality is provided by ``PluginManagerSingleton`` Plugin Description Policy ========================= When creating a ``PluginManager`` instance, one should provide it with a list of directories where plugins may be found. In each directory, a plugin should contain the following elements: For a *Standard* plugin: ``myplugin.yapsy-plugin`` A *plugin info file* identical to the one previously described. ``myplugin`` A directory ontaining an actual Python plugin (ie with a ``__init__.py`` file that makes it importable). The upper namespace of the plugin should present a class inheriting the ``IPlugin`` interface (the same remarks apply here as in the previous case). For a *Single file* plugin: ``myplugin.yapsy-plugin`` A *plugin info file* which is identified thanks to its extension, see the `Plugin Info File Format`_ to see what should be in this file. The extension is customisable at the ``PluginManager``'s instanciation, since one may usually prefer the extension to bear the application name. ``myplugin.py`` The source of the plugin. This file should at least define a class inheriting the ``IPlugin`` interface. This class will be instanciated at plugin loading and it will be notified the activation/deactivation events. Plugin Info File Format ----------------------- The plugin info file gathers, as its name suggests, some basic information about the plugin. - it gives crucial information needed to be able to load the plugin - it provides some documentation like information like the plugin author's name and a short description fo the plugin functionality. Here is an example of what such a file should contain:: [Core] Name = My plugin Name Module = the_name_of_the_pluginto_load_with_no_py_ending [Documentation] Description = What my plugin broadly does Author = My very own name Version = 0.1 Website = My very own website Version = the_version_number_of_the_plugin .. note:: From such plugin descriptions, the ``PluginManager`` will built its own representations of the plugins as instances of the :doc:`PluginInfo` class. Extensibility ============= Several mechanisms have been put up to help extending the basic functionalities of the proivided classes. A few *hints* to help you extend those classes: If the new functionalities do not overlap the ones already implemented, then they should be implemented as a Decorator class of the base plugin. This should be done by inheriting the ``PluginManagerDecorator``. If this previous way is not possible, then the functionalities should be added as a subclass of ``PluginManager``. .. note:: The first method is highly prefered since it makes it possible to have a more flexible design where one can pick several functionalities and litterally *add* them to get an object corresponding to one's precise needs. API === """ import sys import os import logging import ConfigParser from yapsy.IPlugin import IPlugin from yapsy.PluginInfo import PluginInfo PLUGIN_NAME_FORBIDEN_STRING=";;" """ .. warning:: This string (';;' by default) is forbidden in plugin names, and will be usable to describe lists of plugins for instance (see :doc:`ConfigurablePluginManager`) """ class PluginManager(object): """ Manage several plugins by ordering them in categories. The mechanism for searching and loading the plugins is already implemented in this class so that it can be used directly (hence it can be considered as a bit more than a mere interface) The file describing a plugin must be written in the syntax compatible with Python's ConfigParser module as in the `Plugin Info File Format`_ """ def __init__(self, categories_filter={"Default":IPlugin}, directories_list=None, plugin_info_ext="yapsy-plugin"): """ Initialize the mapping of the categories and set the list of directories where plugins may be. This can also be set by direct call the methods: - ``setCategoriesFilter`` for ``categories_filter`` - ``setPluginPlaces`` for ``directories_list`` - ``setPluginInfoExtension`` for ``plugin_info_ext`` You may look at these function's documentation for the meaning of each corresponding arguments. """ self.setPluginInfoClass(PluginInfo) self.setCategoriesFilter(categories_filter) self.setPluginPlaces(directories_list) self.setPluginInfoExtension(plugin_info_ext) def setCategoriesFilter(self, categories_filter): """ Set the categories of plugins to be looked for as well as the way to recognise them. The ``categories_filter`` first defines the various categories in which the plugins will be stored via its keys and it also defines the interface tha has to be inherited by the actual plugin class belonging to each category. """ self.categories_interfaces = categories_filter.copy() # prepare the mapping from categories to plugin lists self.category_mapping = {} # also maps the plugin info files (useful to avoid loading # twice the same plugin...) self._category_file_mapping = {} for categ in categories_filter: self.category_mapping[categ] = [] self._category_file_mapping[categ] = [] def setPluginInfoClass(self,picls): """ Set the class that holds PluginInfo. The class should inherit from ``PluginInfo``. """ self._plugin_info_cls = picls def getPluginInfoClass(self): """ Get the class that holds PluginInfo. The class should inherit from ``PluginInfo``. """ return self._plugin_info_cls def setPluginPlaces(self, directories_list): """ Set the list of directories where to look for plugin places. """ if directories_list is None: directories_list = [os.path.dirname(__file__)] self.plugins_places = directories_list def setPluginInfoExtension(self,plugin_info_ext): """ Set the extension that identifies a plugin info file. The ``plugin_info_ext`` is the extension that will have the informative files describing the plugins and that are used to actually detect the presence of a plugin (see ``collectPlugins``). """ self.plugin_info_ext = plugin_info_ext def getCategories(self): """ Return the list of all categories. """ return self.category_mapping.keys() def removePluginFromCategory(self,plugin,category_name): """ Remove a plugin from the category where it's assumed to belong. """ self.category_mapping[category_name].remove(plugin) def appendPluginToCategory(self,plugin,category_name): """ Append a new plugin to the given category. """ self.category_mapping[category_name].append(plugin) def getPluginsOfCategory(self,category_name): """ Return the list of all plugins belonging to a category. """ return self.category_mapping[category_name][:] def getAllPlugins(self): """ Return the list of all plugins (belonging to all categories). """ allPlugins = [] for pluginsOfOneCategory in self.category_mapping.itervalues(): allPlugins.extend(pluginsOfOneCategory) return allPlugins def _gatherCorePluginInfo(self, directory, filename): """ Gather the core information (name, and module to be loaded) about a plugin described by it's info file (found at 'directory/filename'). Return an instance of ``self.plugin_info_cls`` and the config_parser used to gather the core data *in a tuple*, if the required info could be localised, else return ``(None,None)``. .. note:: This is supposed to be used internally by subclasses and decorators. """ # now we can consider the file as a serious candidate candidate_infofile = os.path.join(directory,filename) # parse the information file to get info about the plugin config_parser = ConfigParser.SafeConfigParser() try: config_parser.read(candidate_infofile) except: logging.debug("Could not parse the plugin file %s" % candidate_infofile) return (None, None) # check if the basic info is available if not config_parser.has_section("Core"): logging.debug("Plugin info file has no 'Core' section (in %s)" % candidate_infofile) return (None, None) if not config_parser.has_option("Core","Name") or not config_parser.has_option("Core","Module"): logging.debug("Plugin info file has no 'Name' or 'Module' section (in %s)" % candidate_infofile) return (None, None) # check that the given name is valid name = config_parser.get("Core", "Name") name = name.strip() if PLUGIN_NAME_FORBIDEN_STRING in name: logging.debug("Plugin name contains forbiden character: %s (in %s)" % (PLUGIN_NAME_FORBIDEN_STRING, candidate_infofile)) return (None, None) # start collecting essential info plugin_info = self._plugin_info_cls(name, os.path.join(directory,config_parser.get("Core", "Module"))) return (plugin_info,config_parser) def gatherBasicPluginInfo(self, directory,filename): """ Gather some basic documentation about the plugin described by it's info file (found at 'directory/filename'). Return an instance of ``self.plugin_info_cls`` gathering the required informations. See also: ``self._gatherCorePluginInfo`` """ plugin_info,config_parser = self._gatherCorePluginInfo(directory, filename) if plugin_info is None: return None # collect additional (but usually quite usefull) information if config_parser.has_section("Documentation"): if config_parser.has_option("Documentation","Author"): plugin_info.author = config_parser.get("Documentation", "Author") if config_parser.has_option("Documentation","Version"): plugin_info.setVersion(config_parser.get("Documentation", "Version")) if config_parser.has_option("Documentation","Website"): plugin_info.website = config_parser.get("Documentation", "Website") if config_parser.has_option("Documentation","Copyright"): plugin_info.copyright = config_parser.get("Documentation", "Copyright") if config_parser.has_option("Documentation","Description"): plugin_info.description = config_parser.get("Documentation", "Description") return plugin_info def getPluginCandidates(self): """ Return the list of possible plugins. Each possible plugin (ie a candidate) is described by a 3-uple: (info file path, python file path, plugin info instance) .. warning: locatePlugins must be called before ! """ if not hasattr(self, '_candidates'): raise ValueError("locatePlugins must be called before getPluginCandidates") return self._candidates[:] def removePluginCandidate(self,candidateTuple): """ Remove a given candidate from the list of plugins that should be loaded. The candidate must be represented by the same tuple described in ``getPluginCandidates``. .. warning: locatePlugins must be called before ! """ if not hasattr(self, '_candidates'): raise ValueError("locatePlugins must be called before removePluginCandidate") self._candidates.remove(candidateTuple) def appendPluginCandidate(self,candidateTuple): """ Append a new candidate to the list of plugins that should be loaded. The candidate must be represented by the same tuple described in ``getPluginCandidates``. .. warning: locatePlugins must be called before ! """ if not hasattr(self, '_candidates'): raise ValueError("locatePlugins must be called before removePluginCandidate") self._candidates.append(candidateTuple) def locatePlugins(self): """ Walk through the plugins' places and look for plugins. Return the number of plugins found. """ # print "%s.locatePlugins" % self.__class__ self._candidates = [] for directory in map(os.path.abspath,self.plugins_places): # first of all, is it a directory :) if not os.path.isdir(directory): logging.debug("%s skips %s (not a directory)" % (self.__class__.__name__,directory)) continue # iteratively walks through the directory logging.debug("%s walks into directory: %s" % (self.__class__.__name__,directory)) for item in os.walk(directory): dirpath = item[0] for filename in item[2]: # eliminate the obvious non plugin files if not filename.endswith(".%s" % self.plugin_info_ext): continue candidate_infofile = os.path.join(dirpath,filename) logging.debug("""%s found a candidate: %s""" % (self.__class__.__name__, candidate_infofile)) # print candidate_infofile plugin_info = self.gatherBasicPluginInfo(dirpath,filename) if plugin_info is None: logging.debug("""Candidate rejected: %s""" % candidate_infofile) continue # now determine the path of the file to execute, # depending on wether the path indicated is a # directory or a file # print plugin_info.path if os.path.isdir(plugin_info.path): candidate_filepath = os.path.join(plugin_info.path,"__init__") elif os.path.isfile(plugin_info.path+".py"): candidate_filepath = plugin_info.path else: continue # print candidate_filepath self._candidates.append((candidate_infofile, candidate_filepath, plugin_info)) return len(self._candidates) def loadPlugins(self, callback=None): """ Load the candidate plugins that have been identified through a previous call to locatePlugins. For each plugin candidate look for its category, load it and store it in the appropriate slot of the ``category_mapping``. If a callback function is specified, call it before every load attempt. The ``plugin_info`` instance is passed as an argument to the callback. """ # print "%s.loadPlugins" % self.__class__ if not hasattr(self, '_candidates'): raise ValueError("locatePlugins must be called before loadPlugins") for candidate_infofile, candidate_filepath, plugin_info in self._candidates: # if a callback exists, call it before attempting to load # the plugin so that a message can be displayed to the # user if callback is not None: callback(plugin_info) # now execute the file and get its content into a # specific dictionnary candidate_globals = {"__file__":candidate_filepath+".py"} if "__init__" in os.path.basename(candidate_filepath): sys.path.append(plugin_info.path) try: candidateMainFile = open(candidate_filepath+".py","r") exec(candidateMainFile,candidate_globals) except Exception,e: logging.debug("Unable to execute the code in plugin: %s" % candidate_filepath) logging.debug("\t The following problem occured: %s %s " % (os.linesep, e)) if "__init__" in os.path.basename(candidate_filepath): sys.path.remove(plugin_info.path) continue if "__init__" in os.path.basename(candidate_filepath): sys.path.remove(plugin_info.path) # now try to find and initialise the first subclass of the correct plugin interface for element in candidate_globals.itervalues(): current_category = None for category_name in self.categories_interfaces: try: is_correct_subclass = issubclass(element, self.categories_interfaces[category_name]) except: continue if is_correct_subclass: if element is not self.categories_interfaces[category_name]: current_category = category_name break if current_category is not None: if not (candidate_infofile in self._category_file_mapping[current_category]): # we found a new plugin: initialise it and search for the next one plugin_info.plugin_object = element() plugin_info.category = current_category self.category_mapping[current_category].append(plugin_info) self._category_file_mapping[current_category].append(candidate_infofile) current_category = None break # Remove candidates list since we don't need them any more and # don't need to take up the space delattr(self, '_candidates') def collectPlugins(self): """ Walk through the plugins' places and look for plugins. Then for each plugin candidate look for its category, load it and stores it in the appropriate slot of the category_mapping. """ # print "%s.collectPlugins" % self.__class__ self.locatePlugins() self.loadPlugins() def getPluginByName(self,name,category="Default"): """ Get the plugin correspoding to a given category and name """ if category in self.category_mapping: for item in self.category_mapping[category]: if item.name == name: return item return None def activatePluginByName(self,name,category="Default"): """ Activate a plugin corresponding to a given category + name. """ pta_item = self.getPluginByName(name,category) if pta_item is not None: plugin_to_activate = pta_item.plugin_object if plugin_to_activate is not None: logging.debug("Activating plugin: %s.%s"% (category,name)) plugin_to_activate.activate() return plugin_to_activate return None def deactivatePluginByName(self,name,category="Default"): """ Desactivate a plugin corresponding to a given category + name. """ if category in self.category_mapping: plugin_to_deactivate = None for item in self.category_mapping[category]: if item.name == name: plugin_to_deactivate = item.plugin_object break if plugin_to_deactivate is not None: logging.debug("Deactivating plugin: %s.%s"% (category,name)) plugin_to_deactivate.deactivate() return plugin_to_deactivate return None class PluginManagerSingleton(object): """ Singleton version of the most basic plugin manager. Being a singleton, this class should not be initialised explicitly and the ``get`` classmethod must be called instead. To call one of this class's methods you have to use the ``get`` method in the following way: ``PluginManagerSingleton.get().themethodname(theargs)`` To set up the various coonfigurables variables of the PluginManager's behaviour please call explicitly the following methods: - ``setCategoriesFilter`` for ``categories_filter`` - ``setPluginPlaces`` for ``directories_list`` - ``setPluginInfoExtension`` for ``plugin_info_ext`` """ __instance = None __decoration_chain = None def __init__(self): """ Initialisation: this class should not be initialised explicitly and the ``get`` classmethod must be called instead. To set up the various configurables variables of the PluginManager's behaviour please call explicitly the following methods: - ``setCategoriesFilter`` for ``categories_filter`` - ``setPluginPlaces`` for ``directories_list`` - ``setPluginInfoExtension`` for ``plugin_info_ext`` """ if self.__instance is not None: raise Exception("Singleton can't be created twice !") def setBehaviour(self,list_of_pmd): """ Set the functionalities handled by the plugin manager by giving a list of ``PluginManager`` decorators. This function shouldn't be called several time in a same process, but if it is only the first call will have an effect. It also has an effect only if called before the initialisation of the singleton. In cases where the function is indeed going to change anything the ``True`` value is return, in all other cases, the ``False`` value is returned. """ if self.__decoration_chain is None and self.__instance is None: logging.debug("Setting up a specific behaviour for the PluginManagerSingleton") self.__decoration_chain = list_of_pmd return True else: logging.debug("Useless call to setBehaviour: the singleton is already instanciated of already has a behaviour.") return False setBehaviour = classmethod(setBehaviour) def get(self): """ Actually create an instance """ if self.__instance is None: if self.__decoration_chain is not None: # Get the object to be decorated # print self.__decoration_chain pm = self.__decoration_chain[0]() for cls_item in self.__decoration_chain[1:]: # print cls_item pm = cls_item(decorated_manager=pm) # Decorate the whole object self.__instance = pm else: # initialise the 'inner' PluginManagerDecorator self.__instance = PluginManager() logging.debug("PluginManagerSingleton initialised") return self.__instance get = classmethod(get) # For backward compatility import the most basic decorator (it changed # place as of v1.8) from yapsy.PluginManagerDecorator import PluginManagerDecorator gecrit-2.8.4/yapsy/VersionedPluginManager.py000777 000000 000000 00000010135 12051462410 021111 0ustar00rootroot000000 000000 #!/usr/bin/python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- """ Role ==== Defines the basic interface for a plugin manager that also keeps track of versions of plugins API === """ from distutils.version import StrictVersion from yapsy.PluginInfo import PluginInfo from yapsy.IPlugin import IPlugin from yapsy.PluginManagerDecorator import PluginManagerDecorator class VersionedPluginInfo(PluginInfo): """ Gather some info about a plugin such as its name, author, description... """ def __init__(self, plugin_name, plugin_path): """ Set the name and path of the plugin as well as the default values for other usefull variables. """ PluginInfo.__init__(self, plugin_name, plugin_path) # version number is now required to be a StrictVersion object self.version = StrictVersion("0.0") def setVersion(self, vstring): self.version = StrictVersion(vstring) class VersionedPluginManager(PluginManagerDecorator): """ Handle plugin versioning by making sure that when several versions are present for a same plugin, only the latest version is manipulated via the standard methods (eg for activation and deactivation) More precisely, for operations that must be applied on a single named plugin at a time (``getPluginByName``, ``activatePluginByName``, ``deactivatePluginByName`` etc) the targetted plugin will always be the one with the latest version. .. note:: The older versions of a given plugin are still reachable via the ``getPluginsOfCategoryFromAttic`` method. """ def __init__(self, decorated_manager=None, categories_filter={"Default":IPlugin}, directories_list=None, plugin_info_ext="yapsy-plugin"): """ Create the plugin manager and record the ConfigParser instance that will be used afterwards. The ``config_change_trigger`` argument can be used to set a specific method to call when the configuration is altered. This will let the client application manage the way they want the configuration to be updated (e.g. write on file at each change or at precise time intervalls or whatever....) """ # Create the base decorator class PluginManagerDecorator.__init__(self,decorated_manager, categories_filter, directories_list, plugin_info_ext) self.setPluginInfoClass(VersionedPluginInfo) # prepare the storage for the early version of the plugins, # for which only the latest version is the one that will be # kept in the "core" plugin storage. self._prepareAttic() def _prepareAttic(self): """ Create and correctly initialize the storage where the wrong version of the plugins will be stored. """ self._attic = {} for categ in self.getCategories(): self._attic[categ] = [] def getLatestPluginsOfCategory(self,category_name): """ Return the list of all plugins belonging to a category. .. warning:: Deprecated ! Please consider using getPluginsOfCategory instead. """ return self.getPluginsOfCategory(category_name) def loadPlugins(self, callback=None): """ Load the candidate plugins that have been identified through a previous call to locatePlugins. In addition to the baseclass functionality, this subclass also needs to find the latest version of each plugin. """ self._component.loadPlugins(callback) for categ in self.getCategories(): latest_plugins = {} allPlugins = self.getPluginsOfCategory(categ) # identify the latest version of each plugin for plugin in allPlugins: name = plugin.name version = plugin.version if name in latest_plugins: if version > latest_plugins[name].version: older_plugin = latest_plugins[name] latest_plugins[name] = plugin self.removePluginFromCategory(older_plugin,categ) self._attic[categ].append(older_plugin) else: self.removePluginFromCategory(plugin,categ) self._attic[categ].append(plugin) else: latest_plugins[name] = plugin def getPluginsOfCategoryFromAttic(self,categ): """ Access the older version of plugins for which only the latest version is available through standard methods. """ return self._attic[categ] gecrit-2.8.4/ConfigWindow.py000777 000000 000000 00000037377 12051462410 015752 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx import wx.richtext from SyntaxHighlight import * from Configuration import * from Logger import * from ColorPFrame import * def CallChangeOption(event, option, val, IdRange=0): """ CallChangeOption Helper function used to call Config.ChangeOption. """ Config.ChangeOption(option, val, IdRange) def CallChangeColorFile(event, item, newcolor): """ CallChangeColorFile Used to call ChangeColorFile """ SyntCol.ChangeColorFile(item, newcolor) event.Skip() def ToggleSpinner(event, state, widget): """ ToggleSpinner Disables or enables the suplied widget depending on the arguments. """ if state == True: widget.Enable() else: widget.Disable() event.Skip() class CfgFrame(wx.Frame): """ CfgFrame Creates the application configuration window and provides the necessary controls to modify the application preferences. """ def __init__(self, parent): """ __init__ Builds the entire frame GUI and binds their events across 3 Notebook tabs. """ self.parent = parent self._ = self.parent._ wx.Frame.__init__(self, self.parent, -1, self._('Settings'), size=(400, 500)) self.SetIcon(wx.Icon('icons/gEcrit.png', wx.BITMAP_TYPE_PNG)) self.cfg_book_pnl = wx.Panel(self) self.book_sizer = wx.BoxSizer(wx.HORIZONTAL) self.ok_bt_pnl = wx.Panel(self) self.ok_bt = wx.Button(self.ok_bt_pnl, -1, self._("OK"), size = (-1, -1)) self.ok_bt.Bind(wx.EVT_BUTTON, self.HideMe) self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.config_book = wx.Notebook(self.cfg_book_pnl) self.general = GeneralSettingsPanel(self.config_book, self.parent.id_range) self.editor = EditorSettingsPanel(self.config_book, self.parent.id_range) self.book_sizer.Add(self.config_book, 1, wx.EXPAND) self.cfg_book_pnl.SetSizer(self.book_sizer) self.cfg_book_pnl.Fit() self.config_book.AddPage(self.general, self._("General")) self.config_book.AddPage(self.editor, self._("Editor")) self.Bind(wx.EVT_CLOSE, self.HideMe) self.main_sizer.Add(self.cfg_book_pnl, 1, wx.EXPAND) self.main_sizer.Add(self.ok_bt_pnl, 0) self.SetSizer(self.main_sizer) self.Fit() self.Hide() self.Centre() def ShowMe(self, event): """ ShowMe Makes window visible. """ #update the id range of documents(do dinamycally update settings) self.id_range = self.parent.id_range self.general.id_range = self.id_range self.editor.id_range = self.id_range self.Show(True) def HideMe(self, event): """ HideMe Hides the window. """ self.Hide() class GeneralSettingsPanel(wx.Panel): def __init__(self, parent, id_range): self.parent = parent self._ = self.parent.GetParent().GetParent().GetParent()._ self.id_range = id_range wx.Panel.__init__(self, self.parent) ColPal.CollorPaletteWindow(0, self,self.id_range) sizer = wx.BoxSizer(wx.VERTICAL) autosave_box = wx.CheckBox(self, -1, self._("Enable Autosave"), (10, 10), (160, -1)) autosave_box.Bind(wx.EVT_CHECKBOX, lambda event: CallChangeOption(event, "Autosave", autosave_box.GetValue(), self.id_range)) inter_info = wx.StaticText(self, -1, self._("Save interval in minutes:"), (20,35)) interval_spin_ctrl = wx.SpinCtrl(self, -1, "", (20, 60), (90, -1)) interval_spin_ctrl.SetRange(1, 500) interval_spin_ctrl.SetValue(Config.GetOption("Autosave Interval")) interval_spin_ctrl.Bind(wx.EVT_SPINCTRL, lambda event: CallChangeOption(event, "Autosave Interval", interval_spin_ctrl.GetValue(), self.id_range)) autosave_box.Bind(wx.EVT_CHECKBOX, lambda event: ToggleSpinner(event, autosave_box.GetValue(), interval_spin_ctrl)) autosave_box.SetValue(Config.GetOption("Autosave")) interval_spin_ctrl.Enable(Config.GetOption("Autosave")) strip_trail_box = wx.CheckBox(self,-1, self._("Strip Trailing Spaces On Save"), pos = (20, 70), size = (-1, -1)) strip_trail_box.Bind(wx.EVT_CHECKBOX, lambda event: CallChangeOption(event, "StripTrails", strip_trail_box.GetValue())) strip_trail_box.SetValue(Config.GetOption("StripTrails")) status_bar_box = wx.CheckBox(self, -1, self._("Enable Status Bar"), (10, 90), (160, -1)) status_bar_box.Bind(wx.EVT_CHECKBOX, lambda event: \ CallChangeOption(event, "StatusBar", status_bar_box.GetValue(), self.id_range)) status_bar_box.SetValue(Config.GetOption("StatusBar")) session_box = wx.CheckBox(self, -1, self._("Enable Session")) session_box.SetValue(Config.GetOption("Session")) session_box.Bind(wx.EVT_CHECKBOX, lambda event: CallChangeOption(event, "Session",session_box.GetValue())) log_act_box = wx.CheckBox(self, -1, self._("Enable Log"), (10, 140), (160, -1)) log_act_box.Bind(wx.EVT_CHECKBOX, lambda event: CallChangeOption(event, "ActLog", log_act_box.GetValue(), self.id_range)) log_act_box.SetValue(Config.GetOption("ActLog")) pallete_button = wx.Button(self, -1, self._("Colour Palette"), pos= (10, 220), size=(-1, -1)) pallete_button.Bind(wx.EVT_BUTTON, ColPal.ShowMe) view_button = wx.Button(self, -1,self._("View Log"), pos=(10, 180), size=(-1, -1)) view_button.Bind(wx.EVT_BUTTON, self.viewLog) erase_button = wx.Button(self, -1,self._("Erase Log"), pos=(50, 180), size=(-1, -1)) erase_button.Bind(wx.EVT_BUTTON, Log.EraseLog) erase_button.Bind(wx.EVT_BUTTON, lambda event: ToggleSpinner(event, False, erase_button)) special_sizer = wx.BoxSizer(wx.HORIZONTAL) special_sizer.Add(view_button, 0) special_sizer.Add(erase_button, 0) sizer.Add(autosave_box, 0, wx.EXPAND, wx.ALL, 5) sizer.Add(inter_info, 0, wx.ALL, 5) sizer.Add(interval_spin_ctrl, 0, wx.LEFT, 30) sizer.Add(strip_trail_box, 0 , wx.EXPAND) sizer.Add(status_bar_box, 0, wx.EXPAND, wx.ALL, 5) sizer.Add(session_box, 0) sizer.Add(log_act_box, 0, wx.EXPAND, wx.ALL, 5) sizer.Add(pallete_button, 0, wx.ALL, 5) sizer.Add(special_sizer, 0, wx.ALL, 5) self.SetSizer(sizer) def viewLog(self, event): """ viewLog Creates child class and the required controls to view the log file. """ logcontent = "" if Config.GetOption("ActLog") == True: log_frame = wx.Frame(None, -1, self._("View Log"), size=(500, 500)) panel5 = wx.Panel(log_frame) data = wx.richtext.RichTextCtrl(panel5, pos=(0, 0), size=(500, 500), style = wx.TE_READONLY) data.AppendText(Log.ReadLog()) log_frame.Centre() log_frame.Show() else: inform = wx.MessageDialog(None, self._("The Log is disabled!\ \nEnable it to view."), self._("Log Status"), wx.OK) inform.ShowModal() class EditorSettingsPanel(wx.Panel): def __init__(self, parent, id_range): self.parent = parent self.id_range = id_range self._ = self.parent.GetParent().GetParent().GetParent()._ wx.Panel.__init__(self, self.parent) sizer = wx.BoxSizer(wx.VERTICAL) line_nr_box = wx.CheckBox(self, -1, self._("Show Line Numbers"), (10, 10), (-1, -1)) line_nr_box.Bind(wx.EVT_CHECKBOX, lambda event: CallChangeOption(event, self._("LineNumbers"), line_nr_box.GetValue(), self.id_range)) line_nr_box.SetValue(Config.GetOption("LineNumbers")) syntax_highlight_box = wx.CheckBox(self, -1, self._("Syntax Highlight"), (10, 35), (-1, -1)) syntax_highlight_box.Bind(wx.EVT_CHECKBOX, lambda event: CallChangeOption(event, "SyntaxHighlight", syntax_highlight_box.GetValue(), self.id_range)) syntax_highlight_box.SetValue(Config.GetOption("SyntaxHighlight")) autoindent_box = wx.CheckBox(self, -1, self._("Autoindentation"), (10, 60), (-1, -1)) autoindent_box.Bind(wx.EVT_CHECKBOX, lambda event: \ CallChangeOption(event, "Autoindentation", autoindent_box.GetValue(), self.id_range)) autoindent_box.SetValue(Config.GetOption("Autoindentation")) indent_size_spinctrl = wx.SpinCtrl(self, -1, "", (35, 85), (90, -1)) autoindent_box.Bind(wx.EVT_CHECKBOX, lambda event: ToggleSpinner(event, autoindent_box.GetValue(), indent_size_spinctrl)) indent_size_spinctrl.SetRange(1, 12) indent_size_spinctrl.SetValue(Config.GetOption("IndentSize")) indent_size_spinctrl.Bind(wx.EVT_SPINCTRL, lambda event: \ CallChangeOption(event, "IndentSize", indent_size_spinctrl.GetValue(), self.id_range)) if Config.GetOption("Autoindentation") == True: indent_size_spinctrl.Enable() else: indent_size_spinctrl.Disable() indent_guides_box = wx.CheckBox(self, -1, self._("Indentation Guides"), (10, 110), (-1, -1)) indent_guides_box.SetValue(Config.GetOption("IndetationGuides")) indent_guides_box.Bind(wx.EVT_CHECKBOX, lambda event: \ CallChangeOption(event, "IndetationGuides", indent_guides_box.GetValue(), self.id_range)) backspc_unindent_box = wx.CheckBox(self, -1, self._("Backspace to Unindent"), (10, 135), (-1, -1)) backspc_unindent_box.SetValue(Config.GetOption("BackSpaceUnindent")) backspc_unindent_box.Bind(wx.EVT_CHECKBOX, lambda event: \ CallChangeOption(event, "BackSpaceUnindent", backspc_unindent_box.GetValue(), self.id_range)) whitespc_box = wx.CheckBox(self, -1, self._("Show Whitespace"), (10, 160), (-1, -1)) whitespc_box.SetValue(Config.GetOption("Whitespace")) whitespc_box.Bind(wx.EVT_CHECKBOX, lambda event: \ CallChangeOption(event, "Whitespace", whitespc_box.GetValue(), self.id_range)) use_tabs_box = wx.CheckBox(self, -1, self._("Use Tabs"), (10, 185), (160, -1)) use_tabs_box.SetValue(Config.GetOption("UseTabs")) use_tabs_box.Bind(wx.EVT_CHECKBOX, lambda event: CallChangeOption(event, "UseTabs", use_tabs_box.GetValue(), self.id_range)) caret_info = wx.StaticText(self, -1, self._('Carret Width:'), (10, 210)) caret_width_spinctrl = wx.SpinCtrl(self, -1, "", (35, 235), (-1, -1)) caret_width_spinctrl.SetRange(1, 20) caret_width_spinctrl.SetValue(Config.GetOption("CarretWidth")) caret_width_spinctrl.Bind(wx.EVT_SPINCTRL, lambda event: \ CallChangeOption(event, "CarretWidth", caret_width_spinctrl.GetValue(), self.id_range)) fold_marks_box = wx.CheckBox(self, -1, self._("Fold Marks"), (10, 265), (160, -1)) fold_marks_box.Bind(wx.EVT_CHECKBOX, lambda event: CallChangeOption(event, "FoldMarks", fold_marks_box.GetValue(), self.id_range)) fold_marks_box.SetValue(Config.GetOption("FoldMarks")) tab_info = wx.StaticText(self, -1, self._("Tab Width:"), pos=(10, 300), size=(-1, -1)) tab_width_box = wx.SpinCtrl(self, -1, "", pos=(35, 320), size=(90, -1)) tab_width_box.SetValue(Config.GetOption("TabWidth")) tab_width_box.Bind(wx.EVT_SPINCTRL, lambda event: CallChangeOption(event, "TabWidth", tab_width_box.GetValue(), self.id_range)) edge_line_box = wx.CheckBox(self, -1, self._("Edge Line"), pos=(10, 350), size=(-1, -1)) edge_line_box.SetValue(Config.GetOption("EdgeLine")) edge_line_box.Bind(wx.EVT_CHECKBOX, lambda event: CallChangeOption(event, "EdgeLine", edge_line_box.GetValue(), self.id_range)) edge_line_box.Bind(wx.EVT_CHECKBOX, lambda event: ToggleSpinner(event, edge_line_box.GetValue(), edge_line_pos)) edge_info = wx.StaticText(self, -1, self._("Edge Line Position:"), pos=(35, 375), size=(-1, -1)) edge_line_pos = wx.SpinCtrl(self, -1, "", pos=(35, 400), size=(-1, -1)) edge_line_pos.SetValue(Config.GetOption("EdgeColumn")) if Config.GetOption("EdgeLine"): edge_line_pos.Enable() else: edge_line_pos.Disable() edge_line_pos.Bind(wx.EVT_SPINCTRL, lambda event: CallChangeOption(event, "EdgeColumn", edge_line_pos.GetValue(), self.id_range)) edge_line_pos.SetRange(0, 1000) brace_comp_box = wx.CheckBox(self,-1, self._("Autocomplete Braces"), pos=(10,200),size=(-1,-1)) brace_comp_box.Bind(wx.EVT_CHECKBOX,lambda event: CallChangeOption( event,"BraceComp",brace_comp_box.GetValue(),self.id_range)) brace_comp_box.SetValue(Config.GetOption("BraceComp")) sizer.Add(line_nr_box, 0, wx.EXPAND) sizer.Add(syntax_highlight_box, 0, wx.EXPAND) sizer.Add(autoindent_box, 0, wx.EXPAND) sizer.Add(indent_size_spinctrl, 0, wx.LEFT, 30) sizer.Add(indent_guides_box, 0, wx.EXPAND) sizer.Add(backspc_unindent_box, 0, wx.EXPAND) sizer.Add(whitespc_box, 0, wx.EXPAND) sizer.Add(use_tabs_box, 0, wx.EXPAND, 30) sizer.Add(caret_info, 0, wx.EXPAND) sizer.Add(caret_width_spinctrl, 0, wx.LEFT, 30) sizer.Add(fold_marks_box, 0, wx.EXPAND) sizer.Add(tab_info, 0, wx.EXPAND) sizer.Add(tab_width_box, 0, wx.LEFT, 30) sizer.Add(edge_line_box, 0, wx.EXPAND) sizer.Add(edge_info, 0, wx.EXPAND) sizer.Add(edge_line_pos, 0, wx.LEFT, 30) sizer.Add(brace_comp_box,0,wx.EXPAND) self.SetSizer(sizer) gecrit-2.8.4/data/plugins/TreeFileBrowser.yapsy-plugin000777 000000 000000 00000000352 12051462410 023002 0ustar00rootroot000000 000000 [Core] Name = Tree File Browser Module = TreeFileBrowser [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Provides a file tree to allow to navigate the file system. gecrit-2.8.4/__init__.py000777 000000 000000 00000001267 12051462410 015101 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . gecrit-2.8.4/README000777 000000 000000 00000000171 12051462410 013641 0ustar00rootroot000000 000000 To run gEcrit: Run the gEcrit.py file. To be able to run gEcrit you need python installed and the wxPython library. gecrit-2.8.4/locale/pl/LC_MESSAGES/000777 000000 000000 00000000000 12051462410 016416 5ustar00rootroot000000 000000 gecrit-2.8.4/Configuration.py000777 000000 000000 00000017736 12051462410 016161 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx import os from SyntaxHighlight import * class Configuration: """ ConfigNanny Manages the application configuration manipulation. """ def __init__(self): """ __init__ Creates a default configuration dictionary and reads the configuration file. """ self.__default_cfg_dict = { "Autosave": False, "Autosave Interval": 15, "StatusBar": True, "ActLog": True, "LineNumbers": False, "Font": "Arial", "FontSize": "12", "SyntaxHighlight": True, "IndentSize": 4, "Whitespace": False, "IndetationGuides": False, "Autoindentation": True, "BackSpaceUnindent": False, "UseTabs": False, "CarretWidth": 7, "FoldMarks": False, "TabWidth": 8, "EdgeLine": False, "EdgeColumn": 80, "RecentFiles":[], "BraceComp":False, "StripTrails":False, "Session" : True, "ActivePlugins": ["Task Keeper","Class Hierarchy Tree", "HTML Converter", "Python Syntax Doctor", "Pastebin.com Uploader","PyTidy","Notes", "Terminator"] } self.update_funct = { "Autosave Interval":self.UpdateAutoSaveInterval, "StatusBar": self.UpdateStatusBar, "LineNumbers": self.UpdateLineNumbers, "SyntaxHighlight": self.UpdateSyntaxHighlight, "IndentSize": self.UpdateIndentSize, "Whitespace": self.UpdateWhitespace, "IndetationGuides": self.UpdateIndentationGuides, "BackSpaceUnindent":self.UpdateBackSpaceUnindent, "UseTabs": self.UpdateUseTabs, "CarretWidth": self.UpdateCarretWidth, "FoldMarks": self.UpdateFoldMarks, "TabWidth": self.UpdateTabWidth, "EdgeLine": self.UpdateEdgeLine, "EdgeColumn": self.UpdateEdgeColumn } self.HOMEDIR = os.path.expanduser('~') self.cfg_dir = os.path.join(self.HOMEDIR, ".config", ".gEcrit") self.cfg_path = os.path.join(self.cfg_dir, "gEcrit.conf") self.__cfg_dict = {} self.ReadConfig() def GetOption(self, option): """ GetOption Return the status of the requested option from the configuration dictionary. If something goes wrong, returns from default. """ return (self.__cfg_dict)[option] def ChangeOption(self, option, val, id_range=0): """ ChangeOption Modifies the status of the requested option to the provided value. Updates the configuration dictionary and writes it to file. """ self.__cfg_dict[option] = val with open(self.cfg_path, "w") as new_cfg: new_cfg.write(str(self.__cfg_dict)) if option in self.update_funct: self.update_funct[option](val,id_range) def ReadConfig(self): """ ReadConfig Reads the configuration file and generates a configuration dictionary. If something goes wrong, returns from default. """ try: cfg_file = open(self.cfg_path, "r") self.__cfg_dict = eval(cfg_file.read()) return self.__cfg_dict except: if not os.path.exists(self.cfg_path): # create the config dir if it is inexistent if not os.path.exists(self.cfg_dir): os.makedirs(self.cfg_dir) self.__cfg_dict = self.__default_cfg_dict cfg_file = open(self.cfg_path, "w") # write default cfg file cfg_file.write(str(self.__default_cfg_dict)) cfg_file.close() return self.__cfg_dict def UpdateIndentSize(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) item.SetIndent(val) def UpdateIndentationGuides(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) item.SetIndentationGuides(val) def UpdateBackSpaceUnindent(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) item.SetBackSpaceUnIndents(val) def UpdateWhitespace(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) item.SetViewWhiteSpace(val) def UpdateUseTabs(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) item.SetUseTabs(val) def UpdateCarretWidth(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) item.SetCaretWidth(val) def UpdateLineNumbers(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) if val == True: item.SetMarginWidth(1, 45) else: item.SetMarginWidth(1, 1) def UpdateFoldMarks(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) if val == True: item.SetMarginType(2, wx.stc.STC_MARGIN_SYMBOL) item.SetMarginMask(2, wx.stc.STC_MASK_FOLDERS) item.SetMarginSensitive(2, True) item.SetMarginWidth(2, 12) elif val == False: item.SetMarginWidth(2, 1) def UpdateSyntaxHighlight(self, val, id_range): if val == False: for id in id_range: item = wx.FindWindowById(id) item.StyleClearAll() elif val == True: for id in id_range: item = wx.FindWindowById(id) item.ActivateSyntaxHighLight() def UpdateStatusBar(self, val=True, id_range=0): item = wx.FindWindowById(999) if val == True: item.Show(True) else: item.Hide() def UpdateTabWidth(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) item.SetTabWidth(val) def UpdateEdgeLine(self, val, id_range): if val == False: for id in id_range: item = wx.FindWindowById(id) item.SetEdgeMode(wx.stc.STC_EDGE_NONE) else: for id in id_range: item = wx.FindWindowById(id) item.SetEdgeMode(wx.stc.STC_EDGE_LINE) def UpdateEdgeColumn(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) item.SetEdgeColumn(val) def UpdateAutoSaveInterval(self, val, id_range): for id in id_range: item = wx.FindWindowById(id) item.RestartAutoSaveTimer() def GetTab(self, tab_name, notebook): """ GetTab Retrieves a AUI NOTEBOOK tab index from a given name. """ end = notebook.GetPageCount() selectedtabText = "" for i in range(end): selectedtabText = notebook.GetPageText(i) if tab_name == selectedtabText: return i None return -1 None Config = Configuration() gecrit-2.8.4/locale/ro/000777 000000 000000 00000000000 12051462410 014636 5ustar00rootroot000000 000000 gecrit-2.8.4/data/plugins/DocumentCloner.yapsy-plugin000777 000000 000000 00000000337 12051462410 022663 0ustar00rootroot000000 000000 [Core] Name = Document Cloner Module = DocumentCloner [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Provides a quick way to duplicate an open buffer. gecrit-2.8.4/data/000777 000000 000000 00000000000 12051462410 013670 5ustar00rootroot000000 000000 gecrit-2.8.4/000777 000000 000000 00000000000 12051462422 012762 5ustar00rootroot000000 000000 gecrit-2.8.4/icons/config.bmp000777 000000 000000 00000006066 12051462410 016052 0ustar00rootroot000000 000000 BM6 6(    ޺VVVJJJKKKJJJIIIIIIJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKSILQINCLL;NK@OIANH8OG0QG4PGGKFTGETTTBBBCCCBBBBBBBBBCCCCCCBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCMAEPADIBCDDCDEABE@=F?;GABEAQCBU@CTTTAAABBBBBBDDDCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;EC;FCFEAPBASBARAAPAAN@CKAFFAG@AETTTBBBCCCCCCCCCBBBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2E?(H>3E>;D>@B>BA@DBBDAD?BH;BK6AHTTTBBBAAA===:::888666666666666666666666666666666666666666966956.85*95,851863986;==>BG>FK=GUUUBBB???666------,,,***,,,---++++++---,,,,,,------------.)-4+1/)-7/05*+?./=++>00?:98;:>EDUUU===555 )))%%% !!!%%%'''///555333.1394:L>B977";3?40F=KG?KE>,=2!B7MMMBBB--- ***444***--- %%%''',,,222666955E54UCB9LC>zE.yc6C6TA;A>81C9^^^666...""",,,???===000+++###%%%)))2229991?29M78E0F\F0YA$N:@QDL=9G339<<&<8RRRCCC***gggEzMLHb̴8@H=@HTTT@@@UUUȕwF |=2u{ɛŵϿ{n}c5KPPPDDDHHHzzzùfbL8.U%Gm{ܵ̽_\^CFAD?@ISSSDDD???EEEȽ÷ĭ¼O[Ej,R(HܦϴDC=BAG>@LUUUCCCDDD;;;̻ĵ19$=0L-EXqǽڻȷǿNBEB;E@AMTTTBBBDDDAAAWWW׺ڌ"(AZ2OitƩ˾żАRAKH?I?@FTTTBBBDDDCCCFFFĘˠ)):ɵƼ̶ļ̾odmH=FF@EBBBSSSBBBDDDDDD>>>ôݶϪХŽøݼüE@G=>@GJC@A9RRRAAACCCDDDCCCпŻܼ˖ب9:=7F@>>gecrit-2.8.4/data/plugins/PastebinDialog.py000777 000000 000000 00000030532 12051462410 020616 0ustar00rootroot000000 000000 #!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx import yapsy.IPlugin from data.plugins.categories import General import urllib class PastebinDialog(wx.Frame,General, yapsy.IPlugin.IPlugin): """ PastebinWin Provides the necessary controls and function to submit data to pastebin.com. Builds the GUI and interacts with the pastebin library. """ def __init__(self): self.name = "Pastebin.com Uploader" def Init(self, parent): """ __init__ Initializes the frame and builds the GUI. Sets the format list dictionary and binds the appropriate events. Initializes the pastebin library. """ self.parent = parent self.current_doc = None self.src_formats = [ 'python', 'abap', 'actionscript', 'actionscript3', 'ada', 'apache', 'applescript', 'apt_sources', 'asm', 'asp', 'autoit', 'avisynth', 'bash', 'basic4gl', 'bibtex', 'blitzbasic', 'bnf', 'boo', 'bf', 'c', 'c_mac', 'cill', 'csharp', 'cpp', 'caddcl', 'cadlisp', 'cfdg', 'klonec', 'klonecpp', 'cmake', 'cobol', 'cfm', 'css', 'd', 'dcs', 'delphi', 'dff', 'div', 'dos', 'dot', 'eiffel', 'email', 'erlang', 'fo', 'fortran', 'freebasic', 'gml', 'genero', 'gettext', 'groovy', 'haskell', 'hq9plus', 'html4strict', 'idl', 'ini', 'inno', 'intercal', 'io', 'java', 'java5', 'javascript', 'kixtart', 'latex', 'lsl2', 'lisp', 'locobasic', 'lolcode', 'lotusformulas', 'lotusscript', 'lscript', 'lua', 'm68k', 'make', 'matlab', 'matlab', 'mirc', 'modula3', 'mpasm', 'mxml', 'mysql', 'text', 'nsis', 'oberon2', 'objc', 'ocaml-brief', 'ocaml', 'glsl', 'oobas', 'oracle11', 'oracle8', 'pascal', 'pawn', 'per', 'perl', 'php', 'php-brief', 'pic16', 'pixelbender', 'plsql', 'povray', 'powershell', 'progress', 'prolog', 'properties', 'providex', 'qbasic', 'rails', 'rebol', 'reg', 'robots', 'ruby', 'gnuplot', 'sas', 'scala', 'scheme', 'scilab', 'sdlbasic', 'smalltalk', 'smarty', 'sql', 'tsql', 'tcl', 'tcl', 'teraterm', 'thinbasic', 'typoscript', 'unreal', 'vbnet', 'verilog', 'vhdl', 'vim', 'visualprolog', 'vb', 'visualfoxpro', 'whitespace', 'whois', 'winbatch', 'xml', 'xorg_conf', 'xpp', 'z80', ] self.exp_dates = ['N', '10M', '1H', '1D', '1M'] self.Paste = Pastebin() wx.Frame.__init__(self, self.parent, -1, "Pastebin Snippet", size=(300, 330)) pastebin_pnl = wx.Panel(self) name_info = wx.StaticText(pastebin_pnl, -1, "Snippet name:", pos= (10, 10), size=(-1, -1)) self.paste_name = wx.TextCtrl(pastebin_pnl, -1, "", pos=(10, 30), size=(200, 30)) formats_info = wx.StaticText(pastebin_pnl, -1, "Choose a source format:", pos=(10, 65), size=(-1, -1)) self.formats = wx.Choice(pastebin_pnl, -1, choices=self.src_formats, pos=(10, 90), size=(-1, -1)) date_info = wx.StaticText(pastebin_pnl, -1, "Expire in:", pos=(10, 130), size=(-1, -1)) self.date = wx.Choice(pastebin_pnl, -1, choices=self.exp_dates, pos=(10, 155), size=(-1, -1)) self.private_paste = wx.CheckBox(pastebin_pnl, -1, "Make this snippet private.", pos=(10, 195), size=(-1, -1)) SubmitBtn = wx.Button(pastebin_pnl, -1, "Submit", pos=(200, 290), size=(-1, -1)) CloseBtn = wx.Button(pastebin_pnl, -1, "Close", pos=(100, 290), size=(-1, -1)) SubmitBtn.Bind(wx.EVT_BUTTON, self.OnSubmit) CloseBtn.Bind(wx.EVT_BUTTON, self.HideMe) self.Bind(wx.EVT_CLOSE, self.HideMe) self.Centre() self.Hide() self.plugins_menu = wx.Menu() show_entry = self.plugins_menu.Append(-1,"Upload to Pastebin") self.menu_item = self.parent.AddToMenuBar("Pastebin Uploader", self.plugins_menu) self.parent.BindMenubarEvent(show_entry, self.ShowMe) def OnSubmit(self, event): """ OnSubmit Collects data from the controls and feeds it to the pastebin library for submition. If successful prompts the user. If not, returns a MessageDialog with the error returned by pastebin. """ try: url = self.Paste.submit(self.current_doc.GetText(), self.paste_name.GetValue(), paste_private= self.private_paste.GetValue(), paste_expire_date=(self.exp_dates)[self.date.GetCurrentSelection()], paste_format=(self.src_formats)[self.formats.GetCurrentSelection()]) except IOError: url = "The connection has timed out." if "http://pastebin" not in url: error_msg = wx.MessageDialog(None, "An error has occured:\n" + url, "Failed", wx.ICON_ERROR) if error_msg.ShowModal() == wx.ID_OK: error_msg.Destroy() return say_url = wx.MessageDialog(None, "The snippet is available at:\n" + url, "Success", wx.ICON_INFORMATION) if say_url.ShowModal() == wx.ID_OK: say_url.Destroy() def ShowMe(self, event): """ ShowMe Makes window visible. """ self.Show() self.current_doc = self.parent.GetCurrentDocument() def HideMe(self, event): """ HideMe Hides the window. """ self.Hide() def NotifyTabChanged(self): try: self.current_doc = self.parent.GetCurrentDocument() except: pass def Stop(self): self.parent.RemoveFromMenubar(self.menu_item) self.Destroy() class Pastebin(object): prefix_url = 'http://pastebin.com/' subdomain_url = 'http://%s.pastebin.com/' # % paste_subdomain api_url = 'http://pastebin.com/api_public.php' paste_expire_date = ('N', '10M', '1H', '1D', '1M') paste_format = ( 'python', 'abap', 'actionscript', 'actionscript3', 'ada', 'apache', 'applescript', 'apt_sources', 'asm', 'asp', 'autoit', 'avisynth', 'bash', 'basic4gl', 'bibtex', 'blitzbasic', 'bnf', 'boo', 'bf', 'c', 'c_mac', 'cill', 'csharp', 'cpp', 'caddcl', 'cadlisp', 'cfdg', 'klonec', 'klonecpp', 'cmake', 'cobol', 'cfm', 'css', 'd', 'dcs', 'delphi', 'dff', 'div', 'dos', 'dot', 'eiffel', 'email', 'erlang', 'fo', 'fortran', 'freebasic', 'gml', 'genero', 'gettext', 'groovy', 'haskell', 'hq9plus', 'html4strict', 'idl', 'ini', 'inno', 'intercal', 'io', 'java', 'java5', 'javascript', 'kixtart', 'latex', 'lsl2', 'lisp', 'locobasic', 'lolcode', 'lotusformulas', 'lotusscript', 'lscript', 'lua', 'm68k', 'make', 'matlab', 'matlab', 'mirc', 'modula3', 'mpasm', 'mxml', 'mysql', 'text', 'nsis', 'oberon2', 'objc', 'ocaml-brief', 'ocaml', 'glsl', 'oobas', 'oracle11', 'oracle8', 'pascal', 'pawn', 'per', 'perl', 'php', 'php-brief', 'pic16', 'pixelbender', 'plsql', 'povray', 'powershell', 'progress', 'prolog', 'properties', 'providex', 'qbasic', 'rails', 'rebol', 'reg', 'robots', 'ruby', 'gnuplot', 'sas', 'scala', 'scheme', 'scilab', 'sdlbasic', 'smalltalk', 'smarty', 'sql', 'tsql', 'tcl', 'tcl', 'teraterm', 'thinbasic', 'typoscript', 'unreal', 'vbnet', 'verilog', 'vhdl', 'vim', 'visualprolog', 'vb', 'visualfoxpro', 'whitespace', 'whois', 'winbatch', 'xml', 'xorg_conf', 'xpp', 'z80', ) @classmethod def submit(cls, paste_code, paste_name=None, paste_subdomain=None, paste_private=None, paste_expire_date=None, paste_format=None): argv = {'paste_code': str(paste_code)} if paste_name is not None: argv['paste_name'] = str(paste_name) if paste_subdomain is not None: paste_subdomain = str(paste_subdomain).strip().lower() argv['paste_subdomain'] = paste_subdomain if paste_private is not None: argv['paste_private'] = int(bool(int(paste_private))) if paste_expire_date is not None: paste_expire_date = str(paste_expire_date).strip().upper() if not paste_expire_date in cls.paste_expire_date: raise ValueError, "Bad expire date: %s" % \ paste_expire_date if paste_format is not None: paste_format = str(paste_format).strip().lower() if not paste_format in cls.paste_format: raise ValueError, "Bad format: %s" % paste_format argv['paste_format'] = paste_format fd = urllib.urlopen(cls.api_url, urllib.urlencode(argv)) try: response = fd.read() finally: fd.close() del fd if argv.has_key('paste_subdomain'): prefix = cls.subdomain_url % paste_subdomain else: prefix = cls.prefix_url if not response.startswith(prefix): return response return response gecrit-2.8.4/icons/plugin_icon.png000777 000000 000000 00000013474 12051462410 017122 0ustar00rootroot000000 000000 PNG  IHDR22] OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3-bKGD pHYs  tIME)- nIDATXõYnvU&nHAdS6`@7$wG#3O< @e0h8mؑD&9;}Xjٖp㔠FP]묽ڻ"¯n9csc19BH)O6&1i<,)8yqGQRJ[E~-|>F(fR*scLJVh40&_3z^QiA@EeYv~~>RJo֯9>??ϲ`cc#"9o6[[[P-z@e^wI/+BD)eȲl}}}&߾`-h4Es.D=&%= p4 Ub"͛7sEQQ$eоp%t 3Xft(0PPsȧKy80߄ܯB8UUIcӧO4BMM3o9G ^߬ZXn>{z%2kd2/]YL:YZY:i&:ʲ:(I~F/l6R^{Y|MmZ󋋋|Ȁ! 87EBW!n#eeXZpX>g\!U3!XMe3N8 x<:* 6 j(ZaRTRx6v;T *SCdȀ9<*Q]D|m4?=4}$|p|>(+H)fQBDQeY#Ic>4<_޿jrYU& nauuO>ι(ݮsn8޺uK;͆!" !8l2?cͳ, í$I<ŋ/o>VJEa.8 (z18;;kɷ~[!WoVBHB2942:d*BJN8W8neQ*mnneZ_?>>Owww(z\M)J9UU))II5-}1&09 Xg+,ӕAjd80`%ZN{IRqajaZ뽽 nV)*$$IA$qYv{m}}> :Q%`Lc j )"M$I677oуZ)PAPBpL,+:D!eE_}t||jJYk>:~W"R/BC`s\! 9*8w0 iVO~{9ǹԧ"2.B(fөװ״B <猁h,XׯQ]4Ѩ0)ciQp!SR$S98'.ۇ9ZX$<ķ嗻 lxA=2aEQy@H4LӔ,/EQ\\\t:n.s.\@.-_hq΍1dPTvwwze(ME1㋢ț|K$NѣG󝝝Niq{#PBft>|xppv]YOֽ~<EA$Vkgg 뿐fgggp:R˫ ~ƍ=GaF~i0헐R)H(( v8Zi-,KV~}Y[[K>6EAWy"G}?ބ[ hsIENDB`gecrit-2.8.4/gEcrit_po_utf.po000777 000000 000000 00000025647 12051462410 016131 0ustar00rootroot000000 000000 # SOME DESCRIPTIVE TITLE. # Copyright (C) 211 Anna Groza # This file is distributed under the same license as gEcrit. # FIRST AUTHOR anna.balerina@yahoo.com, 2011. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION" "Report-Msgid-Bugs-To: " "POT-Creation-Date: 2011-05-05 22:11-0400" "PO-Revision-Date: 2011-05-07 11:23-0500" "Last-Translator: Anna Groza anna.balerina@yahoo.com" "Language-Team: LANGUAGE " "Language: Spanish" "MIME-Version: 1.0" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit" msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2011-05-05 22:11-0400\n" "PO-Revision-Date: 2011-05-07 11:23-0500\n" "Last-Translator: Groza cristi \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" msgid "Session file loaded." msgstr "Sesja załadowana." msgid "Session saved." msgstr "zapisanej sesji." msgid "Could not load file.\nThe file " msgstr "Nie można załadować pliku\n." "Plik" msgid " does not exists." msgstr "nie istnieje." msgid "Input Error" msgstr "Błąd wejścia" msgid "Please make sure that your data is saved.\nAre you sure you want to quit?" msgstr "Proszę się upewnić, że dane są zapisywane.\n" "Czy na pewno chcesz wyjść?" msgid "Are you sure?" msgstr "Czy na pewno?" msgid "The file " msgstr "Plik " msgid " is not saved.\nDo you wish to save it?" msgstr "Nie został zapisany.\n" "Czy chcesz go zapisać?" msgid "Opened file " msgstr "Otwarty plik" msgid "Find" msgstr "Znajdź" msgid "Search and Replace" msgstr "Znajdź i zamień" msgid "The end of file was reached!\nNothing to replace." msgstr "Koniec pliku został osiągnięty! \n" "Nic nie zastąpi." msgid "&New Tab\tCtrl+N" msgstr "Nowa karta \tCtrl+N" msgid "Open a new tab." msgstr "Otwórz nową kartę." msgid "&Open\tCtrl+O" msgstr "Open \tCtrl + O" msgid "Open a new document." msgstr "Otwórz nowy dokument." msgid "&Save\tCtrl+S" msgstr "Zapisz \tCtrl + S" msgid "Save the document." msgstr "Zapisz dokument." msgid "Save As" msgstr "Zapisz jako" msgid "Save the document under a different name." msgstr "Zapisz dokument pod inną nazwą." msgid "Save All" msgstr "Zapisz wszystkie" msgid "Saves all the open documents that have a path." msgstr "Zapisuje wszystkie otwarte dokumenty, które drogą." msgid "Reload\tCtrl+R" msgstr "Odśwież\tCtrl+R" msgid "Reload the current file from disk." msgstr "Odśwież bieżącego pliku z dysku." msgid "&Print\tCtrl+P" msgstr "& Drukuj\tCtrl+P" msgid "Print the current document." msgstr "Drukuje bieżący dokument." msgid "Close &Tab\tCtrl+W" msgstr "Zamknij & Tab\tCtrl+W" msgid "Close the current tab." msgstr "Zamknij bieżącą kartę." msgid "Recent files\tShow the last opened files." msgstr "Ostatnie files \tShow ostatnio otwieranych plików." msgid "&Quit\tCtrl+Q" msgstr "Zakończ \tCtrl + Q" msgid "Quit gEcrit." msgstr "Zamknij gEcrit." msgid "&Undo\tCtrl+Z" msgstr "& Undo \tCtrl + Z" msgid "Cancel the last action." msgstr "An&uluj ostatniej akcji." msgid "&Redo\tCtrl+Y" msgstr "Redo\tCtrl+Y" msgid "Bring back the last action." msgstr "Przywróć ostatnią akcję." msgid "Cut the selection." msgstr "Wytnij zaznaczenie." msgid "&Cut\tCtrl+X" msgstr "&Cut\tCtrl+X" msgid "C&opy\tCtrl+C" msgstr "&Kopiuj\tCtrl+C" msgid "Copy the selection." msgstr "Kopiuj zaznaczenie." msgid "P&aste\tCtrl+V" msgstr "P&aste\tCtrl+V" msgid "Paste the selection." msgstr "Wklej wyboru." msgid "Select All\tCtrl+A" msgstr "Zaznacz wszystko\tCtrl+A" msgid "Select all the document." msgstr "Wybierz dokumentu." msgid "Select Code Block\tCtrl+Shift+A" msgstr "Wybierz Code Block\tCtrl+Shift+A" msgid "Select all the current code block." msgstr "Zaznacz wszystko do końca bloku kodu." msgid "Indent\tCtrl+K" msgstr "Wcięcie\tCtrl+K" msgid "Indent the selected lines." msgstr "wcięcie wybranych linii." msgid "Dedent\tCtrl+J" msgstr "Dedent \tCtrl + J" msgid "Dedent the selected lines." msgstr "Dedent wybranych linii." msgid "Comment Lines\tCtrl+Shift+C" msgstr "Lines komentarz\tCtrl+Shift+C" msgid "Comment the selected lines." msgstr "Komentarz wybranych linii." msgid "Uncomment Lines\tCtrl+Shift+X" msgstr "Odkomentować linie \tCtrl+Shift+X" msgid "Uncomment the selected lines." msgstr "Odkomentować wybrane linie." msgid "Insert date" msgstr "Data dodania" msgid "Insert the date at cursor position." msgstr "Należy podać datę w pozycji kursora." msgid "Preferences\tCtrl+E" msgstr "Ustawienia\tCtrl+E" msgid "Open the configuration window." msgstr "Otwórz okno konfiguracji." msgid "Find\tCtrl+F" msgstr "Pokaż\tCtrl+F" msgid "Search text in the current document." msgstr "Wyszukiwanie tekstu w bieżącym dokumencie." msgid "Find and Replace\tCtrl+H" msgstr "Znajdź i zamień\tCtrl+H" msgid "Search and replace text in the current document." msgstr "Wyszukiwanie i zamiana tekstu w bieżącym dokumencie." msgid "Regex Search\tCtrl+Shift+F" msgstr "Regex Search\tCtrl+Shift+F" msgid "Find text using a regular expression." msgstr "Znajdź tekst za pomocą wyrażenia regularnego." msgid "Regex Search and Replace\tCtrl+Shift+H" msgstr "Regex Znajdź i zamień\tCtrl+ hift+H" msgid "Find and replace text using a regular expression." msgstr "Znajdowanie i zastępowanie tekstu za pomocą wyrażeń regularnych." msgid "Zoom In\tCtrl++" msgstr "Zoom In\tCtrl++" msgid "Increase the size of the text." msgstr "Zwiększ rozmiar tekstu." msgid "Zoom Out\tCtrl+-" msgstr "Zoom Out\tCtrl+-" msgid "Decrease the size of the text." msgstr "Zmniejsz rozmiar tekstu." msgid "Normal Size\tCtrl+0" msgstr "Rozmiar normalny\tCtrl+0" msgid "Set the size of the text to normal." msgstr "Ustaw rozmiar tekstu do normy." msgid "Line Numbers" msgstr "Numery linii" msgid "Show/Hide line numbers." msgstr "Pokaż/Ukryj numery linii." msgid "Fold Marks" msgstr "Pokaż/Ukryj krotnie marek." msgid "Show/Hide fold marks." msgstr "Pokaż/Ukryj krotnie znaków." msgid "White Space" msgstr "White Space" msgid "Show/Hide white spaces." msgstr "Pokaż/Ukryj spacji." msgid "Indentation Guides" msgstr "Wcięcia przewodniki" msgid "Show/Hide indentation guides." msgstr "Pokaż/Ukryj prowadnice wcięcia." msgid "Edge Line" msgstr "Edge Line" msgid "Show/Hide the edge line." msgstr "Pokaż/Ukryj krawędzi." msgid "Syntax Highlight" msgstr "Podświetlanie składni" msgid "Enable/Disable Syntax Highlight." msgstr "Włącz/wyłącz podświetlanie składni." msgid "Python Shell" msgstr "Python Shell" msgid "Stop/Start a python shell." msgstr "Stop/Start powłoki Pythona." msgid "OS Shell" msgstr "OS Shell" msgid "Stop/Start an OS shell." msgstr "Stop/Start powłoki systemu operacyjnego." msgid "Statusbar" msgstr "Pasek stanu" msgid "Show/Hide statusbar." msgstr "Pokaż/Ukryj pasek stanu." msgid "Fullscreen\tF11" msgstr "Pełny ekran\tF11" msgid "Toggle Fullscreen mode." msgstr "Przełącz tryb pełnoekranowy." msgid "Toggle Toolbox" msgstr "Przełącz Toolbox" msgid "Show/Hide Toolbox window." msgstr "Pokaż/Ukryj okno Toolbox." msgid "Toggle Assistants" msgstr "Przełącz asystentów" msgid "Show/Hide Assistants window." msgstr "Pokaż/Ukryj okno asystentów." msgid "Remove Trailing Spaces" msgstr "Usuń spacje na końcu" msgid "Remove spaces at the end of the line." msgstr "Usuń spacje na końcu linii." msgid "Run File\tF5" msgstr "Uruchom File\tF5" msgid "Run the current document.(python only)" msgstr "Uruchom w bieżącym dokumencie. (python tylko)" msgid "Tabify" msgstr "Tabify" msgid "Replace spaces by tabs." msgstr "Zamień spacje kart." msgid "Untabify" msgstr "Untabify" msgid "Replace tabs by spaces." msgstr "Zamień karty spacjami." msgid "Enable Session" msgstr "Włącz Session" msgid "Enable/Disable Session support." msgstr "Włącz/Wyłącz Obsługa sesji." msgid "Save Session" msgstr "Zapisz sesję" msgid "Save the current application state." msgstr "Zapisz bieżący stan aplikacji." msgid "Delete Session" msgstr "Usuń Session" msgid "Delete the saved session file." msgstr "Usuń zapisanego pliku sesji." msgid "Plugin Manager" msgstr "Plugin Manager" msgid "Manage gEcrit Plugins." msgstr "Zarządzaj gEcrit Plugins." msgid "About" msgstr "O" msgid "Open the about window." msgstr "Otwórz okno o programie." msgid "&File" msgstr "Plik" msgid "&Edit" msgstr "&Edycja" msgid "&Search" msgstr "&Szukaj" msgid "&View" msgstr "&Widok" msgid "&Document" msgstr "&Dokument" msgid "&Session" msgstr "&Sesja" msgid "&Plugins" msgstr "&Wtyczki" msgid "&Help" msgstr "&Pomoc" msgid "New" msgstr "Nowy" msgid "Open" msgstr "Open" msgid "Save" msgstr "Zapisz" msgid "Save the current document." msgstr "Zapisz bieżącego dokumentu." msgid "Save the current document under a differend name." msgstr "Zapisz bieżący dokument w differend imię." msgid "Settings" msgstr "Ustawienia" msgid "Quit" msgstr "Quit" msgid "Quit gEcrit" msgstr "Zamknij gEcrit" msgid "Print" msgstr "Drukuj" msgid "Run the current file.(Python only)" msgstr "Uruchom bieżącego pliku. (Python tylko)" msgid "Autocomplete Braces" msgstr "Autouzupełnianie Szelki" msgid "Show Line Numbers" msgstr "Pokaż numery linii" msgid "Autoindentation" msgstr "Autoindentation" msgid "Backspace to Unindent" msgstr "Backspace Usunięcie wcięcia tekstu" msgid "Use Tabs" msgstr "Użyj karty" msgid "Show Whitespace" msgstr "Spacja" msgid "Edge Line Position:" msgstr "Edge Line stanowisko:" msgid "Enable Autosave" msgstr "Autozapis" msgid "Save data each # of characters:" msgstr "Zapisz dane każdego # znaków:" msgid "Strip Trailing Spaces On Save" msgstr "Strip spacje na Zapisz" msgid "Status Bar" msgstr "Pasek stanu" msgid "Enable Log" msgstr "Włącz Log" msgid "Colour Palette" msgstr "Colour Palette" msgid "View Log" msgstr "Zobacz Log" msgid "Erase Log" msgstr "Usuń Log" msgid "OK" msgstr "OK" msgid "Toolbox" msgstr "Toolbox" msgid "Assistants and others" msgstr "Asystentów i innych" msgid "Remove" msgstr "Usuń" msgid "Author: " msgstr "Autor:" msgid "Version: " msgstr "Wersja:" msgid "Website: " msgstr "Strona WWW" msgid "Description: " msgstr "Opis:" msgid "Keywords" msgstr "Słowa kluczowe" msgid "Strings" msgstr "Strings" msgid "Triple Quotes" msgstr "Potrójnych cudzysłowów" msgid "Integers" msgstr "Liczby naturalne" msgid "Comments" msgstr "Komentarze" msgid "Brackets" msgstr "Klamry" msgid "Bad EOL" msgstr "Bad EOL" msgid "Method Names" msgstr "Metoda Names" msgid "Operators" msgstr "Operatorów" msgid "Identifiers" msgstr "Identyfikatory" msgid "Plugins:" msgstr "Wtyczki" gecrit-2.8.4/pyctags/tag_file.py000777 000000 000000 00000017475 12051462410 016576 0ustar00rootroot000000 000000 ## Copyright (C) 2008 Ben Smith ## This file is part of pyctags. ## pyctags is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## pyctags is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU Lesser General Public License ## and the GNU Lesser General Public Licens along with pyctags. If not, ## see . """ Python representation of ctags format file. """ import os try: # do relative imports for tests # try this first in case pyctags is already installed, since we want to be testing the source bundled in the distribution from kwargs_validator import the_validator as validator from tag_entry import ctags_entry, _PYTHON_3000_ except ImportError: from pyctags.kwargs_validator import the_validator as validator from pyctags.tag_entry import ctags_entry, _PYTHON_3000_ class ctags_file: """ Class that parses ctags generated files contains resulting ctags_entry objects. """ def __init__(self, tags=None, **kwargs): """ Initializes instances of ctags_file. - B{Keyword Arguments:} - B{harvesters:} (list) list of harvester classes @param tags: If I{tags} is a sequence, it will automatically be parsed. If it is a filename or path, it will be opened and parsed. @type tags: sequence or str """ valid_kwargs = ['harvesters'] validator.validate(kwargs.keys(), valid_kwargs) self._clear_variables() if tags: if type(tags) == str: tags = open(tags).readlines() self.parse(tags, **kwargs) def _clear_variables(self): """ Sets internal maps to initial values. """ self.format = None """ Format from the header.""" self.format_comment = None """ Format header comment.""" self.sorted = None """ Sorting type.""" self.sorted_comment = None """ Sorting type comment.""" self.author = None """ Ctags author.""" self.author_comment = None """ Ctags author comment.""" self.name = None """ Tag program name.""" self.name_comment = None """ Tag program comment.""" self.url = None """ Tag program url.""" self.url_comment = None """ Tag program url comment.""" self.version = None """ Tag program version.""" self.version_comment = None """ Tag program version comment.""" self.tags = list() """ List of ctags_entry elements.""" self.__feed_harvesters = list() """ List of harvesters used when parsing ctags output on the fly.""" def __header_format(self, line): """ Processes !_ctags_file_FORMAT ctags header.""" if not self.format: self.format = int(line[0]) self.format_comment = line[1].strip('/') def __header_sorted(self, line): """ Processes !_ctags_file_SORTED ctags header.""" self.sorted = int(line[0]) self.sorted_comment = line[1].strip('/') def __header_author(self, line): """ Processes !_TAG_PROGRAM_AUTHOR ctags header.""" self.author = line[0] self.author_comment = line[1].strip('/') def __header_name(self, line): """ Processes !_TAG_PROGRAM_NAME ctags header.""" self.name = line[0] self.name_comment = line[1].strip('/') def __header_url(self, line): """ Processes !_TAG_PROGRAM_URL ctags header.""" self.url = line[0] self.url_comment = line[1].strip('/') def __header_version(self, line): """ Processes !_TAG_PROGRAM_VERSION ctags header.""" self.version = line[0] self.version_comment = line[1].strip('/') __HEADER_ITEMS = { '!_TAG_FILE_FORMAT' : __header_format, '!_TAG_FILE_SORTED' : __header_sorted, '!_TAG_PROGRAM_AUTHOR' : __header_author, '!_TAG_PROGRAM_NAME' : __header_name, '!_TAG_PROGRAM_URL' : __header_url, '!_TAG_PROGRAM_VERSION' : __header_version } def parse(self, tags, **kwargs): """ Parses ctags file and constructs ctags_entry list. - B{Keyword Arguments:} - B{harvesters:} (list) list of harvester classes @param tags: Filename or sequence of tag strings to parse. @type tags: sequence or str @raises ValueError: parsing error """ if type(tags) == str: # we can iterate over the file, it doesn't have to be in a list first tags = open(tags) self.feed_init(**kwargs) for line in tags: if not _PYTHON_3000_ and type(line) is not unicode: line = line.decode("utf-8") if line[0] == '!': # this is part of the file information header line = line.strip() elements = line.split('\t') try: self.__HEADER_ITEMS[elements[0]](self, elements[1:]) except KeyError: print ("Unknown header comment element " + elements[0] + " at line " + line_number + ".") else: self.feed_line(line) self.feed_finish() def harvest(self, harvesters): """ Used to perform new data harvesters with already processed tags. @param harvesters: harvester classes to apply to existing tags. @type harvesters: list @raises ValueError: if no tag data is available to process. """ if not len(self.tags): raise ValueError("No tag data to harvest from.") for h in harvesters: h.do_before() for tag in self.tags: # order n^2 for h in harvesters: h.feed(tag) for h in harvesters: h.do_after() def feed_init(self, **kwargs): """ Initializes ctags_file data members and possible data harvesters. - B{Keyword Arguments:} - B{harvesters:} (list) list of harvester classes @raises ValueError: parsing error """ valid_kwargs = ['harvesters'] validator.validate(kwargs.keys(), valid_kwargs) self._clear_variables() self.__feed_harvesters = list() if 'harvesters' in kwargs: self.__feed_harvesters = kwargs['harvesters'] for h in self.__feed_harvesters: h.do_before() def feed_line(self, tagline): """ Used to parse new ctags formatted output and new tags to the end of the tags list. @param tagline: line from ctags output file @type tagline: unicode str """ entry = ctags_entry(tagline) self.tags.append(entry) for h in self.__feed_harvesters: h.feed(entry) def feed_finish(self): """ Finalizes data harvesters from tag line feed. Drops references to harvesters.""" for h in self.__feed_harvesters: h.do_after() # drop the references to the harvesters self.__feed_harvesters = list()gecrit-2.8.4/data/plugins/__init__.py000777 000000 000000 00000000000 12051462410 017453 0ustar00rootroot000000 000000 gecrit-2.8.4/yapsy/ConfigurablePluginManager.py000777 000000 000000 00000024243 12051462410 021560 0ustar00rootroot000000 000000 #!/usr/bin/python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- """ Role ==== Defines plugin managers that can handle configuration files similar to the ini files manipulated by Python's ConfigParser module. API === """ from yapsy.IPlugin import IPlugin from yapsy.PluginManagerDecorator import PluginManagerDecorator from yapsy.PluginManager import PLUGIN_NAME_FORBIDEN_STRING class ConfigurablePluginManager(PluginManagerDecorator): """ A plugin manager that also manages a configuration file. The configuration file will be accessed through a ``ConfigParser`` derivated object. The file can be used for other purpose by the application using this plugin manager as it will only add a new specific section ``[Plugin Management]`` for itself and also new sections for some plugins that will start with ``[Plugin:...]`` (only the plugins that explicitly requires to save configuration options will have this kind of section). .. warning:: when giving/building the list of plugins to activate by default, there must not be any space in the list (neither in the names nor in between) """ CONFIG_SECTION_NAME = "Plugin Management" def __init__(self, configparser_instance=None, config_change_trigger= lambda x:True, decorated_manager=None, # The following args will only be used if we need to # create a default PluginManager categories_filter={"Default":IPlugin}, directories_list=None, plugin_info_ext="yapsy-plugin"): """ Create the plugin manager and record the ConfigParser instance that will be used afterwards. The ``config_change_trigger`` argument can be used to set a specific method to call when the configuration is altered. This will let the client application manage the way they want the configuration to be updated (e.g. write on file at each change or at precise time intervalls or whatever....) """ # Create the base decorator class PluginManagerDecorator.__init__(self,decorated_manager, categories_filter, directories_list, plugin_info_ext) self.setConfigParser(configparser_instance, config_change_trigger) def setConfigParser(self,configparser_instance,config_change_trigger): """ Set the ConfigParser instance. """ self.config_parser = configparser_instance # set the (optional) fucntion to be called when the # configuration is changed: self.config_has_changed = config_change_trigger def __getCategoryPluginsListFromConfig(self, plugin_list_str): """ Parse the string describing the list of plugins to activate, to discover their actual names and return them. """ return plugin_list_str.strip(" ").split("%s"%PLUGIN_NAME_FORBIDEN_STRING) def __getCategoryPluginsConfigFromList(self, plugin_list): """ Compose a string describing the list of plugins to activate """ return PLUGIN_NAME_FORBIDEN_STRING.join(plugin_list) def __getCategoryOptionsName(self,category_name): """ Return the appropirately formated version of the category's option. """ return "%s_plugins_to_load" % category_name.replace(" ","_") def __addPluginToConfig(self,category_name, plugin_name): """ Utility function to add a plugin to the list of plugin to be activated. """ # check that the section is here if not self.config_parser.has_section(self.CONFIG_SECTION_NAME): self.config_parser.add_section(self.CONFIG_SECTION_NAME) # check that the category's list of activated plugins is here too option_name = self.__getCategoryOptionsName(category_name) if not self.config_parser.has_option(self.CONFIG_SECTION_NAME, option_name): # if there is no list yet add a new one self.config_parser.set(self.CONFIG_SECTION_NAME,option_name,plugin_name) return self.config_has_changed() else: # get the already existing list and append the new # activated plugin to it. past_list_str = self.config_parser.get(self.CONFIG_SECTION_NAME,option_name) past_list = self.__getCategoryPluginsListFromConfig(past_list_str) # make sure we don't add it twice if plugin_name not in past_list: past_list.append(plugin_name) new_list_str = self.__getCategoryPluginsConfigFromList(past_list) self.config_parser.set(self.CONFIG_SECTION_NAME,option_name,new_list_str) return self.config_has_changed() def __removePluginFromConfig(self,category_name, plugin_name): """ Utility function to add a plugin to the list of plugin to be activated. """ # check that the section is here if not self.config_parser.has_section(self.CONFIG_SECTION_NAME): # then nothing to remove :) return # check that the category's list of activated plugins is here too option_name = self.__getCategoryOptionsName(category_name) if not self.config_parser.has_option(self.CONFIG_SECTION_NAME, option_name): # if there is no list still nothing to do return else: # get the already existing list past_list_str = self.config_parser.get(self.CONFIG_SECTION_NAME,option_name) past_list = self.__getCategoryPluginsListFromConfig(past_list_str) if plugin_name in past_list: past_list.remove(plugin_name) new_list_str = self.__getCategoryPluginsConfigFromList(past_list) self.config_parser.set(self.CONFIG_SECTION_NAME,option_name,new_list_str) self.config_has_changed() def registerOptionFromPlugin(self, category_name, plugin_name, option_name, option_value): """ To be called from a plugin object, register a given option in the name of a given plugin. """ section_name = "%s Plugin: %s" % (category_name,plugin_name) # if the plugin's section is not here yet, create it if not self.config_parser.has_section(section_name): self.config_parser.add_section(section_name) # set the required option self.config_parser.set(section_name,option_name,option_value) self.config_has_changed() def hasOptionFromPlugin(self, category_name, plugin_name, option_name): """ To be called from a plugin object, return True if the option has already been registered. """ section_name = "%s Plugin: %s" % (category_name,plugin_name) return self.config_parser.has_section(section_name) and self.config_parser.has_option(section_name,option_name) def readOptionFromPlugin(self, category_name, plugin_name, option_name): """ To be called from a plugin object, read a given option in the name of a given plugin. """ section_name = "%s Plugin: %s" % (category_name,plugin_name) return self.config_parser.get(section_name,option_name) def __decoratePluginObject(self, category_name, plugin_name, plugin_object): """ Add two methods to the plugin objects that will make it possible for it to benefit from this class's api concerning the management of the options. """ plugin_object.setConfigOption = lambda x,y: self.registerOptionFromPlugin(category_name, plugin_name, x,y) plugin_object.setConfigOption.__doc__ = self.registerOptionFromPlugin.__doc__ plugin_object.getConfigOption = lambda x: self.readOptionFromPlugin(category_name, plugin_name, x) plugin_object.getConfigOption.__doc__ = self.readOptionFromPlugin.__doc__ plugin_object.hasConfigOption = lambda x: self.hasOptionFromPlugin(category_name, plugin_name, x) plugin_object.hasConfigOption.__doc__ = self.hasOptionFromPlugin.__doc__ def activatePluginByName(self, plugin_name, category_name="Default", save_state=True): """ Activate a plugin, , and remember it (in the config file). If you want the plugin to benefit from the configuration utility defined by this manager, it is crucial to use this method to activate a plugin and not call the plugin object's ``activate`` method. In fact, this method will also "decorate" the plugin object so that it can use this class's methods to register its own options. By default, the plugin's activation is registered in the config file but if you d'ont want this set the 'save_state' argument to False. """ # first decorate the plugin pta = self._component.getPluginByName(plugin_name,category_name) if pta is None: return None self.__decoratePluginObject(category_name,plugin_name,pta.plugin_object) # activate the plugin plugin_object = self._component.activatePluginByName(plugin_name,category_name) # check the activation and then optionally set the config option if plugin_object.is_activated: if save_state: self.__addPluginToConfig(category_name,plugin_name) return plugin_object return None def deactivatePluginByName(self, plugin_name, category_name="Default", save_state=True): """ Deactivate a plugin, and remember it (in the config file). By default, the plugin's deactivation is registered in the config file but if you d'ont want this set the ``save_state`` argument to False. """ # activate the plugin plugin_object = self._component.deactivatePluginByName(plugin_name,category_name) if plugin_object is None: return None # check the deactivation and then optionnally set the config option if not plugin_object.is_activated: if save_state: self.__removePluginFromConfig(category_name,plugin_name) return plugin_object return None def loadPlugins(self,callback=None): """ Walk through the plugins' places and look for plugins. Then for each plugin candidate look for its category, load it and stores it in the appropriate slot of the ``category_mapping``. """ self._component.loadPlugins() # now load the plugins according to the recorded configuration if self.config_parser.has_section(self.CONFIG_SECTION_NAME): # browse all the categories for category_name in self._component.category_mapping.keys(): # get the list of plugins to be activated for this # category option_name = "%s_plugins_to_load"%category_name if self.config_parser.has_option(self.CONFIG_SECTION_NAME, option_name): plugin_list_str = self.config_parser.get(self.CONFIG_SECTION_NAME, option_name) plugin_list = self.__getCategoryPluginsListFromConfig(plugin_list_str) # activate all the plugins that should be # activated for plugin_name in plugin_list: self.activatePluginByName(plugin_name,category_name) gecrit-2.8.4/gEcritPluginManager.py000777 000000 000000 00000011250 12051462410 017222 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import wx, gettext from Configuration import * class gEcritPluginManager(wx.Frame): def __init__(self, parent, id = -1): self.parent = parent self._ = self.parent._ wx.Frame.__init__(self, self.parent, id, self._("Plugin Manager"), size = (510, 435), pos = (-1, -1)) self._ = self.parent._ self.main_panel = wx.Panel(self) self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL) self.button_sizer = wx.BoxSizer(wx.VERTICAL) self.remove_pl = wx.Button(self.main_panel, -1,self._("Remove"), size = (110,40)) self.remove_pl.Bind(wx.EVT_BUTTON, self.OnDeletePlugin) font = wx.Font(18, wx.ROMAN ,wx.BOLD, wx.NORMAL) self.pl_list_desc = wx.StaticText(self.main_panel, -1, self._("Plugins:"), size = (-1,-1)) self.pl_list_desc.SetFont(font) self.plugin_list = wx.CheckListBox(self,-1, size = (380,280), style = wx.LB_MULTIPLE | wx.RAISED_BORDER|wx.LB_ALWAYS_SB) self.plugin_list_selection = False self.Bind(wx.EVT_LISTBOX, self.OnListItemClick) self.pl_description = wx.TextCtrl(self.main_panel,-1, size = (380,100), style = wx.TE_MULTILINE) self.pl_description.SetEditable(False) self.button_sizer.Add(self.remove_pl, 0 , wx.EXPAND) self.button_sizer.AddSpacer(10) self.horizontal_sizer.AddSpacer(5) self.horizontal_sizer.Add(self.plugin_list, 1, wx.EXPAND) self.horizontal_sizer.AddSpacer(10) self.horizontal_sizer.Add(self.button_sizer, 0, wx.EXPAND) self.main_sizer.AddSpacer(5) self.main_sizer.Add(self.pl_list_desc, 0 , wx.EXPAND) self.main_sizer.AddSpacer(10) self.main_sizer.Add(self.horizontal_sizer, 1, wx.EXPAND) self.main_sizer.AddSpacer(5) self.main_sizer.Add(self.pl_description, 0 , wx.EXPAND) self.main_panel.SetSizer(self.main_sizer) self.main_panel.Fit() self.pl_lst = [] self.PopulatePluginList() self.Hide() self.Bind(wx.EVT_CLOSE, self.HideMe) def PopulatePluginList(self): self.parent.plugin_manager.locatePlugins() self.pl_lst = self.parent.plugin_manager.getPluginCandidates() index = 0 for p in self.pl_lst: self.plugin_list.AppendAndEnsureVisible(p[2].name) if p[2].name in self.parent.activated_plugins: self.plugin_list.Check(index, True) index += 1 def OnDeletePlugin(self, event): if self.plugin_list_selection >= 0: os.remove(self.pl_lst[self.plugin_list_selection][0]) os.remove(self.pl_lst[self.plugin_list_selection][1] + ".py") self.pl_lst.pop(self.plugin_list_selection) self.plugin_list.Delete(self.plugin_list_selection) #update config file conf = Config.GetOption("ActivePlugins") conf = list(self.plugin_list.GetCheckedStrings()) Config.ChangeOption("ActivePlugins", conf) def OnListItemClick(self,event): plugin = self.pl_lst[event.GetSelection()] #read and display plugin description self.pl_description.SetValue(self._("Author: ") + plugin[2].author + "\n"+ self._("Version: ") + plugin[2].version + "\n"+ self._("Website: ") + plugin[2].website + "\n"+ self._("Description: ")+plugin[2].description + "\n") #update config file conf = Config.GetOption("ActivePlugins") conf = list(self.plugin_list.GetCheckedStrings()) Config.ChangeOption("ActivePlugins", conf) self.plugin_list_selection = event.GetSelection() def ShowMe(self, event): self.Show() def HideMe(self, event): self.Hide() gecrit-2.8.4/messages.po000777 000000 000000 00000004353 12051462410 015136 0ustar00rootroot000000 000000 # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2011-05-07 12:38-0400\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" #: ConfigWindow.py:63 msgid "Settings" msgstr "" #: ConfigWindow.py:69 msgid "OK" msgstr "" #: ConfigWindow.py:82 msgid "General" msgstr "" #: ConfigWindow.py:83 msgid "Editor" msgstr "" #: ConfigWindow.py:127 msgid "Enable Autosave" msgstr "" #: ConfigWindow.py:136 msgid "Save data each # of characters:" msgstr "" #: ConfigWindow.py:150 msgid "Strip Trailing Spaces On Save" msgstr "" #: ConfigWindow.py:156 msgid "Enable StatusBar" msgstr "" #: ConfigWindow.py:165 msgid "Enable Session" msgstr "" #: ConfigWindow.py:170 msgid "Enable Log" msgstr "" #: ConfigWindow.py:178 msgid "Colour Palette" msgstr "" #: ConfigWindow.py:183 ConfigWindow.py:222 msgid "View Log" msgstr "" #: ConfigWindow.py:188 msgid "Erase Log" msgstr "" #: ConfigWindow.py:232 msgid "" "The Log is disabled! \n" "Enable it to view." msgstr "" #: ConfigWindow.py:234 msgid "Log Status" msgstr "" #: ConfigWindow.py:245 msgid "Show Line Numbers" msgstr "" #: ConfigWindow.py:249 msgid "LineNumbers" msgstr "" #: ConfigWindow.py:253 msgid "Syntax Highlight" msgstr "" #: ConfigWindow.py:262 msgid "Autoindentation" msgstr "" #: ConfigWindow.py:290 msgid "Indentation Guides" msgstr "" #: ConfigWindow.py:301 msgid "Backspace to Unindent" msgstr "" #: ConfigWindow.py:310 msgid "Show Whitespace" msgstr "" #: ConfigWindow.py:318 msgid "Use Tabs" msgstr "" #: ConfigWindow.py:325 msgid "Carret Width:" msgstr "" #: ConfigWindow.py:337 msgid "Fold Marks" msgstr "" #: ConfigWindow.py:345 msgid "Tab Width:" msgstr "" #: ConfigWindow.py:356 msgid "Edge Line" msgstr "" #: ConfigWindow.py:366 msgid "Edge Line Position:" msgstr "" #: ConfigWindow.py:383 msgid "Autocomplete Braces" msgstr "" gecrit-2.8.4/COPYING000777 000000 000000 00000103551 12051462410 014022 0ustar00rootroot000000 000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright © 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. “This License” refers to version 3 of the GNU General Public License. “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. A “covered work” means either the unmodified Program or a work based on the Program. To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . gecrit-2.8.4/data/plugins/SyntaxChecker.py000777 000000 000000 00000005650 12051462410 020507 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- #!/usr/bin/python # -*- coding: utf-8 -*- import wx import yapsy.IPlugin from data.plugins.categories import General class SyntaxDoctor(General, yapsy.IPlugin.IPlugin): """ SyntaxDoctor Manages the syntax checking feature. """ def __init__(self): self.name = "Python Syntax Doctor" def Init(self, parent = None): self.parent = parent self.current_doc = None self.plugins_menu = wx.Menu() check_entry = self.plugins_menu.Append(-1,"Check Syntax") self.menu_item = self.parent.AddToMenuBar("Py Syntax Doctor", self.plugins_menu) self.parent.BindMenubarEvent(check_entry, self.CheckSyntax) def CheckSyntax(self, event): """ CheckSyntax Finds the current document and calls python to check the correctitude of the file. If error is reported, prompts the user with the error message. If not, prompts the user with a success message. """ file_nm = self.current_doc.GetFilePath() try: ctext = self.current_doc.GetText() ctext = ctext.replace('\r\n', '\n').replace('\r', '\n') compile(ctext, file_nm, 'exec') say_ok = wx.MessageDialog(None, "No errors have been detected.", "Syntax Check") if say_ok.ShowModal() == wx.ID_OK: say_ok.Destroy() except Exception, e: ln_num = "" excstr = str(e) try: for c in exctr: if int(c): ln_num += str(c) n = int(ln_num) cur_doc.ScrollToLine(n) cur_doc.GotoLine(n) except: say_error = wx.MessageDialog(None, 'Error:' + excstr, 'Error Found') if say_error.ShowModal() == wx.ID_OK: say_error.Destroy() def NotifyTabChanged(self): try: #the tab change event is produced prematurely self.current_doc = self.parent.GetCurrentDocument() except: pass def Stop(self): self.parent.RemoveFromMenubar(self.menu_item) gecrit-2.8.4/locale/es/LC_MESSAGES/gEcrit.mo000777 000000 000000 00000025630 12051462410 020175 0ustar00rootroot000000 000000 L|  &  2 ? KU[ag w       ';Kair2Qd    !0 P q{ 1%  " AOj } #   %:Ja  H  & BO T `(m% "%&Ld |&" #19k).0$6[m#5Oe  )1O`0g  ,5 >H Q [gvG !   "*3; S aox   .F N#Z~&# *6)Ku '  ,L_)n= 7 2G z    ! !!(!,9!f!n!}!!!!!! !!! "%""<"_" o"z"Q""""##:#K#Q#d#9x##%##&$*$%1$'W$($($$*$(%8% @% L%X%*g%'%4%%$ &0&CD&&0&&&& '-'M'f'/w''''('/(+D(!p(%("(($( )0)$A)f))5)'))<) .*9*%L*r***2*4* +)+ @+J+ Z+g+y++^| Bka:4Njo_?q70s] HE>#fO h.(We[ +)Lpt;%P*$9SZ1T2,yxQlrn!\6bG/8M"X}vzg<{@&-Iu`3iFd=CYR5'AUcJ DVK~mw does not exists. is not saved. Do you wish to save it?&Copy Ctrl+C&Cut Ctrl+X&Document&Edit&File&Help&New Tab Ctrl+N&Open Ctrl+O&Paste Ctrl+V&Plugins&Print Ctrl+P&Quit Ctrl+Q&Redo Ctrl+Y&Save Ctrl+S&Search&Session&Undo Ctrl+Z&ViewAboutAre you sure?Assistants and othersAuthor: Autocomplete BracesAutoindentationBackspace to UnindentBad EOLBracketsBring back the last action.Cancel the last action.Close &Tab Ctrl+WClose the current tab.Colour PaletteComment Lines Ctrl+Shift+CComment the selected lines.CommentsCopy the selection.Could not load file. The file Cut the selection.Decrease the size of the text.Dedent Ctrl+JDedent the selected lines.Delete SessionDelete the saved session file.Description: Edge LineEdge Line Position:Enable AutosaveEnable LogEnable SessionEnable/Disable Session support.Enable/Disable Syntax Highlight.Erase LogFindFind Ctrl+FFind and Replace Ctrl+HFind and replace text using a regular expression.Find text using a regular expression.Fold MarksFullscreen F11IdentifiersIncrease the size of the text.Indent Ctrl+KIndent the selected lines.Indentation GuidesInput Error.Insert dateInsert the date at cursor position.IntegersKeywordsLine NumbersManage gEcrit Plugins.Method NamesNewNormal Size Ctrl+0OKOS ShellOpenOpen a new document.Open a new tab.Open the about window.Open the configuration window.Opened file OperatorsPaste the selection.Please make sure that your data is saved. Are you sure you want to quit?Plugin ManagerPlugins:Preferences Ctrl+EPrintPrint the current document.Python ShellQuitQuit gEcritQuit gEcrit.Recent files Show the last opened files.Regex Search Ctrl+Shift+FRegex Search and Replace Ctrl+Shift+HReload Ctrl+RReload the current file from disk.RemoveRemove Trailing SpacesRemove spaces at the end of the line.Replace spaces by tabs.Replace tabs by spaces.Run File F5Run the current document.(python only)Run the current file.(Python only)SaveSave AllSave AsSave SessionSave data each # of characters:Save the current application state.Save the current document under a differend name.Save the current document.Save the document under a different name.Save the document.Saves all the open documents that have a path.Search and ReplaceSearch and replace text in the current document.Search text in the current document.Select All Ctrl+ASelect Code Block Ctrl+Shift+ASelect all the document.Session file loaded.Session saved.Set the size of the text to normal.SettingsShow Line NumbersShow WhitespaceShow/Hide Assistants window.Show/Hide Toolbox window.Show/Hide fold marks.Show/Hide indentation guides.Show/Hide line numbers.Show/Hide statusbar.Show/Hide the edge line.Show/Hide white spaces.Status BarStatusbarStop/Start a python shell.Stop/Start an OS shell.StringsStrip Trailing Spaces On SaveSyntax HighlightTabifyThe end of file was reached! Nothing to replace.The file Toggle AssistantsToggle Fullscreen mode.Toggle ToolboxToolboxTriple QuotesUncomment Lines Ctrl+Shift+XUncomment the selected lines.UntabifyUse TabsVersion: View LogWebsite: White SpaceZoom In Ctrl++Zoom Out Ctrl+-Project-Id-Version: PACKAGE VERSIONReport-Msgid-Bugs-To: POT-Creation-Date: 2011-05-05 22:11-0400PO-Revision-Date: 2011-05-07 11:23-0500Last-Translator: Groza cristi Language-Team: LANGUAGE Language: SpanishMIME-Version: 1.0Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bitno existe.no se guarda. Desea guardar esto?&Copio Ctrl+C&Corta Ctrl+X&Documento&Editar&Archivo&Ayudar&Nuevo Documento Ctrl+N&Abrir Ctrl+O&Paste Ctrl+V&Plugins&Imprimir Ctrl+P&Salir Ctrl+Q&Rehace Ctrl+Y&Guarde Ctrl+S&Busca&Sesiones&Undo Ctrl+Z&VerCasiEstás seguro?Asistentes y otrosAutor:Autocompleta TirantesAuto indentaciónRetroceso para UnindentMal EOLParéntesisTraer de vuelta la última acción.Canclearla última acción.Cerrar &Documento Ctrl+WCerrar la documento actual.Paleta de colorLas líneas de comentario Ctrl+Shift+CComentar las líneas seleccionadas.ComentariosCopio la selección.No se pudo cargar el archivo. El archivo.Cortar la selección.Disminuir el tamaño del texto.Dedent Ctrl+JDedent lElimina SesiónElimina el archivo de sesión guardada.Descripción:Edge LinePonga el borde de línea:Activar el guardado automáticoActivar la entradaActive SesiónActivar / Desactivar soporte de Sesión .Activar / Desactivar resaltado de sintaxis(Syntax Highlight).Eliminar EntradaBuscarBuscar Ctrl+FBusca y reemplazarBusca y reemplazar texto usando una expresión regular.Búsca de texto utilizando una expresión regular.Fold Marks(Doble Marcas)Pantalla completa F11IdentificadoresAumenta el tamaño del texto.Indent Ctrl+KIndent las líneas seleccionadas.Sangría GuíasError de entradaInserte la fechaInserte la fecha en la posición del cursor.EnterosClave PalabrasNúmeros de líneaAdministrar gEcrit Plugins.Método NombresNuevoNormal Tamaño Ctrl+0BienOS proyectilAbiertoAbrir un nuevo documentoAbrir un nuevo documento.Abre sobre la ventana.Abra la ventana de configuración.Archivo abiertoOperadoresPaste la selección.Por favor, asegúrese de que sus datos se guardan. Está seguro que quiere dejar?Plugin AdministradorPlugins:Preferencias Ctrl+EImprimirImprimir el documento actual.Python proyectilSalirSalga de la gEcritSalga de la gEcrit.Archivos recientes Mostrar los últimos archivos abiertosRegex Busca Ctrl+Shift+FRegex busca y reemplazar Ctrl+Shift+HActualizar Ctrl+RActualizar el archivo actual de disco.QuitarEliminar (Trailing) espacios al finalElimine espacios al final de la línea.Vuelva a colocar etiquetas con espacios.Vuelva a colocar etiquetas con espacios.Ejecute Archivo F5Ejecute el documento actual.(python sólo)Ejecute el archivo actual.(Python sólo)GuardarGuarde TodoGuarde comoGuarda SesiónGuardar los datos de cada # de caracteres:Guarda el aplicación actual de estado.Guardar el documento actual con un nombre diferente.Guardar el documento actualGuarde el documento con otro nombre.Guarde el documentoGuarda todos los documentos abiertos que tienen una ruta de acceso.Buscar y ReemplazarBusca y reemplazar texto en el documento actual.Busca el texto en el documento actual.Seleccionar todo Ctrl+ASeleccionar el bloque de códigoSeleccionar todo los documentosSesión archivo cargado.Sesión guardadaEstablece el tamaño del texto a la normalidad.ConfiguraciónMostra números de líneaMostrar espacios en blancoMostrar / Ocultar ventana de asistentes.Mostrar / Ocultar ventana Caja de herramientas.Mostrar / Ocultar fold marks(Doble Marcas).Mostrar / Ocultar sangría guíasMostrar / Ocultar Números de Línea.Mostrar / Ocultar barra de estado.Mostrar / Ocultar la edge line.Mostrar / Ocultar espacio en blanco.Barra de estadoBarra de Estado.Stop / Start un proyectil de Python.Stop / Start OS un proyectil.StringsStrip Trailing(Franja de arrastre)Espacios al guardarResaltado de Sintaxis(Syntax Highlight)TabifyEl final del archivo se alcanzado! No hay nada de sustituir.El archivoActivar AsistentesActivar el modo de pantalla completa.Activar Caja de herramientasCaja de herramientasTriple CotizacionesElimine el comentarios de las líneas Ctrl+Shift+XElimine el comentarios de las líneas seleccionadas.UntabifyUtilice los DocumentosVersión:Ver el Entrada Página web:Espacio en BlancoZoom In Ctrl++Zoom Out Ctrl+-gecrit-2.8.4/data/plugins/Terminator.yapsy-plugin000777 000000 000000 00000000660 12051462410 022065 0ustar00rootroot000000 000000 [Core] Name = Terminator Module = Terminator [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = With this plugin you can have multiple terminal tabs for any shell you wish. Shells for Python and Bash are provided by default but you can add and remove as many as you wish. All it needs is the path to the shell interpreter. gecrit-2.8.4/Fonts.py000777 000000 000000 00000001653 12051462410 014432 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx def ChangeFont(event, font, IdRange): """ Change Fond Updates the editor's font. """ for text_id in IdRange: wx.FindWindowById(text_id).StyleSetFont(0, font) gecrit-2.8.4/AboutWindow.py000777 000000 000000 00000004311 12051462410 015575 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx class AboutWindow(wx.Frame): """ AboutWindow Constructs and about window. """ def __init__(self): """ __init__ Initializes the AboutDialogInfo object and sets all the required data. """ about_info = wx.AboutDialogInfo() about_info.Name = "gEcrit" about_info.Version = "2.8.4" about_info.Copyright = """ gEcrit 2.8.4 The Python Code Editor""" about_info.Developers = ["Groza Cristian e-mail: kristi9524@gmail.com\ ", "Groza Mihai e-mail: grozam@ymail.com\n" "Victor Pruteanu e-mail: vikkhackerz@gmail.com"] about_info.Website = "http://www.cristigrozatips.do.am" about_info.License = \ """ Copyright (C) 2011 Groza Cristian This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ wx.AboutBox(about_info) gecrit-2.8.4/Menu.py000777 000000 000000 00000023520 12051462410 014242 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx, gettext import os.path from Configuration import * class MainMenu(wx.MenuBar): """ MainMenu Creates the application menubar. Provides a few helper functios. """ def __init__(self, parent, id=wx.ID_ANY): """ __init__ Build the application menu. Adds the entryes, creates recent file list. """ #creating application menu self.parent = parent self._ = self.parent._ menubar = wx.MenuBar() self.recent_dict = {} wx.MenuBar.__init__(self) file = wx.Menu() self.recent_files = wx.Menu() edit = wx.Menu() help = wx.Menu() search = wx.Menu() view = wx.Menu() document = wx.Menu() session = wx.Menu() self.plugins = wx.Menu() if Config.GetOption("RecentFiles"): # check if list is empty self.last_recent = Config.GetOption("RecentFiles")[-1] else: self.last_recent = "" file.Append(500, self._('&New Tab\tCtrl+N'), self._('Open a new tab.')) file.Append(501, self._('&Open\tCtrl+O'),self._('Open a new document.')) file.Append(502, self._('&Save\tCtrl+S'),self._('Save the document.')) file.Append(503, self._('Save As'), self._('Save the document under a different name.')) file.Append(563, self._("Save All"), self._("Saves all the open documents that have a path.")) file.Append(507,self._("Reload\tCtrl+R"),self._("Reload the current file from disk.")) file.Append(504, self._('&Print\tCtrl+P'), self._('Print the current document.')) file.Append(505, self._('Close &Tab\tCtrl+W'), self._('Close the current tab.')) self.recent_submenu = wx.Menu() self.GenerateRecentFiles() file.AppendMenu(700, self._("Recent files\tShow the last opened files."),self.recent_submenu) file.AppendSeparator() quit = wx.MenuItem(file, 506, self._('&Quit\tCtrl+Q'), self._('Quit gEcrit.')) file.AppendItem(quit) edit.Append(520, self._("&Undo\tCtrl+Z"), self._("Cancel the last action.")) edit.Append(521, self._("&Redo\tCtrl+Y"), self._("Bring back the last action.")) edit.AppendSeparator() edit.Append(522, self._("&Cut\tCtrl+X"), self._("Cut the selection.")) edit.Append(523, self._("C&opy\tCtrl+C"), self._("Copy the selection.")) edit.Append(524, self._("P&aste\tCtrl+V"), self._("Paste the selection.")) edit.AppendSeparator() edit.Append(525, self._("Select All\tCtrl+A"), self._("Select all the document.")) edit.Append(562, self._("Select Code Block\tCtrl+Shift+A"), self._("Select all the current code block.")) edit.AppendSeparator() edit.Append(529, self._("Indent\tCtrl+K"), self._("Indent the selected lines.")) edit.Append(528, self._("Dedent\tCtrl+J"), self._("Dedent the selected lines.")) edit.Append(559, self._("Comment Lines\tCtrl+Shift+C"), self._("Comment the selected lines.")) edit.Append(560, self._("Uncomment Lines\tCtrl+Shift+X"), self._("Uncomment the selected lines.")) edit.AppendSeparator() edit.Append(526, self._("Insert date"), self._("Insert the date at cursor position.")) edit.AppendSeparator() edit.Append(534, self._("Start Macro Recording\tCtrl+Shift+M"), self._("Start recording a macro.")) edit.Append(542, self._("Stop Macro Recording\tCtrl+Alt+M"), self._("Stops recording a macro.")) edit.Append(543, self._("Play Recorded Macro\tCtrl+M"), self._("Plays the recorded macro.")) edit.AppendSeparator() edit.Append(527, self._("Preferences\tCtrl+E"), self._("Open the configuration window.")) search.Append(530, self._("Find\tCtrl+F"), self._("Search text in the current document.")) search.Append(531, self._("Find and Replace\tCtrl+H"), self._("Search and replace text in the current document.")) search.Append(532, self._("Regex Search\tCtrl+Shift+F"),self._("Find text using a regular expression.")) search.Append(533, self._("Regex Search and Replace\tCtrl+Shift+H"), self._("Find and replace text using a regular expression.")) view.Append(535, self._("Zoom In\tCtrl++"), self._("Increase the size of the text.")) view.Append(536, self._("Zoom Out\tCtrl+-"), self._("Decrease the size of the text.")) view.Append(537, self._("Normal Size\tCtrl+0"), self._("Set the size of the text to normal.")) view.AppendSeparator() view.AppendCheckItem(538, self._("Line Numbers"), self._("Show/Hide line numbers.")).Check(Config.GetOption("LineNumbers")) view.AppendCheckItem(539, self._("Fold Marks"), self._("Show/Hide fold marks.")).Check(Config.GetOption("FoldMarks")) view.AppendCheckItem(540, self._("White Space"), self._("Show/Hide white spaces.")).Check(Config.GetOption("Whitespace")) view.AppendCheckItem(541, self._("Indentation Guides"), self._("Show/Hide indentation guides.")).Check(Config.GetOption("IndetationGuides")) view.AppendCheckItem(546, self._("Edge Line"), self._("Show/Hide the edge line.")).Check(Config.GetOption("EdgeLine")) view.AppendCheckItem(547, self._("Syntax Highlight"), self._("Enable/Disable Syntax Highlight.")).Check(Config.GetOption("SyntaxHighlight")) view.AppendSeparator() view.AppendCheckItem(545, self._("Statusbar"), self._("Show/Hide statusbar.")).Check(Config.GetOption("StatusBar")) view.AppendCheckItem(557, self._("Fullscreen\tF11"), self._("Toggle Fullscreen mode.")) view.Append(548, self._("Toggle Toolbox"), self._("Show/Hide Toolbox window.")) view.Append(549, self._("Toggle Assistants"), self._("Show/Hide Assistants window.")) document.Append(551, self._("Remove Trailing Spaces"), self._("Remove spaces at the end of the line.")) document.Append(558, self._("Run File\tF5"), self._("Run the current document.(python only)")) document.Append(552, self._("Tabify"), self._("Replace spaces by tabs.")) document.Append(553, self._("Untabify"), self._("Replace tabs by spaces.")) session.AppendCheckItem(556, self._("Enable Session"), self._("Enable/Disable Session support.")).Check(Config.GetOption("Session")) session.Append(554, self._("Save Session"), self._("Save the current application state.")) session.Append(555, self._("Delete Session"), self._("Delete the saved session file.")) self.plugins.Append(564, self._("Plugin Manager"), self._("Manage gEcrit Plugins.")) help.Append(550, self._("About"), self._("Open the about window.")) self.Append(file, self._('&File')) self.Append(edit, self._('&Edit')) self.Append(search, self._("&Search")) self.Append(view, self._("&View")) self.Append(document, self._("&Document")) self.Append(session, self._("&Session")) self.Append(self.plugins, self._("&Plugins")) self.Append(help, self._('&Help')) def NewTabHelper(self,event): """ NewTabHelper Used to help for calling the NewTab function of this object parent. """ self.parent.NewTab(0,os.path.split(self.recent_dict[event.GetId()])[-1], self.recent_dict[event.GetId()]) self.last_recent = self.recent_dict[event.GetId()] def ClearRecentFiles(self): """ ClearRecentFiles Deletes all the entryes under the Recent Files submenu. """ #deleting items from menu items = self.recent_submenu.GetMenuItems() for i in items: self.recent_submenu.DeleteItem(i) def GenerateRecentFiles(self): """ GenerateRecentFiles Takes the recent files list from config and generates a Recent Files submenu with them. Binds the events to them with NewTabHelper. """ #generating new items st_id = 701 last_nm = "" #cleaning it first (must have less than 10 elements) lst = Config.GetOption("RecentFiles") if len(lst) >10: while len(lst) > 10: lst.remove(lst[0]) Config.ChangeOption("RecentFiles",lst) lst = Config.GetOption("RecentFiles") # refreshing list # creating recent file menu list for i in lst: if last_nm != i: self.recent_submenu.Append(st_id,i) st_id+=1 last_nm = i #binding events st_id = 701 items = self.recent_submenu.GetMenuItems() for item in items: self.parent.Bind(wx.EVT_MENU, self.NewTabHelper,id=item.GetId()) self.recent_dict[item.GetId()] = item.GetLabel() def UpdateRecentFiles(self): """ UpdateRecentFiles Calls the 2 function that are involved in creating a new Recent Files submenu. """ self.ClearRecentFiles() self.GenerateRecentFiles() gecrit-2.8.4/pyctags/__init__.py000777 000000 000000 00000006010 12051462410 016542 0ustar00rootroot000000 000000 ## Copyright (C) 2008 Ben Smith ## This file is part of pyctags. ## pyctags is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## pyctags is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU Lesser General Public License ## and the GNU Lesser General Public Licens along with pyctags. If not, ## see . """ A ctags file reader and a wrapper to the command line program ctags. With the extensions that exuberant ctags provides, this could be useful for static code analysis. This package has been tested against exuberant ctags version 5.7 and SVN revision 686 on Windows XP and Linux with Python 2.5 and 3.0. B{Security Notes:} - This package makes use of the subprocess.Popen() and eval() python constructs. - This package B{does not} filter the parameters for security, instead relying on module users to implement relevant security for their applications. Included in the source distribution are a few examples of usage, the test cases provide a more comprehensive usage reference. Here's a very small sample to show it in action:: from pyctags import exuberant_ctags, ctags_file from pyctags.harvesters import kind_harvester # if you have a list of source files: ctags = exuberant_ctags(files=['path/to/source.h', 'path/to/source.c', 'path/to/source.py']) # you can generate a ctags_file instance right away # ctags_file is what parses lines from the generator or a # tags file and creates a list of ctags_entry instances tag_file = ctags.generate_object() # override the default run parameters for exuberant ctags, so we get full kind names, say tag_file = ctags.generate_object(generator_options={'--fields' : '+iKmn', '-F' : None}) print len(tagfile.tags) # number of tags harvester = kind_harvester() harvester.process_tag_list(tagfile.tags) kinds = harvester.get_data() print(kinds['class']) # print list of classes I'm not certain if ctags generators other than Exuberant Ctags are in much use, but wrappers for them can be derived from ctags_base. Feel free to contact me for or with details. Pyctags is pretty heavy for large projects. A 153 MB tag file generated from linux kernel sources takes a while to process and consumes over 1.1GB of RAM. I hope to discover more ways to trim this down without going for a C implementation. """ from pyctags.tag_file import ctags_file from pyctags.tag_entry import ctags_entry from pyctags.exuberant import exuberant_ctags import pyctags.harvesters gecrit-2.8.4/pyctags/tag_entry.py000777 000000 000000 00000016211 12051462410 017003 0ustar00rootroot000000 000000 ## Copyright (C) 2008 Ben Smith ## This file is part of pyctags. ## pyctags is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## pyctags is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU Lesser General Public License ## and the GNU Lesser General Public Licens along with pyctags. If not, ## see . """ Python representation of ctags data elements. This module uses the eval function, which will let package users execute arbitrary python code, if they want. """ from copy import copy import os try: # do relative imports for tests # try this first in case pyctags is already installed, since we want to be testing the source bundled in the distribution from kwargs_validator import the_validator as validator except ImportError: from pyctags.kwargs_validator import the_validator as validator _PYTHON_3000_ = True import sys if sys.version_info[0] < 3: _PYTHON_3000_ = False _COMMENT_BEGIN_ = ';"' class ctags_entry: """ An entry in the tag file. """ def __init__(self, *args, **kwargs): """ A tag entry from ctags file. Initializes from str or keyword args. - B{Optional Parameters:} - B{args[0]}: (str) a ctags_entry repr or string from a tag file - B{Keyword Arguments:} - B{name}: (str) tag name - B{file}: (str) source file name - B{pattern}: (str) locator pattern for tag - B{line_number}: (int) locator line number - B{extensions}: (dict) extension fields - B{Raises:} - B{ValueError}: line_number or pattern isn't set, or a parameter type can't be transformed. """ valid_kwargs = ['name', 'file', 'pattern', 'line_number', 'extensions'] validator.validate(kwargs.keys(), valid_kwargs) self.name = None """ Tag name.""" self.file = None """ Source file of tag.""" self.pattern = None """ If not None, regular expression to locate this tag in self.file.""" self.line_number = None """ If not None, line number to locate this tag in self.file.""" self.extensions = None """ If not none, dict of extension fields embedded in comments in the tag entry, from exuberant ctags.""" self.__rep = None entry = dict() if len(args) == 1: if len(kwargs): raise ValueError("multiple tag data found in init") if type(args[0]) == dict: entry = args[0] elif (type(args[0]) == str or type(args[0]) == unicode) and len(args[0]): if args[0][0] == '{' and args[0][-1] == '}': # expect this to be a repr string # security anyone? entry = eval(args[0]) else: argstr = args[0].strip() # bah! uglies. if not _PYTHON_3000_ and type(argstr) is not unicode: argstr = unicode(argstr, "utf-8") # this should be a tag line, could use some safety checking here though (entry['name'], entry['file'], the_rest) = argstr.split('\t', 2) extension_fields = None if the_rest.find(_COMMENT_BEGIN_) > 0: (locator, junk, extension_fields) = the_rest.rpartition(_COMMENT_BEGIN_) else: locator = the_rest if locator.isdigit(): try: entry['line_number'] = int(locator) except ValueError: raise ValueError("Line number locator found for tag, but can't be converted to integer") else: # should be a regex pattern entry['pattern'] = locator entry['extensions'] = {} kind_arg_found = False if extension_fields: if extension_fields[0] == '\t': # probably exuberant ctags format extension_list = extension_fields[1:].split('\t') for ext in extension_list: if ':' in ext: (k, v) = ext.split(':', 1) entry['extensions'][k] = v if k == 'line' and 'line_number' not in entry: try: entry['line_number'] = int(v) except ValueError: raise ValueError("Extended tag 'line' found but can't be converted to integer.") else: if kind_arg_found: raise ValueError("Unknown extended tag found.") else: entry['extensions']['kind'] = ext kind_arg_found = True elif len(kwargs): entry = kwargs if 'file' in entry: self.file = entry['file'] else: raise ValueError("'file' parameter is required") if 'name' in entry: self.name = entry['name'] else: raise ValueError("'name' parameter is required") if 'pattern' in entry: self.pattern = entry['pattern'] if 'line_number' in entry: self.line_number = int(entry['line_number']) if not self.line_number and not self.pattern: raise ValueError("No valid locator for this tag.") if 'extensions' in entry: self.extensions = entry['extensions'] self.__rep = entry def __repr__(self): return str(self.__rep) def __str__(self): idx = self.file.rfind('/') if idx == -1: idx = self.file.rfind("\\") short_fn = self.file[idx + 1:] if self.name: return self.name + ':' + short_fn + ':' + str(self.line_number) else: return "Unnamed tag." def __eq__(self, other): return (repr(self) == repr(other)) def __ne__(self, other): return (repr(self) != repr(other)) gecrit-2.8.4/gEcrit_ro_utf.po000777 000000 000000 00000031003 12051462410 016112 0ustar00rootroot000000 000000 # SOME DESCRIPTIVE TITLE. # Copyright (C) 2011 Groza Cristian # This file is distributed under the same license as gEcrit. # FIRST AUTHOR kristi9524@gmail.com, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2011-05-05 22:11-0400\n" "PO-Revision-Date: 2011-05-07 11:23-0500\n" "Last-Translator: Groza Cristian \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: editorClass.py:324 msgid "Session file loaded." msgstr "Fisierul de sesiune incarcat." #: editorClass.py:342 msgid "Session saved." msgstr "Sesiune salvata." #: editorClass.py:381 msgid "" "Could not load file.\n" "The file " msgstr "Imposibil de incarcat fisierul.Fisierul" #: editorClass.py:381 msgid " does not exists." msgstr " nu exista. " #: editorClass.py:381 msgid "Input Error" msgstr "Eroare Intrare" #: editorClass.py:486 msgid "" "Please make sure that your data is saved.\n" "Are you sure you want to quit?" msgstr "" "Va rugam sa fiti sigur daca informatia este salvata.\n" "Sunteti sigur ca vreti sa inchideti?" #: editorClass.py:488 msgid "Are you sure?" msgstr "Sunteti sigur?" #: editorClass.py:530 msgid "The file " msgstr "Fisierul " #: editorClass.py:531 msgid "" " is not saved.\n" "Do you wish to save it?" msgstr "" "Nu este salvat.\n" "Doriti sa il salvati?" #: editorClass.py:593 #: editorClass.py:597 msgid "Opened file " msgstr "Fisier deschis" #: FindReplaceText.py:39 msgid "Find" msgstr "Cautare" #: FindReplaceText.py:101 #: FindReplaceText.py:105 msgid "Search and Replace" msgstr "Cauta si Inlocuieste" #: FindReplaceText.py:181 msgid "" "The end of file was reached!\n" "Nothing to replace." msgstr "" "Sfirsitul fisierului a fost atins!\n" "Nimic de inlocuit." #: Menu.py:47 msgid "&New Tab\tCtrl+N" msgstr "&Document Nou\tCtrl+N" #: Menu.py:47 #: Toolbar.py:40 msgid "Open a new tab." msgstr "Deschideti un fisier nou." #: Menu.py:48 msgid "&Open\tCtrl+O" msgstr "&Deschidere\tCtrl+O" #: Menu.py:48 #: Toolbar.py:42 msgid "Open a new document." msgstr "Deschideti un document nou." #: Menu.py:49 msgid "&Save\tCtrl+S" msgstr "&Salvare\tCtrl+S" #: Menu.py:49 msgid "Save the document." msgstr "Salvati documentul." #: Menu.py:50 #: Toolbar.py:45 msgid "Save As" msgstr "Salvare ca" #: Menu.py:51 msgid "Save the document under a different name." msgstr "Salveaza documentu sub un nume diferit." #: Menu.py:52 msgid "Save All" msgstr "Salvare tot" #: Menu.py:53 msgid "Saves all the open documents that have a path." msgstr "Salveaza toate documentele deschise care au o cale." #: Menu.py:54 msgid "Reload\tCtrl+R" msgstr "Reincarcare\tCtrl+R" #: Menu.py:54 msgid "Reload the current file from disk." msgstr "Reincarca fisierul selectat de pe disc." #: Menu.py:55 msgid "&Print\tCtrl+P" msgstr "Im&primare\tCtrl+P" #: Menu.py:55 #: Toolbar.py:54 msgid "Print the current document." msgstr "Imprimeaza ducumentul selectat." #: Menu.py:56 msgid "Close &Tab\tCtrl+W" msgstr "Inchidere &Document\tCtrl+W" #: Menu.py:56 msgid "Close the current tab." msgstr "Inchide documentul selectat." #: Menu.py:64 msgid "Recent files\tShow the last opened files." msgstr "Fisiere recente\tArata ultimile fisiere deschise." #: Menu.py:66 msgid "&Quit\tCtrl+Q" msgstr "&Inchide\tCtrl+Q" #: Menu.py:66 msgid "Quit gEcrit." msgstr "Inchide gEcrit." #: Menu.py:70 msgid "&Undo\tCtrl+Z" msgstr "&Undo\tCtrl+Z" #: Menu.py:70 msgid "Cancel the last action." msgstr "Inchide ultima actiune." #: Menu.py:71 msgid "&Redo\tCtrl+Y" msgstr "&Redo\tCtrl+Y" #: Menu.py:71 msgid "Bring back the last action." msgstr "Reface ultima actiune." #: Menu.py:73 msgid "&Cut\tCtrl+X" msgstr "&Decupare\tCtrl+X" #: Menu.py:73 msgid "Cut the selection." msgstr "Decupeaza Selectia." #: Menu.py:74 msgid "C&opy\tCtrl+C" msgstr "C&opiere\tCtrl+C" #: Menu.py:74 msgid "Copy the selection." msgstr "Copiaza selectiunea." #: Menu.py:75 msgid "P&aste\tCtrl+V" msgstr "L&ipire\tCtrl+V" #: Menu.py:75 msgid "Paste the selection." msgstr "Lipeste selectiunea." #: Menu.py:77 msgid "Select All\tCtrl+A" msgstr "Selectare Tot\tCtrl+A" #: Menu.py:78 msgid "Select all the document." msgstr "Selecteaza tot documentul." #: Menu.py:79 msgid "Select Code Block\tCtrl+Shift+A" msgstr "Selectare bloc de cod\tCtrl+Shift+A" #: Menu.py:80 msgid "Select all the current code block." msgstr "Selecteaza blocul de cod in intregime." #: Menu.py:82 msgid "Indent\tCtrl+K" msgstr "Identare\tCtrl+K" #: Menu.py:82 msgid "Indent the selected lines." msgstr "Indenteaza liniile selectate." #: Menu.py:83 msgid "Dedent\tCtrl+J" msgstr "Dedentare\tCtrl+J" #: Menu.py:83 msgid "Dedent the selected lines." msgstr "Dedenteaza liniile selectate." #: Menu.py:85 msgid "Comment Lines\tCtrl+Shift+C" msgstr "Comentare Linii\tCtrl+Shift+C" #: Menu.py:85 msgid "Comment the selected lines." msgstr "Comenteaza liniile selectate." #: Menu.py:86 msgid "Uncomment Lines\tCtrl+Shift+X" msgstr "Decomentare Linii\tCtrl+Shift+X" #: Menu.py:86 msgid "Uncomment the selected lines." msgstr "Decomenteaza liniile selectate." #: Menu.py:89 msgid "Insert date" msgstr "Inserare data" #: Menu.py:90 msgid "Insert the date at cursor position." msgstr "Insereaza data la pozitia actuala." #: Menu.py:92 msgid "Preferences\tCtrl+E" msgstr "Preferinte\tCtrl+E" #: Menu.py:93 #: Toolbar.py:48 msgid "Open the configuration window." msgstr "Deschide fereastra de configurare." #: Menu.py:95 msgid "Find\tCtrl+F" msgstr "Cautare\tCtrl+F" #: Menu.py:96 msgid "Search text in the current document." msgstr "Cauta textul in documentul selectat." #: Menu.py:97 msgid "Find and Replace\tCtrl+H" msgstr "Cautare si Inlocuire\tCtrl+H" #: Menu.py:98 msgid "Search and replace text in the current document." msgstr "Cauta si inlocueste textul in documentul selectat." #: Menu.py:100 msgid "Regex Search\tCtrl+Shift+F" msgstr "Cautare prin Regex\tCtrl+Shift+F" #: Menu.py:100 msgid "Find text using a regular expression." msgstr "Cauta text folosind o expresie regulara." #: Menu.py:101 msgid "Regex Search and Replace\tCtrl+Shift+H" msgstr "Cautare prin Regex si Inlocuire\tCtrl+Shift+H" #: Menu.py:101 msgid "Find and replace text using a regular expression." msgstr "Cauta si inlocuieste text folosind o expresie regulara." #: Menu.py:103 msgid "Zoom In\tCtrl++" msgstr "Marire\tCtrl++" #: Menu.py:104 msgid "Increase the size of the text." msgstr "Mareste dimensiunea textului." #: Menu.py:105 msgid "Zoom Out\tCtrl+-" msgstr "Micsorare" #: Menu.py:106 msgid "Decrease the size of the text." msgstr "Micsoreaza dimensiunea textului." #: Menu.py:107 msgid "Normal Size\tCtrl+0" msgstr "Dimensune Normala\tCtrl+0" #: Menu.py:108 msgid "Set the size of the text to normal." msgstr "Seteaza dimensiunea textului normala." #: Menu.py:110 msgid "Line Numbers" msgstr "Numerotare Linii" #: Menu.py:111 msgid "Show/Hide line numbers." msgstr "Comuta numerotare linii." #: Menu.py:112 msgid "Fold Marks" msgstr "Marci de Restringere" #: Menu.py:112 msgid "Show/Hide fold marks." msgstr "Comuta Mmrci de restringere." #: Menu.py:113 msgid "White Space" msgstr "Comuta Spatiul Alb" #: Menu.py:114 msgid "Show/Hide white spaces." msgstr "Comuta afisarea spatiului alb." #: Menu.py:115 msgid "Indentation Guides" msgstr "Ghiduri de Indentare" #: Menu.py:116 msgid "Show/Hide indentation guides." msgstr "Comuta ghidurile de identare." #: Menu.py:117 msgid "Edge Line" msgstr "Linie de Margina" #: Menu.py:118 msgid "Show/Hide the edge line." msgstr "Comuta Linia de margina." #: Menu.py:119 msgid "Syntax Highlight" msgstr "Colorare Sintaxa" #: Menu.py:120 msgid "Enable/Disable Syntax Highlight." msgstr "Comuta colorarea sintaxei. " #: Menu.py:122 msgid "Python Shell" msgstr "Shell Phyton" #: Menu.py:123 msgid "Stop/Start a python shell." msgstr "Comuta shellul phyton." #: Menu.py:124 msgid "OS Shell" msgstr "Shell OS" #: Menu.py:124 msgid "Stop/Start an OS shell." msgstr "Comuta Shellul OS." #: Menu.py:126 msgid "Statusbar" msgstr "Bara de Status" #: Menu.py:126 msgid "Show/Hide statusbar." msgstr "Comuta bara de status." #: Menu.py:127 msgid "Fullscreen\tF11" msgstr "Fullscreen\tF11" #: Menu.py:127 msgid "Toggle Fullscreen mode." msgstr "Comuta modul Fullscreen." #: Menu.py:128 msgid "Toggle Toolbox" msgstr "Comuta Setul de Instrumente" #: Menu.py:128 msgid "Show/Hide Toolbox window." msgstr "Comuta fereastra setului de intrumente." #: Menu.py:129 msgid "Toggle Assistants" msgstr "Comuta Asistenti" #: Menu.py:129 msgid "Show/Hide Assistants window." msgstr "Comuta fereastra asistentilor" #: Menu.py:131 msgid "Remove Trailing Spaces" msgstr "Elimina Spatiile de Coada" #: Menu.py:131 msgid "Remove spaces at the end of the line." msgstr "Elimina spatiile la sfirsitul linii." #: Menu.py:132 msgid "Run File\tF5" msgstr "Executare Fisier\tF5" #: Menu.py:132 msgid "Run the current document.(python only)" msgstr "Executa documentul selectat.(Python)" #: Menu.py:133 msgid "Tabify" msgstr "Tabificare" #: Menu.py:133 msgid "Replace spaces by tabs." msgstr "Substituire spatii cu taburi." #: Menu.py:134 msgid "Untabify" msgstr "Detabificare" #: Menu.py:134 msgid "Replace tabs by spaces." msgstr "Substituire taburi cu spatii." #: Menu.py:136 msgid "Enable Session" msgstr "Activare sesiune" #: Menu.py:136 msgid "Enable/Disable Session support." msgstr "Activare/Dezactivare sesiune." #: Menu.py:137 msgid "Save Session" msgstr "Salvare sesiunea" #: Menu.py:137 msgid "Save the current application state." msgstr "Salveaza starea actuala a aplicatiei." #: Menu.py:138 msgid "Delete Session" msgstr "Stergere Sesiune" #: Menu.py:138 msgid "Delete the saved session file." msgstr "Sterge fisierul de sesiune." #: Menu.py:140 msgid "Plugin Manager" msgstr "Gestionar de Extensii" #: Menu.py:140 msgid "Manage gEcrit Plugins." msgstr "Gestioneaza extensiile gEcrit." #: Menu.py:142 msgid "About" msgstr "Despre gEcrit" #: Menu.py:142 msgid "Open the about window." msgstr "Despre autori." #: Menu.py:144 msgid "&File" msgstr "&Fisier" #: Menu.py:145 msgid "&Edit" msgstr "&Editare" #: Menu.py:146 msgid "&Search" msgstr "&Cautare" #: Menu.py:147 msgid "&View" msgstr "&Afisare" #: Menu.py:148 msgid "&Document" msgstr "&Document" #: Menu.py:149 msgid "&Session" msgstr "&Sesiune" #: Menu.py:150 msgid "&Plugins" msgstr "Extensii" #: Menu.py:151 msgid "&Help" msgstr "A&jutor" #: Toolbar.py:39 msgid "New" msgstr "Document Nou" #: Toolbar.py:41 msgid "Open" msgstr "Deschide" #: Toolbar.py:43 msgid "Save" msgstr "Salveaza" #: Toolbar.py:44 msgid "Save the current document." msgstr "Salzeaza documentul selectat." #: Toolbar.py:46 msgid "Save the current document under a differend name." msgstr "Salveaza documentul selectat sub un alt nume." #: Toolbar.py:47 msgid "Settings" msgstr "Configurare" #: Toolbar.py:50 msgid "Quit" msgstr "Iesire" #: Toolbar.py:50 msgid "Quit gEcrit" msgstr "Iesire gEcrit" #: Toolbar.py:53 msgid "Print" msgstr "Imprimare" #: Toolbar.py:56 msgid "Run the current file.(Python only)" msgstr "Executa fisierul selectat.(Doar pentru Phyton)" msgid "Autocomplete Braces" msgstr "Autocompletare paranteze" msgid "Show Line Numbers" msgstr "Numerotare Linii" msgid "Autoindentation" msgstr "Autoindentare" msgid "Backspace to Unindent" msgstr "Dedentare prin Backspace" msgid "Use Tabs" msgstr "Foloseste Taburi" msgid "Show Whitespace" msgstr "Indicare Spatiile Albe" msgid "Edge Line Position:" msgstr "Positia Liniei de Margina:" msgid "Enable Autosave" msgstr "Autosalvare" msgid "Save data each # of characters:" msgstr "Salvare la fiecare # de caractere:" msgid "Strip Trailing Spaces On Save" msgstr "Elimina Spatiile de Coada la Salvare" msgid "Status Bar" msgstr "Bara de Statut" msgid "Enable Log" msgstr "Activare Log" msgid "Colour Palette" msgstr "Paleta de Culori" msgid "View Log" msgstr "Visionare Log" msgid "Erase Log" msgstr "Stergere Log" msgid "OK" msgstr "OK" msgid "Toolbox" msgstr "Set de instrumente" msgid "Assistants and others" msgstr "Asistenti si altele" msgid "Remove" msgstr "Elimina" msgid "Author: " msgstr "Autor: " msgid "Version: " msgstr "Versiune: " msgid "Website: " msgstr "Pagina Web: " msgid "Description: " msgstr "Descriere: " msgid "Keywords" msgstr "Cuvinte cheie" msgid "Strings" msgstr "Siruri de caractere" msgid "Triple Quotes" msgstr "Ghilimele triple" msgid "Integers" msgstr "Cifre" msgid "Comments" msgstr "Comentari" msgid "Brackets" msgstr "Paranteze" msgid "Bad EOL" msgstr "Linii invalide" msgid "Method Names" msgstr "Nume de metode" msgid "Operators" msgstr "Operatori" msgid "Identifiers" msgstr "Identificatori" msgid "Plugins:" msgstr "Extensii:" gecrit-2.8.4/yapsy/PluginManagerDecorator.py000777 000000 000000 00000006631 12051462410 021103 0ustar00rootroot000000 000000 #!/usr/bin/python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- """ Role ==== Provide an easy way to build a chain of decorators extending the functionalities of the default plugin manager, when it comes to activating, deactivating or looking into loaded plugins. The ``PluginManagerDecorator`` is the base class to be inherited by each element of the chain of decorator. .. warning:: If you want to customise the way the plugins are detected and loaded, you should not try to do it by implementing a new ``PluginManagerDecorator``. Instead, you'll have to reimplement the :doc:`PluginManager` itself. And if you do so by enforcing the ``PluginManager`` interface, just giving an instance of your new manager class to the ``PluginManagerDecorator`` should be transparent to the "stantard" decorators. API === """ import os import logging from yapsy.IPlugin import IPlugin class PluginManagerDecorator(object): """ Add several responsibilities to a plugin manager object in a more flexible way than by mere subclassing. This is indeed an implementation of the Decorator Design Patterns. There is also an additional mechanism that allows for the automatic creation of the object to be decorated when this object is an instance of PluginManager (and not an instance of its subclasses). This way we can keep the plugin managers creation simple when the user don't want to mix a lot of 'enhancements' on the base class. """ def __init__(self, decorated_object=None, # The following args will only be used if we need to # create a default PluginManager categories_filter={"Default":IPlugin}, directories_list=[os.path.dirname(__file__)], plugin_info_ext="yapsy-plugin"): """ Mimics the PluginManager's __init__ method and wraps an instance of this class into this decorator class. - *If the decorated_object is not specified*, then we use the PluginManager class to create the 'base' manager, and to do so we will use the arguments: ``categories_filter``, ``directories_list``, and ``plugin_info_ext`` or their default value if they are not given. - *If the decorated object is given*, these last arguments are simply **ignored** ! All classes (and especially subclasses of this one) that want to be a decorator must accept the decorated manager as an object passed to the init function under the exact keyword ``decorated_object``. """ if decorated_object is None: logging.debug("Creating a default PluginManager instance to be decorated.") from yapsy.PluginManager import PluginManager decorated_object = PluginManager(categories_filter, directories_list, plugin_info_ext) self._component = decorated_object def __getattr__(self,name): """ Decorator trick copied from: http://www.pasteur.fr/formation/infobio/python/ch18s06.html """ # print "looking for %s in %s" % (name, self.__class__) return getattr(self._component,name) def collectPlugins(self): """ This function will usually be a shortcut to successively call ``self.locatePlugins`` and then ``self.loadPlugins`` which are very likely to be redefined in each new decorator. So in order for this to keep on being a "shortcut" and not a real pain, I'm redefining it here. """ self.locatePlugins() self.loadPlugins() gecrit-2.8.4/Toolbar.py000777 000000 000000 00000005721 12051462410 014743 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx, gettext from Fonts import * class MainToolbar(wx.ToolBar): """ MainToolbar Creates the application toolbar object. """ def __init__(self, parent, id=wx.ID_ANY): """ __init__ Builds the ToolBar object and adds elemensts to it. Takes the icons from the icons/ folder. """ wx.ToolBar.__init__(self, parent, id, style=wx.TB_HORIZONTAL | wx.NO_BORDER) self._ = parent._ self.new_tab_img = wx.Image('icons/newtab.bmp', wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.open_img = wx.Image('icons/open.bmp', wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.save_img = wx.Image('icons/save.bmp', wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.saveas_image = wx.Image('icons/saveas.bmp', wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.config_image = wx.Image('icons/config.bmp', wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.quit_img = wx.Image('icons/quit.bmp', wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.print_img = wx.Image("icons/printer.bmp", wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.run_img = wx.Image("icons/run.png", wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.AddSimpleTool(600, self.new_tab_img, self._('New'), self._('Open a new tab.')) self.AddSimpleTool(601, self.open_img, self._('Open'), self._('Open a new document.')) self.AddSimpleTool(602, self.save_img, self._('Save'), self._('Save the current document.')) self.AddSimpleTool(603, self.saveas_image, self._('Save As'), self._('Save the current document under a differend name.')) self.AddSimpleTool(604, self.config_image, self._('Settings'), self._('Open the configuration window.')) self.AddSeparator() self.AddSimpleTool(605, self.quit_img, self._('Quit'), self._('Quit gEcrit')) self.AddSeparator() self.AddSimpleTool(609, self.print_img, self._("Print"), self._("Print the current document.")) self.AddSimpleTool(610, self.run_img, "Run", self._("Run the current file.(Python only)")) self.Realize() gecrit-2.8.4/data/plugins/WordCounter.py000777 000000 000000 00000007733 12051462410 020213 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx from data.plugins.categories import General import yapsy class WordCounter(wx.Frame, General, yapsy.IPlugin.IPlugin): def __init__(self): self.name = "Word Counter" def Init(self, parent): self.parent = parent self.current_doc = None wx.Frame.__init__(self, self.parent, -1, "Word Counter" ,size = (300 , 132)) self.main_panel = wx.Panel(self) self.v_sizer = wx.BoxSizer(wx.VERTICAL) self.h_sizer = wx.BoxSizer(wx.HORIZONTAL) self.plugins_menu = wx.Menu() show_entry = self.plugins_menu.Append(-1, "Advanced") words_entry = self.plugins_menu.Append(-1, "Count Words") char_entry = self.plugins_menu.Append(-1, "Count Characters" ) self.count_desc = wx.StaticText(self.main_panel,-1,"Count:") self.count_string = wx.TextCtrl(self.main_panel) self.count_bt = wx.Button(self.main_panel, -1, "Count", size = (-1, -1)) self.case_sesitive = wx.CheckBox(self.main_panel, -1, "Case Sensitive") self.occurrences = wx.StaticText(self.main_panel, -1, "Occurrences: ") self.h_sizer.Add(self.count_string, 1, wx.EXPAND) self.h_sizer.AddSpacer(10) self.h_sizer.Add(self.count_bt) self.close = wx.Button(self.main_panel, -1, "Close") self.v_sizer.Add(self.count_desc) self.v_sizer.Add(self.h_sizer, 0, wx.EXPAND) self.v_sizer.AddSpacer(5) self.v_sizer.Add(self.case_sesitive) self.v_sizer.AddSpacer(5) self.v_sizer.Add(self.occurrences, 0 ,wx.EXPAND) self.v_sizer.AddSpacer(5) self.v_sizer.Add(self.close) self.menu_item = self.parent.AddToMenuBar("Word Counter", self.plugins_menu) self.parent.BindMenubarEvent(show_entry, self.ShowMe) self.parent.BindMenubarEvent(words_entry, self.OnMenuWordCount) self.parent.BindMenubarEvent(char_entry, self.OnMenuCharCount) self.main_panel.SetSizer(self.v_sizer) self.main_panel.Fit() self.Bind(wx.EVT_CLOSE, self.HideMe) self.close.Bind(wx.EVT_BUTTON, self.HideMe) self.count_bt.Bind(wx.EVT_BUTTON, self.OnWordCount) self.Hide() def NotifyTabChanged(self): self.current_doc = self.parent.GetCurrentDocument() def OnWordCount(self, event): if self.case_sesitive.GetValue(): self.occurrences.SetLabel("Occurrences: " + str( self.current_doc.GetText().lower().count(self.count_string.GetValue().lower()))) else: self.occurrences.SetLabel("Occurrences: " + str( self.current_doc.GetText().count(self.count_string.GetValue()))) def OnMenuCharCount(self, event): msg = str(self.current_doc.GetText().count("")) show = wx.MessageDialog(None, msg+" character have been counted.", style = wx.OK) show.ShowModal() def OnMenuWordCount(self, event): msg = str(len(self.current_doc.GetText().split())) show = wx.MessageDialog(None, msg+" words have been counted.", style = wx.OK) show.ShowModal() def ShowMe(self, event): self.Show() def HideMe(self, event): self.Hide() gecrit-2.8.4/Keywords.py000777 000000 000000 00000005426 12051462410 015152 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . keywords = { "rb": ["alias", "and" "BEGIN", "begin", "break", "case", "class", "def", "defined", "do", "else", "elsif", "END", "end," "ensure", "false", "for", "if", "in", "module", "next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield"], "py": keyword.kwlist, "pyw": keyword.kwlist, "cpp": ["auto", "const", "double", "float", "int", "short", "struct", "unsigned", "break", "continue", "else", "for", "long", "signed", "switch", "void", "case", "default", "enum", "goto", "register", "sizeof", "typedef", "volatile","char", "do", "extern", "if", "return", "static", "union", "while", "asm", "dynamic_cast", "namespace", "reinterpret_cast", "try", "bool", "explicit", "new", "static_cast", "typeid", "catch", "false", "operator", "template", "typename", "class","friend", "private", "this" "using", "const_cast", "inline", "public", "throw", "virtual", "delete", "mutable", "protected", "true", "wchar_t"], "java": ["abstract", "continue", "for", "new", "switch", "assert", "default", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "volatile", "float", "native", "super", "while"] } gecrit-2.8.4/data/plugins/SpellChecker.yapsy-plugin000777 000000 000000 00000000314 12051462410 022301 0ustar00rootroot000000 000000 [Core] Name = Spell Checker Module = SpellChecker [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Provides spell checking facilities. gecrit-2.8.4/icons/newtab.bmp000777 000000 000000 00000006066 12051462410 016065 0ustar00rootroot000000 000000 BM6 6(    ȔԾKKK<<ABCFIA?=@@DHG@FA9C:CMCDzGGGFFF???GGGAAACCCDDDCCCFFFEDDFC?;63.'&-&& 4:;>GJ;BEP>CQDII>FE>GD>HHBII?DM@ASCATC?ƵHHHBBBCCCFFFEEECCCEEEEEE:::CDC  :<=>EF-:<5HI4HJ5BK+>?HGH&%!:97HGF?BA098FVVg|{ryFR5|ck_9QV6EG@FGǺaDNHBC8GA3H<@L@CC7|{q޼VOH9:73AC&BJ!N[Dn{nkwO%UWYȲSILRVU`pm7FE6AE2@H3T`\k\gtyyIaZCrFDKCǬGFGDECDFDDCCGBE>BI[r|ߎI`WFtH=CALDǮKFF@FCC<=Fݠ`\VHtI=CBKDǪ@IFBECHEAIC@HCABHG+CDP|~nZTHtJDECGCDOAFE?D+AC\TTEqG=CAIAC@HK">>XQY3t4@?WG<ȝLHDAGAA&@@dUh@x4DAPH?ȝKGDAGC=FC=FBECDLCFF?BDJK%;<ߠߝ{rDgr:DCLJBǜHFDAFC?GD?DBDCCNGHGADGFDFHD@ǛLMKHLJGLJGJINKKRMNMJKHLM;IH8JJ=SWRhl9MQ.AE5FJ7EK8DJ>JOBLRBJQKIUGKQHNMGJGSNNSDKYHSRDLPIKSPOŻgecrit-2.8.4/data/plugins/AbbreviationCompletion.yapsy-plugin000777 000000 000000 00000000375 12051462410 024403 0ustar00rootroot000000 000000 [Core] Name = Abbreviation Completion Module = AbbreviationCompletion [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Provides abbreviation replacement to speed up typing long words. gecrit-2.8.4/data/plugins/000777 000000 000000 00000000000 12051462410 015351 5ustar00rootroot000000 000000 gecrit-2.8.4/StcTextCtrl.py000777 000000 000000 00000067012 12051462410 015565 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx, gettext import os import wx.lib.inspection from Configuration import * from Logger import * from SyntaxHighlight import * from Logger import * import AutoComplet from StcMode import * from StcLangModes import * import stat class StcTextCtrl(wx.stc.StyledTextCtrl): """ StcTextCtrl Provides the editing facilities and function. Creates the editor object and its environment. Stores its file path. """ class ScheduleTimer(wx.Timer): """ This class calls the parent's OnCheckFile method at a given interval. """ def __init__(self, parent, method): wx.Timer.__init__(self) self.parent = parent self.method = method def Notify(self): self.method() lang_modes = [StcPythonMode, StcRubyMode, StcCppMode, StcPerlMode, StcJavaMode] __brace_dict={ # for barce completion 40:")", 91:"]", 123:"}", 39:"'", 34:'"' } def __init__(self, parent, id, file_path="New Document"): """ __init__ Initializes the StyledTextCtrl object and sets up its environment. Binds the proper events to their functions and sets up the spell checker object. """ wx.stc.StyledTextCtrl.__init__(self, parent, id, pos=(0, 0), size=(1, 1)) self.__save_path = file_path self.parent = parent self.__main_window = self.parent.GetParent() self._ = self.__main_window._ self.__file_last_modified = None if file_path != "New Document" and file_path != "": self.LoadFile(file_path) self.__file_last_modified = os.stat(self.__save_path)[stat.ST_MTIME] else: self.__save_path = "" self._SetTimers() self.__macro_register = [] # stores the macro event sequence self.save_record = self.GetText() self.__HOMEDIR = os.path.expanduser('~') self.nb = wx.FindWindowById(900) self.__status_bar = wx.FindWindowById(999) self.text_id = id self.lang_mode = None # will point to a StcMode object, will be set by UpdateLangMode() self.Bind(wx.stc.EVT_STC_CHARADDED, self.OnCompBrace) self.Bind(wx.stc.EVT_STC_UPDATEUI, self.UpdateCords) self.Bind(wx.stc.EVT_STC_UPDATEUI, self.OnUpdateUI) self.Bind(wx.stc.EVT_STC_MARGINCLICK, self.OnMarginClick) self.Bind(wx.EVT_KEY_UP, self.AutoIndent) self.Bind(wx.stc.EVT_STC_CHARADDED, lambda event: AutoComplet.AutoComp.OnKeyPressed(event, self.text_id)) self.Bind(wx.stc.EVT_STC_MACRORECORD, self.OnMacroRecord) self._DefineMarkers() self.UpdateLangMode() # apply the language mode self.ApplyIDEConfig() # apply the IDE configurations def _SetTimers(self): # set up the timer that will periodically check if the file has been modified on disk. self.__fl_check_timer = StcTextCtrl.ScheduleTimer(self, self.OnCheckFile) self.__fl_check_timer.Start(1000) # set up the autosave timer self.__auto_save_timer = StcTextCtrl.ScheduleTimer(self, self.OnAutosave) self.__auto_save_timer.Start(Config.GetOption("Autosave Interval")*60*1000) # convert minutes to milliseconds def UpdateLangMode(self): ext = self.GetFileExtension() self.lang_mode = StcFundamentalMode(self) # default mode, it will be changed if a specialized one exists for mode in StcTextCtrl.lang_modes: if ext in mode.file_extensions: self.lang_mode = mode(self) self.SetLexer(mode.lexer) break if Config.GetOption("SyntaxHighlight"): self.ActivateSyntaxHighLight() # Refreshes the control to use the current mode def OnReload(self, event): """ OnReload Loads the current file from the hard disk once again. Checks for it's existence first. If it does not exists, prompts the user. """ if self.__save_path: if os.path.exists(self.__save_path): self.LoadFile(self.__save_path) self.__file_last_modified = os.stat(self.__save_path)[stat.ST_MTIME] Log.AddLogEntry("Reloaded "+self.__save_path) else: fl_not_exists = wx.MessageDialog(self,self._("The file ")+self.__save_path+self._(" does\ not exists. Do you wish to save it?"), self._("Missing File"),style = wx.YES | wx.NO) if fl_not_exists.ShowModal() == 5103: self.Save(0) else: self.file_last_modified = None fl_not_exists.Destroy() else: message = wx.MessageDialog(self, self._("The file seems unsaved, it does not exists\ on the disk. Do you wish to save it?"), self._("File Not Saved"), style = wx.YES | wx.NO) if message.ShowModal() == 5103: self.Save(0) else: self.file_last_modified = None message.Destroy() def OnCompBrace(self,event): """ OnCompBrace If the feature is enabled, it adds a closing brace at the current cursor position. """ key = event.GetKey() if key in [40,91,123,39,34]: if Config.GetOption("BraceComp"): self.AddText(StcTextCtrl.__brace_dict[key]) self.CharLeft() event.Skip() def SaveAs(self, event): """ SaveAs Ask the user for a path via a file dialog and the uses the StyledTextCtrl's function to write the date to file. Returns False if the user did not complete the process. Checks if there is a lexer for the file type and enables it if the option is active. Adds a log entry. """ savefileas_dlg = wx.FileDialog(None, style=wx.SAVE) if self.__main_window.menubar.last_recent != "": savefileas_dlg.SetDirectory(os.path.split(self.__main_window.menubar.last_recent)[0]) else: savefileas_dlg.SetDirectory(self.__HOMEDIR) if savefileas_dlg.ShowModal() == wx.ID_OK: filename = savefileas_dlg.GetFilename() saveas_path = os.path.join(savefileas_dlg.GetDirectory(), filename) if Config.GetOption("StripTrails"): self.OnRemoveTrails(0) self.SaveFile(saveas_path) self.__save_path = saveas_path self.__file_last_modified = os.stat(self.__save_path)[stat.ST_MTIME] self.save_record = self.GetText() if Config.GetOption("StatusBar"): self.__status_bar.SetStatusText(self._("Saved as") + saveas_path) self.nb.SetPageText(self.nb.GetSelection(), filename) # update the lang mode if self.GetFileExtension not in self.lang_mode.__class__.file_extensions: self.UpdateLangMode() self.SetStatusFileMode() #notify general plugins for t in self.__main_window.general_plugins: try: #insulate from possible plugin errors self.__main_window.general_plugins[t].NotifyDocumentSaved() except: pass #update the ctags files with the new content AutoComplet.AutoComp.UpdateCTagsFiles(self.__main_window.id_range) savefileas_dlg.Destroy() return True else: savefileas_dlg.Destroy() return False def Save(self, event): """ Save Checks if the objects file path is valid and saves to it. If not, it calls the SaveAs function to. Checks if there is a lexer for the file type and enables it if the option is active. Adds a log entry. """ if self.__save_path == "" or self.__save_path == "New Document": self.SaveAs(0) return try: if Config.GetOption("StripTrails"): self.OnRemoveTrails(0) self.SaveFile(self.__save_path) if Config.GetOption("StatusBar"): self.__status_bar.SetStatusText("Saved") self.__file_last_modified = os.stat(self.__save_path)[stat.ST_MTIME] self.save_record = self.GetText() Log.AddLogEntry(self._("Saved file ") + self.__save_path) #notify text generalt plugins for t in self.__main_window.general_plugins: try: #insulate from possible plugin errors self.__main_window.general_plugins[t].NotifyDocumentSaved() except: pass #update the ctags files with the new content AutoComplet.AutoComp.UpdateCTagsFiles(self.__main_window.id_range) except: print("An exception was thrown during save, falling back to default behavior") self.SaveAs(0) def OnAutosave(self): """ OnAutoSave Count the numbers of characters entered. If they reach a value, calls Save. Adds a log entry. """ if Config.GetOption("Autosave"): if file_path != "New Document" and file_path != "": self.Save(0) Log.AddLogEntry(self._("Autosaved ")+self.__save_path) def OnDedent(self, event): """ OnDedent Dedents the selected lines. """ self.BackTab() def OnIndent(self, event): """ OnIndent Indents the selected lines. """ sel_end = self.LineFromPosition(self.GetSelectionEnd()) sel_start = self.LineFromPosition(self.GetSelectionStart()) for line in range(sel_start, sel_end + 1): self.SetLineIndentation(line, self.GetLineIndentation(line) + self.GetIndent()) def OnZoomIn(self, event): """ OnZoomIn Zooms in the editor. """ self.ZoomIn() event.Skip() def OnZoomOut(self, event): """ OnZoomOut Zooms out the editor. """ self.ZoomOut() event.Skip() def OnResetZoom(self, event): """ OnResetZoom Resets the zoom at the normal state. """ self.SetZoom(0) event.Skip() def OnRedo(self, event): """ OnRedo Redos the editor one step. """ if self.CanRedo(): self.Redo() event.Skip() def OnUndo(self, event): """ OnUndo Undos the editor one step. """ if self.CanUndo(): self.Undo() event.Skip() def OnCut(self, event): """ OnCut Cuts the selected text and copies it to clipboard. """ self.Cut() event.Skip() def OnCopy(self, event): """ OnCopy Copies the selected text to clipboard. """ self.Copy() event.Skip() def OnSelectAll(self, event): """ OnSelectAll Selects all the text in the editor. """ self.SelectAll() event.Skip() def OnPaste(self, event): """ OnPaste Pastes from clipboard. """ self.Paste() event.Skip() def OnInsertDate(self, event): """ OnInsertDate Find the date and inserts it in the current postion. """ self.AddText(str(time.ctime())) event.Skip() def OnRemoveTrails(self,event): """ OnRemoveTrails Removes the trailing whitespace in the current document. """ c = self.GetCurrentPos() line_nr = self.GetLineCount() ln = 1 while ln <= line_nr: ln += 1 length = self.LineLength(ln) if " " not in self.GetLine(ln): continue st = self.GetLineEndPosition(ln) - length end = self.GetLineEndPosition(ln) txt = self.GetTextRange(st,end) self.SetTargetStart(st) self.SetTargetEnd(end) self.ReplaceTarget(txt.rstrip(" ").rstrip("\t")) self.SetCurrentPos(c) self.SetSelection(c,c) def Tabify(self, event): st = 0 tab_size = self.GetTabWidth() end = self.GetTextLength() temp_doc = self.GetText() temp_doc = temp_doc.replace(" "*tab_size,"\t") self.SetText(temp_doc) def OnStartRecordMacro(self, event): self.__status_bar.SetStatusText(self._("Recording macro..."), 0) self.__macro_register = [] # delete old macro self.StartRecord() event.Skip() def OnStopRecordMacro(self, event): self.__status_bar.SetStatusText(self._("Stopped recording macro..."), 0) self.StopRecord() event.Skip() def OnMacroRecord(self, event): "Records keystrokes and events for macro recording." this_event = (event.GetMessage(), event.GetWParam(), event.GetLParam()) self.__macro_register.append(this_event) event.Skip() def OnMacroPlayback(self, event): "Plays the recorded macro." for m in self.__macro_register: self.SendMsg(m[0], m[1], m[2]) event.Skip() def UnTabify(self, event): st = 0 tab_size = self.GetTabWidth() end = self.GetTextLength() temp_doc = self.GetText() temp_doc = temp_doc.replace("\t"," "*tab_size) self.SetText(temp_doc) def OnComment(self,event): """ OnComment """ self.lang_mode.OnComment(event) def OnUnComment(self,event): """ OnUnComment """ self.lang_mode.OnUnComment(event) def SetStatusFileMode(self): self.__status_bar.SetStatusText(self.lang_mode.__class__.lang_name+" file.",2) def UpdateCords(self, event): """ UpdateCords Updates the x,y coordinates of the cursor. """ self.__status_bar.SetStatusText(self._("line: ") + str(self.GetCurrentLine()) + " col: " + str(self.GetColumn(self.GetCurrentPos())), 1) event.Skip() def AutoIndent(self, event): """ AutoIndent Responsible for the autoindentation feature. """ key = event.GetKeyCode() if key == wx.WXK_NUMPAD_ENTER or key == wx.WXK_RETURN: if Config.GetOption("Autoindentation"): self.lang_mode.AutoIndent(event) event.Skip() def OnUpdateUI(self ,evt): """ OnUpdateUI Responsible for the bad brace check feature. """ braceAtCaret = -1 braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos - 1) styleBefore = self.GetStyleAt(caretPos - 1) if charBefore and chr(charBefore) in "[]{}()" and styleBefore == wx.stc.STC_P_OPERATOR: braceAtCaret = caretPos - 1 if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in "[]{}()" and styleAfter == wx.stc.STC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) evt.Skip() def OnMarginClick(self, evt): """ OnMarginClick Responsible for the interaction of the user with code folding. """ if evt.GetMargin() == 2: if evt.GetShift() and evt.GetControl(): self.FoldAll() else: lineClicked = self.LineFromPosition(evt.GetPosition()) if self.GetFoldLevel(lineClicked) & wx.stc.STC_FOLDLEVELHEADERFLAG: if evt.GetShift(): self.SetFoldExpanded(lineClicked, True) self.Expand(lineClicked, True, True, 1) elif evt.GetControl(): if self.GetFoldExpanded(lineClicked): self.SetFoldExpanded(lineClicked, False) self.Expand(lineClicked, False, True, 0) else: self.SetFoldExpanded(lineClicked, True) self.Expand(lineClicked, True, True, 100) else: self.ToggleFold(lineClicked) elif evt.GetMargin() == 1: ln = self.LineFromPosition(evt.GetPosition()) marker = self.MarkerGet(ln) if marker == 0: self.MarkerAdd( ln , 3) elif marker == 8: self.MarkerDelete( ln , 3) evt.Skip() def FoldAll(self): """ FoldAll Folds all the code when given the command. """ lineCount = self.GetLineCount() expanding = True for lineNum in range(lineCount): if self.GetFoldLevel(lineNum) & wx.stc.STC_FOLDLEVELHEADERFLAG: expanding = not self.GetFoldExpanded(lineNum) break lineNum = 0 while lineNum < lineCount: level = self.GetFoldLevel(lineNum) if level & wx.stc.STC_FOLDLEVELHEADERFLAG and level & wx.stc.STC_FOLDLEVELNUMBERMASK == \ wx.stc.STC_FOLDLEVELBASE: if expanding: self.SetFoldExpanded(lineNum, True) lineNum = self.Expand(lineNum, True) lineNum = lineNum - 1 else: lastChild = self.GetLastChild(lineNum, -1) self.SetFoldExpanded(lineNum, False) if lastChild > lineNum: self.HideLines(lineNum + 1, lastChild) lineNum = lineNum + 1 def Expand(self, line, doExpand, force=False, visLevels=0, level=-1): """ Expand Expands the provided line in argument line. """ lastChild = self.GetLastChild(line, level) line = line + 1 while line <= lastChild: if force: if visLevels > 0: self.ShowLines(line, line) else: self.HideLines(line, line) else: if doExpand: self.ShowLines(line, line) if level == -1: level = self.GetFoldLevel(line) if level & wx.stc.STC_FOLDLEVELHEADERFLAG: if force: if visLevels > 1: self.SetFoldExpanded(line, True) else: self.SetFoldExpanded(line, False) line = Expand(text_id, line, doExpand, force, visLevels - 1) else: if doExpand and self.GetFoldExpanded(line): line = Expand(text_id, line, True, force, visLevels - 1) else: line = Expand(text_id, line, False, force, visLevels - 1) else: line = line + 1 return line def OnSelectCodeBlock(self,event): self.lang_mode.OnSelectCodeBlock(event) def RestartAutoSaveTimer(self): self.__auto_save_timer.Stop() self.__auto_save_timer.Start(Config.GetOption("Autosave Interval")*60*1000) # convert minutes to milliseconds def Deactivate(self): """ This is a clean up class that is called when this control is no longer needed. """ self.__fl_check_timer.Stop() self.__auto_save_timer.Stop() def OnCheckFile(self): """ Check if the loaded file has not been changed by a third party. """ if self.__file_last_modified != None: if not os.path.exists(self.__save_path): self.OnReload(0) else: last_modified = os.stat(self.__save_path)[stat.ST_MTIME] if last_modified != self.__file_last_modified: check_file_ask = wx.MessageDialog(self,self._("The file ")+self.__save_path+self._(" has\ been modified and the loaded buffer is out of date. Do you wish to reload it?"),self._("File Modified"),style = wx.YES | wx.NO) if check_file_ask.ShowModal() == 5103: self.OnReload(0) else: check_file_ask.Destroy() self.__file_last_modified = None def _DefineMarkers(self): #marker definitions (fold nodes, line numbers...) self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDEROPEN, wx.stc.STC_MARK_BOXMINUS, "white", "#808080") self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDER, wx.stc.STC_MARK_BOXPLUS, "white", "#808080") self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERSUB, wx.stc.STC_MARK_VLINE, "white", "#808080") self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERTAIL, wx.stc.STC_MARK_LCORNER, "white", "#808080") self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDEREND, wx.stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080") self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDEROPENMID, wx.stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080") self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERMIDTAIL, wx.stc.STC_MARK_TCORNER, "white", "#808080") self.MarkerDefine(3, wx.stc.STC_MARK_CIRCLE, "#0000FF", "#FF0000") def GetEndOfLineCharacter(self): emode = self.GetEOLMode() if emode == wx.stc.STC_EOL_CR: return '\r' elif emode == wx.stc.STC_EOL_CRLF: return '\r\n' return '\n' #################################################################### # PLUGIN INTERFACE # #################################################################### def GetFilePath(self): """ GetFilePath Returns the file from which the buffer is loaded. """ return self.__save_path def GetFileName(self): """ GetFileName Returns the filename of the current buffer. """ return os.path.split(self.__save_path)[-1] def GetFileExtension(self): """ GetFileExtension Returns the file extension of the current buffer. """ return os.path.split(self.__save_path)[-1].split(".")[-1] def ApplyIDEConfig(self): """ ApplyIDEConfig Configures the StcTextCtrl with the user settings """ if Config.GetOption("SyntaxHighlight"): self.ActivateSyntaxHighLight() if Config.GetOption("Autoindentation"): self.SetIndent(Config.GetOption("IndentSize")) self.SetIndentationGuides(Config.GetOption("IndetationGuides")) self.SetBackSpaceUnIndents(Config.GetOption("BackSpaceUnindent")) self.SetViewWhiteSpace(Config.GetOption("Whitespace")) self.SetUseTabs(Config.GetOption("UseTabs")) self.SetCaretWidth(Config.GetOption("CarretWidth")) self.SetTabWidth(Config.GetOption("IndentSize")) self.SetMarginType(1, wx.stc.STC_MARGIN_NUMBER) if Config.GetOption("LineNumbers"): self.SetMarginWidth(1, 45) self.SetMarginSensitive(1, True) else: self.SetMarginWidth(1, 1) self.SetMarginSensitive(1, False) if Config.GetOption("FoldMarks"): self.SetMarginType(2, wx.stc.STC_MARGIN_SYMBOL) self.SetMarginMask(2, wx.stc.STC_MASK_FOLDERS) self.SetMarginSensitive(2, True) self.SetMarginWidth(2, 12) self.SetTabWidth(Config.GetOption("TabWidth")) if Config.GetOption("EdgeLine"): self.SetEdgeColumn(Config.GetOption("EdgeColumn")) self.SetEdgeMode(wx.stc.STC_EDGE_LINE) self.SetEdgeColour(SyntCol.GetColor("EdgeLine")) def ActivateSyntaxHighLight(self): """ ActivateSyntaxHighLight Initializes the lexer and sets the color styles. """ keywords = self.lang_mode.__class__.keywords self.SetKeyWords(0, (" ").join(keywords)) self.SetProperty("fold", "1") self.StyleSetSpec(wx.stc.STC_P_DEFAULT, "fore:#000000") self.StyleSetSpec(wx.stc.STC_P_COMMENTLINE, "fore:" + SyntCol.GetColor("Comments").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_NUMBER, "fore:" + SyntCol.GetColor("Integers").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_STRING, "fore:" + SyntCol.GetColor("Strings").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_CHARACTER, "fore:" + SyntCol.GetColor("Strings").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_WORD, "fore:" + SyntCol.GetColor("Keywords").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_TRIPLE, "fore:" + SyntCol.GetColor("TripleQuotes").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_TRIPLEDOUBLE, "fore:" + SyntCol.GetColor("TripleQuotes").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_CLASSNAME, "fore:" + SyntCol.GetColor("MethodNames").GetAsString(wx.C2S_HTML_SYNTAX) + ",bold,underline") self.StyleSetSpec(wx.stc.STC_P_DEFNAME, "fore:" + SyntCol.GetColor("MethodNames").GetAsString(wx.C2S_HTML_SYNTAX) + ",bold,underline") self.StyleSetSpec(wx.stc.STC_P_OPERATOR, "fore:" + SyntCol.GetColor("Operators").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_IDENTIFIER, "fore:" + SyntCol.GetColor("Identifiers").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_COMMENTBLOCK, "fore:" + SyntCol.GetColor("Comments").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_P_STRINGEOL, "fore:#000000,face:%s,back:" + SyntCol.GetColor("BadEOL").GetAsString(wx.C2S_HTML_SYNTAX) + "eol") self.StyleSetSpec(wx.stc.STC_STYLE_BRACELIGHT, "back:" + SyntCol.GetColor("Brackets").GetAsString(wx.C2S_HTML_SYNTAX)) self.StyleSetSpec(wx.stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold") self.SetCaretForeground("BLUE") self.SetEdgeColour(SyntCol.GetColor("EdgeLine")) gecrit-2.8.4/runner.sh000777 000000 000000 00000002060 12051462410 014625 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/bin/sh F=$1 EXT=${F#*.} if [ "$EXT" = "py" ] then python $1 elif [ "$EXT" = "pl" ] then perl $1 elif [ "$EXT" = "perl" ] then perl $1 elif [ "$EXT" = "rb" ] then irb $1 fi echo " ------------------ (program exited with code: $?)" echo "Press return to continue" #to be more compatible with shells like dash dummy_var="" read dummy_var gecrit-2.8.4/AutoComplet.py000777 000000 000000 00000006757 12051462410 015607 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx import re from pyctags import exuberant_ctags, ctags_file from pyctags.harvesters import name_lookup_harvester, by_name_harvester class AutoComplet: """ AutoComplet Manages the editors autocompletion features. """ def __init__(self): """ __init__ Creates the re pattern used for special character removal. """ #self.pattern = re.compile('\W') self.source_files = [] self.UpdateCTagsFiles([]) self.entered_chars = 0 def CreateCompList(self, chunk): """ CreateCompList Interacts with pyctags to create a completition list. """ #text = re.sub(self.pattern, " ", text) #split_text = text.split(" ") names = self.names.starts_with(chunk) return list(set(names)) def OnKeyPressed(self, event, text_id): """ OnKeyPressed Using the editors facilities, it pops a list of possible completions on Ctrl+Space shortcut. """ cur_doc = wx.FindWindowById(text_id) cur_doc.AutoCompSetIgnoreCase(False) key = event.GetKey() #if key == 32 and event.ControlDown(): self.entered_chars += 1 if self.entered_chars == 3 and key not in [10,32]: pos = cur_doc.GetCurrentPos() word_start = cur_doc.WordStartPosition(pos, True) word = cur_doc.GetTextRange(word_start, pos) try: del lst[0] except: pass lst = self.CreateCompList(word) st = (" ").join(lst) if st != "": if cur_doc.CallTipActive(): cur_doc.CallTipCancel() cur_doc.AutoCompShow(pos - word_start, st) self.entered_chars = 0 if self.entered_chars > 3: self.entered_chars = 0 event.Skip() def UpdateCTagsFiles(self, id_range): for i in id_range: doc = wx.FindWindowById(i) file_path = doc.GetFilePath() if file_path not in self.source_files: self.source_files.append(file_path) self.UpdateCTagsGenerator() def UpdateCTagsGenerator(self): self.ctags_generator = exuberant_ctags(files = self.source_files) try: if self.source_files: self.list_of_tags = self.ctags_generator.generate_tags( generator_options={'--fields' : '+n'}) self.names = name_lookup_harvester() self.by_name = by_name_harvester() self.tagfile = ctags_file(self.list_of_tags, harvesters=[ self.names, self.by_name]) except: pass AutoComp = AutoComplet() gecrit-2.8.4/gEcrit.py000777 000000 000000 00000071251 12051462410 014557 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx.lib.inspection import sys, types import collections from Configuration import * from Logger import * from AboutWindow import * from SyntaxHighlight import * from ConfigWindow import * from PrettyPrinter import * from FindReplaceText import * from AutoComplet import * from StcTextCtrl import * from Menu import * from Toolbar import * from gEcritPluginManager import * from yapsy.PluginManager import PluginManager from data.plugins.categories import * from AuiNoteBook import * from gEcritSession import * import Exceptions import wx.aui import gettext import logging logging.basicConfig(level=logging.DEBUG) class gEcrit(wx.Frame): """ Editor This class is the entry point in the program. It creates all the user interface and initializes the required objects and classes. The functions that cannot go into another objects for diverse reasons go here. """ def dummy_tr(self, tr): return tr def __init__(self, id, parent): """ __init__ Creates the user interface. Initializez the terminals if enabled. Creates the required GUI and non GUI objects. """ BOTTOMPANEL_ID = 4002 SIDEPANEL_ID = 3999 try: self.presLang = gettext.translation("gEcrit", "./locale") self._ = self.presLang.ugettext self.presLang.install() except: print("Translation for local language not found.") self._ = self.dummy_tr pathname = os.path.abspath(os.path.dirname((sys.argv)[0])) # Finding where os.chdir(pathname) # gEcrit is running #Setting up the plugin envirenment self.general_plugins = {} self.passive_plugins = {} self.plugin_manager = PluginManager( categories_filter={"General": General, "Passives" : Passive}) #Sets YAPSY the plugin directory. self.plugin_path = os.path.join(pathname, "data", "plugins") self.plugin_manager.setPluginPlaces([self.plugin_path]) self.plugin_manager.locatePlugins() #self.plugin_manager.collectPlugins() self.plugin_manager.loadPlugins() self.activated_plugins = Config.GetOption("ActivePlugins") #populating the general plugin index for f in self.plugin_manager.getPluginsOfCategory("General"): if f.plugin_object.name in self.activated_plugins: self.general_plugins[f.plugin_object.name] = f.plugin_object #the passive plugins now for p in self.plugin_manager.getPluginsOfCategory("Passives"): if p.plugin_object.name in self.activated_plugins: self.passive_plugins[p.plugin_object.name] = p.plugin_object self.id_range = [] #getting the command line file argument if "gEcrit.py" not in (sys.argv)[-1]: target_file = os.path.normpath(os.path.realpath(sys.argv[-1])) #no file was provided else: target_file = None wx.Frame.__init__(self, parent, 1000, 'gEcrit', size=(700, 600)) self.Bind(wx.EVT_CLOSE, self.OnQuit) #this object will handle layout and docking/undocking of widgets self.aui_manager = wx.aui.AuiManager(self) #creating the status bar self.status_bar = self.CreateStatusBar() self.status_bar.SetStatusText("Done") self.status_bar.SetFieldsCount(3) self.status_bar.SetId(999) if not Config.GetOption("StatusBar"): self.status_bar.Hide() self.menubar = MainMenu(self) self.SetMenuBar(self.menubar) #setting the application icon self.SetIcon(wx.Icon('icons/gEcrit.png', wx.BITMAP_TYPE_PNG)) #this variable is incremented each time we create a StcControl self.text_id = 0 #finding the user home folder self.HOMEDIR = os.path.expanduser('~') os.chdir(os.path.abspath(self.HOMEDIR)) #creating a plugin manager instance self.plugin_conf_manager = gEcritPluginManager(self) #creating the left side notebook self.side_notebook = wx.aui.AuiNotebook(self, id=SIDEPANEL_ID, size=(-1,-1), style=wx.BORDER_SUNKEN|wx.aui.AUI_NB_TAB_SPLIT|wx.aui.AUI_NB_TAB_MOVE|wx.aui.AUI_NB_SCROLL_BUTTONS ) #creating the bottom side notebook self.bottom_notebook = wx.aui.AuiNotebook(self, id=BOTTOMPANEL_ID, size=(-1, -1), style=wx.BORDER_SUNKEN|wx.aui.AUI_NB_TAB_SPLIT|wx.aui.AUI_NB_TAB_MOVE|wx.aui.AUI_NB_SCROLL_BUTTONS ) #the aui notebook that will manage editor tabs self.nb = AuiNoteBook(parent = self) #going back to application running point os.chdir(pathname) #binding the menubar events f = wx.FindWindowById self.Bind(wx.EVT_MENU, lambda event: self.NewTab(event, "New Document", "New Document"), id=500) self.Bind(wx.EVT_MENU, lambda event: self.OnOpenFile(event), id= 501) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).Save(event), id=502) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).SaveAs(event), id=503) self.Bind(wx.EVT_MENU, self.OnPrint,id=504) self.Bind(wx.EVT_MENU, lambda event: self.OnMenuCloseTab(event, (self.id_range)[self.nb.GetSelection()]), id=505) self.Bind(wx.EVT_MENU, lambda event: self.OnQuit(event), id=506) self.Bind(wx.EVT_MENU, self.SaveAll, id=563) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnReload(event),id = 507) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnUndo(event), id=520) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnRedo(event), id=521) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnCut(event), id=522) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnCopy(event), id=523) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnPaste(event), id=524) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnSelectAll(event), id=525) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnSelectCodeBlock(event), id=562) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnInsertDate(event), id=526) self.Bind(wx.EVT_MENU, lambda event: self.OnPrefs(event), id=527) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnDedent(event), id=528) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnIndent(event), id=529) self.Bind(wx.EVT_MENU, lambda event:f((self.id_range)[self.nb.GetSelection()]).OnComment(event), id=559) self.Bind(wx.EVT_MENU, lambda event:f((self.id_range)[self.nb.GetSelection()]).OnUnComment(event), id=560) self.Bind(wx.EVT_MENU, lambda event: FindRepl.FindDocText(event, (self.id_range)[self.nb.GetSelection()]), id=530) self.Bind(wx.EVT_MENU, lambda event: FindRepl.ReplaceDocText(event, (self.id_range)[self.nb.GetSelection()]), id=531) self.Bind(wx.EVT_MENU, lambda event: FindRepl.FindDocText(event, (self.id_range)[self.nb.GetSelection()],wx.stc.STC_FIND_REGEXP), id=532) self.Bind(wx.EVT_MENU, lambda event: FindRepl.ReplaceDocText(event ,(self.id_range)[self.nb.GetSelection()], wx.stc.STC_FIND_REGEXP), id=533) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnStartRecordMacro(event), id=534) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnStopRecordMacro(event), id=542) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnMacroPlayback(event), id=543) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnZoomIn(event), id=535) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnZoomOut(event), id=536) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnResetZoom(event), id=537) self.Bind(wx.EVT_MENU, lambda event: Config.ChangeOption("LineNumbers", self.menubar.IsChecked(538), self.id_range), id=538) self.Bind(wx.EVT_MENU, lambda event: Config.ChangeOption("FoldMarks", self.menubar.IsChecked(539), self.id_range), id=539) self.Bind(wx.EVT_MENU, lambda event: Config.ChangeOption("Whitespace", self.menubar.IsChecked(540), self.id_range), id=540) self.Bind(wx.EVT_MENU, lambda event: Config.ChangeOption("IndetationGuides", self.menubar.IsChecked(541), self.id_range), id=541) self.Bind(wx.EVT_MENU, lambda event: Config.ChangeOption("EdgeLine", self.menubar.IsChecked(546), self.id_range), id=546) self.Bind(wx.EVT_MENU, lambda event: Config.ChangeOption("SyntaxHighlight", self.menubar.IsChecked(547), self.id_range), id=547) self.Bind(wx.EVT_MENU, lambda event: Config.ChangeOption("StatusBar", self.menubar.IsChecked(545), self.id_range), id=545) self.Bind(wx.EVT_MENU, self.OnFullScreen, id=557) self.Bind(wx.EVT_MENU, self.ToggleSidePanel, id = 548) self.Bind(wx.EVT_MENU, self.ToggleBottomPanel, id = 549) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).OnRemoveTrails(event),id=551) self.Bind(wx.EVT_MENU, lambda event: self.OnRun(event,self.id_range[self.nb.GetSelection()]), id = 558) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).Tabify(event), id = 552 ) self.Bind(wx.EVT_MENU, lambda event: f((self.id_range)[self.nb.GetSelection()]).UnTabify(event), id = 553 ) self.Bind(wx.EVT_MENU, self.SaveSessionFile , id = 554) self.Bind(wx.EVT_MENU, gEcritSession.DeleteSessionFile , id = 555) self.Bind(wx.EVT_MENU, lambda event: Config.ChangeOption("Session",self.menubar.IsChecked(556)) , id = 556) self.Bind(wx.EVT_MENU, self.plugin_conf_manager.ShowMe, id = 564 ) self.Bind(wx.EVT_MENU, lambda event: self.OnAbout(event), id=550) #setting up the toolbar self.toolbar = MainToolbar(self, -1) self.FontCtrl = wx.FontPickerCtrl(self.toolbar, 607, size=(100, 30)) self.Bind(wx.EVT_FONTPICKER_CHANGED, lambda event: ChangeFont(event, self.FontCtrl.GetSelectedFont(), self.id_range)) #the goto line text box self.toolbar.AddControl(self.FontCtrl) self.toolbar.AddControl(wx.TextCtrl(self.toolbar, 608, size=(-1, -1), style=wx.TE_PROCESS_ENTER)) #Binding toolbar events self.Bind(wx.EVT_TOOL, lambda event: self.NewTab(event, "New Document", "New Document"), id=600) self.Bind(wx.EVT_TOOL, self.OnOpenFile, id=601) self.Bind(wx.EVT_TOOL, lambda event: f((self.id_range)[self.nb.GetSelection()]).Save(event), id=602) self.Bind(wx.EVT_TOOL, lambda event: f((self.id_range)[self.nb.GetSelection()]).SaveAs(event), id=603) self.Bind(wx.EVT_TOOL, self.OnPrefs, id=604) self.Bind(wx.EVT_TOOL, self.OnQuit, id=605) self.Bind(wx.EVT_TEXT_ENTER, lambda event: self.OnGotoBox(event, (self.id_range)[self.nb.GetSelection()]), id=608) self.Bind(wx.EVT_TOOL, self.OnPrint, id=609) self.Bind(wx.EVT_TOOL, lambda event: self.OnRun(event, (self.id_range)[self.nb.GetSelection()]), id=610) #Give the plugins a chance to set themselves in the system #generals first for g in self.general_plugins: self.general_plugins[g].Init(self) #passives now for p in self.passive_plugins: self.passive_plugins[p].Init(self) #put it in the middle of the sceen self.Centre() #the preferences window self.conf_win = ConfFrame = CfgFrame(self) #addung the pane to the aui manager. self.aui_manager.AddPane(self.toolbar, wx.aui.AuiPaneInfo().Name("toolbar").Caption(self._("Toolbar")).ToolbarPane().Top().CloseButton(False)) self.aui_manager.AddPane(self.nb, wx.aui.AuiPaneInfo().Name("editor tabs").Caption(self._("Tabs")).CenterPane()) self.aui_manager.AddPane(self.bottom_notebook, wx.aui.AuiPaneInfo().Name("bottom panel").Caption(self._("Assistants and others")).Bottom().BestSize((700,150)).PinButton(True).MaximizeButton(True)) self.aui_manager.AddPane(self.side_notebook, wx.aui.AuiPaneInfo().Name("left_side panel").Caption(self._("Toolbox")).Left().BestSize((150,400)).PinButton(True).MaximizeButton(True)) #loading saved session if any exists and if enabled if Config.GetOption("Session"): self.LoadSessionFile() #make changes visible self.aui_manager.Update() if target_file: #load command line file path argument self.NewTab(0, os.path.split(target_file)[-1], target_file) def LoadSessionFile(self): """ LoadSessionFile Loads the session file if it exists. If it does not, creates an instance. """ try: self.session = gEcritSession.LoadFromFile() self.session.RestoreAppState(self) self.SetStatus(0,self._ ( "Session file loaded.")) except Exceptions.NoSessionFile: self.session = gEcritSession() def SaveSessionFile(self, event): """ SaveSessionFile Reccords the application state and saves it to disk via the session instance. """ try: #testing if a session object exists self.session except AttributeError: self.session = gEcritSession() self.session.RecordAppState(self) self.session.SaveToFile() self.SetStatus(event, self._ ("Session saved.")) def OnFullScreen(self,event): """ OnFullScreen Makes the main window fullscreen. """ self.ShowFullScreen(not self.IsFullScreen(),wx.FULLSCREEN_NOCAPTION) def OnPrefs(self, event): """ OnPrefs Shows the preferences window. """ self.conf_win.ShowMe(0) def NewTab(self, event, nb, file_path): """ NewTab Creates a new AUI NOTEBOOK tab, adds the contents, initializez a STC object for it and binds some of its events. Creates the sidebar, adds a notebook and adds its utilities in its tabs. """ if not file_path: return #update recent file list if file_path != "New Document" and file_path != "": if not os.path.exists(file_path): wx.MessageDialog(None, self._ ("Could not load file.\nThe file ")+file_path+self._ (" does not exists."),self._ ("Input Error") ,wx.OK).ShowModal() return lst = Config.GetOption("RecentFiles") lst.append(file_path) Config.ChangeOption("RecentFiles",lst) self.menubar.UpdateRecentFiles() #the parent of the StcControl panel = wx.Panel(self) panel.identifierTag = nb #hiding self.text_id text_id = self.text_id #set up the editor text_ctrl = StcTextCtrl(panel, self.text_id, file_path) #the StcControl sizer text_ctrl_sizer = wx.BoxSizer(wx.HORIZONTAL) text_ctrl_sizer.Add(text_ctrl, 1, wx.EXPAND) panel.SetSizer(text_ctrl_sizer) panel.Fit() #append the id of this StcControl to the id_range self.id_range.append(text_id) text_ctrl.SetBufferedDraw(True) #apply the font text_ctrl.StyleSetFont(0, self.FontCtrl.GetSelectedFont()) #add the panel as a new tab self.nb.AddPage(panel, str(nb), select=True) if file_path == "New Document" or file_path == "": #notify plugins for g in self.general_plugins: self.general_plugins[g].NotifyNewTabOpened() self.text_id += 1 return text_ctrl def OnRun(self, event, text_id): """ Runs the current document in a xterm window, for testing. """ cur_doc = wx.FindWindowById(text_id) cur_doc.Save(0) os.system("xterm -e sh runner.sh "+cur_doc.GetFilePath()) def OnGotoBox(self, event, text_id): """ OnGotoBox Finds the current document, and scrolls to the line indicated by its input upon the Return key. """ cur_doc = wx.FindWindowById(text_id) goto = wx.FindWindowById(608) scroll_pos = int(goto.GetLineText(0)) cur_doc.ScrollToLine(scroll_pos - 1) def OnPrint(self, event): """ OnPrint Finds the document, sets the prints name, and calls the wxPython toolkit to print the contents """ print_dlg = PrettyPrinter(self) del print_dlg def OnAbout(self, event): """ OnAbout Shows the about window. """ #ShowAbout = AboutWindow about_win = AboutWindow() del about_win def OnQuit(self, event): """ OnQuit Closes the main window, stops the terminals, and kills the application process. It promps the user for confirmation. """ #warn the user warn_dlg = wx.MessageDialog(None, self._ ("Please make sure that your data is\ saved.\nAre you sure you want to quit?"), self._ ("Are you sure?"), style=wx.YES_NO) warn_dlg_val = warn_dlg.ShowModal() if warn_dlg_val != 5104: #YES #call the quit method to stop the terminals and the plugins self.Quit() def Quit(self): #stop ond notify all plugins of application shutdown. #generals now for g in self.general_plugins: self.general_plugins[g].Stop() for p in self.passive_plugins: self.passive_plugins[p].Stop() #stop the shells if activated if Config.GetOption("Session"): self.SaveSessionFile(0) #exit status 0, all ok sys.exit(0) def OnMenuCloseTab(self, event, text_id): self.ManageCloseTab(False, text_id) def ManageCloseTab(self, event, text_id): """ ManageCloseTab Manages the process of closing a tab. Checks if document is saved, prompts the user if not. If this is the last tab in the application, it closes the terminals, the window and kills the application. If not, it decreases the number of tabs and delted the AUI NETBOOK page. """ cur_doc = wx.FindWindowById(text_id) current_text = cur_doc.GetText() #check if the user saved the changes if cur_doc.save_record != current_text: #if not, notify him save_prompt = wx.MessageDialog(None, self._ ("The file ") + os.path.split(cur_doc.GetFilePath())[-1] + self._ (" is not saved.\n\ Do you wish to save it?"), "", style=wx.CANCEL | wx.YES | wx.NO) prompt_val_ = save_prompt.ShowModal() if prompt_val_ == 5103: #YES if not cur_doc.Save(0): event.Veto() return else: self.id_range.remove(text_id) elif prompt_val_ == 5101: #CANCEL event.Veto() return elif prompt_val_ == 5104: #NO self.id_range.remove(text_id) save_prompt.Destroy() else: self.id_range.remove(text_id) # skip the event and let the AuiNotebook handle the deletion cur_doc.Deactivate() # tell the StcTextCtrl to prepare for deletition if not event: # check if it was fired from menu self.nb.DeletePage(self.nb.GetSelection()) else: event.Skip() def OnOpenFile(self, event): """ OnOpenFile Collects a path for a new file via a file dialog. """ open_file_dlg = wx.FileDialog(None, style=wx.OPEN | wx.FD_MULTIPLE) if self.menubar.last_recent != "": #go to the last accessed folder open_file_dlg.SetDirectory(os.path.split(self.menubar.last_recent)[0]) else: open_file_dlg.SetDirectory(self.HOMEDIR) if open_file_dlg.ShowModal() == wx.ID_OK: paths = open_file_dlg.GetPaths() self.OpenFile(paths) del open_file_dlg def OpenFile(self, paths): """ OpenFile Calls NewTab with the collected path. Supports multiple path selection. """ # if paths is a list, open an StcContrel for each of them if isinstance(paths, types.ListType): for f in paths: self.NewTab(0, os.path.split(f)[-1], f) Log.AddLogEntry(self._ ("Opened file ") + f) #if a string, open an StcControl for it else: self.NewTab(0, os.path.split(paths)[-1], paths) Log.AddLogEntry(self._ ("Opened file ") + paths) #notify general plugins for t in self.general_plugins: try: #insulate from possible plugin errors self.general_plugins[t].NotifyDocumentOpened() except: pass AutoComp.UpdateCTagsFiles(self.id_range) def SetStatus(self, event, text): """ ResetStatus Sets the status of statusbar. """ self.status_bar.SetStatusText(text) # event.Skip() def ResetStatus(self, event): """ ResetStatus Sets the status bar status to nothing. """ self.status_bar.SetStatusText("") event.Skip() def SaveAll(self, event): """ SaveAll Saves all the current documents using the objects Save function. """ for id in self.id_range: cur_doc = wx.FindWindowById(id) if cur_doc.GetFilePath() != "" and cur_doc.GetFilePath() != \ "New Document": cur_doc.Save(0) #################################################################### # PLUGIN INTERFACE # #################################################################### def ToggleSidePanel(self, event): pane = self.aui_manager.GetPane(self.side_notebook) if pane.IsShown(): pane.Hide() else: pane.Show() self.aui_manager.Update() def ToggleBottomPanel(self, event): pane = self.aui_manager.GetPane(self.bottom_notebook) if pane.IsShown(): pane.Hide() else: pane.Show() self.aui_manager.Update() def GetCurrentDocument(self): """ GetCurrentDocument Returns the selected active buffer object. """ try: return wx.FindWindowById(self.id_range[self.nb.GetSelection()]) except IndexError: return None def GetAllDocuments(self): """ GetALlDocuments Returns all existing buffers. """ docs = [] for d in self.id_range: docs.append(wx.FindWindowById((d))) return docs def AddToMenuBar(self,label,menu): """ AddToMenuBar @id The id of the new menu entry. @label The label of the new menu entry. @menu A wx.Menu object which will be added in the Plugins menu. Adds a wx.Menu object to menubar. """ return self.menubar.plugins.AppendMenu(-1,label,menu) def RemoveFromMenubar(self, menu): """ RemoveFromMenubar Removes the supplied argument menu from the plugins submenu. """ self.menubar.plugins.RemoveItem(menu) def BindMenubarEvent(self, item, function): """ BindMenuBarEvent @item The menu entry object which to be bint. @function The function the item to be bint to. Binds a wx.EVT_MENU event to the suplied function. """ self.Bind(wx.EVT_MENU, function, id = item.GetId()) def GetBottomPanel(self): """ GetBottomPanel Returns the lower notebook. """ return self.bottom_notebook def AddToBottomPanel(self, panel, name): """ AddToBottomPanel Adds the suplied panel to the lower notebook with tho supplied name label. """ self.bottom_notebook.AddPage(panel, name) def GetSidePanel(self): """ GetSidePanel Returns the side notebook. """ return self.side_notebook def AddToSidePanel(self, panel, name): """ AddToSidePanel Adds the suplied panel to the side notebook with tho supplied name label. """ self.side_notebook.AddPage(panel, name) def DeleteBottomPage(self, name): """ DeleteBottomPage Deletes the tab named name from the lower notebook. """ self.bottom_notebook.DeletePage(Config.GetTab(name, self.bottom_notebook)) def DeleteSidePage(self, name): """ DeleteSidePage Deletes the tab named name from the side notebook. """ self.side_notebook.DeletePage(Config.GetTab(name, self.side_notebook)) def AddPaneToAui(self, widget ,pane_info): """ "AddPaneToAui @widget the widget to be added @pane needs to be an AuiPaneInfo object. Adds the pane to the aui manager. """ self.aui_manager.AddPane(widget, pane_info) def AddToolbarToAui(self, toolbar, pane_info): """ AddToosbartoAui @toolbar the wx.Toolbar object @pane_info needs to be a wx.AuiPaneInfo object with it's name and caption defined. """ self.aui_manager.AddPane(toolbar, pane_info.ToolbarPane().Top().CloseButton(False)) def GetAuiManager(self): """ GetAuiManager Returns the AuiManager that is responsable for window layout. """ return self.aui_manager def GetTabManager(self): """ GetTabManager Returns the AuiNoteBook that is resposible for tabs management. """ return self.nb def CreateNewDocument(self, name): """ CreateNewDocument @name a string to be given to the new document as a name. Creates a new empty document. Returns a reference to the now StcControl """ return self.NewTab(0, name, "") def main(): app = wx.PySimpleApp() frame = gEcrit(parent=None, id=-1) frame.Show() app.MainLoop() if __name__ == '__main__': main() gecrit-2.8.4/data/plugins/PythonSourceBrowser.py000777 000000 000000 00000012552 12051462410 021741 0ustar00rootroot000000 000000 #!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx from data.plugins.categories import General import yapsy.IPlugin class SrcTree(wx.TreeCtrl): def __init__(self, parent, file_br): self.parent = parent wx.TreeCtrl.__init__(self ,self.parent, -1, size = (-1,-1) ,name="Source Browser", style=wx.TR_HIDE_ROOT | wx.TR_HAS_BUTTONS | wx.TR_HAS_VARIABLE_ROW_HEIGHT) self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnTreeClick) self.file_br = file_br def OnTreeClick(self, event): """ OnTreeClick Scrolls the editor to the appropriate line upon right click. """ id = self.GetSelection() text = self.GetItemText(id) self.parent.current_doc.ScrollToLine(int(text.split(" ")[-1]) - 1) def RefreshTree(self): """ RefreshTree Finds the current document, gathers data and displays it in the TreeCtrl. """ self.DeleteAllItems() #collect data and add it on the tree if self.file_br not in ["","New Document"]: try: br_file = open(self.file_br, "r") n = 0 root = self.AddRoot("Top") for line in br_file.readlines(): n += 1 if "class " in line and ":" in line: root2 = self.AppendItem(root, line + " " + str(n)) self.SortChildren(root2) elif " def " in line and ":" in line: self.AppendItem(root2, line.strip(" def ") + " " + str(n)) self.SortChildren(root2) elif "def " in line and ":" in line and line[0] != " ": self.AppendItem(root, line.strip("def ") + " " + str(n)) self.SortChildren(root) br_file.close() except: pass class PythonSourceBrowser(wx.Panel, General, yapsy.IPlugin.IPlugin): """ SrcBrowser Provides the necessary functions for collecting data and displays the date using a TreeCtrl. Used to display the classes and functions in the current file. """ def __init__(self): self.name = "Python Source Browser" def Init(self, parent): #set up the plugin into the application self.parent = parent wx.Panel.__init__(self, self.parent.GetSidePanel()) self.parent.AddToSidePanel(self, "Source Browser") self.src_trees = {} self.current_doc = None self.last_doc = None self.tree_sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.tree_sizer) self.Fit() def NewTree(self,file, doc): """ NewTree Creates a new source tree. """ #createa a new tree for the new file new_tree = SrcTree(self, file) new_tree.RefreshTree() self.src_trees[doc] = new_tree return new_tree def NotifyTabChanged(self): #update the displayed tree for the current file self.last_doc = self.current_doc self.current_doc = self.parent.GetCurrentDocument() if self.current_doc in self.src_trees: if self.last_doc != None: self.src_trees[self.last_doc].Hide() self.src_trees[self.current_doc].Show() else: self.src_trees[self.current_doc] = self.NewTree( self.current_doc.GetFilePath(), self.current_doc) self.tree_sizer.Add(self.src_trees[self.current_doc], 1, wx.EXPAND) if self.last_doc != None: self.src_trees[self.last_doc].Hide() self.src_trees[self.current_doc].Show() self.Layout() def NotifyDocumentOpened(self): #create a new tree because a new document is present self.last_doc = self.current_doc self.current_doc = self.parent.GetCurrentDocument() if self.current_doc not in self.src_trees: self.src_trees[self.current_doc] = self.NewTree( self.current_doc.GetFilePath(), self.current_doc) def NotifyDocumentSaved(self): #update the tree information because the contents of the file changed self.current_doc = self.parent.GetCurrentDocument() self.src_trees[self.current_doc].file_br = self.current_doc.GetFilePath() self.src_trees[self.current_doc].RefreshTree() def NotifyNewTabOpened(self): self.NotifyDocumentOpened() def Stop(self): self.parent.DeleteSidePage("Source Browser") gecrit-2.8.4/pyctags/tag_base.py000777 000000 000000 00000010363 12051462410 016556 0ustar00rootroot000000 000000 ## Copyright (C) 2008 Ben Smith ## This file is part of pyctags. ## pyctags is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## pyctags is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU Lesser General Public License ## and the GNU Lesser General Public Licens along with pyctags. If not, ## see . """ Base class for wrappers around ctags programs. This module uses the subprocess.Popen function. Users of this module could pass arbitrary commands to the system. """ import subprocess try: # do relative imports for tests # try this first in case pyctags is already installed, since we want to be testing the source bundled in the distribution from kwargs_validator import the_validator as validator except ImportError: from pyctags.kwargs_validator import the_validator as validator class ctags_base: """ This class exists to provide a template and some functionality for wrapping command line ctags programs. The functions B{_query_tag_generator}, B{generate_tags}, and B{generate_tagfile} should be overriden in child classes. """ def __init__(self, *args, **kwargs): """ Base class to wrap ctags program. - B{Keyword Arguments:} - B{tag_program:} (str) path to ctags executable, or name of a ctags program in path - B{files:} (sequence) files to process with ctags """ valid_kwargs = ['tag_program', 'files'] validator.validate(kwargs.keys(), valid_kwargs) self._file_list = list() """ A list of file names to process.""" self._executable_path = None """ The ctags executable.""" self.command_line = None """ The command line generated and used.""" self.warnings = list() """ A place to store warnings from ctags.""" if 'tag_program' in kwargs: if (self.ctags_executable(kwargs['tag_program'])): self._executable_path = kwargs['tag_program'] if 'files' in kwargs: self._file_list = list(kwargs['files']) def ctags_executable(self, path): """ Sets ctags path and executable. @param path: ctags executable name or path to it @type path: str @return: executable found @rtype: boolean """ rval = False if type(path) == str: # see if exe_file is executable try: subprocess.Popen(path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) rval = True except OSError: pass if rval: self._query_tag_generator(path) return rval def _query_tag_generator(self, path): """ Abstract method, used to test ctags generator. @raise NotImplementedError: Abstract method, must be overridden. """ raise NotImplementedError def generate_tags(self, *args, **kwargs): """ Abstract function to parse source files, returns list of tag strings. @raise NotImplementedError: Abstract method, must be overridden per ctags program """ raise NotImplementedError def generate_tagfile(self, *args, **kwargs): """ Abstract method to generate a tags file. @raise NotImplementedError: Abstract method, must be overridden per ctags program """ raise NotImplementedError def input_files(self, files): """ Sets the list of files to process with ctags. @param files: sequence of files, relative or absolute path @type files: sequence """ self._file_list = list(files) gecrit-2.8.4/yapsy/PluginInfo.py000777 000000 000000 00000002631 12051462410 016555 0ustar00rootroot000000 000000 #!/usr/bin/python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- """ Role ==== Encapsulate a plugin instance as well as some metadata. API === """ class PluginInfo(object): """ Representation of the most basic set of information related to a given plugin such as its name, author, description... """ def __init__(self, plugin_name, plugin_path): """ Set the name and path of the plugin as well as the default values for other usefull variables. .. warning:: The ``path`` attribute is the full path to the plugin if it is organised as a directory or the full path to a file without the ``.py`` extension if the plugin is defined by a simple file. In the later case, the actual plugin is reached via ``plugin_info.path+'.py'``. """ self.name = plugin_name self.path = plugin_path self.author = "Unknown" self.version = "?.?" self.website = "None" self.copyright = "Unknown" self.description = "" self.plugin_object = None self.category = None def _getIsActivated(self): """ Return the activated state of the plugin object. Makes it possible to define a property. """ return self.plugin_object.is_activated is_activated = property(fget=_getIsActivated) def setVersion(self, vstring): """ Set the version of the plugin. Used by subclasses to provide different handling of the version number. """ self.version = vstring gecrit-2.8.4/data/plugins/README000777 000000 000000 00000000471 12051462410 016236 0ustar00rootroot000000 000000 This folder holds all installed gEcrit plugins. The plugin manager is YAPSY and all plugins must conform to its standards. Please check the gEcrit Plugin API to facilitate your interaction with the appliaction. For more information or te report problems please use this e-mail: kristi9524@gmail.com Thank you.gecrit-2.8.4/locale/es/000777 000000 000000 00000000000 12051462410 014625 5ustar00rootroot000000 000000 gecrit-2.8.4/icons/run.png000777 000000 000000 00000004256 12051462410 015416 0ustar00rootroot000000 000000 PNG  IHDR szzsBIT|deIDATXŗo#W?؞8ƎlG64V]JBv'*(HHTxw> 7>R( kcf7?6:cOf1"ߧ\dkǤ%ef4MFHI Z+JS,jXcHӔ4M1Ɛ$)nG$$ip<_* b-xRb$I](P7hޥ^o t `fF ) 4X,)_B+RryB"HqnY-؈z!3:RA)1Sl)`f*cG&'5 #9i)TJ1q+#GFQp@tIΦ09yJ*R'z=Z+++(%٥P,0;;KǴmf b`@>8P,hԳ0c n X,=s%U[cZZFRV 牢Ok&e* Z!$AKQ>3yXa\yu!2Ey!%J+Vx@=c #zDKt;a((gD^\K˵H% j!2pΑ0%JΆZz}\\XpO",!8}h ӕ+xnWHʅs8(\y59Jik5B0 i6ڭ5vv35 ܹC0 kY&s'06b3WX˵ImDu!.5aue9ro^\Z ͛7Y]]lpqb9667'"nN q&nx$X3X>`p""8f8ug%@͈ ;4Mўp0ˣl6&hAQKxµI/!b-dVYg&K94%RXCP T*8Í u0O;ύ7exo̖"IZIS֐BtXY]pY1ݼfsgؤ\.s9wxgZ?,Uri8%^_TV8._8^c 99Xp(X[ET/|+0`y*Jf8!7oqg8~sJ)yI^6֞50u EW6qz-*'u}}7~/;'? ٱ# +%'JJSJi䴒ғJi%Rj!GS|硵Ӳ1(}{߼0JAc 5PCuYkQdnnZ&JRJ$W7ֻo)}%^XZXXxV͉̩;K7lP1-1#CIENDB`gecrit-2.8.4/doc/gecrit.1000777 000000 000000 00000000603 12051462410 015065 0ustar00rootroot000000 000000 .TH GECRIT "1" "July 2011" "gEcrit 2.7" .SH NAME gecrit \- a python text editor .SH SYNOPSIS \fBgecrit\fR [\fIfilename\fR] .SH DESCRIPTION gEcrit is a Python text editor. It implements all the usual features found in a capable editor, as well as a plugin system that allows easy expansion. It comes with plugins such as a terminal emulator, a code refactoring tool based on pyTidy, etc. gecrit-2.8.4/StcLangModes.py000777 000000 000000 00000036005 12051462410 015663 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from StcMode import StcMode import keyword import wx import wx.lib.inspection class StcPythonMode(StcMode): """ This class implements a python language mode.""" lexer = wx.stc.STC_LEX_PYTHON file_extensions = ["py","pyw"] keywords = keyword.kwlist lang_name = "Python" def __init__(self, stc_ctrl): StcMode.__init__(self, stc_ctrl) def OnComment(self, event): self.CommentSelection("#") def OnUnComment(self, event): self.UnCommentSelection("#") def AutoIndent(self, event): try: #to silence a useless error message line = self.stc_ctrl.GetCurrentLine() if self.stc_ctrl.GetLine(line - 1)[-2].rstrip() == ":": self.stc_ctrl.SetLineIndentation(line,self.stc_ctrl.GetLineIndentation(line-1)+self.stc_ctrl.GetIndent()) self.stc_ctrl.LineEnd() else: self.stc_ctrl.SetLineIndentation(line, self.stc_ctrl.GetLineIndentation(line - 1)) self.stc_ctrl.LineEnd() except: event.Skip() def OnSelectCodeBlock(self, event): up_line = self.stc_ctrl.GetCurrentLine() down_line = up_line indent = self.stc_ctrl.GetLineIndentation(up_line) max_line = self.stc_ctrl.GetLineCount() while up_line > 0: if self.stc_ctrl.GetLineIndentation(up_line) >= indent: up_line -= 1 elif self.stc_ctrl.GetLineIndentation(up_line) < indent: if self.stc_ctrl.GetLine(up_line).isspace(): up_line -= 1 else: break while down_line < max_line: if self.stc_ctrl.GetLineIndentation(down_line) >= indent: down_line += 1 elif self.stc_ctrl.GetLineIndentation(down_line) < indent: if self.stc_ctrl.GetLine(down_line).isspace(): down_line += 1 else: break self.stc_ctrl.SetSelection(self.stc_ctrl.GetLineEndPosition(up_line), self.stc_ctrl.GetLineEndPosition(down_line-1)) class StcRubyMode(StcMode): """ This class implements the Ruby language mode. """ lexer = wx.stc.STC_LEX_RUBY file_extensions= ["rb"] keywords = ["alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined", "do", "else", "elsif", "END", "end," "ensure", "false", "for", "if", "in", "module", "next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield"] lang_name = "Ruby" __block_start = ["begin", "BEGIN", "case", "class", "def", "do", "else", "elseif", "ensure", "for", "if", "module", "rescue", "then", "unless", "until", "when", "while"] __block_end = ["end", "END", ] def __init__(self, stc_ctrl): StcMode.__init__(self, stc_ctrl) def OnComment(self, event): self.CommentSelection("#") def OnUnComment(self, event): self.UnCommentSelection("#") def AutoIndent(self, event): linenr = self.stc_ctrl.GetCurrentLine() line = self.stc_ctrl.GetLine(linenr - 1) if not line.isspace(): line = line.split() if line[-1].rstrip() in ["do","begin","ensure","{","else","then"] or line[0].lstrip() in ["def","class", "module", "rescue","while", "for", "when", "if", "case", "until","unless"]: self.stc_ctrl.SetLineIndentation(linenr,self.stc_ctrl.GetLineIndentation(linenr-1)+self.stc_ctrl.GetIndent()) self.stc_ctrl.LineEnd() else: self.stc_ctrl.SetLineIndentation(linenr, self.stc_ctrl.GetLineIndentation(linenr - 1)) self.stc_ctrl.LineEnd() else: self.stc_ctrl.SetLineIndentation(linenr, self.stc_ctrl.GetLineIndentation(linenr - 1)) self.stc_ctrl.LineEnd() def OnSelectCodeBlock(self, event): up_line = self.stc_ctrl.GetCurrentLine() down_line = up_line max_line = self.stc_ctrl.GetLineCount() cur_line = "" while up_line > 0: cur_line = self.stc_ctrl.GetLine(up_line) if cur_line.isspace(): pass elif StcRubyMode.__HasBlockStart(cur_line): break up_line -= 1 ignore_delims = 0 # to keep track of nested blocks orig_line = down_line while down_line < max_line: cur_line = self.stc_ctrl.GetLine(down_line) if cur_line.isspace(): pass elif StcRubyMode.__HasBlockStart(cur_line) and down_line != orig_line: ignore_delims += 1 elif StcRubyMode.__HasBlockEnd(cur_line) and ignore_delims == 0: break down_line += 1 self.stc_ctrl.SetSelection(self.stc_ctrl.GetLineEndPosition(up_line), self.stc_ctrl.GetLineEndPosition(down_line-1)) # helper functions for OnSelectCodeBlock @staticmethod def __HasBlockStart(line): """ This method checks for Ruby block Starters""" line = line.split() for word in line: if word in StcRubyMode.__block_start: return True return False @staticmethod def __HasBlockEnd(line): """ This class check for Ruby block such as end """ line = line.split() for word in line: if word in StcRubyMode.__block_end: return True return False class StcCppMode(StcMode): lexer = wx.stc.STC_LEX_CPP file_extensions = ["h", "cpp" ,"hpp", "c", "cxx", "C"] keywords = ["auto", "const", "double", "float", "int", "short", "struct", "unsigned", "break", "continue", "else", "for", "long", "signed", "switch", "void", "case", "default", "enum", "goto", "register", "sizeof", "typedef", "volatile","char", "do", "extern", "if", "return", "static", "union", "while", "asm", "dynamic_cast", "namespace", "reinterpret_cast", "try", "bool", "explicit", "new", "static_cast", "typeid", "catch", "false", "operator", "template", "typename", "class","friend", "private", "this" "using", "const_cast", "inline", "public", "throw", "virtual", "delete", "mutable", "protected", "true", "wchar_t"] lang_name = "C/C++" def __init__(self, stc_ctrl): StcMode.__init__(self, stc_ctrl) def OnComment(self, event): self.CommentSelection("//") def OnUnComment(self, event): # remove the // in front of every selected line self.UnCommentSelection("//") def AutoIndent(self, event): try: #to silence a useless error message line = self.stc_ctrl.GetCurrentLine() if self.stc_ctrl.GetLine(line - 1)[-2].rstrip() == "{": self.stc_ctrl.SetLineIndentation(line,self.stc_ctrl.GetLineIndentation(line-1)+self.stc_ctrl.GetIndent()) self.stc_ctrl.LineEnd() else: self.stc_ctrl.SetLineIndentation(line, self.stc_ctrl.GetLineIndentation(line - 1)) self.stc_ctrl.LineEnd() except: event.Skip() def OnSelectCodeBlock(self, event): up_line = self.stc_ctrl.GetCurrentLine() down_line = up_line max_line = self.stc_ctrl.GetLineCount() cur_line = "" while up_line > 0 or "{" in cur_line: cur_line = self.stc_ctrl.GetLine(up_line) up_line -= 1 cur_line = "" ignore_delim = 0 # to keep track of nested blocks orig_line = down_line while down_line < max_line: cur_line = self.stc_ctrl.GetLine(down_line) if down_line == orig_line: pass elif "}" in cur_line and ignore_delim == 0: break down_line += 1 self.stc_ctrl.SetSelection(self.stc_ctrl.GetLineEndPosition(up_line), self.stc_ctrl.GetLineEndPosition(down_line-1)) class StcPerlMode(StcMode): """ This class implements the Perl mode. """ lexer = wx.stc.STC_LEX_PERL file_extensions = ["perl", "pl"] keywords = ["if", "unless", "else", "elsif", "for", "foreach", "while", "until", "continue", "do", "use", "no", "last", "next", "redo", "goto", "my", "our", "state", "local", "sub", "eval", "package", "require", "defined", "delete", "eval", "exists", "grep", "map", "pos", "print", "return", "scalar", "sort", "split", "undef", "chop", "abs", "binmode", "bless", "caller", "chdir", "chr", "close", "die", "each", "glob", "hex", "index", "int", "join", "keys", "lc", "lcfirst", "length", "oct", "open", "ord", "pipe", "pop", "push", "quotemeta", "readline", "ref", "reverse", "rmdir", "shift", "splice", "sprintf", "substr", "uc", "ucfirst", "unlink", "unshift", "values", "vec", "wantarray", "warn"] lang_name = "Perl" def OnComment(self, event): self.CommentSelection("#") def OnUnComment(self, event): self.UnCommentSelection("#") def AutoIndent(self, event): try: #to silence a useless error message line = self.stc_ctrl.GetCurrentLine() if self.stc_ctrl.GetLine(line - 1)[-2].rstrip() == "{": self.stc_ctrl.SetLineIndentation(line,self.stc_ctrl.GetLineIndentation(line-1)+self.stc_ctrl.GetIndent()) self.stc_ctrl.LineEnd() else: self.stc_ctrl.SetLineIndentation(line, self.stc_ctrl.GetLineIndentation(line - 1)) self.stc_ctrl.LineEnd() except: event.Skip() def OnSelectCodeBlock(self, event): up_line = self.stc_ctrl.GetCurrentLine() down_line = up_line max_line = self.stc_ctrl.GetLineCount() cur_line = "" while up_line > 0 or "{" in cur_line: cur_line = self.stc_ctrl.GetLine(up_line) up_line -= 1 cur_line = "" ignore_delim = 0 # to keep track of nested blocks orig_line = down_line while down_line < max_line: cur_line = self.stc_ctrl.GetLine(down_line) if down_line == orig_line: pass elif "}" in cur_line and ignore_delim == 0: break down_line += 1 self.stc_ctrl.SetSelection(self.stc_ctrl.GetLineEndPosition(up_line), self.stc_ctrl.GetLineEndPosition(down_line-1)) class StcJavaMode(StcCppMode): lexer = wx.stc.STC_LEX_CPP file_extensions = ["java"] keywords = ["abstract", "continue", "for", "new", "switch", "assert", "default", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "volatile", "float", "native", "super", "while"] lang_name = "Java" def __init__(self, stc_ctrl): StcCppMode.__init__(self, stc_ctrl) class StcFundamentalMode(StcMode): """ This mode is used for files for wich no appropriate mode exists. """ lexer = wx.stc.STC_LEX_NULL file_extensions = [] keywords = [] lang_name = "Fundamental" def __init__(self, stc_ctrl): self.stc_ctrl = stc_ctrl StcMode.__init__(self, stc_ctrl); gecrit-2.8.4/yapsy/000777 000000 000000 00000000000 12051462410 014124 5ustar00rootroot000000 000000 gecrit-2.8.4/data/plugins/PythonSourceBrowser.yapsy-plugin000777 000000 000000 00000000431 12051462410 023743 0ustar00rootroot000000 000000 [Core] Name = Python Source Browser Module = PythonSourceBrowser [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Collects the function and class definition from a python source file and displays them in a tree. gecrit-2.8.4/data/plugins/ClipboardViewer.yapsy-plugin000777 000000 000000 00000000336 12051462410 023022 0ustar00rootroot000000 000000 [Core] Name = Clipboard Viewer Module = ClipboardViewer [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Provides a quick way to peak at the clipboard. gecrit-2.8.4/data/plugins/StampIt.py000777 000000 000000 00000007737 12051462410 017325 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- #!/usr/bin/python # -*- coding: utf-8 -*- import wx, os import yapsy.IPlugin from data.plugins.categories import General class StampIt(wx.Frame, yapsy.IPlugin.IPlugin, General): """ DefaultColderFr Creates a window and all the control necessary to change the contents of the text added upon a new tab. """ def __init__(self): self.name = "StampIt" def Init(self, parent): """ __init__ Creates the frame and all the controls. Binds their events to the neccesary functions. """ self.parent = parent self.__text_file = self.parent.HOMEDIR + "/.gEcrit/StampIt.txt" wx.Frame.__init__(self, self.parent, -1, 'StampIt', size=(500, 410)) panel = wx.Panel(self) descr = wx.StaticText(panel, -1, 'The folowing text will be added automatically when creating a new tab:' , pos=(10, 10), size=(-1, -1)) self.text_ctrl = wx.TextCtrl( panel, -1, '', size=(300, 350), pos=(10, 300), style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER ) save_btn = wx.Button(panel, -1, 'Save', size=(-1, -1), pos=(600, 460)) close_btn = wx.Button(panel, -1, 'Close', size=(-1, -1), pos=(600, 460)) btn_sizer = wx.BoxSizer(wx.HORIZONTAL) btn_sizer.Add(save_btn, 0, wx.EXPAND) btn_sizer.Add(close_btn, 0, wx.EXPAND) self.Bind(wx.EVT_CLOSE, self.HideMe) close_btn.Bind(wx.EVT_BUTTON, self.HideMe) save_btn.Bind(wx.EVT_BUTTON, self.Save) main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(descr, 0, wx.EXPAND) main_sizer.AddSpacer(10) main_sizer.Add(self.text_ctrl, 0, wx.EXPAND) main_sizer.Add(btn_sizer, 0, wx.EXPAND) panel.SetSizer(main_sizer) panel.Fit() self.plugins_menu = wx.Menu() show_entry = self.plugins_menu.Append(-1,"Edit Stamp Text") self.menu_item = self.parent.AddToMenuBar("StampIt", self.plugins_menu) self.parent.BindMenubarEvent(show_entry, self.ShowMe) self.ReadTextFile() self.Bind(wx.EVT_CLOSE, self.HideMe) self.Centre() self.Hide() def Save(self, event): """ OnSave Saves the contents of the TextCtrl to the text file. """ self.text_ctrl.SaveFile(self.__text_file) event.Skip() def ReadTextFile(self): """ ReadTextFile Reads the plugin's text file and sets the text to the wx.TextCtrl. """ if not os.path.exists(self.__text_file): source = open(self.__text_file, "w") source.write("") source.close() return self.text_ctrl.LoadFile(self.__text_file) def NotifyNewTabOpened(self): doc = self.parent.GetCurrentDocument() doc.AddText(self.text_ctrl.GetValue()) def ShowMe(self, event): """ ShowMe Makes window visible. """ self.Show() def HideMe(self, event): """ Hides the window. """ self.Hide() gecrit-2.8.4/icons/saveas.bmp000777 000000 000000 00000006066 12051462410 016067 0ustar00rootroot000000 000000 BM6 6(    沲444???;;;<<<;;;999<<<======>>><<<;;;:::<<<<<<;;;>>><<<<<<<<<<<<<<<<<<9;;<=>;==:;;===<<<;;;uuuBBB333)))+++(((000---******((('''))),,,***+++***(((+++)))))))))))))))$+(%+)#)&"(%(,*253>A?uvt888FFFZZZ\\\^^^!!!######666IIIVVV^^^NNN:::<<<:::>>>ZZZ[[[[[[[[[[[[\[\P\YV`]ZdaZc`X^[BGE7:8tvt555[\[kkkhhhvvv >==bbbihillliiiiiiRSS/00556011666jjjkkkkkkjkkkkkkjk^oj^mh`okgqndmj]ca7:8sus;;;<8:J=CD>BCGG 6B<=E@DFCE@AHADJCHC7:>23<2/60+<63GBBB<@IAHKBHH?BNDD>AA698EGGBDD?BB;==143uuu444¿688qtt---þɭ+--tuu...ǻſʣ+,,uww888vzyοǷǿǭƨ޽ѰС777tuu@@@lml۷|jpNlLdFlP{_s|Ȫя<<a6j@kʦ;;;uvv>>>ROOvSwIьVڨkԚ٥ǒ㿇Il:kIεpoo;;;uwwBBBPMM׽ŵqUf:x:w,S֣„ƗTo2b2}P2޶ihh@@@tuu@@@MLLڨƐUHI*c/n#/Ǡoߺ֘̒Lj&]%K%@$Эa__BCCrtt>>>GGGݑؓid:*L+Vx)˞>֩ٻԴӭɘӔtp*^$M#A!bQQ؝UVW@BBtst@@@IEH٣öu4#:K"c*ڜUÏ@ڮڵקԘ|߭aМQюKh.NA=2?NQ=CC{tuAAADBD׿vi|6!G*Y/цO{9~6ɓԟєx͛N0{.x4n4X)I8)`OGLPABCxtuBBB@@BrC35@ O$zEf,ݪmJŕQD3ċ6Ç/},q*o7c3I :'h2!LCGIBEsvuBBB==@t8'4E!e:~M佊Ⰰ‹J95Ä0&~&v$l%b'h9uKR;J9׵ܾQlCܸƤzңtĎMۢZޡSu#z'p!i$\!j9ȄXtYYG^SU8?PCEkwuBBB<>@߹n)6!?"oL}֬֨|֦t֢h۠at/k#fe%Sq@lz_P>٠T8>N@BmxwBBB<>>sz}[F7N8ҧպֿ޽jșmyFa(g*_#VT"[.|SɁk@0ܽ؋K8=K@CpxwBBB>?@^adj=7d]rᷣηDzƫ㹙xSZ.a/W#W#OHW1oKcQN=ӀA<@GACuwwBBB@@@FGHĉkitrzt廮Ϻ߶黚͗qvMW(Z+HL#H&_CI.N?n]jhm7>A@BCzvwBBBCBB746σoqmo~wóͶϣnHܡxk>c4Y)`5;G)cK|3H<ŴaZb/@C=CD}uwBBB@BB*36؁opեS5iK\=gH?!A&F0L9͈zaT]cdIJIDDDCCCtwwBBBACC5;?Ƶζpk{俴ʽ沝x_fMlQَsqVdL\HxguhI=>>>CCCCCCuwwBBBABC48:żɹ餌طǐcR\Jp\mY]JxdqarxQFܷ999CCCCCCuwwBBBCCC=<>zyyȯmjŨϛri`UcWQEcUwi{VK|ŲǷ777DDDCCCwww===?>>E?@FEE333699364432:44B67TBA9$$~ZW}z~zqjf`iG@F+$SA;C9551/554555999;;;>>>>>>@@@>>>tttgecrit-2.8.4/data/plugins/Notes.py000777 000000 000000 00000003746 12051462410 017030 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx, os import yapsy.IPlugin from data.plugins.categories import Passive class Notes(wx.Panel, Passive,yapsy.IPlugin.IPlugin): def __init__(self): self.name = "Notes" def Init(self, parent): self.parent = parent self.save_point = parent.HOMEDIR + "/.gEcrit/Notes.plugin.conf" wx.Panel.__init__(self, self.parent.GetBottomPanel()) self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.txt_input = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE | wx.TE_PROCESS_ENTER) self.txt_input.Bind(wx.EVT_TEXT_ENTER, self.Save) self.ReadTxtFile() self.sizer.Add(self.txt_input, 1, wx.EXPAND) self.SetSizer(self.sizer) self.Fit() self.parent.AddToBottomPanel(self, "Notes") def ReadTxtFile(self): if not os.path.exists(self.save_point): source = open(self.save_point, "w") source.write("") source.close() return self.txt_input.LoadFile(self.save_point) def Save(self, event): self.txt_input.SaveFile(self.save_point) event.Skip() def Stop(self): self.txt_input.SaveFile(self.save_point) self.parent.DeleteBottomPage(self.name) gecrit-2.8.4/locale/ro/LC_MESSAGES/000777 000000 000000 00000000000 12051462410 016423 5ustar00rootroot000000 000000 gecrit-2.8.4/data/plugins/TreeFileBrowser.py000777 000000 000000 00000004301 12051462410 020767 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx from data.plugins.categories import General import yapsy.IPlugin class TreeFileBrowser(wx.GenericDirCtrl): def __init__(self, parent): file_filter ="Python files (.py)|*.py|PythonW files (.pyw)|*.pyw|Ruby files (.rb) |*.rb|Text files (.txt) |*.txt|All files (*.*)|*.*" self.parent = parent wx.GenericDirCtrl.__init__(self, self.parent, -1, filter =file_filter, style =wx.DIRCTRL_SHOW_FILTERS) def OnItemActivated(self, event): file_path = self.GetFilePath() if file_path != "": self.parent.parent.OpenFile(file_path) event.Skip() class TreeFilePanel(wx.Panel, General, yapsy.IPlugin.IPlugin): def __init__(self): self.name = "Tree File Browser" def Init(self, parent): self.parent = parent wx.Panel.__init__(self, self.parent.GetSidePanel()) self.main_sizer = wx.BoxSizer(wx.HORIZONTAL) self.file_browser = TreeFileBrowser(self) self.file_browser.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.file_browser.OnItemActivated) self.main_sizer.Add(self.file_browser, 1, wx.EXPAND) self.SetSizer(self.main_sizer) self.Fit() self.Layout() self.parent.AddToSidePanel(self,"File Browser") def NotifyTabChanged(self): self.file_browser.ExpandPath(self.parent.GetCurrentDocument().GetFilePath()) def Stop(self): self.parent.DeleteSidePage("File Browser") gecrit-2.8.4/icons/open.bmp000777 000000 000000 00000006066 12051462410 015546 0ustar00rootroot000000 000000 BM6 6(    θXYWJKHJLKKNMDIIJHFOIASJ=SH;NG?KIGEHKFGHJFAOH>HHHJGGIFFKGELHELFCKFBKFCKGBKGBKIHGHGEGHEFGCDEVWWNF=SMFWTQWY[\_efhkrpn|uqtyyw{{vz|twxpsulkngegb^^\VTVOLID>FC@BDE@DJ;?DY[[<@D:@G4;C?ELP@0K<-A3"C5%D9+JA5QI<\PBfUEo[GkaMj`Oi_Pe\O`WL`WM[NCVF:R@2K6'VI;ME=DCCo;l8g2x]A[I7HA><@I5=KRV[A@F9ANPU\?BFIC>WF5\C%א9ޚEGDD@?PNYUߠJIG<720؇+Ӂ'v7W&^F/FBC>DNNT\AADRF9sW7]0זGݠRߦUTQWWڧ`⺇Ϭѱխvў[ܟPGBܒ>Ӌ:˅6ʃ1WzX7ND??AILS]BAAYG3lBIMX\\Z^lݷwui\nnkul^dɢrۧdUKEٓAЌ>ۉ,p%tKSD:@@EPTZGCBVD6k=;NZ``^appϪ|kXPDCؑ>5u rAOC:BCG[WVGC?FACpFݏ1ZhlmhjlϋwL{p]̤eq^PTLߖLՐK{}BCAB?ADYVVGB?GBCtJ:dlpu|͋Ϙ˘פաۙڕъɀlk\YMHؖOԁ!FDCD>@CZWWGB?E@BvL@bqt~ґ̘ϠݪښݓؙАȇ{~idQQګ=ٛRք%ICCD?ADZWWEC?CBB{PF]tͅҘ٦ߟܓ܎؅yxokΜ^əaڞYڊ+MDCF>ACWVVEC@ECDTMmʇ֪ޝڌׁ{}yϟp䳑۠]ߐ1PDDF>@DVTTFDABBCZOܝ߶ڍԄ΀xqܥ_:TAAC>@DUUTEDA@BC\TʎώٚҘĊuh֟]ʓQÌH:Ɨ^BBE>?CTUTCD@?AB`]d΄kxʆΘѤڬޭۭݰѣНלʈўYFÕ]>?B@?DTUTBD?>BBcd̝[ߣɗֲ֮ۺ޻޷ޯؤњ֝Ӛ˚UJǚaCBG?>CSUTBD@=BAei\ơȖXOțbA@EBAEWUSBB?;AEquҧqyT۫}ɂ٩ضjǓҒѐ҉Ђ~xyخw_XMRBDD'9SWUREC?=BBrz̏ЩxҮyֽxȅ޿ĎъˆϰyЯѰҮӭԫyեq֥o֣n֞jѕcڪkV]EB@4>O]WQID>?AAt~ҕЛܥޞܟދچ܃ujidr\ީfFA;@ABx؄ܚ۝ݜ֔ԎЅ}vpbۮwIC:>@mLVU]euz}ρ΅υ΁|yvpgaWKڕBϋ5ɂ-x-^5KE>>=<^XTDA?:AHp\Afcfq͈̄҇ҌѕєҏuspjbVOE<ې3Ѓ+w5jR5HAZUTCAB8BN\L6wkl}͓Қؗڜ֪֪ٞ۝חҎ̄ymcYݚQ֐Iډ0u?TC6GB@MHB[WXACG2?PPD3pqo׀є؝ݭؠӒˁtf[RݑI4n?G>A??ကgecrit-2.8.4/Exceptions.py000777 000000 000000 00000001472 12051462410 015461 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . class NoSessionFile(): """ NoSessionFile Raised when the serialized gEcritSession file is not found. """ pass gecrit-2.8.4/icons/gEcrit.png000777 000000 000000 00000062232 12051462410 016025 0ustar00rootroot000000 000000 PNG  IHDR}z\sRGB pHYs  tIME ;*Y' IDATxypwzyϾ}Ѹy D"%Q5d&;fڎ7;[um&&N]x,wfVHx 4Fo/uؕxSF $>\y^m;[mWQ$ I۶wyԲc EQ ~ ?ݶmb~: A߶msݟ+eYmz>X,NVՑ`0A,@Ax[m!뼈; ﻆ$i`{Ajubuuuј4-H$d2E{W2>>a?(oXoa!#.Nvݲ,܋`&i"TU4mZNlll/AJ&$ 95tV=VT0 t]  n~5 d˲0M}Q 85YT&Z6j IӤi|>߶۶Eы. H2pRU_UUEQ~7vh׃ym1h4& DX_ղPd2I("  =:s\EPٶ,˼߿IA ]Y$fx?ŝ_;o;A8fYdٜT*BaT*EE!Lihr׫EW}vgh Qt0,@@E,eYw_刺R,>˲l>wMn{>gYa C,5 cVM B^(( lt`ЏeAeaA)A `? l; dYVy뭷8p@TUt(dН͵j׽Ȇa IR$I>olNM>d2I&a^[~ Dc;#AhAa4 &coZ|>նȜy\wA^c{nXeYUeYu]ܜl4j5^TH&Ŷ=)mh>`~{weeiڶ7 LDUU ( $( T*$~P(,dv~;3HHtL LɍMEdX,6si2Uapg;#ƃ~o7A^hj0MY=B>_ufpp~$IZPQin=DQ I&|>~M&dVE&fٽ{7/]NwBfΰ w^M].b7T'{Vq3}(kB'"}NU՟eZ?f~5 >IEq4fsT*_[[udYFUUb===.ɰ nN~P\D}C;nif >ߏ(CUU/4H'>yp4M^i`D{.]]]D"BC~ƒBl -]Tn>ydYl6K__v7"<('"H -їa4^E}EN9;F٤ljhZ\ ϝu{8:`gZF^pwAqdY$ 2<<̽{Ø4/*=ͣ}wG}_xԾ}`wQG"v 0MVE^0 /m(ma y4Mhw[ws,/E|;СCz- zPtIu]WLz}[t.PA(n{rg~oٞGm$I Vк;?e]0nu/eYXFqO4QUUD,k  ܿVPȍMm{cN3:ub)o愦ia"dr[ 7N5b'Չ ( m:V]2O c{ rs÷뭆axQBdYD[҇[?7q=lgP7Y|.mt]<sC[;ws ( pos1dY~- ṽ< p=ȽPn,z6{p' aCVn>{xEy_ :ugwhN+]]|>DQl; AOTU3}wf;{ett?+ wWAhv:Gw)4wT6e ä<$ $=CBwm{W |F, VțBjWW@`[aF 9 FGG) i4Mp|ܜ~}pp'|h4eY~yAg~s(6?|q>Qv}4W[|~.\QN:ug4mwӃ6wFN=5;w~P(裏 mj,|OO~s@ӲmcN'6 h4|j;LTgu3e^8vE(/v3-R\yRTf(~b1σ-Bh80Wvnuu%K^~2jQwNL:pM\'TU (+i,_}U>L6Ee˙f}}Ǐj>UVH$>4[) ìgtMf $aϧq"<٩euFKA.8Pzk Yߗ; CvI]u)۾7# 0MX,$D"i Yi/vP5M)<#`Yjyfgg :tS(B!p~',MY-@Fܽ{L&'R uRVm ]5F8&wa&kkkٳo311~`&K;=h>z}i(tB>>dYQj\.;H@"=y˲^|P,/b^xT"If1J;wO?66B]fݻk׮188p8\tm,{;Nqù{]#Pz{{y駹|2.eF9w<d}=OTa߾ 377"ETO2(^qm(ekN#܈>N,CEVZ E",s-VVVXZZzr2T7nh4^>I˲NZZ'N"5Ë/]]]hlO7>EcnT+5~?~:͏4z[|8%gbP(=Oqk]~ؿ?O>$$qR|_gllӧOcY:t ._ʙ3gX\\/z['> Üɹsj!tww{dL*"paCUU}5LgX,|뭷~4`["Hz2K * ǎw DQrX,ƽ{ؿ?Rɫ]Pb``d279}4\իW9vkkktww#Ft:M4… .)Çٻw/HD"J.F 7 ?s譭- U(\p]_'LR.4Ç^,d2DQzzz&&===^t:͵kWa_qizfž={8:yxF"_\}[ESex<neIZ ˲)$ =ALӤ;A4VVVH"A>G%zNբZ 4QUJg>o{zOOY&!M8FVh4[?msER}}}(Hw쭏݋,ˣ>z P(#GCD~ꧼl6v;iNutOB|+"zk(ڵ7x>|/_F4xrz;M 0V2D}.]app]'UUm{}饗0TL&C s4&}8u5ą?}{`0]&? )I>'IחA%R@h{œJZZpcP NV.`3}}677X__Ge\i[%6 AB7 ,$ » twqUdYlۦT*sU=4Gܹsܼy%2 f+O3Yw{M$V188H  }|O(( j",beP#=.D wuj,--h4(ˬȲ̾}8q(rMy~?`{ͦƍ7;ES,jLOOc6󬭭J4H$§>)8tG}@mgdY2w\zt:۷$|w4ۘw}S,*^m9A_ d{2 ŵ ?[M6\C,)ݻiN:E$H|B@$*Ӭ*O077.`EQH$$n2 {ꐀ;݋ͦ={u(d'OH$u;ם\4.D~*k6ڵˋ2G\&*] w1::J8h`6D۶BQ%wȆ8:j4ɽ9L$Жn" [ /^d```0ȝ;wF|;i%$F|>OVcqqIH$RabBALB * T ]יemmB@P8 yz{{fa~s r9Y_hP(}6]]]>|Y* DFA&addt:M?H 7lFGGys!|>߉o|dY$t+묮˭b"=j5{C"4M2 333?~܅+(ʇ"reY~۶}.*zQ|V ﺮ# N/k.Х !HE(ƶm=e&jFٳ|>Z< ׮]X,=6{U={8~8$ô(Z\dff+WP(BHV#z4Kd24Eo9V鴄 R EQ({ﱺC=D__dSEYYYaXcDv"KW;J,,, jK.h4fi6 {(vuq\nw:׮]Gq$`V{0^Vo Jgœ@[#D)IM3PD>ƞ{vO=+Ye7dSm 1 _k Ҡ$^k<ʥ۬0t_u͕ 677)W(m@mI R IDATAy SZVyyy˲(\rz MӸpjJnmm111A,#NDždo\ȕB;Z-Ubsss\vl6(@:T*111A̙3twwe7x"Vܰ===ͽ{jH䤗bk EQP:LN'I%id,-/Z@S$)o_$[f|(AIr`6E7Jٶl&:, 5LI_[|yn>^N m46 45'-h4?*6>`nnx@ݴQ{{)Fl[ DQhb MIBV֊>iܻwB&Xk׮yW4cttaVVV'$xă~Bjya`6dQyWHRb1ܹYDwwGslmzܸq|3ܹs}kP,0룷kˢѨkX4lnY^]beq5x=GVX4?M47lklK.8ȲNV(J͟QGx{i%:آ m؂)覀*E EQTE@SPD?VVr[uy2,so"cmmGH$<*'9tPȫ٬W:vX9QY__G42 _)D"`[AC?}}}amaqVC?믿N"R0Vk=e;{fvtWjq=zT*+++qT_@@|>/=hUmm0֔YHtYDޛBBhYX b&-ulABTDJ-J+@o_fUb&my(Ү]s*ovPBU(r1 p׮8ׯOyDJ.k+f,,,0??OXϳg Rp UR@ '?F"h쎌022Bp؛X a6Jt]'HP.wdaas!I JA0O4]]]zzD"aXms^'c&\xL&4`9.\eY2e||B U>gee-cP~Js),p 0͝8xe//UI;_8}: I et(+Am.M ݲq$! *-Y DKDoYh&eɓ|> CCCS)BP[ !sTʁ)jyssh4J>gnnAA`xxaV=`q7mll`&Pb{ȑ#\r/ (JJ%/yn߾ͩS)w2kkk )V.4kz?7x"{=4__$ T*a'Ȏ`ky4=}Hfgg) N!'Hn(t4=CV+J*W0  ,$[%2P5hԪlZ*%xj֧~ۿj5ZlM~mb\~EQطo+++uOs*]{9≄řZ޵sT* =Ci&>Gݻwڢ7nY\\jqmRԲ,ŢǦMOOa8Ln}/kkR)gZ5FN(=K~y3gc( ڃ B\U[narv@Ft$K_ jM |mclaR{u$R7IHRٳg[ p>,+++m98H9j}FA!&a^RvD9w]Q᤼ord2F[pGZpdT͛lnn( Of}}Y9t,,,8g]Ƕ0~E&'oV|?ZK˕4O>'R]KuJ0C͛7)J:u 2 EEr⵽uVDk~E G)Z!l -B"#p= YPdm,5Ii2 zΡCXXXhpiWm_2tF&,fyטa``zy#pWG,kt-W9|p[4@&ajj۷o{Uczz$Ivލ(iKQU )֊@@W^wϒ/fL>NKea)l Ko=hl9~`c:\~6(9O\g9a4dVP7\{葧Q- @DZmk KL vКD]ƻK__7$022B4ehh˗9x xcݚZ{+++H.]2w嶺u͇ONN288m.TR GV{\p/}KKR)\q9~EU;2Vaml4ַQ?co),W._DlLF i3O?sdW vj5>,˿o-kMhe1B m :2s%"}h2B{M%skF%ZITœ$ږDQ(f[h4bRDoo/2 T 49sCXt,[ZZ VE\fiiyoYAP𔴒$ob<D EwlDV Ù }ȭog} ׯ_ZBΐw"A[g>| @ WZG&jpg|n%b70{A ='H TS.o( %Nr7SRVcqu=͛LLL000@4#LFguQGREEfggss_Ε+WF ǹ{."2 *MĸsI\iwEљ^ַ?~Q٪TY]]a(]#TWVhDQ| O7kɲ_asW~h$IZvKTK_ 1X[NJ` :eD(CoMw'_TVJmlK~FGGX_g}}ݓ^~/y(h-3zfEOj8qZBLNNRLNNǍO9JABmn6[[ oJ4u,ˤ\7G E$杷`jj%8@.QŋEErp4ޡ#"ᰟP4@+L 5IvkobX⿕χM_nަϳi(H%Kϯϗ&hü_魖,-/;uKT Α7?"^2baRٳݻ*Νcxx7|{RdϞ=j5{1ږt8AV]eꘆAR6=S}.^ZMGC_מb~~wyYѴ:(A{ؘYH2$**_3BͮHA kƋhqE"k5b"["nn[ʕ<]>ŏ"ߵmqz]D"(hP𕖡?E{72_ChȒMC`>gқlU L8|萷R,o͡C0w$]z`0H.ZH$xcDT*ݎCTEdqq"o!I bi#j{ͫ5["i YJ{=>b{KޅzW^."?/cX6< +v/ &F67Us _""dQ1,i߇]? 6Mս{l[eYVm}4~CЏKy66lSd2uT_0r 8 {-T3GF;`d2^#T{B>R8CXdeeC%Q,8 ҃Z*LBpCUUAZ7gE$5F ŬQ'S8j4UU<#͔ ~K$̫\2G ?DXe}]>sw0 ľI'B^Z,!KޥݐFQ\.mwT=OmJ+!\Yfh 1333s=# 5YOWTv4d|;/;;*t\yJ IDATߣsZe9x2 8(& Cr_},ϧNϳ>K̙3MBa7#K80̡x^Cxիvjj}mNhE8^~o|Xd= 5 >7MyЧbY9BpeMgĞ46Kc;۪bl^ב;G20")e eU4wvĢb|KZӲL$yLT ʺY(U{:<̳)B["{/Mt.- @AsWgV.;!Y\\duy'N277G0^mBb"Dayw$3܀kFh/ ||n)KbI!edcE0 #e{+{%em.PUmc9|cg727]wùsh }A1~5ks^d۶O?-aNawj/%ƃifnF?63Kn|=. Da,T143 ~2,;w7>lnn𗿜-,.z=%vJV,FJrrѲ|_8ҌtO -9eTj|S^t~lm7X_ q@0 1l_D6ͨBZO6s5jun8JEo#,[kX_{yuhmnfeC b&XXfm+Y<*_B{3>ŠG> G.ל[_Mq,$crʻ+g;s\>/اdk#M~ŦPR/ p{&j\-vX3q7_͑[l15qLx TMALUP(wAP^S*RsdY.ɞ^nս .AOত{juX0ۭ$DiG*Qλ;瞦Qҥ q`O&l_#_ٌO&e[uK> +odrqj!3=;ϣ9|OQBWk$Íހ[0 :z,I:w%w>dWN`?qg- RoFgDqڙ۫8>Ё/f0u7XX\K>/a}Nf.O6F_MEDdݜJaZX|nz(XT(Zv\ǺMhz Tm0VMq=rm^qICx:N*6 u]ŴrϻgԮDq-lۖpŧ?qe|W %5z/+ Z5;ssfhz(u9̣}Ï`&mGd Q:{iG~/Ͷ\sG97ͦwX'=E0e>QM7CZm6γx} }+봶<{"hÐp26I\3,;OM885WSxDv@&zd)B1]MfM˲OKE\FTlL!@{d[5Fu0bWƾW?5+w-< r% HT݌,N(gkwHkdAnk=J}˗1P=p`Nƃw'cccT+iUl;׷nk8.m}o)oZ\..NCS`L!"R%{2YItȮ(=1BS7ܻ>M{,u},^:C,f$df!?aiiz"k`O-Oy jAI>OiȲڴҫdCwzjj.pMGfLaض^qm*U9̠z~`Kwv 3QH jlj-ɥ&~ّ^7S&Hrw1T?q5Wyӛѣ|Fٳ&oalR_:rB+g 2H%;r&0c2֟>ټ7}/imۓclv;loaJVvNBGx,EN BY%;cսɜ,Z-f|1{2gϞj( +Wfvv 3404=KpםKGqtvpv.j#Ȓ1HF4M;%Qy6 ?X{Pp .-`X&':Q|tvD.K+oCd][VnX4e8qz]5&Vgmeu "Ү2heG:&R #`0 A4_g?aò_1܌&TT]gM1 `FgcptqWNo@%Ώ%A'sE)C8edYE$@HNesnns$4oY__Ob 6 ǚt l\kr-NÇ3==(6\+=xW(ZEw+9_(74mhgmټ'6YXX`$ B+ѮG$"d<~8ui'rɊsO7W%R)qC(+K,--C?:#Adh*JPYX, ,|JZt&c+ґlZU'l8,..233Cc{+}2c\we2ݲin\#'dr9 U$KnG7>jw_nF[Ao$˩nzfk kϻ,..l{*r)̰7dHmDNoZ-4qT^C!X\+D<<[52z?cvn5/_Ѭ# sN80uӔ:gϞeaa4)77w)-W-+i9!ăRu#}!:aR=^cyz<}ix:P`vvg.Wu>/}KA2?ðX\YfkNmyDL.ޡ5Z]+y& =8@5meKZQi`9$_mY@z4gOjYwOqLmIxWcG݇I&-YtLAQM2v%"b8BH!X&wBAz ;=:PѬ"TP>Rgv2sK88=͛#ϟ n02@4s ]^䉯P(0>>]L^Y#KCgotȪ4M{rd3B4Mj(|FnI8pXZZAWY&sٶhD+3 kWb%m(J3'21MA }(B3`#MۇCHYY[f桷^*s"Qh7괷VUrE&''SـYZWӴPU 4 !YfS- T=>Ou]8vAVWPu7zޖ ɎdFhB!m؆ƨ$~!B%V~)ė•+6ryZ >J)~mrNѣJ%Ǚbbb"iMN !N !NzIUafBtiMFKC'5?:2G ^>9s@Y Q@ cC iЉ!LZ|ӟEQ=oÈeV6X]^#&UҤwm) gll{V񜪪A#キz=e?;ĜWUzNDFQ'd#]vRnD{ڣ.Raum(mS5R :A0DW Y&,ut+,xr/RJm}$}j-pHeFތ9r|9pJ>9r١׻׃]F;~ٍ>JT8BܛUCʂ%^fk:c1c(&"|%,!t Ttzm^*׸I;/lAvߡӨjlo}WfYZ_fB2$Ne_r˗q1ɟ< fM/t_eEcmmjJdfQ% Nz4{Pb1@p0 (Tl[]*][k 2T4V52/r?k :>Ξ@bav`2DU9@)D۫TN;NX s\n׸4[ھF~E~J%=$ #=Dj01aQ0 66YXZ⩥6slZ4>[A@c5(ng0wѻIw`CCqcܔ0ao]dC3 Dr>۶Sw_v!t]o%!033ӤgP)UU)*yS*:~kmשz\]opnqffk8bؖh |T"#&"o;Nn4y0HJvݱ12O<ZnJ"UUB/nðIrֈ}!qzήreiՆO'cESM [w(U,_ 牄*bM`6öx#[jkBy#j=F4[_/ks&S}^UU߲,}0$rմ.C5Myu6J|MA ,K|Ebb Ux^xmYn)**I8m{K^5]ʙFdZm>6{ɲFqLJqb?]ToN&& OnUޓs]E;F64M[ i]XB˲p'mΤE[KY;=HAT0Lnn6!q`hkC̛]uM۶ݳC*@!JqryףYgyyap[!MV{n5o U(W+LV+.+m軉dL $I'V"_a]r,N}t-Y #7V1PQC 5m_dznaj:Eqpնߴ,c3(h2P~De:)!b| X\.jFͣBLKsi>(JUӴQq\x>z̫_e2{JwDC-&D & b04 ˫# um>IDATE˲&{ usa,-|B"Wwky-N[aR]7qJ6P~4+1pIhUUC;J~nMgCת^UF DGdfIyբ:]%&^.i8eYlf,wUUEhjG3z%عvImc0- ]|aVLLLL\ޒ{{ĸgG.)hF j0pSO n[>lP*Un_'0Uay涝söfY_&HHQ#<~Lu0mfIpJy ,עT*111Ji֭聯t/߻sFO ˽![OmYny3ܸ4cŜlcySi85v &)0]վ_Im{sǽrÍG1,<1}trrccc=|F6Q^{wڠYwtis=!EIWT[r;c]%@D?PxOOC'R&Č 'ԁrY<Ɗyz8~ U:b`lZu~ԏXFC3QU% '"K.JNI^|6mwJŢpz*8V,{7ax!A@. =h "B|5繹麾m(a!Bh+fp+_ qO7MhA!L*;'?msaz[tac3o_ q0 TB2J "f+Ї>j;yۭ,c1V)b15+`6BSgne̕]?{0藁OȤ, ^~ͣ=_;t///aQUb>?]޻WK^T6IENDB`gecrit-2.8.4/locale/000777 000000 000000 00000000000 12051462410 014216 5ustar00rootroot000000 000000 gecrit-2.8.4/gecrit000777 000000 000000 00000000064 12051462410 014162 0ustar00rootroot000000 000000 #!/bin/sh cd /usr/share/gEcrit python gEcrit.py $@ gecrit-2.8.4/yapsy/FilteredPluginManager.py000777 000000 000000 00000006326 12051462410 020720 0ustar00rootroot000000 000000 #!/usr/bin/python """ Role ==== Defines a basic interface for plugin managers which filter the available list of plugins before loading. One use fo this would be to prevent untrusted plugins from entering the system API === """ from yapsy.IPlugin import IPlugin from yapsy.PluginManagerDecorator import PluginManagerDecorator class FilteredPluginManager(PluginManagerDecorator): """ Base class for decorators which filter the plugins list before they are loaded. """ def __init__(self, decorated_manager=None, categories_filter={"Default":IPlugin}, directories_list=None, plugin_info_ext="yapsy-plugin"): """ """ # Create the base decorator class PluginManagerDecorator.__init__(self,decorated_manager, categories_filter, directories_list, plugin_info_ext) # prepare the mapping of the latest version of each plugin self.rejectedPlugins = [ ] def filterPlugins(self): """ This method goes through the currently available candidates, and and either leaves them, or moves them into the list of rejected Plugins. This method can be overridden if the isPluginOk() sentinel is not powerful enough. """ self.rejectedPlugins = [ ] for candidate_infofile, candidate_filepath, plugin_info in self._component.getPluginCandidates(): if not self.isPluginOk( plugin_info): self.rejectPluginCandidate((candidate_infofile, candidate_filepath, plugin_info) ) def rejectPluginCandidate(self,pluginTuple): """ This is method can be called to mark move a plugin from Candidates list to the rejected List. """ if pluginTuple in self.getPluginCandidates(): self._component.removePluginCandidate(pluginTuple) if not pluginTuple in self.rejectedPlugins: self.rejectedPlugins.append(pluginTuple) def unrejectPluginCandidate(self,pluginTuple): """ This is method can be called to mark move a plugin from the rejected list to into the Candidates List. """ if not pluginTuple in self.getPluginCandidates(): self._component.appendPluginCandidate(pluginTuple) if pluginTuple in self.rejectedPlugins: self.rejectedPlugins.remove(pluginTuple) def removePluginCandidate(self,pluginTuple): if pluginTuple in self.getPluginCandidates(): self._component.removePluginCandidate(pluginTuple) if pluginTuple in self.rejectedPlugins: self.rejectedPlugins.remove(pluginTuple) def appendPluginCandidate(self,pluginTuple): if self.isPluginOk(pluginTuple[2]): if pluginTuple not in self.getPluginCandidates(): self._component.appendPluginCandidate(pluginTuple) else: if not pluginTuple in self.rejectedPlugins: self.rejectedPlugins.append(pluginTuple) def isPluginOk(self,info): """ Sentinel function to detect if a plugin should be filtered. Subclasses should override this function and return false for any plugin which they do not want to be loadable. """ return True def locatePlugins(self): """ locate and filter plugins. """ #Reset Catalogue self.setCategoriesFilter(self._component.categories_interfaces) #Reread and filter. self._component.locatePlugins() self.filterPlugins() return len(self._component.getPluginCandidates()) def getRejectedPlugins(self): return self.rejectedPlugins[:] gecrit-2.8.4/yapsy/IPlugin.py000777 000000 000000 00000002246 12051462410 016054 0ustar00rootroot000000 000000 #!/usr/bin/python # -*- coding: utf-8 -*- """ Role ==== Defines the basic interfaces for a plugin. These interfaces are inherited by the *core* class of a plugin. The *core* class of a plugin is then the one that will be notified the activation/deactivation of a plugin via the ``activate/deactivate`` methods. For simple (near trivial) plugin systems, one can directly use the following interfaces. Extensibility ============= In your own software, you'll probably want to build derived classes of the ``IPlugin`` class as it is a mere interface with no specific functionality. Your software's plugins should then inherit your very own plugin class (itself derived from ``IPlugin``). Where and how to code these plugins is explained in the section about the :doc:`PluginManager`. API === """ class IPlugin(object): """ The most simple interface to be inherited when creating a plugin. """ def __init__(self): """ Set the basic variables. """ self.is_activated = False def activate(self): """ Called at plugin activation. """ self.is_activated = True def deactivate(self): """ Called when the plugin is disabled. """ self.is_activated = False gecrit-2.8.4/yapsy/AutoInstallPluginManager.py000777 000000 000000 00000006615 12051462410 021422 0ustar00rootroot000000 000000 #!/usr/bin/python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- """ Role ==== Defines plugin managers that can handle the installation of plugin files into the right place. Then the end-user does not have to browse to the plugin directory to install them. API === """ import os import logging import shutil from yapsy.IPlugin import IPlugin from yapsy.PluginManagerDecorator import PluginManagerDecorator class AutoInstallPluginManager(PluginManagerDecorator): """ A plugin manager that also manages the installation of the plugin files into the appropriate directory. """ def __init__(self, plugin_install_dir=None, decorated_manager=None, # The following args will only be used if we need to # create a default PluginManager categories_filter={"Default":IPlugin}, directories_list=None, plugin_info_ext="yapsy-plugin"): """ Create the plugin manager and set up the directory where to install new plugins. Arguments ``plugin_install_dir`` The directory where new plugins to be installed will be copied. .. warning:: If ``plugin_install_dir`` does not correspond to an element of the ``directories_list``, it is appended to the later. """ # Create the base decorator class PluginManagerDecorator.__init__(self, decorated_manager, categories_filter, directories_list, plugin_info_ext) # set the directory for new plugins self.plugins_places=[] self.setInstallDir(plugin_install_dir) def setInstallDir(self,plugin_install_dir): """ Set the directory where to install new plugins. """ if not (plugin_install_dir in self.plugins_places): self.plugins_places.append(plugin_install_dir) self.install_dir = plugin_install_dir def getInstallDir(self): """ Return the directory where new plugins should be installed. """ return self.install_dir def install(self, directory, plugin_info_filename): """ Giving the plugin's info file (e.g. ``myplugin.yapsy-plugin``), and the directory where it is located, get all the files that define the plugin and copy them into the correct directory. Return ``True`` if the installation is a success, ``False`` if it is a failure. """ # start collecting essential info about the new plugin plugin_info, config_parser = self._gatherCorePluginInfo(directory, plugin_info_filename) # now determine the path of the file to execute, # depending on wether the path indicated is a # directory or a file if not (os.path.exists(plugin_info.path) or os.path.exists(plugin_info.path+".py") ): logging.warning("Could not find the plugin's implementation for %s." % plugin_info.name) return False if os.path.isdir(plugin_info.path): try: shutil.copytree(plugin_info.path, os.path.join(self.install_dir,os.path.basename(plugin_info.path))) shutil.copy(os.path.join(directory, plugin_info_filename), self.install_dir) except: logging.error("Could not install plugin: %s." % plugin_info.name) return False else: return True elif os.path.isfile(plugin_info.path+".py"): try: shutil.copy(plugin_info.path+".py", self.install_dir) shutil.copy(os.path.join(directory, plugin_info_filename), self.install_dir) except: logging.error("Could not install plugin: %s." % plugin_info.name) return False else: return True else: return False gecrit-2.8.4/pyctags/exuberant.py000777 000000 000000 00000035705 12051462410 017015 0ustar00rootroot000000 000000 ## Copyright (C) 2008 Ben Smith ## This file is part of pyctags. ## pyctags is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## pyctags is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU Lesser General Public License ## and the GNU Lesser General Public Licens along with pyctags. If not, ## see . """ Exuberant Ctags (U{http://ctags.sourceforge.net}) wrapper. This module uses the subprocess.Popen function. Users of this module could pass arbitrary commands to the system. """ import subprocess, os, sys from copy import copy try: # do relative imports for tests # try this first in case pyctags is already installed, since we want to be testing the source bundled in the distribution from tag_base import ctags_base from kwargs_validator import the_validator as validator from tag_file import ctags_file except ImportError: from pyctags.tag_base import ctags_base from pyctags.kwargs_validator import the_validator as validator from pyctags import ctags_file class exuberant_ctags(ctags_base): """ Wraps the Exuberant Ctags program. U{http://ctags.sourceforge.net} The B{generate_tags} and B{generate_tagfile} methods will accept custom command line parameters for exuberant ctags via the generator_options keyword dict. The Exuberant Ctags output flags (-f and -o) are reserved for internal use and will trigger an exception. """ __version_opt = "--version" __list_kinds_opt = "--list-kinds" __argless_args = ["--version", "--help", "--license", "--list-languages", "-a", "-B", "-e", "-F", "-n", "-N", "-R", "-u", "-V", "-w", "-x"] __default_opts = {"-L" : "-", "-f" : "-"} __exuberant_id = "exuberant ctags" __supported_versions = ["5.7", "5.6b1"] __warning_str = ": Warning:" def __init__(self, *args, **kwargs): """ Wraps the Exuberant Ctags program. - B{Keyword Arguments:} - B{tag_program:} (str) path to ctags executable, or name of a ctags program in path - B{files:} (sequence) files to process with ctags """ valid_kwargs = ['tag_program', 'files'] validator.validate(kwargs.keys(), valid_kwargs) self.version = None """ Exuberant ctags version number.""" self.language_info = None """ Exuberant ctags supported language parsing features.""" ctags_base.__init__(self, *args, **kwargs) def __process_kinds_list(self, kinds_list): """ Slice n dice the --list-kinds output from exuberant ctags.""" d = dict() key = "" for k in kinds_list: if len(k): if k[0].isspace(): if len(key): kind_info = k.strip().split(' ') if len(kind_info) > 2: raise ValueError("Kind information is in an unexpected format.") d[key][kind_info[0]] = kind_info[1] else: key = k.strip().lower() if key not in d: d[key] = dict() return d def _query_tag_generator(self, path): """ Gets Exuberant Ctags program information. @raise ValueError: No valid ctags executable set. @raise TypeError: Executable is not Exuberant Ctags. """ shell_str = path + ' ' + self.__version_opt p = subprocess.Popen(shell_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (out, err) = p.communicate() outstr = out.decode("utf-8") if outstr.lower().find(self.__exuberant_id) < 0: raise TypeError("Executable file " + str(self._executable_path) + " is not Exuberant Ctags") comma = outstr.find(',') self.version = outstr[len(self.__exuberant_id):comma].strip() if self.version not in self.__supported_versions: #print("Version %s of Exuberant Ctags isn't known to work, but might." % (self.version)) pass # find out what this version of ctags supports in terms of language and kinds of tags p = subprocess.Popen(path + ' ' + self.__list_kinds_opt, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (out, err) = p.communicate() self.language_info = self.__process_kinds_list(out.decode("utf-8").splitlines()) def _dict_to_args(self, gen_opts): """ Converts from a dict with command line arguments to a string to feed exuberant ctags on the comand line. @param gen_opts: command line arguments, key=argument, value=setting @type gen_opts: dict @rtype: str """ # because yargs sounds like a pirate yargs = "" for k, v in gen_opts.items(): if k in self.__argless_args: yargs += k + ' ' continue if k[0:2] == '--': # long opt yargs += k + '=' + v elif k[0] == '-': # short opt yargs += k + ' ' + v + ' ' return yargs def _prepare_to_generate(self, kw): """ Prepares parameters to be passed to exuberant ctags. @returns: tuple (generator_options_dict, files_str) """ input_file_override = False self.warnings = list() if 'generator_options' in kw: if '-f' in kw['generator_options'] or '-o' in kw['generator_options']: raise ValueError("The options -f and -o are used internally.") if '-L' in kw['generator_options']: input_file_override = True if 'tag_program' in kw: if self.ctags_executable(kw['tag_program']): self._executable_path = kw['tag_program'] if 'files' in kw: self._file_list = list(kw['files']) if not self._executable_path: if self.ctags_executable('ctags'): self._executable_path = 'ctags' else: raise ValueError("No ctags executable set.") gen_opts = copy(self.__default_opts) if 'generator_options' in kw: gen_opts.update(kw['generator_options']) file_list = '' if not input_file_override: for f in self._file_list: file_list += f + os.linesep return (gen_opts, file_list) def generate_tags(self, **kwargs): """ Parses source files into list of tags. - B{Keyword Arguments:} - B{tag_program:} (str) path to ctags executable, or name of a ctags program in path - B{files:} (sequence) files to process with ctags - B{generator_options:} (dict) command-line options to pass to ctags program @returns: strings output by exuberant ctags @rtype: list @raise ValueError: ctags executable path not set, fails execution """ valid_kwargs = ['tag_program', 'files', 'generator_options'] validator.validate(kwargs.keys(), valid_kwargs) (gen_opts, file_list) = self._prepare_to_generate(kwargs) tag_args = self._dict_to_args(gen_opts) self.command_line = self._executable_path + ' ' + tag_args p = subprocess.Popen(self.command_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (out, err) = p.communicate(input=file_list.encode()) if p.returncode != 0: raise ValueError("Ctags execution did not complete, return value: " + p.returncode + ".\nCommand line: " + self.command_line) results = out.decode("utf-8").splitlines() if sys.platform == 'win32': # check for warning strings in output if self._executable_path.rfind("/") >= 0: shortname = self._executable_path[self._executable_path.rfind("/"):] elif self._executable_path.rfind("\\") >= 0: shortname = self._executable_path[self._executable_path.rfind("\\"):] else: shortname = self._executable_path idxs = [] i = 0 for r in results: if r.find(shortname + self.__warning_str) == 0: idxs.append(i) i += 1 # reverse the list so we don't mess up index numbers as we're removing them idxs.sort(reverse=True) for i in idxs: self.warnings.append(results.pop(i)) else: self.warnings = err.decode("utf-8").splitlines() return results def generate_tagfile(self, output_file, **kwargs): """ Generates tag file from list of files. - B{Keyword Arguments:} - B{tag_program:} (str) path to ctags executable, or name of a ctags program in path - B{files:} (sequence) files to process with ctags - B{generator_options:} (dict) options to pass to ctags program @param output_file: File name and location to write tagfile. @type output_file: str @returns: file written @rtype: boolean @raise ValueError: ctags executable path not set or output file isn't valid """ valid_kwargs = ['tag_program', 'files', 'generator_options'] validator.validate(kwargs.keys(), valid_kwargs) # exuberant ctags 5.7 chops 'def' off the beginning of variables, if it starts with def _default_output_file = 'tags' if 'generator_options' in kwargs: if '-e' in kwargs['generator_options']: _default_output_file.upper() if output_file: if output_file != "-": if os.path.isdir(output_file): output_file = os.path.join(output_file, _default_output_file) else: (head, tail) = os.path.split(output_file) if len(head) == 0 and len(tail) == 0: raise ValueError("No output file set") if len(head) != 0: if not os.path.isdir(head): raise ValueError("Output directory " + head + " does not exist.") else: raise ValueError("No output file set") (gen_opts, file_list) = self._prepare_to_generate(kwargs) gen_opts['-f'] = '"' + output_file + '"' tag_args = self._dict_to_args(gen_opts) self.command_line = self._executable_path + ' ' + tag_args p = subprocess.Popen(self.command_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (out, err) = p.communicate(input=file_list.encode()) if sys.platform == 'win32': self.warnings = out.decode("utf-8").splitlines() else: self.warnings = err.decode("utf-8").splitlines() if (p.returncode == 0): return True return False def generate_object(self, **kwargs): """ Parses source files into a ctags_file instance. This method exists to avoid storing ctags generated data in an intermediate form before parsing. According to python documentation, this mechanism could deadlock due to other OS pipe buffers filling and blocking the child process. U{http://docs.python.org/library/subprocess.html} - B{Keyword Arguments:} - B{tag_program:} (str) path to ctags executable, or name of a ctags program in path - B{files:} (sequence) files to process with ctags - B{generator_options:} (dict) options to pass to ctags program - B{harvesters:} (list) list of harvester data classes for ctags_file to use while parsing @returns: generated instance of ctags_file on success, None on failure @rtype: (ctags_file or None) @raise ValueError: ctags executable path not set """ valid_kwargs = ['tag_program', 'files', 'generator_options', 'harvesters'] validator.validate(kwargs.keys(), valid_kwargs) (gen_opts, file_list) = self._prepare_to_generate(kwargs) tag_args = self._dict_to_args(gen_opts) tagfile = ctags_file() harvesters = list() if 'harvesters' in kwargs: harvesters = kwargs['harvesters'] tagfile.feed_init(harvesters=harvesters) self.command_line = self._executable_path + ' ' + tag_args p = subprocess.Popen(self.command_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.stdin.write(file_list.encode()) # is this the cleanest way to do this? it makes the program execute, but I haven't found another way p.stdin.close() if sys.platform == "win32": if self._executable_path.rfind("/") >= 0: shortname = self._executable_path[self._executable_path.rfind("/"):] elif self._executable_path.rfind("\\") >= 0: shortname = self._executable_path[self._executable_path.rfind("\\"):] else: shortname = self._executable_path while p.poll() is None: line = p.stdout.readline().decode("utf-8") if not len(line): continue if sys.platform == 'win32' and line.find(shortname + self.__warning_str) == 0: self.warnings.append(line) else: tagfile.feed_line(line) # process the remaining buffer for line in p.stdout.read().decode("utf-8").splitlines(): if not len(line): continue if sys.platform == 'win32' and line.find(shortname + self.__warning_str) == 0: self.warnings.append(line) else: tagfile.feed_line(line) if sys.platform != 'win32': self.warnings = p.stderr.read().decode("utf-8").splitlines() tagfile.feed_finish() if p.returncode == 0: return tagfile else: return None gecrit-2.8.4/yapsy/__init__.py000777 000000 000000 00000010537 12051462410 016246 0ustar00rootroot000000 000000 """ Overview ======== Yapsy's main purpose is to offer a way to easily design a plugin system in Python, and motivated by the fact that many other Python plugin system are either too complicated for a basic use or depend on a lot of libraries. Yapsy only depends on Python's standard library. |yapsy| basically defines two core classes: - a fully functional though very simple ``PluginManager`` class - an interface ``IPlugin`` which defines the interface of plugin instances handled by the ``PluginManager`` Getting started =============== The basic classes defined by |yapsy| should work "as is" and enable you to load and activate your plugins. So that the following code should get you a fully working plugin management system:: from yapsy.PluginManager import PluginManager # Build the manager simplePluginManager = PluginManager() # Tell it the default place(s) where to find plugins simplePluginManager.setPluginPlaces(["path/to/myplugins"]) # Load all plugins simplePluginManager.collectPlugins() # Activate all loaded plugins for pluginInfo in simplePluginManager.getAllPlugins(): simplePluginManager.activatePluginByName(pluginInfo.name) .. _extend: Extensibility ============= For applications that require the plugins and their managers to be more sophisticated, several techniques make such enhancement easy. The following sections detail the three most frequent needs for extensions and what you can do about it. More sophisticated plugin classes --------------------------------- You can define a plugin class with a richer interface that ``IPlugin``, so long as it inherits from IPlugin, it should work the same. The only thing you need to know is that the plugin instance is accessible via the ``PluginInfo`` instance from its ``PluginInfo.plugin_object``. It is also possible to define a wider variety of plugins, by defining as much subclasses of IPlugin. But in such a case you have to inform the manager about that before collecting plugins:: # Build the manager simplePluginManager = PluginManager() # Tell it the default place(s) where to find plugins simplePluginManager.setPluginPlaces(["path/to/myplugins"]) # Define the various categories corresponding to the different # kinds of plugins you have defined simplePluginManager.setCategoriesFilter({ "Playback" : IPlaybackPlugin, "SongInfo" : ISongInfoPlugin, "Visualization" : IVisualisation, }) Enhance the manager's interface ------------------------------- To make the plugin manager more helpful to the other components of an application, you should consider decorating it. Actually a "template" for such decoration is provided as :doc:`PluginManagerDecorator`, which must be inherited in order to implement the right decorator for your application. Such decorators can be chained, so that you can take advantage of the ready-made decorators such as: :doc:`ConfigurablePluginManager` Implements a ``PluginManager`` that uses a configuration file to save the plugins to be activated by default and also grants access to this file to the plugins. :doc:`AutoInstallPluginManager` Automatically copy the plugin files to the right plugin directory. Modify the way plugins are loaded --------------------------------- To tweak the plugin loading phase it is highly advised to re-implement your own manager class. The nice thing is, if your new manager inherits ``PluginManager``, then it will naturally fit as the start point of any decoration chain. You just have to provide an instance of this new manager to the first decorators, like in the following:: # build and configure a specific manager baseManager = MyNewManager() # start decorating this manager to add some more responsibilities myFirstDecorator = AFirstPluginManagerDecorator(baseManager) # add even more stuff mySecondDecorator = ASecondPluginManagerDecorator(myFirstDecorator) .. note:: Some decorators have been implemented that modify the way plugins are loaded, this is however not the easiest way to do it and it makes it harder to build a chain of decoration that would include these decorators. Among those are :doc:`VersionedPluginManager` and :doc:`FilteredPluginManager` """ # tell epydoc that the documentation is in the reStructuredText format __docformat__ = "restructuredtext en" gecrit-2.8.4/locale/pl/000777 000000 000000 00000000000 12051462410 014631 5ustar00rootroot000000 000000 gecrit-2.8.4/gecrit.desktop000777 000000 000000 00000000416 12051462410 015633 0ustar00rootroot000000 000000 [Desktop Entry] Version=1.0 Type=Application Terminal=false Icon[fr_CA]=gnome-panel-launcher Name[fr_CA]=gEcrit Exec=gecrit Comment[fr_CA]=A python text editor. Categories=Development;IDE;GTK; Icon=/usr/share/pixmaps/gEcrit.png Name=gEcrit Comment=A python text editor. gecrit-2.8.4/data/plugins/HtmlConverter.py000777 000000 000000 00000006160 12051462410 020525 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- #!/usr/bin/python # -*- coding: utf-8 -*- import wx import yapsy.IPlugin from data.plugins.categories import General class HtmlConverter(General, yapsy.IPlugin.IPlugin): def __init__(self): self.name = "HTML Converter" def Init(self, parent): self.parent = parent self.current_doc = None self.plugins_menu = wx.Menu() convert_entry = self.plugins_menu.Append(-1,"Convert File") self.menu_item = self.parent.AddToMenuBar("HTML Converter ", self.plugins_menu) self.parent.BindMenubarEvent(convert_entry, self.ToHtmlHelper) def ToHtmlHelper(self,event): save_path = wx.FileDialog(None, style=wx.SAVE) if save_path.ShowModal() == wx.ID_OK: html_file = open(save_path.GetPath(),"w") html_file.write(self.ToHTML()) html_file.close() def ToHTML(self): """ ToHTML Formats the document text to HTML form. Returns it. """ text = self.current_doc.GetText().replace('&', "&").replace('<', "<").replace('>', ">") if self.current_doc.GetLineCount(): text = "100000" + text.replace(' ', "  ") x = 0 l = len(text) line = 2 n = "" while x < l: if text[x] == "\n": n = n + "\n" + str(line) if line < 10: n = n + "00000" elif line < 100: n = n + "0000" elif line < 1000: n = n + "000" else: n = n + "00" line = line + 1 else: n = n + text[x] x = x + 1 text = n thehtml = \ "" + \ text.replace("\n", "\n
") + "" return thehtml def NotifyTabChanged(self): try: #the tab change event is produced prematurely self.current_doc = self.parent.GetCurrentDocument() except: pass def Stop(self): self.parent.RemoveFromMenubar(self.menu_item) gecrit-2.8.4/data/plugins/PyTidyFormatter.yapsy-plugin000777 000000 000000 00000000347 12051462410 023051 0ustar00rootroot000000 000000 [Core] Name = PyTidy Module = PyTidyFormatter [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Formats python source code using the well known Python Tidy script. gecrit-2.8.4/icons/quit.bmp000777 000000 000000 00000006066 12051462410 015567 0ustar00rootroot000000 000000 BM6 6(    ~~~~>>>???@@@CCC@@@@ABK?4JB:A?<@FH+8@- $</M7Y:_:O 0C"5#325BEAKG>FE?AAA@CA;5;>*:(GcJs@p7k/d&\"c/m=q3\}4T#?-2G?>KEAFLEEHDBBBBDDDFFFBBBDDDCCCCCCFFFEDC6DR1C;XuMwI7t/n'f#_!\%a$a+j8u=tCr=`'>7=ID?DFBCEEEAAA===IIIDDEDDDEEDFED<83 0[>f38?CBDFEFCCDFFFJEEKDAEBA8@I'>V ?_"a-h1l2n9y3w-r(l"`X_%g/p3s7xDD[T~E'yBA~FLUoj.E19;EHG@=:JFEGDC=CI2HUy?m#h!a(b3jCz']4i5h =k :c :i 8h4d@sZDU\t߄f'8:=IDDJJFE@BD/V/4FABMHFD=CK/E`E}-p2r5r4k5a0X 8c,Z4cL{JvI{,^.] 5d-]3fmՌ"2<>GDFE*7C`}[A2{@{?w5e4_-W :h/dF0j#\,g=w;p ;i1^/\]xvc]]Lv)T!M8gWE6t!`9u'^@{cϞb$I D&2DQJlyklt+S}I)VkeTNIEx:i F!KCo+F0CQRvxz冸8bK7a{݂}灱Lx45U؜ܒ֍C M'N}zw폷!;Y3AS_|/?gE6S Bh$8(Zrebfr@F'Gu|ktꉲ%;Q9CPbxao5"A0X"3)ZQLK[S7;/Zpbgხ+@@FLUbq26sm-U /"QE{=?L-T|2,XWYcz0DFHCIP 8;@퍼mW*S'!P7p=;|b9 0.jWNaZ&7FEE146(B`4 0/>`bK $P)I?v8l[J2 +8UvnOR[5^&8GFEF8m6  " 1FwFPMjUz(?>GLFFEAAB>GLex` 2$%LvS C!F;i,N=@iDBE`c0K2?LBCDIFCGD?GHH-8ǧpn}dFtTEs =?+]>h=e1FP.Mc>fmpTI{GQR{4Ot-8V//DE?HNECLG9MJ6HH;CCCBBBAAAFFFDDDDDDDDDDDDCCCMEFD>@C@C=X:L1B 1>28DEBIUKQE;=GBADC@=B>DGECCCDDDBBB^^^ffffffffffffefegaljblldjmcgrehqeepddoeemdfibejeelhfkfckhblhbge`hhgcehbdn\ao`ckgggdddfffgecrit-2.8.4/pyctags/kwargs_validator.py000777 000000 000000 00000003342 12051462410 020353 0ustar00rootroot000000 000000 ## Copyright (C) 2008 Ben Smith ## This file is part of pyctags. ## pyctags is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## pyctags is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU Lesser General Public License ## and the GNU Lesser General Public Licens along with pyctags. If not, ## see . """ A simple validator to make sure keyword arguments are valid. """ class ParameterError(Exception): """ Raised if an invalid argument is passed to kwargs_validator. """ def __init__(self, value): self.value = value def __str__(self): return str(self.value) class kwargs_validator: """ Used to validate arguments. """ def validate(self, args, allowed_args): """ @param args: arguments to check for validity. @type args: iterable @param allowed_args: list of valid arguments. @type allowed_args: list @raises ParameterError: if an element of args is not in allowed_args. """ for arg in args: if arg not in allowed_args: raise ParameterError("Parameter " + arg + " is not accepted by calling function.") the_validator = kwargs_validator()gecrit-2.8.4/pyctags/harvesters.py000777 000000 000000 00000020650 12051462410 017177 0ustar00rootroot000000 000000 ## Copyright (C) 2008 Ben Smith ## This file is part of pyctags. ## pyctags is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published ## by the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## pyctags is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU Lesser General Public License ## and the GNU Lesser General Public Licens along with pyctags. If not, ## see . """ Classes that process tag data to collect information.""" from copy import copy try: # do relative imports for tests # try this first in case pyctags is already installed, since we want to be testing the source bundled in the distribution from kwargs_validator import the_validator as validator except ImportError: from pyctags.kwargs_validator import the_validator as validator class base_harvester: """ This class definition outlines the basic interface for harvesting classes.""" def do_before(self): """ Called before any entries are processed with self.feed().""" pass def feed(self, entry): """ Called once per ctags_entry. @param entry: a tag entry to process. @type entry: ctags_entry """ pass def do_after(self): """ Called after all ctags_entry instances are processed with self.feed().""" pass def get_data(self): """ Used to retrieve derived-class specific harvested data.""" pass def process_tag_list(self, taglist): """ Allows processing of a list of ctags_entry instances without an associated ctags_file. @param taglist: list of ctags_entry instances @type taglist: list """ self.do_before() for tag in taglist: self.feed(tag) self.do_after() class kind_harvester(base_harvester): """ Harvests exuberant ctags' extended "kind" information, such as class, member, variable, etc.""" def __init__(self): self.kinds = {} def feed(self, entry): """ Organizes data into a dict with kind as the keys, values are a list of entries of that kind. @param entry: entry to process @type entry: ctags_entry """ if 'kind' in entry.extensions: # note: case sensitive output from exuberant ctags entkey = entry.extensions['kind'] if entkey not in self.kinds: self.kinds[entkey] = list() self.kinds[entkey].append(entry) def get_data(self): """ Gets the dict built with self.feed(). Dict keys are tag kinds, values are lists of ctags_entry instances sporting that kind. @returns: tag data organized by exuberant ctags kind @rtype: dict """ return self.kinds class by_name_harvester(base_harvester): """ Organizes tags by name.""" def __init__(self): self.names = dict() def feed(self, entry): """ Builds a ctags_entry.name keyed dict. """ if entry.name not in self.names: self.names[entry.name] = list() self.names[entry.name].append(entry) def get_data(self): """ Gets the name-organized data. @returns: entries organized with entry.name as key, value is a list of ctags_entry instances that correspond to entry.name @rtype: dict """ return self.names class name_lookup_harvester(base_harvester): """ Builds a sorted list of unique tag names.""" def __init__(self): self.__unique_names = dict() self.__sorted_names = list() self.__name_index = dict() def __len__(self): """ Number of unique tag names found.""" return len(self.__sorted_names) def feed(self, entry): """ Records unique names. @param entry: the entry to collect the name from. @type entry: ctags_entry """ # use dict characteristic of unique keys instead of testing if the key is already there self.__unique_names[entry.name] = None def do_after(self): """ Process the unique names into a form easier to query.""" self.__sorted_names = list(self.__unique_names.keys()) self.__sorted_names.sort() i = 0 prev_char = self.__sorted_names[0][0] self.__name_index[prev_char] = {'first' : 0} for f in self.__sorted_names: if f[0] not in self.__name_index: self.__name_index[prev_char]['last'] = i - 1 self.__name_index[f[0]] = {'first' : i} prev_char = f[0] i += 1 self.__name_index[prev_char]['last'] = i def starts_with(self, matchstr, **kwargs): """ Fetches an alphabetical list of unique tag names that begin with matchstr. - B{Parameters:} - B{matchstr:} (str) string to search for in tags db - B{Keyword Arguments:} - B{num_results:} (int) maximum number of results to return, 0 for all, default - B{case_sensitive:} (bool) whether to match case, default False @returns: matching tag names @rtype: list """ valid_kwargs = ['num_results', 'case_sensitive'] validator.validate(kwargs.keys(), valid_kwargs) final_list = [] case_sensitive = False num_results = 0 if 'num_results' in kwargs: num_results = int(kwargs['num_results']) if len(matchstr) == 0: if num_results: return self.__sorted_names[0:num_results] return self.__sorted_names[:] if 'case_sensitive' in kwargs: if kwargs['case_sensitive']: case_sensitive = True tag_names_that_start_with_char = [] if case_sensitive: if matchstr[0] not in self.__name_index: return [] else: if matchstr[0].lower() not in self.__name_index and matchstr[0].upper() not in self.__name_index: return [] if case_sensitive: idxs = self.__name_index[matchstr[0]] if idxs['first'] == idxs['last'] + 1: tag_names_that_start_with_char = self.__sorted_names[idxs['first']] else: tag_names_that_start_with_char = self.__sorted_names[idxs['first']:idxs['last'] + 1] else: if matchstr[0].lower() in self.__name_index: idxs = self.__name_index[matchstr[0].lower()] if idxs['first'] == idxs['last'] + 1: tag_names_that_start_with_char = self.__sorted_names[idxs['first']] else: tag_names_that_start_with_char = self.__sorted_names[idxs['first']:idxs['last'] + 1] if matchstr[0].upper() in self.__name_index: idxs = self.__name_index[matchstr[0].upper()] if idxs['first'] == idxs['last'] + 1: tag_names_that_start_with_char += [self.__sorted_names[idxs['first']]] else: tag_names_that_start_with_char += self.__sorted_names[idxs['first']:idxs['last'] + 1] if len(matchstr) == 1: if num_results == 0: return tag_names_that_start_with_char[:] else: return tag_names_that_start_with_char[0:num_results] if case_sensitive: for t in tag_names_that_start_with_char: if (t.find(matchstr) == 0): final_list.append(copy(t)) if num_results > 0 and len(final_list) == num_results: return final_list else: for t in tag_names_that_start_with_char: if (t.lower().find(matchstr.lower()) == 0): final_list.append(copy(t)) if num_results > 0 and len(final_list) == num_results: return final_list return final_list gecrit-2.8.4/data/plugins/TaskKeeper.py000777 000000 000000 00000006307 12051462410 017772 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . #!/usr/bin/python # -*- coding: utf-8 -*- import wx import yapsy.IPlugin from data.plugins.categories import General class TaskKeeper(wx.Panel ,General , yapsy.IPlugin.IPlugin): def __init__(self): self.name = "Task Keeper" def Init(self, parent): self.parent = parent self.documents = None self.documents_tasks = {} self.key_words = ["#TODO","#FIXME","#HACK","#BUG"] wx.Panel.__init__(self, self.parent.GetBottomPanel()) self.sizer = wx.BoxSizer(wx.VERTICAL) self.tasks = wx.ListCtrl(self, style = wx.LC_REPORT) self.tasks.InsertColumn(0, "File") self.tasks.InsertColumn(1, "Line") self.tasks.InsertColumn(2, "Type") self.tasks.InsertColumn(3, "Task") self.tasks.SetColumnWidth(3, 400) self.sizer.Add(self.tasks, 1 ,wx.EXPAND) self.SetSizer(self.sizer) self.Fit() self.parent.AddToBottomPanel(self, "Task Keeper") #self.PopulateList() def PopulateList(self): self.tasks.DeleteAllItems() try: for d in self.documents: lst = self.CollectTasks(d.GetFileName(), d.GetText()) self.documents_tasks[d] = lst except: pass garbage = [] # quick hack for i in self.documents: for j in self.documents_tasks: for k in self.documents_tasks[j]: for l in k: if l not in garbage: self.tasks.Append(l) garbage.append(l) def CollectTasks(self, doc_name ,text): lines = text.splitlines() tasks = [] lnr = 1 for line in lines: z = 0 for t in self.key_words: task = [] if t in line: task.append([doc_name, lnr, self.key_words[z], line.split(self.key_words[z])[-1]]) if task: tasks.append(task) z += 1 lnr += 1 return tasks def NotifyDocumentOpened(self): self.Notify() def NotifyDocumentSaved(self): self.Notify() def Notify(self): self.documents = self.parent.GetAllDocuments() cur_doc = self.parent.GetCurrentDocument() try: self.documents_tasks[cur_doc] except: self.documents_tasks[cur_doc] = [] self.PopulateList() def Stop(self): self.parent.DeleteBottomPage(self.name) gecrit-2.8.4/data/plugins/PastebinDialog.yapsy-plugin000777 000000 000000 00000000332 12051462410 022622 0ustar00rootroot000000 000000 [Core] Name = Pastebin.com Uploader Module = PastebinDialog [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Uploads the text buffer to pastebin.com gecrit-2.8.4/gEcritSession.py000777 000000 000000 00000007077 12051462410 016130 0ustar00rootroot000000 000000 # Copyright (C) 2011 Groza Cristian # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import cPickle import os import Exceptions class gEcritSession: """ gEcritSession This class represents the saved state of the gEcrit application. It stores and manages information such as open documents, GUI perspective and current selected tab. """ __session_dump_path = os.path.join(os.path.expanduser("~"), ".config" ,".gEcrit", "session.gecrit") def __init__(self): """ __init__ Basic constructor. """ self.opened_files = [] self.layout_perspective = "" self.current_tab = 0 self.current_positions = [] def RecordAppState(self, app_instance): """ RecordAppState Saves the state of the application. The data it collects is: open documents, GUI perspective, current selected tab. """ self.opened_files = [] documents = app_instance.GetAllDocuments() for d in documents: if d is not None: if d.GetFilePath(): self.opened_files.append(d.GetFilePath()) self.current_positions.append(d.GetCurrentPos()) self.layout_perspective = app_instance.GetAuiManager().SavePerspective() self.current_tab = app_instance.GetTabManager().GetSelection() if self.current_tab < 0: self.current_tab = 0 def RestoreAppState(self, app_instance): """ RestoreAppState Restores the open documents, the GUI perspective and selected document. """ app_instance.OpenFile(self.opened_files) app_instance.GetAuiManager().LoadPerspective(self.layout_perspective) app_instance.GetTabManager().SetSelection(self.current_tab) cur_doc = app_instance.GetCurrentDocument() if cur_doc != None: cur_doc.SetFocus() i = 0 for d in app_instance.GetAllDocuments(): d.GotoPos(self.current_positions[i]) i += 1 def SaveToFile(self): """ SaveToFile Serializes and saves this object to file. """ dump_file = open(gEcritSession.__session_dump_path, "w") cPickle.dump(self, dump_file) @staticmethod def LoadFromFile(): """ LoadFromFile Loads the serialized object of this class. If it does not exist, throws NoSessionFile exception. """ if os.path.exists(gEcritSession.__session_dump_path): session_file = open(gEcritSession.__session_dump_path, "r") return cPickle.load(session_file) else: raise Exceptions.NoSessionFile @staticmethod def DeleteSessionFile(event): """ DeleteSessionFile Deletes the file where this object is serialized. """ if os.path.exists(gEcritSession.__session_dump_path): os.remove(gEcritSession.__session_dump_path) gecrit-2.8.4/data/plugins/Notes.yapsy-plugin000777 000000 000000 00000000354 12051462410 021031 0ustar00rootroot000000 000000 [Core] Name = Notes Module = Notes [Documentation] Author = Groza Cristian Version = 0.1 Website = http://www.sourceforge/projects/gecrit Description = Provides a simple way to write down your ideas and save them for the next session.