Beispiel #1
0
def find_extension_modules(folder, builtins):
    importlib.invalidate_caches()
    #base = os.path.dirname(os.path.abspath(__file__))
    base = sublime.packages_path()
    path = base + '/' + folder
    moduleTable = {}
    # Built in extensions
    #for root, dirnames, filenames in os.walk(path):
    #	for filename in fnmatch.filter(filenames, '*.py'):
    #		if '__init__' in filename or 'abstract' in filename:
    #			continue
    for filename in builtins:
        filename = filename + ".py"
        force = sets.Get("forceLoadInternalExtensions", False)
        module = load_module("OrgExtended", folder, filename, force)
        moduleTable[filename.split('.')[0]] = module
    # User generated extensions
    path = os.path.join(base, 'User', folder)
    for root, dirnames, filenames in os.walk(path):
        for filename in fnmatch.filter(filenames, '*.py'):
            if '__init__' in filename or 'abstract' in filename:
                continue
            # Only reload if the file is newer.
            # NOTE: Due to how import works, it will not
            #       reload the file until sublime reloads
            #       so we have to track that ourselves
            #       in the loadModCache.
            fullfilename = os.path.join(path, filename)
            lastMod = os.path.getmtime(fullfilename)
            force = fullfilename not in lastModCache or lastMod > lastModCache[
                fullfilename] or sets.Get("forceLoadExternalExtensions", False)
            lastModCache[fullfilename] = lastMod
            module = load_module("User", folder, filename, force)
            moduleTable[filename.split('.')[0]] = module
    return moduleTable
 def RebuildDb(self):
     if(evt.Get().listeners('tagsfound')):
         evt.Get().clear_listeners('tagsfound')
     evt.Get().on("tagsfound",self.OnTags)
     self.Files = []
     self.files = {}
     self.orgPaths = sets.Get("orgDirs",None)
     self.orgFiles = sets.Get("orgFiles",None)
     self.orgExcludePaths = sets.Get("orgExcludeDirs",None)
     self.orgExcludeFiles = sets.Get("orgExcludeFiles",None)
     matches = []
     if(self.orgPaths):
         for orgPath in self.orgPaths:
             orgPath = orgPath.replace('\\','/')
             globSuffix = sets.Get("validOrgExtensions",[".org"])
             for suffix in globSuffix:
                 if('archive' in suffix):
                     continue
                 suffix = "*" + suffix
                 dirGlobPos = orgPath.find("*")
                 if(dirGlobPos > 0):
                     suffix  = os.path.join(orgPath[dirGlobPos:],suffix)
                     orgPath = orgPath[0:dirGlobPos]
                 if("*" in orgPath):
                     log.error(" orgDirs only supports double star style directory wildcards! Anything else is not supported: " + str(orgPath))
                     if(sublime.active_window().active_view()):
                         sublime.active_window().active_view().set_status("Error: ","orgDirs only supports double star style directory wildcards! Anything else is not supported: " + str(orgPath))
                     log.error(" skipping orgDirs value: " + str(orgPath))
                     continue
                 if not Path(orgPath).exists():
                     log.warning('orgDir path {} does not exist!'.format(orgPath))
                     continue
                 try:
                     for path in Path(orgPath).glob(suffix):
                         if OrgDb.IsExcluded(str(path), self.orgExcludePaths, self.orgExcludeFiles):
                             continue
                         try:
                             filename = str(path)
                             file = FileInfo(filename,loader.load(filename), self.orgPaths)
                             self.AddFileInfo(file)
                         except Exception as e:
                             #x = sys.exc_info()
                             log.warning("FAILED PARSING: %s\n  %s",str(path),traceback.format_exc())
                 except Exception as e:
                     log,logging.warning("ERROR globbing {}\n{}".format(orgPath, traceback.format_exc()))
     if(self.orgFiles):
         for orgFile in self.orgFiles:
             path = orgFile.replace('\\','/')
             if OrgDb.IsExcluded(str(path), self.orgExcludePaths, self.orgExcludeFiles):
                 continue
             try:
                 filename = str(path)
                 file = FileInfo(filename,loader.load(filename), self.orgPaths)
                 self.AddFileInfo(file)
             except Exception as e:
                 #x = sys.exc_info()
                 log.warning("FAILED PARSING: %s\n  %s",str(path),traceback.format_exc())
     self.SortFiles()
     self.RebuildIds()
Beispiel #3
0
def onActivated(view):
    shouldHandleActivationFolding = sets.Get("onFocusRespectStartupFolds",
                                             None)
    if (shouldHandleActivationFolding):
        # Now lets respect the fold state if we have any.
        file = db.Get().FindInfo(view)
        if (file):
            r = file.org[0]
            globalStartup = sets.Get("startup", ["showall"])
            startup = r.startup(globalStartup)
            if (Startup.overview in startup or Startup.fold in startup):
                fold_all_but_my_tree(view)
            elif (Startup.content in startup):
                fold_all_but_my_tree(view)
        fold_all_links(view)
Beispiel #4
0
def dayPageFilenameToDateTime(view):
    filename = view.file_name()
    if (not filename):
        return None
    formatStr = sets.Get("dayPageNameFormat", "%a_%Y_%m_%d")
    filename = os.path.splitext(os.path.basename(filename))[0]
    return datetime.datetime.strptime(filename, formatStr)
Beispiel #5
0
def plugin_loaded():
    evt.Get().off("tagsfound",db.Get().OnTags)
    sets.setup_user_settings()
    # Load our settings file.
    # We probably need a command to reload it
    # When it is modified, and probably to reload
    # the DB automatically when your orgs change.
    sets.Load()
    clocking.Load()

    # To enable debug logging, set the env var to a non-blank value.
    # This is the same pattern that neovintageous uses and I think
    # it is a reasonably decent mechanism
    _DEBUG = bool(os.getenv('SUBLIME_ORGEXTENDED_DEBUG'))
    _DEBUG = _DEBUG or sets.Get("enableDebugLogging",False)
    #_DEBUG = True
    if _DEBUG:
        logger = logging.getLogger('OrgExtended')
        logger.propagate = 0
        if not logger.hasHandlers():
            logger.setLevel(logging.DEBUG)
            stream_handler = logging.StreamHandler()
            stream_handler.setFormatter(logging.Formatter(
                'Org: %(levelname)-7s [%(filename)15s:%(lineno)4d] %(message)s'
            ))
            logger.addHandler(stream_handler)
            logger.debug('debug logger initialized')
    global log
    log = logging.getLogger(__name__)
    db.Get().RebuildDb()
    #window = sublime.active_window()
    #if window is None:
    sublime.set_timeout_async(lambda: sync_up_on_loaded(), 1000)
    log.debug("DONE INITIALIZING ORG CAPTURE")
Beispiel #6
0
 def HandleEntering(self, m, l, orgnode):
     self.skipSrc = False
     language = m.group('lang')
     paramstr = l[len(m.group(0)):]
     p = type('', (), {})() 
     src.BuildFullParamList(p,language,paramstr,orgnode)
     exp = p.params.Get("exports",None)
     # Have to pass on parameter to the results block
     self.e.sparams = p
     if(isinstance(exp,list) and len(exp) > 0):
         exp = exp[0]
     if(exp == 'results' or exp == 'none'):
         self.skipSrc = True
         return
     # Some languages we skip source by default
     skipLangs = sets.Get("revealDefaultSkipSrc",[])
     if(exp == None and language == skipLangs):
         self.skipSrc = True
         return
     attribs = ""
     if("data-noescape" in params):
         attribs += " data-noescape"
     if("data-trim" in params):
         attribs += " data-trim"
     if("data-line-numbers" in params):
         attribs += " data-line-numbers=\"{nums}\"".format(nums=params["data-line-numbers"])
     self.options, self.float, self.caption = self.HandleOptions()
     if(haveLang(language)):
         self.e.doc.append("    <pre><code language=\"{language}\" {attribs}>".format(language=mapLanguage(language),attribs=attribs))
     else:
         self.e.doc.append("    <pre><code {attribs}>".format(attribs=attribs))
Beispiel #7
0
 def HandleEntering(self, m, l, orgnode):
     self.skipSrc = False
     language = m.group('lang')
     paramstr = l[len(m.group(0)):]
     p = type('', (), {})()
     src.BuildFullParamList(p, language, paramstr, orgnode)
     exp = p.params.Get("exports", None)
     # Have to pass on parameter to the results block
     self.e.sparams = p
     if (isinstance(exp, list) and len(exp) > 0):
         exp = exp[0]
     if (exp == 'results' or exp == 'none'):
         self.skipSrc = True
         return
     # Some languages we skip source by default
     skipLangs = sets.Get("latexDefaultSkipSrc", [])
     if (exp == None and language == skipLangs):
         self.skipSrc = True
         return
     attribs = ""
     self.options, self.float, self.caption = self.HandleOptions()
     self.e.doc.append(r"  \begin{center}")
     self.e.doc.append(r"  \centering")
     if (haveLang(language)):
         self.e.doc.append(
             r"  \begin{options}{{lstlisting}}[language={{{lang}}}]".format(
                 options=self.options, lang=mapLanguage(language)))
     else:
         self.e.doc.append(r"  \begin{options}{{lstlisting}}".format(
             options=self.options))
Beispiel #8
0
 def __GetPaths(self, name):
     paths = sets.Get(name, None)
     if (str == type(paths)):
         return os.path.expanduser(paths)
     if (list == type(paths)):
         return list(map(os.path.expanduser, paths))
     return None
 def redraw(self):
     if(None == self.inputpanel):
         return
     ff = sets.Get("input_font_face","Arial")
     content = "<html><body id=\"orgselect\">"
     content += """<style>
     div.orgselect {
         background-color: #202020;
         font-family: """ + ff + """;
         padding: 7px;
         border: 2px solid #73AD21;
         border-style: none none none solid;
     }
     div.currentsel {
         background-color: #353555;
     }
     </style><div class=\"orgselect\">"""
     if(hasattr(self,'matched')):
         if(not self.current in self.matched and len(self.matched) > 0):
             self.current = self.matched[0]
         for i in self.matched:
             if(i == self.current):
                 content += "<div class=\"currentsel\">" + i + "</div>"
             else:
                 content += i + "<br>"
     content += "</div></body></html>"
     #self.inputpanel.show_popup_menu(self.matched,None) 
     #self.inputpanel.show_popup(content,sublime.COOPERATE_WITH_AUTO_COMPLETE,-1) 
     if(None != content and content != ""):
         self.popup(content)
Beispiel #10
0
def Setup():
    global notice
    checkPeriod = sets.Get("noticePeriod", 1) * 60
    if (checkPeriod < 60):
        checkPeriod = 60
    notice = NotificationSystem(interval=timedelta(seconds=checkPeriod))
    notice.start()
    log.debug("NOTIFICATION SYSTEM IS UP AND RUNNING: " + str(checkPeriod))
Beispiel #11
0
 def run(self, edit):
     refile = sets.Get("refile", None)
     log.debug("REFILE: ", refile)
     if (refile):
         self.view.window().open_file(refile)
     else:
         log.error(
             "Could not find refile file, have you set it in your config?")
Beispiel #12
0
    def CheckNotifications(self):
        log.debug("CHECKING...")
        if (datetime.now().day > self.todaysDate or self.today == None):
            self.todaysDate = datetime.now().day
            self.notified = {}
            self.BuildToday()
        # Periodically rebuild the day.
        if ((self.checkcount % 4) == 0):
            self.checkcount += 1
            self.BuildToday()

        hours = sets.Get("notifyHoursBefore", 0)
        minutes = sets.Get("notifyMinsBefore", 15)
        for item in self.today:
            n = item['node']
            if (IsWithinNotificationWindow(n, hours, minutes)
                    and not self.HaveNotifiedFor(item)):
                log.debug("DO NOTIFY CALLED")
                self.DoNotify(item)
Beispiel #13
0
def dayPageGetPath():
    dpPath = sets.Get("dayPagePath", None)
    if (dpPath == None):
        sublime.status_message(
            "Day Page error. dayPagePath setting is not set!")
        log.error(
            " Cannot create day page without dayPathPath in configuration")
        return None
    os.makedirs(dpPath, exist_ok=True)
    return dpPath
Beispiel #14
0
 def Reload(self, fileOrView):
     self.orgPaths = sets.Get("orgDirs", None)
     fi = self.FindInfo(fileOrView)
     if (fi != None):
         fi.Reload()
         self.RebuildIds()
         return fi
     else:
         rv = self.LoadNew(fileOrView)
         self.RebuildIds()
         return rv
Beispiel #15
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)
Beispiel #16
0
 def run(self, edit):
     style = sets.Get("PandocStyle", "blocky")
     css = GetCssForHtmlExport(style)
     outFile = tf.GetViewFileAs(self.view, ".html")
     cmd = [Pandoc(), "-s", "-c", css]
     inHeader = GetHeaderData(style)
     if (inHeader):
         cmd.extend(inHeader)
     cmd.extend(["-o", outFile, self.view.file_name()])
     print(cmd)
     Execute(cmd)
Beispiel #17
0
 def run(self, edit):
     templates = sets.Get("captureTemplates", [])
     temps = []
     for temp in templates:
         log.debug("TEMPLATE: ", temp)
         temps.append(temp['name'])
     if (int(sublime.version()) >= 4096):
         self.view.window().show_quick_panel(temps, self.on_done_base_st4,
                                             -1, -1)
     else:
         self.view.window().show_quick_panel(temps, self.on_done_base_st3,
                                             -1, -1)
Beispiel #18
0
def FindImageFile(view, url):
    # ABS
    if (os.path.isabs(url)):
        return url
    # Relative
    if (view != None):
        curDir = os.path.dirname(view.file_name())
        filename = os.path.join(curDir, url)
        if (os.path.isfile(filename)):
            return filename
    # In search path
    searchHere = sets.Get("imageSearchPath", [])
    for direc in searchHere:
        filename = os.path.join(direc, url)
        if (os.path.isfile(filename)):
            return filename
    searchHere = sets.Get("orgDirs", [])
    for direc in searchHere:
        filename = os.path.join(direc, "images", url)
        if (os.path.isfile(filename)):
            return filename
Beispiel #19
0
def onDeactivated(view):
    global captureBufferName
    global lastHeader
    if (view.name() == captureBufferName):
        tempIndex = view.settings().get('cap_index')
        templates = sets.Get("captureTemplates", [])
        template = templates[tempIndex]
        #outpath, outfile = GetCaptureOutput()
        #print('template index was: ' + str(tempIndex))
        target, capturePath, captureFile, at = GetCapturePath(
            GetViewById(view.settings().get('cap_view')), template)
        #refilePath = sets.Get("refile","UNKNOWN")
        #refile = load(refilePath)
        captureFileRoot = None
        if (captureFile != None):
            captureFileRoot = captureFile.org

        bufferContentsToInsert = view.substr(sublime.Region(0, view.size()))
        if not bufferContentsToInsert.endswith('\n'):
            bufferContentsToInsert += "\n"
        didInsert = False
        # Get a capture node
        captureNode = loader.loads(bufferContentsToInsert)
        # if we moused out of the window we might be replacing
        # ourselves again.
        if (lastHeader == None):
            lastHeader = str(captureNode[1].heading)
        # We may haved moved around in the capture file
        # so find the old heading.
        for heading in captureFileRoot:
            if (type(heading) is node.OrgRootNode):
                continue
            if str(heading.heading) == lastHeader:
                #log.debug("REPLACING: " + str(heading.heading))
                heading.replace_node(captureNode[1])
                didInsert = True
                continue
        if (not didInsert):
            insertAt = captureFileRoot
            inserted = captureNode[1]
            if (at != None and at > 0):
                # This does not work? its a node not a file
                insertAt = captureFile.At(at)
            insertAt.insert_child(inserted)
        f = open(capturePath, "w+")
        # reauthor the ENTIRE file.
        # This can get expensive!
        for item in captureFileRoot:
            f.write(str(item))
        f.close()
        lastHeader = str(captureNode[1].heading)
        log.debug("***************>>>>> [" + view.name() + "] is no more")
Beispiel #20
0
def plot_table_command(table,view):
    # First get parameters
    ps = plot_get_params(table,view)
    # Next build the data file
    datafile = plot_build_data_file(table,ps)
    # Next build the plot command file
    plot_build_command_file(table,ps)
    # Shell out to gnu plot
    plotcmd = sets.Get("gnuplot",r"C:\Program Files\gnuplot\bin\gnuplot.exe")
    output = ps['_filename']

    outpath    = os.path.dirname(output)
    sourcepath = os.path.dirname(view.file_name())
    commandLine = [plotcmd, "-c", ps['_gpltfile'] ]
    try:
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    except:
        startupinfo = None
    cwd = os.path.join(sublime.packages_path(),"User") 
    if(output == "viewer" and platform.system() == "Windows"):
        global ppp
        ppp = subprocess.Popen(commandLine, universal_newlines=True, cwd=cwd, startupinfo=startupinfo, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        o = ""
        e = ""
    else:
        popen = subprocess.Popen(commandLine, universal_newlines=True, cwd=cwd, startupinfo=startupinfo, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (o,e) = popen.communicate()
    print("Attempting to plot data from table:")
    print("STDOUT: \n" + str(o))
    print("STDERR: \n" + str(e))
    cullTempFiles = True
    if(cullTempFiles):
        if(os.path.exists(ps['_datafile'])):
            os.remove(ps['_datafile']) 
        if(os.path.exists(ps['_gpltfile'])):
            os.remove(ps['_gpltfile']) 
    row = view.curRow()
    node = db.Get().At(view, row)
    level = 1
    indent = " "
    if(node):
        level = node.level
        indent = " " * level + " "
    o = indent + "#+RESULTS:\n"+indent+"[[file:" + output.replace("\\","/") + "]]"
    if(output != "viewer"):
        have = plot_find_results(table,view)
        if(not have):
            o = "\n" + o
        view.run_command("org_internal_replace", {"start": table.resultsRegion.begin(), "end": table.resultsRegion.end(), "text": o})
    print(o)
Beispiel #21
0
def Execute(cmd, sets):
    exe = sets.Get("graphviz", None)
    if (exe == None):
        print(
            "ERROR: cannot find graphviz executable file. Please setup the graphviz key in your settings file"
        )
        return ["ERROR - missing graphviz executable file"]
    output = "diagram"
    format = cmd.params.Get('fmt', "png")
    engine = cmd.params.Get('engine', "default")
    output = output + "." + format
    cmd.output = cmd.params.Get('file', output)

    if (engine != "default"):
        if (platform.system() == "Windows"):
            if (not engine.endswith(".exe")):
                engine = engine + ".exe"
        exe = os.path.join(os.path.dirname(exe), engine)
    outpath = os.path.dirname(cmd.filename)
    sourcepath = os.path.dirname(cmd.sourcefile)
    destFile = os.path.join(sourcepath, cmd.output)
    commandLine = [exe, "-T" + format, cmd.filename, "-o", destFile]
    #print(str(commandLine))
    #commandLine = [r"java", "-jar", jarfile, "-help"]
    try:
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    except:
        startupinfo = None
    # cwd=working_dir, env=my_env,
    os.makedirs(os.path.dirname(destFile), exist_ok=True)
    cwd = os.path.join(sublime.packages_path(), "User")
    popen = subprocess.Popen(commandLine,
                             universal_newlines=True,
                             cwd=cwd,
                             startupinfo=startupinfo,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

    #popen.wait()
    (o, e) = popen.communicate()

    #convertFile = os.path.join(outpath,os.path.splitext(os.path.basename(cmd.filename))[0] + ".png")
    #copyfile(convertFile, destFile)
    #print(str(os.path.basename(cmd.sourcefile)))
    #print(str(os.path.splitext(cmd.filename)))
    #print(str(os.path.splitext(cmd.sourcefile)))
    #destFile = os.path.relpath(destFile, sourcepath)
    #o = "[[file:" + destFile + "]]" + o
    return o.split('\n') + e.split('\n')
Beispiel #22
0
 def EscAndLinks(self, l):
   line = html.escape(l)
   m = RE_LINK.search(line)
   if(m):
     link = m.group('link').strip()
     desc = m.group('desc')
     if(not desc):
       desc = link
     else:
       desc = desc.strip()
     if(link.endswith(".png") or link.endswith(".jpg") or link.endswith(".jpeg") or link.endswith(".gif")):
       if(link.startswith("file:")):
         link = re.sub(r'^file:','',link)  
       extradata = ""  
       if(self.commentName and self.commentName in link):
         extradata =  " " + self.commentData
         self.commentName = None
       if(hasattr(self,'attrs')):
         for key in self.attrs:
           extradata += " " + str(key) + "=\"" + str(self.attrs[key]) + "\""
       preamble = ""
       postamble = ""
       if(hasattr(self,'caption') and self.caption):
         preamble = "<div class=\"figure\"><p>"
         postamble = "</p><p><span class=\"figure-number\">Figure {index}: </span>{caption}</p></div>".format(index=self.figureIndex,caption=self.caption)
         self.figureIndex += 1
       line = RE_LINK.sub("{preamble}<img src=\"{link}\" alt=\"{desc}\"{extradata}>{postamble}".format(preamble=preamble,link=link,desc=desc,extradata=extradata,postamble=postamble),line)
       self.ClearAttributes()
     else:
       line = RE_LINK.sub("<a href=\"{link}\">{desc}</a>".format(link=link,desc=desc),line)
       self.ClearAttributes()
   else:
     line = exp.RE_BOLD.sub(r"<b>\1</b>",line)
     line = exp.RE_ITALICS.sub(r"<i>\1</i>",line)
     line = exp.RE_UNDERLINE.sub(r"<u>\1</u>",line)
     line = exp.RE_STRIKETHROUGH.sub(r"<strike>\1</strike>",line)
     line = exp.RE_VERBATIM.sub(r"<pre>\1</pre>",line)
     line = exp.RE_CODE.sub(r"<code>\1</code>",line)
     line = RE_STARTQUOTE.sub(r"<blockquote>",line)
     line = RE_ENDQUOTE.sub(r"</blockquote>",line)
     line = RE_STARTNOTE.sub(r'<aside class="notes">',line)
     line = RE_ENDNOTE.sub(r"</aside>",line)
     line = RE_CHECKBOX.sub(r'<input type="checkbox">',line)
     line = RE_CHECKED_CHECKBOX.sub(r'<input type="checkbox" checked>',line)
     if(sets.Get("htmlExportPartialCheckboxChecked",True)):
       line = RE_PARTIAL_CHECKBOX.sub(r'<input type="checkbox" checked>',line)
     else:
       line = RE_PARTIAL_CHECKBOX.sub(r'<input type="checkbox">',line)
     line = exp.RE_HR.sub(r'<hr>',line)
   return line
Beispiel #23
0
def ShowBalloon(todo, time):
    log.debug("SHOW BALLOON POPUP")
    formatDict = {"time": time, "todo": todo}
    if (sublime.platform() == 'windows'):
        commandLine = sets.Get("ExternalNotificationCommand", [
            r"C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe",
            "-ExecutionPolicy", "Unrestricted", ".\\balloontip.ps1",
            "\"{todo}\"", "\"{time}\""
        ], formatDict)
    elif (sublime.platform() == 'osx'):
        commandLine = sets.Get("ExternalNotificationCommand", [
            'osascript', '-e',
            "display notification \"{time}\" with title \"{todo}\" subtitle \""
            + "Org Mode TODO" + "\""
        ], formatDict)
    else:
        print("ERROR: platform not yet supported for notifications")
    # Expand all potential macros.
    for i in range(len(commandLine)):
        commandLine[i] = commandLine[i].format(todo=todo, time=time)
    try:
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    except:
        startupinfo = None
    # cwd=working_dir, env=my_env,
    cwd = os.path.join(sublime.packages_path(), "OrgExtended")
    if (sublime.platform() == 'windows'):
        popen = subprocess.Popen(commandLine,
                                 universal_newlines=True,
                                 cwd=cwd,
                                 startupinfo=startupinfo,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
        popen.wait()
    elif (sublime.platform() == 'osx'):
        subprocess.check_call(commandLine, stderr=subprocess.STDOUT)
Beispiel #24
0
def Execute(cmd, sets):
    jarfile = sets.Get("ditaa", None)
    if (jarfile == None):
        print(
            "ERROR: cannot find ditaa jar file. Please setup the ditaa key in your settings file"
        )
        return ["ERROR - missing ditaa.jar file"]
    cmd.output = cmd.params.Get('file', 'diagram.png')
    outpath = os.path.dirname(cmd.filename)
    sourcepath = os.path.dirname(cmd.sourcefile)
    #commandLine = [r"java", "-jar", jarfile, mypath, "-o", output]
    commandLine = [r"java", "-jar", jarfile, cmd.filename, "-o"]
    print(str(commandLine))
    #commandLine = [r"java", "-jar", jarfile, "-help"]
    try:
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    except:
        startupinfo = None
    # cwd=working_dir, env=my_env,
    os.makedirs(outpath, exist_ok=True)
    cwd = os.path.join(sublime.packages_path(), "User")
    popen = subprocess.Popen(commandLine,
                             universal_newlines=True,
                             cwd=cwd,
                             startupinfo=startupinfo,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

    #popen.wait()
    (o, e) = popen.communicate()

    convertFile = os.path.join(
        outpath,
        os.path.splitext(os.path.basename(cmd.filename))[0] + ".png")
    destFile = os.path.join(sourcepath, cmd.output)
    copyfile(convertFile, destFile)
    #print(str(os.path.basename(cmd.sourcefile)))
    #print(str(os.path.splitext(cmd.filename)))
    #print(str(os.path.splitext(cmd.sourcefile)))
    #destFile = os.path.relpath(destFile, sourcepath)
    out = o
    o = ""
    #o = "[[file:" + destFile + "]]"
    if ("error" in out or "failed" in out or "Failed" in out or "Error" in out
            or "not" in out):
        o = o + out
    return o.split('\n') + e.split('\n')
Beispiel #25
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()
def onLoad(view):
    remove_all_folds(view)
    # Now lets respect the fold state if we have any.
    file = db.Get().FindInfo(view)
    if (file):
        r = file.org[0]
        globalStartup = sets.Get("startup", ["showall"])
        startup = r.startup(globalStartup)
        if (Startup.overview in startup or Startup.fold in startup):
            fold_all(view)
        elif (Startup.content in startup):
            fold_content(view)
            #if(Startup.showall in startup or Startup.nofold in startup):
        else:
            fold_showall(view)
        fold_all_links(view)
Beispiel #27
0
 def on_done(self, index):
     if (index < 0):
         return
     global captureBufferName
     captureBufferName = sets.Get("captureBufferName", captureBufferName)
     window = self.view.window()
     template = self.templates[index]
     target, capturePath, captureFile, at = GetCapturePath(
         self.view, template)
     openas = False
     if ('openas' in template and 'direct' == template['openas']):
         panel = window.open_file(capturePath)
         openas = True
     else:
         panel = window.create_output_panel("orgcapture")
     self.on_panel_ready(index, openas, panel)
Beispiel #28
0
 def on_done(self, index, modifiers=None):
     if(index >= 0):
         f = self.files[index]
         link = self.view.MakeRelativeToMe(f[0])
         desc = os.path.basename(link)
         if(len(f) > 1):
             desc = f[1]
             includeRoamTag = sets.Get("insertRoamTagToFileLink", True)
             if includeRoamTag is False:
                 log.error(self.rawTitles[f[0]])
                 desc = self.rawTitles[f[0]]
         indent = ""
         node = db.Get().AtInView(self.view)
         if(node):
             indent = node.indent()
         data = r"{indent}[[file:{link}][{desc}]]".format(indent=indent, link=link, desc=desc)
         self.view.run_command("org_internal_insert", {"location": self.view.sel()[0].begin(), "text": data})
Beispiel #29
0
 def run(self, edit):
     self.files = []
     self.rawTitles = {}
     for i in range(0, len(db.Get().Files)):
         filename = db.Get().Files[i].filename
         title = " ".join(db.Get().Files[i].org.get_comment("TITLE", "")).strip()
         self.rawTitles[filename] = title
         useRoamTags = sets.Get("linkFindUseRoamTags", True)
         if(useRoamTags):
             tags = " ".join(db.Get().Files[i].org.get_comment("ROAM_TAGS", "")).strip()
             if(tags != ""):
                 title = "(" + tags + ") " + title
         if(title != ""):
             self.files.append([filename, title])
         else:
             self.files.append([filename])
     self.view.window().show_quick_panel(self.files, self.on_done, -1, -1)
Beispiel #30
0
 def run(self, edit, onDone=None):
     self.edit   = edit
     self.onDone = onDone
     self.dt = datetime.datetime.now()
     dpPath = sets.Get("dayPagePath",None)
     os.makedirs(dpPath, exist_ok=True)
     if(dpPath == None):
         sublime.status_message("Day Page error. dayPagePath setting is not set!")
         log.error(" Cannot create day page without dayPathPath in configuration")
         return
     dateString = self.dt.strftime("%a_%Y_%m_%d")
     dpPath = os.path.join(dpPath,dateString + ".org")
     if(not os.path.exists(dpPath)):
         with open(dpPath,"w") as f:
             f.write("#+TITLE: {}\n".format(dateString))
             f.write("#+AUTHOR: {}\n".format(getpass.getuser()))
     sublime.active_window().open_file(dpPath, sublime.ENCODED_POSITION)
     self.OnDone()