Пример #1
0
def get_search(options):
    input_text = epp.readline()

    if len(input_text.strip()) > 0:
        return input_text
    else:
        epp.log(options.filename)
        return epp.getCurrWord(options.filename, options.cursor)
Пример #2
0
 def handle_key_press(self, event):
     epp.log(event.keysym)
     cur_element = self.get_selection()
     if cur_element != None:
         if event.keysym in ("Return", "<Return>", "Enter", "<Enter>"):
             # Entrée -> même action que le bouton Ok
             self.handle_word(event)
         elif event.char != '':
             # Autre touche -> choix + caractère correspondant à la touche
             self.choix = cur_element + event.char
             self.quit()
Пример #3
0
 def create_tab(self, tab_name):
     if not tab_name in self.tabIndexes:
         listBox = tk.Listbox(self, selectmode=tk.BROWSE, activestyle="none")
         listBox.configure(font=("Courier New", "8"))
         listBox.bind("<Double-Button-1>", self.handle_word)
         
         self.notebook.add(listBox, text=tab_name)
         
         tabID = len(self.tabIndexes)
         self.tabIndexes[tab_name] = tabID
         epp.log("Tabs : {0}".format(self.tabIndexes))
         
         self.arrListBox.append(listBox)
     else:
         tabID = self.tabIndexes[tab_name]
         
     return tabID
def get_language_words(search, language):
    # Retourne la liste des mots candidat correspondant au langage
    # Les mots sont stockés dans un fichier de ce type : ./language_words/[language].words
    language_file = path.join(epp.getcwd(), "language_words", language + ".words")
    
    if path.exists(language_file):
        epp.log("language file Ok : %s" % language_file)
        candidates = Candidate.Candidates()
        r1 = get_regex(search)
        
        # Parcours du fichier du langage pour trouver les candidats
        with open(language_file, "r") as fileh:
            for match in [r1.findall(l) for l in fileh]:
                candidates.extend(match, is_language_word=True)
        
        return set(candidates.get_list())
    else:
        return set()
Пример #5
0
def main(argv):
    parser = optparse.OptionParser()
    parser.add_option("-p","--project",action="store",type="string",dest="project",help="Project file")
    parser.add_option("-f","--file",action="store",type="string",dest="file",help="Current file (if no project are found)")
    parser.add_option("-m","--markers",action="store",type="string",dest="markers",help="Marker to search for, comma separated")
    
    parser.set_defaults(markers='TODO')
    
    (options, args) = parser.parse_args(argv)
    
    epp.log("project file: %s, current file: %s, markers: %s" % (options.project, options.file, options.markers))
    
    # Commentaires gérés : //, /*, #, --, '
    r1 = re.compile(r"(?://|/\*|#|--|')\s*(" + options.markers.replace(',', '|') + r")\s*:?\s+(.*)\s*$", re.IGNORECASE)
    epp.log ("r1 : %s" % r1.pattern)
    
    if options.project or options.file:
        if options.project:
            files = epp.getProjectFiles(options.project)
        else:
            files = (options.file,)
        for f in files:
            epp.log(f)
            if path.exists(f):
                with open(f, 'r') as fileh:
                    l_num = 1
                    for l in fileh:
                        match = r1.search(l)
                        if (match):
                            epp.print(("[%s] %s:%d %s" % ( match.group(1), f, l_num, match.group(2).strip() )))
                        l_num = l_num + 1
    else: 
        # On provoque une erreur
        parser.error('project') 
        sys.exit(1)
def get_search(fileh, pos):
    # TODO La methode boggue parfois, et ne renvoie pas toutes les lettres (espaces à la place)...
    # Verification de l'encodage    
    epp.log("pos : %d" % pos)
    
    search = ""
    
    f_tell = fileh.tell
    f_read = fileh.read
    f_seek = fileh.seek
    
    # On recule de 1 caractères par rapport à la position d'origine
    seek_pos = f_seek(pos - 1)
    
    while seek_pos >= 0:
        f_seek(seek_pos)
        char = f_read(1)
        
        epp.log(char)
        if char in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$@_":
            search = char + search
            # on recule de 1 caractère
            seek_pos = seek_pos - 1
        else:
            epp.log("!")
            break
    
    return search
Пример #7
0
def main(argv):
    parser = optparse.OptionParser()
    parser.add_option("-p", "--project", action="store", type="string", dest="project", help="Project file")
    parser.add_option("-s", "--selection", action="store", type="string", dest="selection", help="Current selection")

    parser.set_defaults(selection="")
    (options, args) = parser.parse_args(argv)
    
    epp.log("project file: {0:>s}, current selection: {1:>s}".format(options.project, options.selection))
    
    if options.project:
        files = epp.getProjectFiles(options.project)
        
        app = TkFastOpen(availableFiles=files, selection=options.selection)
        app.mainloop()
    
        if app.chosenFile != None:
            # Open the file with EPP
            epp.openWithEPP(app.chosenFile)
        
    else:
        # On provoque une erreur
        if not options.project: parser.error('project')
        sys.exit(1)
Пример #8
0
 def add_words(self, wordObjs, addSeparator=False, tabName='Default'):
     # Cree l'onglet si il n'existe pas, ou retourne l'onglet existant de meme nom
     tabID = self.create_tab(tabName)
     epp.log("Adding words to tab {0} (ID {1})".format(tabName, tabID))
     
     listBox = self.get_tab_listbox(tabID)
     
     # Ajoute une sequence de mots à la liste
     if addSeparator and listBox.size() > 0 and len(wordObjs) > 0:
         listBox.insert(tk.END, self.__separator)
         self.wordsList.append(None)
     for wordObj in wordObjs:
         if isinstance(wordObj, str):
             wordObj = Struct(string=wordObj, infos="")
         
         listBox.insert(tk.END, "%-30s|%s" % (wordObj.string, wordObj.infos))
         
         # Mot du langage en couleur
         if hasattr(wordObj, "color"):
             listBox.itemconfig(len(self.wordsList), fg=wordObj.color)
         
         self.wordsList.append(wordObj)
         
     listBox.select_set(0)
Пример #9
0
def main(argv):
    parser = optparse.OptionParser()
    parser.add_option("-f","--file",action="store",type="string",dest="file",help="File to search")
    parser.add_option("-p","--project",action="store",type="string",dest="project",help="Project file to search")
    parser.add_option("-b","--basedir",action="store",type="string",dest="basedir",help="Base directory to search")
    parser.add_option("-m","--filemask",action="store",type="string",dest="filemask",help="Limit search to file mask")
    parser.add_option("-i","--ignore-case",action="store_true",dest="ignore_case",help="Ignore case")
    parser.add_option("","--interactive",action="store_true",dest="interactive",help="Use dialogs to define search options")
    
    parser.set_defaults(ignore_case=False, interactive=False)
    
    (options, args) = parser.parse_args(argv)
    
    epp.log("project file: %s, file : %s, ignore_case: %s" % (options.project, options.file, options.ignore_case))
    
    input_text = sys.stdin.readline()
    epp.log("-> %s" % input_text)
    
    if options.ignore_case:
        case_flag = re.IGNORECASE 
    else: 
        case_flag = 0
    
    if options.interactive:
        epp.print("test")
    elif (options.project or options.file or options.basedir) and input_text.strip() != '':
        if (options.project):
            files = epp.getProjectFiles(options.project)
        if (options.basedir):
            files = epp.getFilesInTree(options.basedir, options.filemask)
        elif (options.file):
            files = [options.file]
        
        for f in files:
            if path.exists(f):
                try:
                    with open(f, 'r') as fileh:
                        l_num = 1
                        for l in fileh:
                            if l.find(input_text) != -1:
                                epp.print("%s:%d %s" % ( f, l_num, l.strip() ))
                            l_num = l_num + 1
                except UnicodeError:
                    epp.err("Can't read file {0}".format(f))
    else: 
        # Provoque une erreur
        parser.print_help()
        epp.log("-f and -p are mutually exclusive")
        sys.exit(1)
Пример #10
0
def main(argv):
    parser = optparse.OptionParser()
    parser.add_option("-c","--cursor",action="store",type="int",dest="cursor",help="Cursor position in file (byte)")
    parser.add_option("-f","--filename",action="store",type="string",dest="filename",help="File to parse")
    parser.add_option("--keywords",action="store",type="string",dest="keywords",help="Additionnal keywords that should be sent with the query")
    parser.add_option("-n", action="store",type="string",dest="real_filename")

    parser.set_defaults()
    (options, args) = parser.parse_args(argv)

    if options.filename and options.cursor:
        if not options.real_filename:
            options.real_filename = options.filename
            
        search_term = get_search(options)
        epp.log(search_term)
    
        # Preparation pour google
        tags = epp.getFileTags(options.real_filename)
        if len(tags) > 0:
            epp.log(tags)
            search_term = " ".join(tags) + " " + search_term
        
        if options.keywords:
            search_term = options.keywords + " " + search_term
            
        search_term = re.sub(r"\s+", "+", search_term.strip())
    
        # Lance un navigateur avec une recherche
        url = "http://www.google.com/search?q={0}".format(search_term)
        epp.log("url: " + url)
        
        webbrowser.open_new_tab(url)
        
    else:
        # On provoque une erreur
        if not options.filename:
            parser.error("filename")
        elif not options.cursor:
            parser.error("cursor")
        sys.exit(1)
Пример #11
0
def get_language(forced_language, filetype):
    if forced_language != None:
        epp.log("Use options.language: {0}".format(forced_language))
        return forced_language
    else:
        epp.log("Scan filetypes for extensions {0}".format(filetype))
        language = None
        
    config_file = path.join(epp.getcwd(), "language_words", "filetypes.txt")
    
    if filetype != '' and path.exists(config_file):
        r = re.compile(r"^(?:\w+;)*{0}\S*\t(?P<language>\w+)".format(filetype), re.IGNORECASE)
        
        with open(config_file, "r") as f:
            for l in f:
                match = r.search(l)
                if match:
                	language = match.group("language")
                	epp.log("language found: {0}".format(language))
                	break
    return language
Пример #12
0
def tidySQL(sql, uppercase):
    #TODO Detecter le format
    NL = '\n'
    MAX_WIDTH = 80

    # Suppression des sauts de lignes existants
    sqlNorm = sql.replace(NL, ' ')
    
    # Suppression des espaces en trop
    sqlNorm = re.sub(r"\s{2,}", " ", sqlNorm)

    kwSQL = ('SELECT', 'AS', 'CASE WHEN', 'THEN', 'ELSE', 'END', 'INTO', 'FROM', 'LEFT JOIN', 'RIGHT JOIN', 'JOIN', 'ON', 'WHERE', 'AND', 'OR', 'LIKE', 'GROUP BY', 'HAVING', 'ORDER BY', 'UNION')
    kwNewSection = ('SELECT', 'FROM', 'WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'UNION')
    
    for word in kwSQL:
        if uppercase:
            wordNormalized = word.upper()
        else:
            wordNormalized = word.lower()
            
        if word.upper() in kwNewSection:
            wordNormalized = NL + wordNormalized
            
        sqlNorm = re.sub('(?i)' + aloner(word), wordNormalized, sqlNorm)

    epp.log(sqlNorm)
    sqlNorm = normalizeOperators(sqlNorm)
    epp.log ('-----')
    epp.log(sqlNorm)

    sections = sqlNorm.splitlines()
    sectionsNorm = list()

    for section in [e for e in sections if e != '' ]:
        sectionNorm = normalizeSection(section, NL, MAX_WIDTH)
        sectionsNorm.append(sectionNorm)

    return NL.join(sectionsNorm)
Пример #13
0
 def handle_tabChanged(self, event):
     self.currTab = event.widget.index("current")
     epp.log("Selected tab : {0}".format(self.currTab))
Пример #14
0
 def handle_Ok(self, event=None):
     idx = self._getCurrentSelIndex()
     if idx != None:
         self.chosenFile = self.listCandidates.get(idx)
     epp.log("handle_Ok")
     self.quit()
Пример #15
0
 def handle_Escape(self, event=None):
     if event == None or event.widget != self.listCandidates:
         epp.log("handle_Escape")
         self.quit()
     elif event.widget == self.listCandidates:
         self.focusToTextInput()
Пример #16
0
import os
import sys
import os.path as path

import epp_utils as epp

if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option("-e","--editor_path",action="store",type="string",dest="editor_path",help="EditPad path")
    parser.add_option("-p","--path",action="store",type="string",dest="path",help="Current file path")
    
    parser.set_defaults()
    (options, args) = parser.parse_args()
    
    input_text = sys.stdin.readline()
    epp.log("-> %s" % input_text)
    
    if len(input_text) == 0:
        epp.log("Selectionner le fichier a ouvrir\n");
    elif options.editor_path and options.path:
        if path.isabs(input_text):
            # Chemin absolu
            file_to_open = path.normpath(input_text)
        else:
            # Chemin relatif
            file_to_open = path.normpath(path.join(options.path, input_text))            
        
        editor_exec = options.editor_path + '\EditPadPro.exe'
        epp.log("exec : %s %s" % (editor_exec, file_to_open))
        
        if exists(file_to_open):
Пример #17
0
 def quit(self):
     epp.log("QUIT")
     self.master.quit()
Пример #18
0
import os
import sys
import os.path as path
import epp_utils as epp

if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option("-e","--editor_path",action="store",type="string",dest="editor_path",help="EditPad path")
    parser.add_option("-p","--path",action="store",type="string",dest="path",help="Current file path")
    parser.add_option("-d","--default",action="store",type="string",dest="default_path",help="Default path for include")
    
    parser.set_defaults(default_path=".")
    (options, args) = parser.parse_args()
    
    input_text = epp.readline()
    epp.log("-> %s" % input_text)
    
    if options.editor_path and options.path and len(input_text) > 0:
        if not path.isabs(input_text):
            # Chemin relatif
            file_to_open = path.normpath(path.join(options.path, input_text))
            # Nom simple : On teste si l'include existe dans le meme rep
            if not path.exists(file_to_open):
                # Introuvable dans le repertoire courant -> on utilise le repertoire par defaut
                file_to_open = path.normpath(path.join(options.default_path, input_text))
        else:
            file_to_open = path.normpath(input_text)
        
        editor_exec = options.editor_path + "\EditPadPro7.exe"
        epp.log("exec : %s %s" % (editor_exec, file_to_open))
        
Пример #19
0
def main(argv):
    parser = optparse.OptionParser()
    parser.add_option("-c","--cursor",action="store",type="int",dest="cursor",help="Cursor position in file (byte)")
    parser.add_option("-f","--fileName",action="store",type="string",dest="filename",help="File to parse")
    parser.add_option("-l","--currLine",action="store",type="int",dest="currline",help="Current line in the file")
    parser.add_option("-t","--type",action="store",type="string",dest="type",help="File type (extension without dot)")
    parser.add_option("-w","--width",action="store",type="int",dest="width",help="How many lines to scan above and below the current line. 0 -> whole file (Optional)")
    parser.add_option("--language",action="store",type="string",dest="language",help="The language file to use to get keywords (Optional)")
    
    parser.set_defaults(width=0)
    
    (options, args) = parser.parse_args(argv)
    
    epp.log("cursor:%s, currLine:%s, width:%s" % (options.cursor, options.currline, options.width))
    
    if options.filename and options.currline and options.cursor:
        epp.log(options.filename)
        
        # DEBUG Parfois le programme ne trouve pas le bon terme à chercher...
        if DEBUG_FILE:
            distutils.file_util.copy_file(options.filename, os.path.join(os.environ["TMP"], "EPP_TMP.txt"))
        
        # Check UTF8
        codecName = epp.getFileCodecName(options.filename)
        epp.log("codec detecté: %s" % codecName)
        if codecName == "utf_8":
            options.cursor += 3
        
        with open(options.filename, 'r', encoding=codecName) as fileh:
            # Recuperation des lettres precedants le curseur
            search = ac.get_search(fileh, options.cursor)
            epp.log("Search for %s...\n--------------" % search)
            
            # Taille minimum du mot de recherche
            if len(search) <= 1:
                epp.log("Search term too little, 2 letters minimum")
                sys.exit(1)
                        
            # Scan du fichier pour retrouver les candidats
            file_words = ac.get_file_words(search, fileh, options.currline, options.width)
        
        language = ac.get_language(options.language, options.type)
        if language:
            # Récupération de la liste des mots du langage
            lang_words = ac.get_language_words(search, language)
        else:
            lang_words = set()
        
        # MAJ des mots du fichier étant également des mots du language
        for wordObj in [w for w in file_words if w in lang_words]:
            wordObj.color = "blue"
        
        # on supprime les mots du langage appartenant deja au fichier (pour garder les caracteristiques du mot)
        lang_words = lang_words - file_words
        for wordObj in lang_words:
             wordObj.color = "blue"
        
        nb_words = len(lang_words) + len(file_words)
        
        # Affichage du résultat
        if nb_words == 1:
            # 1 seul candidat -> on l'utilise
            epp.write(ac.get_result(search, (lang_words | file_words).pop()))
        elif nb_words > 1:
            # Plusieurs candidats : Affichage des candidats
            choix = choix_liste_mots(search, lang_words, file_words)
            if choix != None:
                epp.write(ac.get_result(search, choix))
        else:
            # Aucun candidat 
            #import winsound
            #winsound.MessageBeep(winsound.MB_ICONEXCLAMATION);
            epp.log("Aucun candidat trouve")
            # Ajout d'un espace pour montrer que rien n'a été trouvé
            epp.write(' ')
            
        sys.exit()
        
    else: 
        # On provoque une erreur
        if not options.filename:
            parser.error("filename") 
        elif not options.currline:
            parser.error("currline") 
        elif not options.cursor:
            parser.error("cursor") 
        sys.exit(1)
Пример #20
0
import optparse
import os
import sys
import os.path as path
import epp_utils as epp

if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option("-w","--surround_with",action="store",type="string",dest="surround_with",help="String to surround the text with")
    parser.add_option("-b","--begin",action="store",type="string",dest="begin",help="String to add before the text")
    parser.add_option("-e","--end",action="store",type="string",dest="end",help="String to add after the text")
    
    (options, args) = parser.parse_args()
    
    input_text = ''.join(sys.stdin.readlines())
    epp.log("-> %s" % input_text)
    
    if options.surround_with or (options.begin and options.end):
        if options.surround_with:
            begin = options.surround_with
            end = options.surround_with
        else:
            begin = options.begin
            end = options.end
            
        sys.stdout.write(begin + input_text + end)
        
    else: 
        # Provoquer une erreur
        parser.print_help()
        sys.exit(1)
Пример #21
0
    
    if options.interactive:
        epp.print("test")
    elif (options.project or options.file or options.basedir) and input_text.strip() != '':
        if (options.project):
            files = epp.getProjectFiles(options.project)
        if (options.basedir):
            files = epp.getFilesInTree(options.basedir, options.filemask)
        elif (options.file):
            files = [options.file]
        
        for f in files:
            if path.exists(f):
                try:
                    with open(f, 'r') as fileh:
                        l_num = 1
                        for l in fileh:
                            if l.find(input_text) != -1:
                                epp.print("%s:%d %s" % ( f, l_num, l.strip() ))
                            l_num = l_num + 1
                except UnicodeError:
                    epp.err("Can't read file {0}".format(f))
    else: 
        # Provoque une erreur
        parser.print_help()
        epp.log("-f and -p are mutually exclusive")
        sys.exit(1)

if __name__ == "__main__":
    epp.log(sys.argv)
    main(sys.argv[1:])