codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
r"""Simple module for quick document manipulation from the gedit Python console Example: import doc d = doc.Doc(window) d.set_lines( ['one', 'two', 'three'] ) d.append('\n') d.append('four') lines = d.get_lines() lines.reverse() d.set_lines(lines) Ideas: * Add function to create a menu item automatically for a function defined in console * Paste Python history into new document to save program """ class Doc: """Class for manipulating a gedit document""" def __init__(self, window): self.document = window.get_active_document() def get_line(self): """Return the contents of the line that the cursor is currently on""" current_pos_mark = self.document.get_insert() start = self.document.get_iter_at_mark(current_pos_mark) start.set_line_offset(0) end = start.copy() end.forward_to_line_end() return start.get_slice(end) def get_text(self): """Return the full text of the document""" start, end = self.document.get_bounds() return start.get_slice(end) def get_selection(self): """Return the selected text""" selection = self.document.get_selection_bounds() current_pos_mark = self.document.get_insert() if len(selection): start, end = selection if start.ends_line(): start.forward_char() elif not start.starts_line(): start.set_line_offset(0) if end.starts_line(): end.backward_char() elif not end.ends_line(): end.forward_to_line_end() return start.get_slice(end) return '' def set_text(self, text): """Set the full text of the document""" self.clear() self.append(text) def get_lines(self): """Return a list containing all of the lines in the document""" start, end = self.document.get_bounds() #return start.get_slice(end).split('\n') # This way is longer but should be more durable lines = [] num_lines = end.get_line() - start.get_line() + 1 line_start = start.copy() for i in range(0, num_lines): line_end = line_start.copy() line_end.forward_to_line_end() line = line_start.get_slice(line_end) lines.append(line) line_start.forward_line() return lines def set_lines(self, lines): """Replace the current document with the lines in the supplied list""" self.clear() self.append( '\n'.join(lines) ) def clear(self): """Clear the document""" start, end = self.document.get_bounds() self.document.begin_user_action() self.document.delete(start, end) self.document.end_user_action() def append(self, text): """Add text to the bottom of the document""" start, end = self.document.get_bounds() self.document.begin_user_action() self.document.insert(end, text) self.document.end_user_action()
Private
[
?
]
Run code
Submit