Example #1
0
 def __idle_save_text(self, status):
     self.__save_text_id = 0
     _logger.debug("autosaving to %s", self.__filename)
     dn,bn = os.path.split(self.__filename)
     try:
         perms = os.stat(self.__filename).st_mode
     except:
         perms = None
     (tempfd, temppath) = tempfile.mkstemp('.tmp', self.__filename, dn)
     os.close(tempfd)
     f = open_text_file(temppath, 'w')
     text = self.input.get_property("text")
     utext = str(text)
     f.write(utext)
     f.flush()
     os.fsync(tempfd)
     f.close()
     if perms is not None:
         os.chmod(temppath, perms)
     atomic_rename(temppath, self.__filename)
     self.__show_msg(status + _("...done"))
     self.__modified = False
     self.__sync_modified_sensitivity()
     _logger.debug("autosave complete")
     return False
Example #2
0
def head(context, *files):
    _("""Return a subset of items from start of input stream.""")
    count = 10
    countidx = -1
    # Create a copy so we can delete from it safely
    files = list(files)
    for i, arg in enumerate(files):
        if arg.startswith('-'):
            count = int(arg[1:])
            countidx = i
            break
    if countidx >= 0:
        del files[countidx]
    if context.input is not None:
        for i, value in enumerate(context.input):
            if i >= count:
                break
            yield value
    for fpath in files:
        fpath = path_join(context.cwd, fpath)
        f = None
        f = open_text_file(fpath)
        for i, line in enumerate(f):
            if i >= count:
                break
            yield line
        f.close()
Example #3
0
def head(context, *files):
    _("""Return a subset of items from start of input stream.""")
    count = 10
    countidx = -1
    # Create a copy so we can delete from it safely
    files = list(files)
    for i,arg in enumerate(files):
        if arg.startswith('-'):
            count = int(arg[1:])
            countidx = i
            break
    if countidx >= 0:
        del files[countidx]
    if context.input is not None:
        for i,value in enumerate(context.input):
            if i >= count:
                break
            yield value
    for fpath in files:
        fpath = path_join(context.cwd, fpath)
        f = None
        f = open_text_file(fpath)
        for i,line in enumerate(f):
            if i>= count:
                break
            yield line
        f.close()
Example #4
0
 def execute(self, context, args, options=[]):
     regexp = args[0]
     if len(args) == 2:
         path = args[1]
     else:
         path = context.cwd
     regexp = args[0]
     comp_regexp = re.compile(
         regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
     walk_builtin = BuiltinRegistry.getInstance()['walk']
     newctx = HotwireContext(context.cwd)
     for fobj in walk_builtin.execute(newctx, [path]):
         fp = None
         try:
             fp = open_text_file(fobj.path)
             for i, line in enumerate(fp):
                 match = comp_regexp.search(line)
                 if match:
                     yield FileStringMatch(fobj.path, line[:-1], i,
                                           match.start(), match.end())
             fp.close()
         except OSError, e:
             pass
         except UnicodeDecodeError, e:
             pass
Example #5
0
 def __idle_save_text(self, status):
     self.__save_text_id = 0
     _logger.debug("autosaving to %s", self.__filename)
     dn, bn = os.path.split(self.__filename)
     try:
         perms = os.stat(self.__filename).st_mode
     except:
         perms = None
     (tempfd, temppath) = tempfile.mkstemp('.tmp', self.__filename, dn)
     os.close(tempfd)
     f = open_text_file(temppath, 'w')
     text = self.input.get_property("text")
     utext = unicode(text)
     f.write(utext)
     f.flush()
     os.fsync(tempfd)
     f.close()
     if perms is not None:
         os.chmod(temppath, perms)
     atomic_rename(temppath, self.__filename)
     self.__show_msg(status + _("...done"))
     self.__modified = False
     self.__sync_modified_sensitivity()
     _logger.debug("autosave complete")
     return False
Example #6
0
 def execute(self, context, args, options=[]):
     open_mode = ('-a' in options) and 'a+' or 'w'
     do_pickle = '-p' in options
     with_newline = '-n' in options
     if do_pickle:
         open_mode = 'wb'
     if not context.input:
         return
     streams = map(lambda x: open_text_file(FilePath(x, context.cwd), open_mode), args)
     if not do_pickle:
         for arg in context.input:
             for stream in streams:
                 stream.write('%s' % (unicode(arg),))
                 if with_newline:
                     stream.write('\n')
     else:
         # Kind of annoying pickle makes you do this.
         arglist = list(context.input)
         for stream in streams:
             pickle.dump(arglist, stream)
     map(lambda x: x.close(), streams)
     return []
Example #7
0
 def execute(self, context, args, options=[]):       
     regexp = args[0]
     if len(args) == 2:
         path = args[1]
     else:
         path = context.cwd
     regexp = args[0]
     comp_regexp = re.compile(regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
     walk_builtin = BuiltinRegistry.getInstance()['walk']
     newctx = HotwireContext(context.cwd)
     for fobj in walk_builtin.execute(newctx, [path]):
         fp = None
         try:
             fp = open_text_file(fobj.path) 
             for i,line in enumerate(fp):
                 match = comp_regexp.search(line)
                 if match:
                     yield FileStringMatch(fobj.path, line[:-1], i, match.start(), match.end())
             fp.close()
         except OSError as e:
             pass
         except UnicodeDecodeError as e:
             pass
Example #8
0
 def execute(self, context, args, options=[]):
     open_mode = ('-a' in options) and 'a+' or 'w'
     do_pickle = '-p' in options
     with_newline = '-n' in options
     if do_pickle:
         open_mode = 'wb'
     if not context.input:
         return
     streams = map(
         lambda x: open_text_file(FilePath(x, context.cwd), open_mode),
         args)
     if not do_pickle:
         for arg in context.input:
             for stream in streams:
                 stream.write('%s' % (unicode(arg), ))
                 if with_newline:
                     stream.write('\n')
     else:
         # Kind of annoying pickle makes you do this.
         arglist = list(context.input)
         for stream in streams:
             pickle.dump(arglist, stream)
     map(lambda x: x.close(), streams)
     return []
Example #9
0
    def __init__(self, filename=None, content=None, title=None, parent=None, autosave=False):
        gtk.Window.__init__(self, type=gtk.WINDOW_TOPLEVEL)
        vbox = gtk.VBox()
        self.add(vbox)
        self.__ui_string = """
<ui>
  <menubar name='Menubar'>
    <menu action='FileMenu'>
      <menuitem action='Save'/>
      <menuitem action='SaveAs'/>
      <separator/>
      <menuitem action='ReadOnly'/>
      <separator/>
      <menuitem action='Revert'/>
      <separator/>
      <menuitem action='Close'/>
    </menu>
    <menu action='EditMenu'>
      <menuitem action='Undo'/>
      <menuitem action='Redo'/>
      <separator/>
      <menuitem action='Find'/>
      <menuitem action='GotoLine'/>
    </menu>
    <menu action='ToolsMenu'>
      <menuitem action='About'/>
    </menu>
  </menubar>
</ui>
"""
        self.__create_ui()
        vbox.pack_start(self._ui.get_widget('/Menubar'), expand=False)

        self.__filename = os.path.abspath(filename)
        self.__autosave = autosave
        self.__modified = False
        self.__last_len = 0
         
        self.__save_text_id = 0

        self.gtksourceview_mode = gtksourceview_avail

        if gtksourceview_avail:
            self.input = SourceBuffer()
            self.input_view = SourceView(self.input)
            if gtksourceview2_avail:
                self.input.connect('notify::can-undo', lambda *args: self.__sync_undoredo())
                self.input.connect('notify::can-redo', lambda *args: self.__sync_undoredo())
            else:
                self.input.connect('can-undo', lambda *args: self.__sync_undoredo())
                self.input.connect('can-redo', lambda *args: self.__sync_undoredo())
        else:
            self.input = gtk.TextBuffer()
            self.input_view = gtk.TextView(self.input)
        self.input_view.set_wrap_mode(gtk.WRAP_WORD)
        self.input_view.connect("key-press-event", self.__handle_key_press_event)
        
        scroll = gtk.ScrolledWindow()
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)        
        scroll.add(self.input_view)
        
        vbox.pack_start(scroll, True, True)

        if filename and os.path.isfile(self.__filename):
            _logger.debug("reading %s", self.__filename)
            f = open_text_file(self.__filename, 'r')
            self.__original_text = f.read()
        else:
            self.__original_text = content
            
        if self.__original_text:
            if gtksourceview_avail:
                self.input.begin_not_undoable_action()
            self.input.set_property('text', self.__original_text)
            self.__last_len = self.input.get_char_count()             
            if gtksourceview_avail:
                self.input.end_not_undoable_action()            
        
        self.input.move_mark_by_name('insert', self.input.get_start_iter())
        self.input.move_mark_by_name('selection_bound', self.input.get_start_iter())
        
        self.input.connect('mark-set', self.__on_mark_set)

        self.__searcharea = InlineSearchArea(self.input_view)
        self.__searcharea.connect('close', self.__on_search_close)
        self.__searcharea.show_all()
        self.__searcharea.hide()
        self.__searcharea.set_no_show_all(True)
        vbox.pack_start(self.__searcharea, expand=False)

        self.__status_hbox = gtk.HBox()
        self.__statusbar = gtk.Statusbar()
        self.__status_hbox.pack_start(self.__statusbar, expand=True)
        self.__statusbar_ctx = self.__statusbar.get_context_id("HotEditor")
        self.__pos_status = gtk.Statusbar()
        self.__pos_status.set_size_request(160, 10) # Taken from GEdit
        self.__pos_context = self.__pos_status.get_context_id("HotEditor")
        self.__status_hbox.pack_start(self.__pos_status, expand=False)
        vbox.pack_start(self.__status_hbox, expand=False)
        self.__sync_undoredo()
        self.__sync_modified_sensitivity()

        self.input.connect("changed", self.__handle_text_changed)

        self.connect("delete-event", self.__handle_delete_event)
        self.__sync_title()
        if parent:
            self.set_transient_for(parent)
        self.set_size_request(800, 600)
Example #10
0
 def __run(self, *args, **kwargs):
     if self._cancelled:
         _logger.debug("%s cancelled, returning", self)
         self.output.put(self.map_fn(None))
         return
     try:
         matched_files = []
         oldlen = 0
         for globarg_in in self.args:
             if isinstance(globarg_in,
                           CommandArgument) and globarg_in.isquoted:
                 globarg = globarg_in
                 newlen = oldlen
             else:
                 globarg = os.path.expanduser(globarg_in)
                 matched_files.extend(
                     hotwire.fs.dirglob(self.context.cwd, globarg))
                 _logger.debug("glob on %s matched is: %s", globarg_in,
                               matched_files)
                 newlen = len(matched_files)
             if oldlen == newlen:
                 matched_files.append(globarg)
                 newlen += 1
             oldlen = newlen
         target_args = [matched_files]
         _logger.info("Execute '%s' args: %s options: %s", self.builtin,
                      target_args, self.context.options)
         kwargs = {}
         if self.context.options and not self.builtin.flattened_args:
             kwargs['options'] = self.context.options
         if self.input is not None and self.input.opt_type and not self.in_redir:
             kwargs['in_opt_format'] = self.input.opt_type
         if self.output.opt_type and not self.out_redir:
             kwargs['out_opt_format'] = self.output.opt_type
         if self.in_redir:
             _logger.debug("input redirected, opening %s", self.in_redir)
             self.context.input = CommandFileQueue(
                 open_text_file(self.in_redir, 'r'))
         if self.out_redir:
             _logger.debug("output redirected, opening %s", self.out_redir)
             outfile = open_text_file(self.out_redir,
                                      self.out_append and 'a+' or 'w')
         else:
             outfile = None
         try:
             exectarget = self.builtin.execfunc
             if self.builtin.flattened_args:
                 target_args = target_args[0]
             execresult = exectarget(self.context, *target_args, **kwargs)
             if self.builtin.singlevalue:
                 if outfile:
                     outfile.write(str(execresult))
                 else:
                     self.output.put(execresult)
             else:
                 for result in execresult:
                     # if it has status, let it do its own cleanup
                     if self._cancelled and not self.builtin.hasstatus:
                         _logger.debug("%s cancelled, returning", self)
                         self.output.put(self.map_fn(None))
                         dispatcher.send('complete', self)
                         return
                     if outfile and (result is not None):
                         result = str(result)
                         outfile.write(result)
                     else:
                         self.output.put(self.map_fn(result))
         finally:
             if outfile:
                 outfile.close()
             self.builtin.cleanup(self.context)
     except Exception as e:
         _logger.debug("Caught exception from command: %s",
                       e,
                       exc_info=True)
         if self.__executing_sync:
             raise
         else:
             dispatcher.send('exception', self, e)
     self.output.put(self.map_fn(None))
     dispatcher.send('complete', self)
Example #11
0
 def __run(self, *args, **kwargs):
     if self._cancelled:
         _logger.debug("%s cancelled, returning", self)
         self.output.put(self.map_fn(None))
         return
     try:
         matched_files = []
         oldlen = 0
         for globarg_in in self.args:
             if isinstance(globarg_in, CommandArgument) and globarg_in.isquoted:
                 globarg = globarg_in
                 newlen = oldlen                    
             else:
                 globarg = os.path.expanduser(globarg_in)
                 matched_files.extend(hotwire.fs.dirglob(self.context.cwd, globarg))
                 _logger.debug("glob on %s matched is: %s", globarg_in, matched_files) 
                 newlen = len(matched_files)
             if oldlen == newlen:
                 matched_files.append(globarg)
                 newlen += 1
             oldlen = newlen
         target_args = [matched_files]
         _logger.info("Execute '%s' args: %s options: %s", self.builtin, target_args, self.context.options)
         kwargs = {}
         if self.context.options and not self.builtin.flattened_args:
             kwargs['options'] = self.context.options
         if self.input is not None and self.input.opt_type and not self.in_redir:
             kwargs['in_opt_format'] = self.input.opt_type                
         if self.output.opt_type and not self.out_redir:
             kwargs['out_opt_format'] = self.output.opt_type
         if self.in_redir:
             _logger.debug("input redirected, opening %s", self.in_redir)
             self.context.input = CommandFileQueue(open_text_file(self.in_redir, 'r'))
         if self.out_redir:
             _logger.debug("output redirected, opening %s", self.out_redir)
             outfile = open_text_file(self.out_redir, self.out_append and 'a+' or 'w')
         else:
             outfile = None
         try:
             exectarget = self.builtin.execfunc
             if self.builtin.flattened_args:
                 target_args = target_args[0]
             execresult = exectarget(self.context, *target_args, **kwargs)                
             if self.builtin.singlevalue:
                 if outfile:
                     outfile.write(unicode(execresult))
                 else:
                     self.output.put(execresult)
             else:
                 for result in execresult:
                     # if it has status, let it do its own cleanup
                     if self._cancelled and not self.builtin.hasstatus:
                         _logger.debug("%s cancelled, returning", self)
                         self.output.put(self.map_fn(None))
                         self.emit("complete")                        
                         return
                     if outfile and (result is not None):
                         result = unicode(result)
                         outfile.write(result)
                     else:                        
                         self.output.put(self.map_fn(result))
         finally:
             if outfile:
                 outfile.close()
             self.builtin.cleanup(self.context)
     except Exception, e:
         _logger.debug("Caught exception from command: %s", e, exc_info=True)
         if self.__executing_sync:
             raise
         else:
             self.emit("exception", e)
Example #12
0
    def __init__(self,
                 filename=None,
                 content=None,
                 title=None,
                 parent=None,
                 autosave=False):
        gtk.Window.__init__(self, type=gtk.WINDOW_TOPLEVEL)
        vbox = gtk.VBox()
        self.add(vbox)
        self.__ui_string = """
<ui>
  <menubar name='Menubar'>
    <menu action='FileMenu'>
      <menuitem action='Save'/>
      <menuitem action='SaveAs'/>
      <separator/>
      <menuitem action='ReadOnly'/>
      <separator/>
      <menuitem action='Revert'/>
      <separator/>
      <menuitem action='Close'/>
    </menu>
    <menu action='EditMenu'>
      <menuitem action='Undo'/>
      <menuitem action='Redo'/>
      <separator/>
      <menuitem action='Find'/>
      <menuitem action='GotoLine'/>
    </menu>
    <menu action='ToolsMenu'>
      <menuitem action='About'/>
    </menu>
  </menubar>
</ui>
"""
        self.__create_ui()
        vbox.pack_start(self._ui.get_widget('/Menubar'), expand=False)

        self.__filename = os.path.abspath(filename)
        self.__autosave = autosave
        self.__modified = False
        self.__last_len = 0

        self.__save_text_id = 0

        self.gtksourceview_mode = gtksourceview_avail

        if gtksourceview_avail:
            self.input = SourceBuffer()
            self.input_view = SourceView(self.input)
            if gtksourceview2_avail:
                self.input.connect('notify::can-undo',
                                   lambda *args: self.__sync_undoredo())
                self.input.connect('notify::can-redo',
                                   lambda *args: self.__sync_undoredo())
            else:
                self.input.connect('can-undo',
                                   lambda *args: self.__sync_undoredo())
                self.input.connect('can-redo',
                                   lambda *args: self.__sync_undoredo())
        else:
            self.input = gtk.TextBuffer()
            self.input_view = gtk.TextView(self.input)
        self.input_view.set_wrap_mode(gtk.WRAP_WORD)
        self.input_view.connect("key-press-event",
                                self.__handle_key_press_event)

        scroll = gtk.ScrolledWindow()
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
        scroll.add(self.input_view)

        vbox.pack_start(scroll, True, True)

        if filename and os.path.isfile(self.__filename):
            _logger.debug("reading %s", self.__filename)
            f = open_text_file(self.__filename, 'r')
            self.__original_text = f.read()
        else:
            self.__original_text = content

        if self.__original_text:
            if gtksourceview_avail:
                self.input.begin_not_undoable_action()
            self.input.set_property('text', self.__original_text)
            self.__last_len = self.input.get_char_count()
            if gtksourceview_avail:
                self.input.end_not_undoable_action()

        self.input.move_mark_by_name('insert', self.input.get_start_iter())
        self.input.move_mark_by_name('selection_bound',
                                     self.input.get_start_iter())

        self.input.connect('mark-set', self.__on_mark_set)

        self.__searcharea = InlineSearchArea(self.input_view)
        self.__searcharea.connect('close', self.__on_search_close)
        self.__searcharea.show_all()
        self.__searcharea.hide()
        self.__searcharea.set_no_show_all(True)
        vbox.pack_start(self.__searcharea, expand=False)

        self.__status_hbox = gtk.HBox()
        self.__statusbar = gtk.Statusbar()
        self.__status_hbox.pack_start(self.__statusbar, expand=True)
        self.__statusbar_ctx = self.__statusbar.get_context_id("HotEditor")
        self.__pos_status = gtk.Statusbar()
        self.__pos_status.set_size_request(160, 10)  # Taken from GEdit
        self.__pos_context = self.__pos_status.get_context_id("HotEditor")
        self.__status_hbox.pack_start(self.__pos_status, expand=False)
        vbox.pack_start(self.__status_hbox, expand=False)
        self.__sync_undoredo()
        self.__sync_modified_sensitivity()

        self.input.connect("changed", self.__handle_text_changed)

        self.connect("delete-event", self.__handle_delete_event)
        self.__sync_title()
        if parent:
            self.set_transient_for(parent)
        self.set_size_request(800, 600)
Example #13
0
def cat(context, *files):
    _("""Yield content lines from file path arguments.""")
    for f in files:
        fpath = FilePath(f, context.cwd)
        for line in open_text_file(fpath):
            yield line