Debian Codegraph @

envisage/plugins/text_editor/editor/text_editor.py

raw
1 # (C) Copyright 2007-2025 Enthought, Inc., Austin, TX
2 # All rights reserved.
3 #
4 # This software is provided without warranty under the terms of the BSD
5 # license included in LICENSE.txt and may be redistributed only under
6 # the conditions described in the aforementioned license. The license
7 # is also available online at http://www.enthought.com/licenses/BSD.txt
8 #
9 # Thanks for using Enthought open source!
10 """ A text editor. """
11
12
13 # Standard library imports.
14 from os.path import basename
15
16 from pyface.api import CANCEL, FileDialog
17
18 # Enthought library imports.
19 from pyface.workbench.api import TraitsUIEditor
20 from traits.api import Code, Instance, observe
21 from traitsui.api import CodeEditor, Group, Item, View
22 from traitsui.key_bindings import KeyBinding, KeyBindings
23 from traitsui.menu import NoButtons
24
25 # Local imports.
26 from .text_editor_handler import TextEditorHandler
27
28
29 def _id_generator():
30 """A generator that returns the next number for untitled files."""
31
32 i = 1
33 while True:
34 yield (i)
35 i += 1
36
37
38 _id_generator = _id_generator()
39
40
41 class TextEditor(TraitsUIEditor):
42 """A text editor."""
43
44 #### 'TextEditor' interface ###############################################
45
46 # The key bindings used by the editor.
47 key_bindings = Instance(KeyBindings)
48
49 # The text being edited.
50 text = Code
51
52 ###########################################################################
53 # 'IEditor' interface.
54 ###########################################################################
55
56 def save(self):
57 """Saves the text to disk."""
58
59 # If the file has not yet been saved then prompt for the file name.
60 if len(self.obj.path) == 0:
61 self.save_as()
62
63 else:
64 with open(self.obj.path, "w", encoding="utf-8") as f:
65 f.write(self.text)
66
67 # We have just saved the file so we ain't dirty no more!
68 self.dirty = False
69
70 def save_as(self):
71 """Saves the text to disk after prompting for the file name."""
72
73 dialog = FileDialog(
74 parent=self.window.control,
75 action="save as",
76 default_filename=self.name,
77 wildcard=FileDialog.WILDCARD_PY,
78 )
79 if dialog.open() != CANCEL:
80 # Update the editor.
81 self.id = dialog.path
82 self.name = basename(dialog.path)
83
84 # Update the resource.
85 self.obj.path = dialog.path
86
87 # Save it!
88 self.save()
89
90 ###########################################################################
91 # 'TraitsUIEditor' interface.
92 ###########################################################################
93
94 def create_ui(self, parent):
95 """Creates the traits UI that represents the editor."""
96
97 ui = self.edit_traits(
98 parent=parent, view=self._create_traits_ui_view(), kind="subpanel"
99 )
100
101 return ui
102
103 ###########################################################################
104 # 'TextEditor' interface.
105 ###########################################################################
106
107 def run(self):
108 """Runs the file as Python."""
109
110 # The file must be saved first!
111 self.save()
112
113 # Execute the code.
114 if len(self.obj.path) > 0:
115 view = self.window.get_view_by_id(
116 "envisage.plugins.python_shell_view"
117 )
118
119 if view is not None:
120 view.execute_command(
121 'exec(open(r"%s").read())' % self.obj.path, hidden=False
122 )
123
124 def select_line(self, lineno):
125 """Selects the specified line."""
126
127 self.ui.info.text.selected_line = lineno
128
129 ###########################################################################
130 # Private interface.
131 ###########################################################################
132
133 #### Trait initializers ###################################################
134
135 def _key_bindings_default(self):
136 """Trait initializer."""
137
138 key_bindings = KeyBindings(
139 KeyBinding(
140 binding1="Ctrl-s",
141 description="Save the file",
142 method_name="save",
143 ),
144 KeyBinding(
145 binding1="Ctrl-r",
146 description="Run the file",
147 method_name="run",
148 ),
149 )
150
151 return key_bindings
152
153 #### Trait change handlers ################################################
154
155 @observe("obj")
156 def _handle_update_to_object(self, event):
157 """Static trait change handler."""
158 new = event.new
159 # The path will be the empty string if we are editing a file that has
160 # not yet been saved.
161 if len(new.path) == 0:
162 self.id = self._get_unique_id()
163 self.name = self.id
164
165 else:
166 self.id = new.path
167 self.name = basename(new.path)
168
169 with open(new.path, "r", encoding="utf-8") as f:
170 self.text = f.read()
171
172 @observe("text")
173 def _update_dirty(self, event):
174 """Static trait change handler."""
175
176 if self.traits_inited():
177 self.dirty = True
178
179 @observe("dirty")
180 def _update_name(self, event):
181 """Static trait change handler."""
182 dirty = event.new
183 if len(self.obj.path) > 0:
184 if dirty:
185 self.name = basename(self.obj.path) + "*"
186
187 else:
188 self.name = basename(self.obj.path)
189
190 #### Methods ##############################################################
191
192 def _create_traits_ui_view(self):
193 """Create the traits UI view used by the editor.
194
195 fixme: We create the view dynamically to allow the key bindings to be
196 created dynamically (we don't use this just yet, but obviously plugins
197 need to be able to contribute new bindings).
198
199 """
200
201 view = View(
202 Group(
203 Item(
204 "text", editor=CodeEditor(key_bindings=self.key_bindings)
205 ),
206 show_labels=False,
207 ),
208 id="envisage.editor.text_editor",
209 handler=TextEditorHandler(),
210 kind="live",
211 resizable=True,
212 width=1.0,
213 height=1.0,
214 buttons=NoButtons,
215 )
216
217 return view
218
219 def _get_unique_id(self, prefix="Untitled "):
220 """Return a unique id for a new file."""
221
222 id = prefix + str(next(_id_generator))
223 while self.window.get_editor_by_id(id) is not None:
224 id = prefix + str(next(_id_generator))
225
226 return id