Exemplo n.º 1
0
 def do_close_if_needed(self):
     if (ShouldClose(self.node, self.fromState, self.newState)):
         InsertClosed(self.view, self.node,
                      evt.Make(self.do_recurrence_if_needed))
     else:
         RemoveClosed(self.view, self.node,
                      evt.Make(self.do_recurrence_if_needed))
Exemplo n.º 2
0
def UpdateProperty(view, node, key, value, onDone=None):
    def OnDrawer():
        # File is reloaded have to regrab node
        n = db.Get().At(view, node.start_row)
        if(not n):
            log.error("Failed to look up property drawer! Something is wrong!")
        start, end = n.property_drawer_location
        lkey = key.lower().strip()
        mrow = None
        # Work backwards, want to find the latest incarnation of this
        for row in range(end-1, start, -1):
            line = view.getLine(row)
            m = RE_PROPERTY_EXTRACT.search(line)
            if(m):
                k = m.group(1).strip()
                v = m.group(2).strip()
                if(k.lower() == lkey):
                    mrow = row
                    break
        # We found our property, replace it!
        if(mrow != None):
            pt = view.text_point(mrow, 0)
            rw = view.line(pt)
            text = "  {0}:{1}: {2}".format(n.indent(),key,value)
            view.ReplaceRegion(rw,text,onDone)
        # Otherwise add a new property
        else:
            AddProperty(view, n, key, value, onDone)
    InsertDrawerIfNotPresent(view, node, ":PROPERTIES:", evt.Make(OnDrawer))
Exemplo n.º 3
0
 def OnPostPostProcess(self):
     if (hasattr(self.curmod, "GeneratesImages")
             and self.curmod.GeneratesImages(self)):
         self.view.run_command("org_cycle_images",
                               {"onDone": evt.Make(self.OnDone)})
     else:
         self.OnDone()
Exemplo n.º 4
0
 def run(self, edit, dateval=None):
     if (type(dateval) == str):
         dateval = orgdate.OrgDateFreeFloating.from_str(dateval)
     # TODO: Find scheduled and replace it as well.
     node = db.Get().AtInView(self.view)
     if (node and not node.is_root()):
         self.oldsel = self.view.sel()[0]
         pt = self.view.text_point(node.start_row, 0)
         l = self.view.line(pt)
         # Last row handling If we are the last row we can't jump over the newline
         # we have to add one.
         nl = ""
         addnl = 1
         if (self.view.isBeyondLastRow(node.start_row + 1)):
             nl = "\n"
             addnl = 0
         insertpt = l.end() + addnl
         endpt = insertpt + len(nl) + len(node.indent()) + len(self.prefix)
         self.reg = sublime.Region(insertpt, endpt)
         self.view.insert(edit, insertpt, nl + node.indent() + self.prefix)
         pt = self.view.text_point(node.start_row + 1, 0)
         l = self.view.line(pt)
         self.view.sel().clear()
         self.view.sel().add(l.end())
         if (dateval == None):
             datep.Pick(evt.Make(self.insert))
         else:
             self.insert(dateval)
Exemplo n.º 5
0
 def on_done(self, index):
     if (index < 0):
         return
     newState = self.todoStates[index]
     if (newState == "none"):
         newState = ""
     # if we don't have a TODO state then we have to handle that as well.
     m = self.todoRe.search(self.bufferContents)
     fromState = None
     if (m == None):
         self.todoRe = re.compile(r"^([*]+ (\[\#[a-zA-Z0-9]+\]\s+)?)( )*")
     else:
         fromState = m.group(3)
     if (newState != ""):
         newState += " "
     self.bufferContents = self.todoRe.sub(r"\g<1>" + newState,
                                           self.bufferContents)
     # We have to do the editing in sequence because the reloads can get mixed up otherwise
     if (fromState):
         self.fromState = fromState.strip()
     else:
         self.fromState = ""
     self.newState = newState.strip()
     # Recurring events do not hit the done state when you toggle them
     # They bounce back to TODO they just get a new note in them
     if (ShouldRecur(self.node, self.fromState, self.newState)):
         self.do_note_if_needed()
     else:
         self.view.ReplaceRegion(self.row, self.bufferContents,
                                 evt.Make(self.do_note_if_needed))
Exemplo n.º 6
0
 def do_recurrence_if_needed(self):
     self.rec = ShouldRecur(self.node, self.fromState, self.newState)
     if (self.rec):
         InsertRecurrence(self.view, self.node, self.fromState,
                          self.newState,
                          evt.Make(self.on_update_timestamps_if_needed))
     else:
         self.on_totally_done()
Exemplo n.º 7
0
 def run(self, edit, text=None, onDone=None):
     self.onDone = onDone
     self.text = text.strip() if text != None else text
     if (self.text != None and self.text != ""):
         self.OnDone(self.text)
     else:
         self.input = insSel.OrgInput()
         self.input.run("Tag:", db.Get().tags, evt.Make(self.OnDone))
Exemplo n.º 8
0
 def on_panel_ready(self, index, openas, panel):
     self.panel = panel
     global captureBufferName
     captureBufferName = sets.Get("captureBufferName", captureBufferName)
     window = self.view.window()
     template = self.templates[index]
     target, capturePath, captureFile, at = GetCapturePath(
         self.view, template)
     if (panel.is_loading()):
         sublime.set_timeout_async(
             lambda: self.on_panel_ready(index, openas, panel), 100)
         return
     startPos = -1
     # Try to store the capture index
     panel.settings().set('cap_index', index)
     panel.settings().set('cap_view', self.view.id())
     self.openas = openas
     if ('template' in template):
         startPos = self.insert_template(template['template'], panel)
         window.run_command('show_panel',
                            args={'panel': 'output.orgcapture'})
         panel.sel().clear()
         panel.sel().add(startPos)
         window.focus_view(panel)
         self.cleanup_capture_panel()
     elif ('snippet' in template):
         self.level = 0
         self.pt = None
         prefix = ""
         if (self.openas):
             insertAt = captureFile.At(at)
             self.pt = panel.text_point(insertAt.end_row + 1, 0)
             self.insertRow = insertAt.end_row + 1
             linev = panel.line(self.pt)
             linetxt = panel.substr(linev)
             if (linetxt and not linetxt.strip() == ""):
                 prefix = "\n"
                 self.pt = linev.end()
                 self.insertRow += 1
             else:
                 self.pt = linev.begin()
             panel.sel().clear()
             panel.sel().add(self.pt)
             self.level = insertAt.level
         else:
             window.run_command('show_panel',
                                args={'panel': 'output.orgcapture'})
         if (self.openas and self.level > 0):
             self.index = index
             self.panel = panel
             self.panel.Insert(self.pt, prefix + ("*" * self.level),
                               evt.Make(self.on_added_stars))
         else:
             self.insert_snippet(index)
Exemplo n.º 9
0
def InsertRecurrence(view, node, fromState, toState, onDone=None):
    #   - State "DONE"       from "TODO"       [2009-09-29 Tue]"
    stamp = OrgDate.format_clock(datetime.datetime.now(), active=False)

    def OnLogAdded():
        props.UpdateProperty(view, node, "LAST_REPEAT", stamp, onDone)

    props.AddLogbook(
        view, node,
        "- State {0:12} from {1:12} ".format('"' + toState + '"',
                                             '"' + fromState + '"'), stamp,
        evt.Make(OnLogAdded))
Exemplo n.º 10
0
 def run(self, edit):
     n = db.Get().AtInView(self.view)
     s = self.view.text_point(n.start_row, 0)
     e = self.view.line(self.view.text_point(n.end_row, 0)).end()
     r = sublime.Region(s, e)
     ct = self.view.substr(r)
     start = ""
     #if "#+TITLE:" not in ct:
     #	start = "#+TITLE: " + os.path.splitext(os.path.basename(self.view.file_name()))[0]
     tempFile = tf.CreateTempFileFromRegion(self.view, r, ".org", start)
     #print("temp file: " + str(tempFile))
     self.tempView = self.view.window().open_file(tempFile)
     self.tempView.run_command('org_export_file_org_html',
                               {"onDone": evt.Make(self.onDone)})
Exemplo n.º 11
0
 def run(self,edit,onDone=None):
   self.onDone = onDone
   n = db.Get().AtInView(self.view)
   if(n == None):
     log.error(" Failed to find node! Subtree cannot be exported!")
     return
   index = 0
   for i in range(0,len(n.env._nodes)):
     if(n == n.env._nodes[i]):
       index = i
   if(index == 0):
     log.error(" Failed to find node in file! Something is wrong. Cannot export subtree!")
     return
   self.view.run_command('org_export_file_org_html', {"onDone": evt.Make(self.OnDone), "index": index, "suffix":"_subtree"})
Exemplo n.º 12
0
 def run(self,edit, onDone=None, index=None, suffix=""):
   self.file = db.Get().FindInfo(self.view)
   self.onDone = onDone
   self.suffix = suffix
   if(index != None):
     self.index = index
   else:
     self.index = None
   if(None == self.file):
     log.error("Not an org file? Cannot build reveal document")
     evt.EmitIf(onDone)  
     return
   if(sets.Get("htmlExecuteSourceOnExport",True)):
     self.view.run_command('org_execute_all_source_blocks',{"onDone":evt.Make(self.OnDoneSourceBlockExecution),"amExporting": True})
   else:
     self.OnDoneSourceBlockExecution()
Exemplo n.º 13
0
 def run(self, edit, onDone=None):
     self.onDone = onDone
     # Schedule this item so it is in the agenda
     self.view.run_command("org_schedule",
                           {"dateval": str(datetime.datetime.now())})
     # Create a link to the current location so we can insert it in our today item
     self.link = orglink.CreateLink(self.view)
     curNode = db.Get().AtInView(self.view)
     # Should we add a heading to this?
     if (curNode and not curNode.is_root()):
         self.ed = RunEditingCommandOnToday(
             self.view, "org_insert_text_as_child_heading",
             {'heading': curNode.heading})
         self.ed.Run(evt.Make(self.InsertLink))
     else:
         self.InsertLink()
Exemplo n.º 14
0
def ProcessPossibleSourceObjects(cmd, language, cmdArgs):
    #BuildFullParamList(cmd,language,cmdArgs)
    var = cmd.params.GetDict('var', None)
    cmd.params.Replace('var', var)
    cmd.deferedSources = 0
    hadDeferred = False
    if (var):
        for k in var:
            n = var[k]
            if (not util.numberCheck(n)):
                td = tbl.LookupTableFromNamedObject(n)
                if (td):
                    # I think it's better to just pass through the table here.
                    # Each language may want to do something very different and abstracting away
                    # What the data source actually is may actually be a disservice
                    #var[k] = GetGeneratorForTable(td,cmd.params)
                    var[k] = td
                else:
                    l = lst.LookupNamedListInFile(n)
                    if (l):
                        var[k] = l
                    else:
                        pt = LookupNamedSourceBlockInFile(n)
                        if (None != pt):
                            if (not n in cmd.sourcefns):
                                cmd.deferedSources += 1
                                hadDeferred = True
                                cmd.sourcefns[n] = {
                                    'at': pt,
                                    'key': k,
                                    'name': n
                                }
                                cmd.view.run_command(
                                    'org_execute_source_block', {
                                        'at':
                                        pt,
                                        'onDoneResultsPos':
                                        evt.Make(cmd.OnDoneFunction),
                                        'onDoneFnName':
                                        n
                                    })
    return hadDeferred
Exemplo n.º 15
0
 def run(self, edit, onDone=None):
     self.onDone = onDone
     self.input = insSel.OrgInput()
     #print(str(db.Get().customids))
     self.input.run("Custom Id:",
                    db.Get().customids, evt.Make(self.on_done))
Exemplo n.º 16
0
 def run(self, edit, onDone=None):
     self.onDone = onDone
     self.view.run_command("org_insert_tag", {
         "onDone": evt.Make(self.OnDone),
         "text": "ARCHIVE"
     })
Exemplo n.º 17
0
 def OnHidden(self):
     self.view.run_command("org_show_images",
                           {"onDone": evt.Make(self.OnShown)})
Exemplo n.º 18
0
 def run(self, edit, onDone=None):
     self.onDone = onDone
     self.cursor = self.view.sel()[0]
     self.view.run_command("org_hide_images",
                           {"onDone": evt.Make(self.OnHidden)})
Exemplo n.º 19
0
 def run(self, edit):
     datep.Pick(evt.Make(self.insert))
Exemplo n.º 20
0
 def on_insert_note(self, text):
     InsertNote(self.view, self.node, text, self.fromState, self.newState,
                evt.Make(self.do_close_if_needed))
Exemplo n.º 21
0
    def Execute(self):
        view = self.view
        self.outHandler = SetupOutputHandler(self)
        self.outFormatter = SetupOutputFormatter(self)

        # Run the "writer"
        if (hasattr(self.curmod, "Execute")):
            # Okay now time to replace the contents of the block
            self.source = view.substr(self.region)
            if (hasattr(self.curmod, "PreProcessSourceFile")):
                self.curmod.PreProcessSourceFile(self)
            if (hasattr(self.curmod, "Extension")):
                tmp = tempfile.NamedTemporaryFile(
                    delete=False, suffix=self.curmod.Extension(self))
                try:
                    self.filename = tmp.name
                    if (hasattr(self.curmod, "WrapStart")):
                        tmp.write((self.curmod.WrapStart(self) +
                                   "\n").encode("ascii"))
                    tmp.write(self.source.encode('ascii'))
                    if (hasattr(self.curmod, "WrapEnd")):
                        tmp.write(
                            ("\n" + self.curmod.WrapEnd(self)).encode("ascii"))
                    tmp.close()
                    self.outputs = self.curmod.Execute(self, sets)
                except:
                    log.debug(" " + traceback.format_exc())
                finally:
                    pass
            else:
                self.filename = None
                self.outputs = self.curmod.Execute(self, sets)
            log.debug("OUTPUT: " + str(self.outputs))
        else:
            log.error("No execute in module, abort")
            return
        # Reformat adding indents to each line!
        # No bad formatting allowed!
        n = db.Get().AtPt(view, self.s)
        self.level = n.level
        self.outHandler.SetIndent(n.level)
        if (self.outFormatter):
            self.outFormatter.SetIndent(n.level)
        output = self.outHandler.FormatOutput(self.outputs)
        self.preFormattedOutput = output
        self.resultsTxtStart = self.resultsStartPt + self.level + 1
        rowadjust = 0
        if (self.outFormatter):
            output, rowadjust = self.outFormatter.FormatOutput(output)
        # If our formatter wrapped us we have to adjust our text point for post processing
        # and results text.
        if (rowadjust > 0):
            row, col = self.view.rowcol(self.resultsTxtStart)
            row += rowadjust
            self.resultsTxtStart = self.view.text_point(row, col)
        ## Keep track of this so we know where we are inserting the text.
        self.formattedOutput = (" " * self.level + " ") + output + '\n'
        if (self.CheckResultsFor('silent')):
            # We only echo to the console in silent mode.
            print(self.formattedOutput)
            self.silent = True
            self.OnReplaced()
        # Add after other text
        elif (self.CheckResultsFor('append')):
            self.view.run_command(
                "org_internal_replace", {
                    "start": self.resultsEndPt,
                    "end": self.resultsEndPt,
                    "text": self.formattedOutput,
                    "onDone": evt.Make(self.OnReplaced)
                })
        # Add before other text
        elif (self.CheckResultsFor('prepend')):
            self.view.run_command(
                "org_internal_replace", {
                    "start": self.resultsStartPt,
                    "end": self.resultsStartPt,
                    "text": self.formattedOutput,
                    "onDone": evt.Make(self.OnReplaced)
                })
        # Replace mode
        else:
            self.view.run_command(
                "org_internal_replace", {
                    "start": self.resultsStartPt,
                    "end": self.resultsEndPt,
                    "text": self.formattedOutput,
                    "onDone": evt.Make(self.OnReplaced)
                })
Exemplo n.º 22
0
 def InsertLink(self):
     self.ed = RunEditingCommandOnToday(self.view, "org_append_text",
                                        {'text': self.link})
     self.ed.Run(evt.Make(self.OnDone))
Exemplo n.º 23
0
 def on_update_timestamps_if_needed(self, row=0):
     # We have to reload our node as we updated things.
     self.node = db.Get().At(self.view, self.node.start_row)
     if (row > (self.node.local_end_row + 1)):
         self.on_totally_done()
     for i in range(self.node.start_row + row, self.node.local_end_row + 1):
         pt = self.view.text_point(i, 0)
         line = self.view.line(pt)
         txt = self.view.substr(line)
         m = RE_T.search(txt)
         now = datetime.datetime.now()
         if (m):
             tsl = OrgDate.list_from_str(m.group('time'))
             if (tsl):
                 t = tsl[0]
                 if (t.repeating):
                     next = t.start
                     next2 = t.end
                     if (t.repeatpre == "+"):
                         next = t.next_repeat_from(oa.EnsureDateTime(next))
                     elif (t.repeatpre == "++"):
                         while (next < now):
                             next = t.next_repeat_from(
                                 oa.EnsureDateTime(next))
                     elif (t.repeatpre == ".+"):
                         next = t.next_repeat_from(now)
                     s = m.start(1)
                     e = m.end(1)
                     rpt = t.repeatpre + str(t.repeatnum) + t.repeatdwmy
                     wrn = ""
                     if (t.warning):
                         wrn = " " + t.warnpre + str(t.warnnum) + t.warndwmy
                     if (t.has_end()):
                         if (t.has_time()):
                             nout = txt[:s] + next.strftime(
                                 "<%Y-%m-%d %a %H:%M-") + t.end.strftime(
                                     "%H:%M ") + rpt + wrn + ">" + txt[e:]
                         else:
                             # This really shouldn't happen.
                             nout = txt[:s] + next.strftime(
                                 "<%Y-%m-%d %a "
                             ) + rpt + wrn + ">" + txt[e:]
                     else:
                         if (t.has_time()):
                             nout = txt[:s] + next.strftime(
                                 "<%Y-%m-%d %a %H:%M "
                             ) + rpt + wrn + ">" + txt[e:]
                         else:
                             nout = txt[:s] + next.strftime(
                                 "<%Y-%m-%d %a "
                             ) + rpt + wrn + ">" + txt[e:]
                     self.view.run_command(
                         "org_internal_replace", {
                             "start":
                             line.begin(),
                             "end":
                             line.end(),
                             "text":
                             nout,
                             "onDone":
                             evt.Make(lambda: self.
                                      on_update_timestamps_if_needed(i + 1))
                         })
                     return
     self.on_totally_done()
Exemplo n.º 24
0
    def run(self, edit):
        view = self.view
        at = view.sel()[0]
        if (view.match_selector(at.begin(), 'orgmode.fence.dynamicblock')):
            # Okay we have a dynamic block, now we need to know where it ends.
            start = at.begin()
            end = None
            erow = view.endRow()
            row = view.curRow()
            for rw in range(row, erow + 1):
                line = view.substr(view.line(view.text_point(rw, 0)))
                if (RE_END.search(line)):
                    end = rw
                    break
            if (not end):
                log.debug("Could not locate #+END: tag")
                return
            # Okay now we have a start and end to build a region out of.
            # time to run a command and try to get the output.
            dynamic = ext.find_extension_modules(
                'orgdynamic', ["insertdatetime", "clocktable", "columnview"])
            line = view.substr(view.line(start))
            m = RE_DYN_BLOCK.search(line)
            if (not m):
                log.error("FAILED TO PARSE DYNAMIC BLOCK: " + line)
                return
            fnname = m.group('name')
            #log.debug("DYN NAME: " + fnname)
            params = PList.createPList(line[len(m.group(0)):])
            # Now find me that function!
            if (fnname not in dynamic):
                log.error(
                    "Function not found in dynamic folder! Cannot execute!")
                return
            # Run the "writer"
            if (hasattr(dynamic[fnname], "Execute")):
                self.curmod = dynamic[fnname]
                self.params = params
                outputs = self.curmod.Execute(view, params)
                #log.debug("OUTPUT: " + str(outputs))

            # Okay now time to replace the contents of the block
            s = view.text_point(row + 1, 0)
            e = view.text_point(end, 0)
            self.region = sublime.Region(s, e)
            # Reformat adding indents to each line!
            # No bad formatting allowed!
            n = db.Get().AtInView(view)
            level = n.level
            indent = "\n" + (" " * level) + " "
            #outputs = output.split('\n')
            output = indent.join(outputs)
            print(output)
            self.view.run_command(
                "org_internal_replace", {
                    "start": s,
                    "end": e,
                    "text": (" " * level + " ") + output + "\n",
                    "onDone": evt.Make(self.on_replaced)
                })
        else:
            log.error("NOT in A DynamicBlock, nothing to run")