blob: 6324b4f112f91410804c21e9ed42e0c3fe8754d0 [file] [log] [blame]
David Scherer7aced172000-08-15 01:13:23 +00001import os
David Scherer7aced172000-08-15 01:13:23 +00002import fnmatch
Terry Jan Reedy47623822014-06-10 02:49:35 -04003import re # for htest
David Scherer7aced172000-08-15 01:13:23 +00004import sys
Terry Jan Reedy47623822014-06-10 02:49:35 -04005from tkinter import StringVar, BooleanVar, Checkbutton # for GrepDialog
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -04006from idlelib import searchengine
7from idlelib.searchbase import SearchDialogBase
Terry Jan Reedy47623822014-06-10 02:49:35 -04008# Importing OutputWindow fails due to import loop
9# EditorWindow -> GrepDialop -> OutputWindow -> EditorWindow
David Scherer7aced172000-08-15 01:13:23 +000010
11def grep(text, io=None, flist=None):
12 root = text._root()
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040013 engine = searchengine.get(root)
David Scherer7aced172000-08-15 01:13:23 +000014 if not hasattr(engine, "_grepdialog"):
15 engine._grepdialog = GrepDialog(root, engine, flist)
16 dialog = engine._grepdialog
Kurt B. Kaiseref58adf2003-06-07 03:21:17 +000017 searchphrase = text.get("sel.first", "sel.last")
18 dialog.open(text, searchphrase, io)
David Scherer7aced172000-08-15 01:13:23 +000019
20class GrepDialog(SearchDialogBase):
21
22 title = "Find in Files Dialog"
23 icon = "Grep"
24 needwrapbutton = 0
25
26 def __init__(self, root, engine, flist):
27 SearchDialogBase.__init__(self, root, engine)
28 self.flist = flist
29 self.globvar = StringVar(root)
30 self.recvar = BooleanVar(root)
31
Kurt B. Kaiseref58adf2003-06-07 03:21:17 +000032 def open(self, text, searchphrase, io=None):
33 SearchDialogBase.open(self, text, searchphrase)
David Scherer7aced172000-08-15 01:13:23 +000034 if io:
35 path = io.filename or ""
36 else:
37 path = ""
38 dir, base = os.path.split(path)
39 head, tail = os.path.splitext(base)
40 if not tail:
41 tail = ".py"
42 self.globvar.set(os.path.join(dir, "*" + tail))
43
44 def create_entries(self):
45 SearchDialogBase.create_entries(self)
Terry Jan Reedy5283c4e2014-07-13 17:27:26 -040046 self.globent = self.make_entry("In files:", self.globvar)[0]
David Scherer7aced172000-08-15 01:13:23 +000047
48 def create_other_buttons(self):
Terry Jan Reedy5283c4e2014-07-13 17:27:26 -040049 f = self.make_frame()[0]
David Scherer7aced172000-08-15 01:13:23 +000050
51 btn = Checkbutton(f, anchor="w",
52 variable=self.recvar,
53 text="Recurse down subdirectories")
54 btn.pack(side="top", fill="both")
55 btn.select()
56
57 def create_command_buttons(self):
58 SearchDialogBase.create_command_buttons(self)
59 self.make_button("Search Files", self.default_command, 1)
60
61 def default_command(self, event=None):
62 prog = self.engine.getprog()
63 if not prog:
64 return
65 path = self.globvar.get()
66 if not path:
67 self.top.bell()
68 return
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040069 from idlelib.outwin import OutputWindow # leave here!
David Scherer7aced172000-08-15 01:13:23 +000070 save = sys.stdout
71 try:
72 sys.stdout = OutputWindow(self.flist)
73 self.grep_it(prog, path)
74 finally:
75 sys.stdout = save
76
77 def grep_it(self, prog, path):
78 dir, base = os.path.split(path)
79 list = self.findfiles(dir, base, self.recvar.get())
80 list.sort()
81 self.close()
82 pat = self.engine.getpat()
Guido van Rossumbe19ed72007-02-09 05:37:30 +000083 print("Searching %r in %s ..." % (pat, path))
David Scherer7aced172000-08-15 01:13:23 +000084 hits = 0
Terry Jan Reedy47623822014-06-10 02:49:35 -040085 try:
86 for fn in list:
87 try:
88 with open(fn, errors='replace') as f:
89 for lineno, line in enumerate(f, 1):
90 if line[-1:] == '\n':
91 line = line[:-1]
92 if prog.search(line):
93 sys.stdout.write("%s: %s: %s\n" %
94 (fn, lineno, line))
95 hits += 1
96 except OSError as msg:
97 print(msg)
98 print(("Hits found: %s\n"
99 "(Hint: right-click to open locations.)"
100 % hits) if hits else "No hits.")
101 except AttributeError:
102 # Tk window has been closed, OutputWindow.text = None,
103 # so in OW.write, OW.text.insert fails.
104 pass
David Scherer7aced172000-08-15 01:13:23 +0000105
106 def findfiles(self, dir, base, rec):
107 try:
108 names = os.listdir(dir or os.curdir)
Terry Jan Reedyc3111fc2014-02-23 00:37:16 -0500109 except OSError as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000110 print(msg)
David Scherer7aced172000-08-15 01:13:23 +0000111 return []
112 list = []
113 subdirs = []
114 for name in names:
115 fn = os.path.join(dir, name)
116 if os.path.isdir(fn):
117 subdirs.append(fn)
118 else:
119 if fnmatch.fnmatch(name, base):
120 list.append(fn)
121 if rec:
122 for subdir in subdirs:
123 list.extend(self.findfiles(subdir, base, rec))
124 return list
125
126 def close(self, event=None):
127 if self.top:
128 self.top.grab_release()
129 self.top.withdraw()
Terry Jan Reedyde3beb22013-06-22 18:26:51 -0400130
Terry Jan Reedy47623822014-06-10 02:49:35 -0400131
Terry Jan Reedycd567362014-10-17 01:31:35 -0400132def _grep_dialog(parent): # htest #
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -0400133 from idlelib.pyshell import PyShellFileList
Terry Jan Reedyb60adc52016-06-21 18:41:38 -0400134 from tkinter import Toplevel, Text, Button, SEL, END
135 top = Toplevel(parent)
136 top.title("Test GrepDialog")
Terry Jan Reedy2e8234a2014-05-29 01:46:26 -0400137 width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
Terry Jan Reedyb60adc52016-06-21 18:41:38 -0400138 top.geometry("+%d+%d"%(x, y + 150))
Terry Jan Reedy2e8234a2014-05-29 01:46:26 -0400139
Terry Jan Reedyb60adc52016-06-21 18:41:38 -0400140 flist = PyShellFileList(top)
141 text = Text(top, height=5)
Terry Jan Reedy2e8234a2014-05-29 01:46:26 -0400142 text.pack()
143
144 def show_grep_dialog():
145 text.tag_add(SEL, "1.0", END)
146 grep(text, flist=flist)
147 text.tag_remove(SEL, "1.0", END)
148
Terry Jan Reedyb60adc52016-06-21 18:41:38 -0400149 button = Button(top, text="Show GrepDialog", command=show_grep_dialog)
Terry Jan Reedy2e8234a2014-05-29 01:46:26 -0400150 button.pack()
Terry Jan Reedy2e8234a2014-05-29 01:46:26 -0400151
Terry Jan Reedyde3beb22013-06-22 18:26:51 -0400152if __name__ == "__main__":
Terry Jan Reedyde3beb22013-06-22 18:26:51 -0400153 import unittest
154 unittest.main('idlelib.idle_test.test_grep', verbosity=2, exit=False)
Terry Jan Reedy2e8234a2014-05-29 01:46:26 -0400155
156 from idlelib.idle_test.htest import run
157 run(_grep_dialog)