Ejemplo n.º 1
0
 def open(self):
     '''open received file'''
     if self.localPath:
         try:
             desktop.open(self.localPath)
         except OSError:
             pass
Ejemplo n.º 2
0
def ShowGraph(filename):
    '''
    Creates an .svg from the profile generated file and opens it (a proper association to .svg
    files must be already defined in the machine).

    :param unicode filename:
        This is the file generated from ProfileMethod.
    '''
    import gprof2dot
    initial = sys.argv[:]
    output_filename = filename + '.dot'
    sys.argv = ['', '-o', output_filename, '-f', 'pstats', filename]
    try:
        # Handle differences between versions
        try:
            gprof2dot.Main().main()  # @UndefinedVariable
        except AttributeError:
            gprof2dot.main()  # @UndefinedVariable
    finally:
        sys.argv = initial

    try:
        dot = os.environ['GRAPHVIZ_DOT']
    except KeyError:
        raise AssertionError('The GRAPHVIZ_DOT environment variable must be defined to show graph.')

    assert os.path.exists(dot), "Expected: %s to exist and point to dot.exe.\nDid you run 'aa eden.install graphviz'?" % dot
    subprocess.call([dot, '-Tsvg', '-O', output_filename])

    print 'Opening svg created at:', os.path.realpath((output_filename + '.svg'))
    import desktop
    desktop.open(output_filename + '.svg')
Ejemplo n.º 3
0
    def run(self, edit, target='external', output_type='html'):
        output_type = output_type if output_type in FORMATS else 'html'
        pygmented = self.highlight(output_type)

        if target == 'external':
            filename = '%s.%s' % (self.view.id(), output_type,)
            tmp_file = self.write_file(filename, pygmented)
            sublime.status_message(u'Written %s preview file: %s'
                                   % (output_type.upper(), tmp_file))
            if desktop.get_desktop() == 'Mac OS X':
                # for some reason desktop.open is broken under OSX Lion
                subprocess.call("open %s" % tmp_file, shell=True)
            else:
                desktop.open(tmp_file)
        elif target == 'clipboard':
            if desktop.get_desktop() == 'Mac OS X':
                # on mac osx we have `pbcopy` :)
                filename = '%s.%s' % (self.view.id(), output_type,)
                tmp_file = self.write_file(filename, pygmented)
                subprocess.call("cat %s | pbcopy -Prefer %s"
                                % (tmp_file, output_type,), shell=True)
                os.remove(tmp_file)
            else:
                sublime.set_clipboard(pygmented)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            if output_type == 'html':
                new_view.set_syntax_file('Packages/HTML/HTML.tmLanguage')
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, pygmented)
            new_view.end_edit(new_edit)
        else:
            sublime.error_message(u'Unsupported target "%s"' % target)
Ejemplo n.º 4
0
    def try_open(self, window, maybe_path):
        # TODO: Add this somewhere WAY earlier since we are doing so much data
        # processing regarding paths prior to this
        if re.match(r'https?://', maybe_path):
            # HTTP URL
            if BINARY.search(maybe_path) or s.get("open_http_in_browser", False):
                sublime.status_message("Opening in browser " + maybe_path)

                import webbrowser
                webbrowser.open_new_tab(maybe_path)
            else:
                sublime.status_message("Opening URL " + maybe_path)
                # Create thread to download url in background
                threading.Thread(target=self.read_url, args=(maybe_path,)).start()

        elif os.path.isfile(maybe_path):
            if IMAGE.search(maybe_path):
                window.open_file(maybe_path)
            elif BINARY.search(maybe_path):
                try:
                    import desktop
                except:
                    from . import desktop
                desktop.open(maybe_path)
            else:
                # Open within ST
                window.open_file(maybe_path)
            sublime.status_message("Opening file " + maybe_path)
        else:
            return False

        return True
Ejemplo n.º 5
0
    def run(self, edit, target='browser'):
        region = sublime.Region(0, self.view.size())

        contents = self.get_contents(region)

        markdown_html = self.convert_markdown(contents)

        full_html = u'<!DOCTYPE html>'
        full_html += '<html><head><meta charset="utf-8">'
        full_html += self.getCSS()
        full_html += self.getHighlight()
        full_html += self.getMathJax()
        full_html += '</head><body>'
        full_html += markdown_html
        full_html += '</body>'
        full_html += '</html>'

        if target in ['disk', 'browser']:
            # check if LiveReload ST2 extension installed and add its script to the resulting HTML
            livereload_installed = ('LiveReload' in os.listdir(sublime.packages_path()))
            # build the html
            if livereload_installed:
                full_html += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>'
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, 'w')
            tmp_html.write(full_html.encode('utf-8'))
            tmp_html.close()
            # now opens in browser if needed
            if target == 'browser':
                config_browser = settings.get('browser')
                if config_browser and config_browser != 'default':
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == 'darwin':
                        cmd = "open -a %s" % cmd
                    elif sys.platform == 'linux2':
                        cmd += ' &'
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message('cannot execute "%s" Please check your Markdown Preview settings' % config_browser)
                    else:
                        sublime.status_message('Markdown preview launched in %s' % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message('Markdown preview launched in default html viewer')
        elif target == 'sublime':
            # create a new buffer and paste the output HTML
            new_view = self.view.window().new_file()
            new_view.set_scratch(True)
            new_view.run_command('append', {
                'characters': markdown_html,
            })
            #new_edit = new_view.begin_edit()
            #new_view.insert(new_edit, 0, markdown_html)
            #new_view.end_edit(new_edit)
            sublime.status_message('Markdown preview launched in sublime')
        elif target == 'clipboard':
            # clipboard copy the full HTML
            sublime.set_clipboard(full_html)
            sublime.status_message('Markdown export copied to clipboard')
    def run(self, edit, target='browser'):
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == 'Undefined':
            encoding = 'utf-8'
        elif encoding == 'Western (Windows 1252)':
            encoding = 'windows-1252'
        contents = self.view.substr(region)

        # convert the markdown
        markdown_html = markdown.markdown(contents)

        # build the html
        html_contents = u'<html><head><meta charset="%s">' % encoding
        styles = self.getCSS()
        html_contents += '<style>%s</style>' % styles
        html_contents += '</head><body>'
        html_contents += markdown_html
        html_contents += '</body>'

        if target in ['disk', 'browser']:
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, 'w')
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            # todo : livereload ?
            if target == 'browser':
                desktop.open(tmp_fullpath)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
        print 'markdown converted'
Ejemplo n.º 7
0
	def try_open(self, window, maybe_path):
		if maybe_path[:4] == 'http':
			if BINARY.search(maybe_path) or s.get("open_http_in_browser", False):
				try:
					sublime.status_message("Opening in browser " + maybe_path)
					import webbrowser
					webbrowser.open_new_tab(maybe_path)
					return True
				except:
					return False
			else:
				sublime.status_message("Opening URL " + maybe_path)
				thread.start_new_thread(self.read_url, (maybe_path, maybe_path))
				return True

		if os.path.isfile(maybe_path):
			if BINARY.search(maybe_path):
				import sys
				path = os.path.join(sublime.packages_path(), 'Open-Include')
				if path not in sys.path:
					sys.path.append(path)
				import desktop
				desktop.open(maybe_path)
			else:
				window.open_file(maybe_path)
			sublime.status_message("Opening file " + maybe_path)
			return True
		else:
			return False
    def open_in_browser(cls, path, browser="default"):
        if browser == "default":
            if sys.platform == "darwin":
                # To open HTML files, Mac OS the open command uses the file
                # associated with .html. For many developers this is Sublime,
                # not the default browser. Getting the right value is
                # embarrassingly difficult.
                import shlex
                import subprocess

                env = {"VERSIONER_PERL_PREFER_32_BIT": "true"}
                raw = """perl -MMac::InternetConfig -le 'print +(GetICHelper "http")[1]'"""
                process = subprocess.Popen(shlex.split(raw), env=env, stdout=subprocess.PIPE)
                out, err = process.communicate()
                default_browser = out.strip().decode("utf-8")
                cmd = "open -a '%s' %s" % (default_browser, path)
                os.system(cmd)
            else:
                desktop.open(path)
            sublime.status_message("Markdown preview launched in default browser")
        else:
            cmd = '"%s" %s' % (browser, path)
            if sys.platform == "darwin":
                cmd = "open -a %s" % cmd
            elif sys.platform == "linux2":
                cmd += " &"
            elif sys.platform == "win32":
                cmd = 'start "" %s' % cmd
            result = os.system(cmd)
            if result != 0:
                sublime.error_message('cannot execute "%s" Please check your Markdown Preview settings' % browser)
            else:
                sublime.status_message("Markdown preview launched in %s" % browser)
Ejemplo n.º 9
0
    def exportAccommodationObjectsFromMongoToCSV(self, date):

        cursor = self.accommodations.find()
        dictArr = []

        for accommodation in list(cursor):

            accommodationId = accommodation["accommodationId"]
            name = accommodation["name"]
            address = accommodation["address"]
            latitude = accommodation["latitude"]
            longitude = accommodation["longitude"]
            reviewScore = accommodation["reviewScore"]
            starRating = accommodation["starRating"]
            rooms = accommodation["rooms"]
            floors = accommodation["floors"]
            facilities = accommodation["facilities"]
            accommodationType = accommodation["accommodationType"]
            yearEstablished = accommodation["yearEstablished"]
            yearClosed = accommodation["yearClosed"]

            createdAt = accommodation["createdAt"]
            cratedAtStr = createdAt.strftime('%d/%m/%Y')
            lastModified = accommodation["lastModified"]
            lastModifiedStr = lastModified.strftime('%d/%m/%Y')
            
            dictArr.append({'accommodationId': accommodationId, 'name': name, 'address': address, 'latitude': latitude, 'longitude': longitude, "review": reviewScore, "starRating": starRating, "rooms": rooms, "floors": floors, "facilities": facilities, "type": accommodationType, "yearEstablished": yearEstablished, "yearClosed": yearClosed, "cratedAt": cratedAtStr, "lastModified": lastModifiedStr})

        sortingColum = ['accommodationId','name','address','latitude','longitude','review','starRating','rooms','floors','facilities','type','yearEstablished','yearClosed','cratedAt','lastModified']

        df =  pd.DataFrame(dictArr)
        
        # sorting column in excel following sortingColum list
        df.loc[:,sortingColum].to_csv(('{}{}{}'.format('ข้อมูลที่พัก_',date,'.csv')))
        desktop.open('{}{}{}'.format('ข้อมูลที่พัก_',date,'.csv'))
Ejemplo n.º 10
0
def launching_web_browser_for_url(url,
                                  success_msg_default=None,
                                  success_msg_user=None):
    try:
        setting = Setting.instance()
        if setting.browser_command:
            browser_command = [
                os.path.expandvars(arg).format(url=url)
                for arg in setting.browser_command
            ]

            if os.name == 'nt':
                # unicode arguments broken under windows
                encoding = locale.getpreferredencoding()
                browser_command = [
                    arg.encode(encoding) for arg in browser_command
                ]

            subprocess.Popen(browser_command)
            if success_msg_user:
                sublime.status_message(success_msg_user)
        else:
            # Default web browser
            desktop.open(url)
            if success_msg_default:
                sublime.status_message(success_msg_default)
    except:
        if setting.browser_command:
            log.exception('Error while launching user defined web browser')
        else:
            log.exception('Error while launching default web browser')
Ejemplo n.º 11
0
 def playWink(self, path):
     if self.hasGnash == True:
         retval = subprocess.call(['gnash', '-1', path])
     elif os.name != "nt":
         retval = subprocess.call(['firefox', path])
     else:
         desktop.open(path)
Ejemplo n.º 12
0
    def run(self, edit, target='browser'):
        self.settings = sublime.load_settings(
            'MarkdownPreview.sublime-settings')
        region = sublime.Region(0, self.view.size())

        contents = self.get_contents(region)

        markdown_html = self.convert_markdown(contents)

        full_html = u'<!DOCTYPE html>'
        full_html += '<html><head><meta charset="utf-8">'
        full_html += self.getCSS()
        full_html += self.getJS()
        full_html += self.getHighlight()
        full_html += self.getMathJax()
        full_html += self.get_title()
        full_html += '</head><body>'
        full_html += markdown_html
        full_html += '</body>'
        full_html += '</html>'

        if target in ['disk', 'browser']:
            # check if LiveReload ST2 extension installed and add its script to the resulting HTML
            livereload_installed = ('LiveReload'
                                    in os.listdir(sublime.packages_path()))
            # build the html
            if livereload_installed:
                full_html += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>'
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            save_utf8(tmp_fullpath, full_html)
            # now opens in browser if needed
            if target == 'browser':
                config_browser = self.settings.get('browser')
                if config_browser and config_browser != 'default':
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == 'darwin':
                        cmd = "open -a %s" % cmd
                    elif sys.platform == 'linux2':
                        cmd += ' &'
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message(
                            'cannot execute "%s" Please check your Markdown Preview settings'
                            % config_browser)
                    else:
                        sublime.status_message(
                            'Markdown preview launched in %s' % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message(
                        'Markdown preview launched in default html viewer')
        elif target == 'sublime':
            # create a new buffer and paste the output HTML
            new_scratch_view(self.view.window(), markdown_html)
            sublime.status_message('Markdown preview launched in sublime')
        elif target == 'clipboard':
            # clipboard copy the full HTML
            sublime.set_clipboard(full_html)
            sublime.status_message('Markdown export copied to clipboard')
Ejemplo n.º 13
0
 def playWink(self, path):
     if self.hasGnash == True:
         retval = subprocess.call(['gnash', '-1', path])
     elif os.name != "nt":
         retval = subprocess.call(['firefox',  path])
     else:
         desktop.open(path)
Ejemplo n.º 14
0
 def open_in_browser(cls, path, browser='default'):
     if browser == 'default':
         if sys.platform == 'darwin':
             # To open HTML files, Mac OS the open command uses the file
             # associated with .html. For many developers this is Sublime,
             # not the default browser. Getting the right value is
             # embarrassingly difficult.
             import shlex, subprocess
             env = {'VERSIONER_PERL_PREFER_32_BIT': 'true'}
             raw = """perl -MMac::InternetConfig -le 'print +(GetICHelper "http")[1]'"""
             process = subprocess.Popen(shlex.split(raw), env=env, stdout=subprocess.PIPE)
             out, err = process.communicate()
             default_browser = out.strip().decode('utf-8')
             cmd = "open -a '%s' %s" % (default_browser, path)
             os.system(cmd)
         else:
             desktop.open(tmp_fullpath)
         sublime.status_message('Markdown preview launched in default browser')
     else:
         cmd = '"%s" %s' % (browser, path)
         if sys.platform == 'darwin':
             cmd = "open -a %s" % cmd
         elif sys.platform == 'linux2':
             cmd += ' &'
         elif sys.platform == 'win32':
             cmd = 'start "" %s' % cmd
         result = os.system(cmd)
         if result != 0:
             sublime.error_message('cannot execute "%s" Please check your Markdown Preview settings' % config_browser)
         else:
             sublime.status_message('Markdown preview launched in %s' % config_browser)
Ejemplo n.º 15
0
 def open(self):
     '''open received file'''
     if self.localPath:
         try:
             desktop.open(self.localPath)
         except OSError:
             pass
    def run(self, edit, target='browser'):
        print edit, target
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == 'Undefined':
            encoding = 'UTF-8'
        elif encoding == 'Western (Windows 1252)':
            encoding = 'windows-1252'
        view_contents = self.view.substr(region)

        # convert the markdown
        markdown_html = markdown.markdown(view_contents)

        # build the html
        html_contents = u'<meta charset="%s">' % self.view.encoding()
        styles = self.getCSS()
        html_contents += '<style>%s</style>' % styles
        html_contents += markdown_html
        # output
        if target == 'browser':
            tmp_html = tempfile.NamedTemporaryFile(delete=False, suffix='.html')
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            desktop.open(tmp_html.name)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
        elif target == 'tumblr':
            tumblr = TumblrManager()
            tumblr.post_to_tumblr(view_contents, False)
        elif target == 'tumblr_draft':
            tumblr = TumblrManager()
            tumblr.post_to_tumblr(view_contents, True)
Ejemplo n.º 17
0
    def try_open(self, window, maybe_path):
        if maybe_path[:4] == 'http':
            if BINARY.search(maybe_path) or s.get("open_http_in_browser",
                                                  False):
                try:
                    sublime.status_message("Opening in browser " + maybe_path)
                    import webbrowser
                    webbrowser.open_new_tab(maybe_path)
                    return True
                except:
                    return False
            else:
                sublime.status_message("Opening URL " + maybe_path)
                thread.start_new_thread(self.read_url,
                                        (maybe_path, maybe_path))
                return True

        if os.path.isfile(maybe_path):
            if BINARY.search(maybe_path):
                import sys
                path = os.path.join(sublime.packages_path(), 'Open-Include')
                if path not in sys.path:
                    sys.path.append(path)
                import desktop
                desktop.open(maybe_path)
            else:
                window.open_file(maybe_path)
            sublime.status_message("Opening file " + maybe_path)
            return True
        else:
            return False
    def run(self, edit, target="browser"):
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == "Undefined":
            encoding = "utf-8"
        elif encoding == "Western (Windows 1252)":
            encoding = "windows-1252"
        contents = self.view.substr(region)

        # convert the markdown
        markdown_html = markdown.markdown(contents)

        # build the html
        html_contents = u'<html><head><meta charset="%s">' % encoding
        styles = self.getCSS()
        html_contents += "<style>%s</style>" % styles
        html_contents += "</head><body>"
        html_contents += markdown_html
        html_contents += "</body>"

        if target in ["disk", "browser"]:
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, "w")
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            # todo : livereload ?
            if target == "browser":
                desktop.open(tmp_fullpath)
        elif target == "sublime":
            new_view = self.view.window().new_file()
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
        print "markdown converted"
Ejemplo n.º 19
0
 def run(self, edit):
     self._view = View(self.view)
     self.md = Markdown(self._view.contents(), self._view.encoding())
     tfile = tempfile.NamedTemporaryFile(delete=False, suffix='.html')
     tfile.write(self.md.html().encode(self._view.encoding()))
     tfile.close()
     desktop.open(tfile.name)
Ejemplo n.º 20
0
def launching_web_browser_for_url(url, success_msg_default=None, success_msg_user=None):
    try:
        setting = Setting.instance()
        if setting.browser_command:
            browser_command = [os.path.expandvars(arg).format(url=url)
                               for arg in setting.browser_command]

            if os.name == 'nt':
                # unicode arguments broken under windows
                encoding = locale.getpreferredencoding()
                browser_command = [arg.encode(encoding) for arg in browser_command]

            subprocess.Popen(browser_command)
            if success_msg_user:
                sublime.status_message(success_msg_user)
        else:
            # Default web browser
            desktop.open(url)
            if success_msg_default:
                sublime.status_message(success_msg_default)
    except:
        if setting.browser_command:
            log.exception('Error while launching user defined web browser')
        else:
            log.exception('Error while launching default web browser')
Ejemplo n.º 21
0
    def exportRoomObjectsFromMongoToCSV(self, date):

        cursor = self.rooms.find()
        dictArr = []

        for accommodation in list(cursor):

            accommodationId = accommodation["accommodationId"]
            name = accommodation["name"]
            roomType = accommodation["roomType"]
            bestPrice = accommodation["bestPrice"]
            totalPrice = accommodation["totalPrice"]
            soldOut = accommodation["soldOut"]

            createdAt = accommodation["createdAt"]
            cratedAtStr = createdAt.strftime('%d/%m/%Y')

            checkInDate = accommodation["checkInDate"]
            checkInDateStr = checkInDate.strftime('%d/%m/%Y')
            
            dictArr.append({'accommodationId': accommodationId, 'name': name, "roomType": roomType, "bestPrice": bestPrice, "totalPrice": totalPrice, "soldOut": soldOut, "checkInDate": checkInDateStr, "cratedAt": cratedAtStr})

        sortingColum = ['accommodationId','name','roomType','bestPrice','totalPrice','soldOut','checkInDate','cratedAt']

        df =  pd.DataFrame(dictArr)
        df.loc[:,sortingColum].to_csv(('{}{}{}'.format('ข้อมูลราคาห้องพัก_',date,'.csv')))
        desktop.open('{}{}{}'.format('ข้อมูลราคาห้องพัก_',date,'.csv'))
Ejemplo n.º 22
0
    def run(self, edit, target="browser"):
        region = sublime.Region(0, self.view.size())

        contents = self.get_contents(region)

        markdown_html = self.convert_markdown(contents)

        full_html = u"<!DOCTYPE html>"
        full_html += '<html><head><meta charset="utf-8">'
        full_html += self.getCSS()
        full_html += self.getHighlight()
        full_html += self.getMathJax()
        full_html += "</head><body>"
        full_html += markdown_html
        full_html += "</body>"
        full_html += "</html>"

        if target in ["disk", "browser"]:
            # check if LiveReload ST2 extension installed and add its script to the resulting HTML
            livereload_installed = "LiveReload" in os.listdir(sublime.packages_path())
            # build the html
            if livereload_installed:
                full_html += "<script>document.write('<script src=\"http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1\"></' + 'script>')</script>"
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, "w")
            tmp_html.write(full_html.encode("utf-8"))
            tmp_html.close()
            # now opens in browser if needed
            if target == "browser":
                config_browser = settings.get("browser")
                if config_browser and config_browser != "default":
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == "darwin":
                        cmd = "open -a %s" % cmd
                    elif sys.platform == "linux2":
                        cmd += " &"
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message(
                            'cannot execute "%s" Please check your Markdown Preview settings' % config_browser
                        )
                    else:
                        sublime.status_message("Markdown preview launched in %s" % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message("Markdown preview launched in default html viewer")
        elif target == "sublime":
            # create a new buffer and paste the output HTML
            new_view = self.view.window().new_file()
            new_view.set_scratch(True)
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, markdown_html)
            new_view.end_edit(new_edit)
            sublime.status_message("Markdown preview launched in sublime")
        elif target == "clipboard":
            # clipboard copy the full HTML
            sublime.set_clipboard(full_html)
            sublime.status_message("Markdown export copied to clipboard")
Ejemplo n.º 23
0
			def tvOpen():
				for mission in table.selected():
					savepath = mission.module.config["savepath"]
					folder = os.path.join(savepath, safefilepath(mission.title))
					folder = os.path.expanduser(folder)
					if not os.path.isdir(folder):
						os.makedirs(folder)
					desktop.open(folder)
Ejemplo n.º 24
0
 def select_dir(self, o):
     new_file = o.get_current_folder()
     if os.path.isdir(new_file):
         self.cur_dir = new_file
     else:
         print 'not a dir:', new_file
         desktop.open(new_file)
     self.refresh_file_list()
Ejemplo n.º 25
0
    def run(self, edit, target='browser'):
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == 'Undefined':
            encoding = 'utf-8'
        elif encoding == 'Western (Windows 1252)':
            encoding = 'windows-1252'
        contents = self.view.substr(region)

        # convert the markdown
        markdown_html = markdown2.markdown(contents, extras=['footnotes', 'toc'])

        # postprocess the html
        markdown_html = self.postprocessor(markdown_html)

        # check if LiveReload ST2 extension installed
        livereload_installed = ('LiveReload' in os.listdir(sublime.packages_path()))

        # build the html
        html_contents = u'<!DOCTYPE html>'
        html_contents += '<html><head><meta charset="%s">' % encoding
        styles = self.getCSS()
        html_contents += '<style>%s</style>' % styles
        if livereload_installed:
            html_contents += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>'
        html_contents += '</head><body>'
        html_contents += markdown_html
        html_contents += '</body>'

        if target in ['disk', 'browser']:
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, 'w')
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            # todo : livereload ?
            if target == 'browser':
                config_browser = settings.get('browser')
                if config_browser != 'default':
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == 'darwin':
                        cmd = "open -a %s" % cmd
                    print "Markdown Preview: executing", cmd
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message('cannot execute "%s" Please check your Markdown Preview settings' % config_browser)
                    else:
                        sublime.status_message('Markdown preview launched in %s' % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message('Markdown preview launched in default html viewer')
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
            sublime.status_message('Markdown preview launched in sublime')
Ejemplo n.º 26
0
 def start_explorer(event=None):
     for mission in table.selected():
         savepath = profile(mission.module.config["savepath"])
         folder = os.path.join(savepath,
                               safefilepath(mission.title))
         folder = os.path.expanduser(folder)
         if not os.path.isdir(folder):
             os.makedirs(folder)
         desktop.open(folder)
	def run(self, edit, target = 'browser'):
		region = sublime.Region(0, self.view.size())
		enc = self.view.encoding();
		contents = self.view.substr(region)
		style = "qsd"
		text = contents
		pngFile = getTempPreviewPath(self.view)
		if getSequenceDiagram(text, pngFile, style):
			desktop.open(pngFile)
    def run(self, edit, target='browser'):
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == 'Undefined':
            encoding = 'utf-8'
        elif encoding == 'Western (Windows 1252)':
            encoding = 'windows-1252'
        contents = self.view.substr(region)

        # convert the markdown
        markdown_html = markdown2.markdown(contents, extras=['footnotes', 'toc', 'fenced-code-blocks', 'cuddled-lists', 'code-friendly'])

        # postprocess the html
        markdown_html = self.postprocessor(markdown_html)

        # check if LiveReload ST2 extension installed
        livereload_installed = ('LiveReload' in os.listdir(sublime.packages_path()))

        # build the html
        html_contents = u'<!DOCTYPE html>'
        html_contents += '<html><head><meta charset="%s">' % encoding
        styles = self.getCSS()
        html_contents += '<style>%s</style>' % styles
        if livereload_installed:
            html_contents += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>'
        html_contents += '</head><body>'
        html_contents += markdown_html
        html_contents += '</body>'

        if target in ['disk', 'browser']:
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, 'w')
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            # todo : livereload ?
            if target == 'browser':
                config_browser = settings.get('browser')
                if config_browser and config_browser != 'default':
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == 'darwin':
                        cmd = "open -a %s" % cmd
                    print "Markdown Preview: executing", cmd
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message('cannot execute "%s" Please check your Markdown Preview settings' % config_browser)
                    else:
                        sublime.status_message('Markdown preview launched in %s' % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message('Markdown preview launched in default html viewer')
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
            sublime.status_message('Markdown preview launched in sublime')
Ejemplo n.º 29
0
	def open(self):
		if sublime.platform() == 'osx':
			import subprocess
			subprocess.Popen(['open', '-a', self.nameSystem()], cwd=self.dirnameSystem())
		elif sublime.platform() == 'windows':
			import subprocess
			subprocess.Popen([self.nameSystem()], cwd=self.dirnameSystem(), shell=True)
		else:
			desktop.open(self.path())
    def run(self, edit, target='external', output_type='html'):
        output_type = output_type if output_type in FORMATS else 'html'
        platform = desktop.get_desktop()

        # html clipboard output on windows should not be self-contained
        win = all([
            platform == 'Windows', output_type == 'html', target == 'clipboard'
        ])
        full = False if win else settings.get('full', True)

        pygmented = self.highlight(output_type, full)

        if target == 'external':
            filename = '%s.%s' % (
                self.view.id(),
                output_type,
            )
            tmp_file = self.write_file(filename, pygmented)
            sublime.status_message(u'Written %s preview file: %s' %
                                   (output_type.upper(), tmp_file))
            if platform == 'Mac OS X':
                # for some reason desktop.open is broken under OSX Lion
                subprocess.call("open %s" % tmp_file, shell=True)
            else:
                desktop.open(tmp_file)
        elif target == 'clipboard':
            if platform == 'Mac OS X':
                # on mac osx we have `pbcopy` :)
                filename = '%s.%s' % (
                    self.view.id(),
                    output_type,
                )
                tmp_file = self.write_file(filename, pygmented)
                subprocess.call("cat %s | pbcopy -Prefer %s" % (
                    tmp_file,
                    output_type,
                ),
                                shell=True)
                os.remove(tmp_file)
            elif platform == 'Windows':
                if self.view.line_endings != 'Windows':
                    pygmented = WIN_CR_RE.sub("\r\n", pygmented)
                    plaintext = WIN_CR_RE.sub("\r\n", self.code)
                else:
                    plaintext = self.code
                winclip.Paste(pygmented, output_type, plaintext)
            else:
                sublime.set_clipboard(pygmented)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            if output_type == 'html':
                new_view.set_syntax_file('Packages/HTML/HTML.tmLanguage')
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, pygmented)
            new_view.end_edit(new_edit)
        else:
            sublime.error_message(u'Unsupported target "%s"' % target)
Ejemplo n.º 31
0
	def open(self):
		if sublime.platform() == 'osx':
			import subprocess
			subprocess.Popen(['open', '-a', self.nameSystem()], cwd=self.dirnameSystem())
		elif sublime.platform() == 'windows':
			import subprocess
			subprocess.Popen([self.nameSystem()], cwd=self.dirnameSystem(), shell=True)
		else:
			desktop.open(self.path())
Ejemplo n.º 32
0
    def run(self, edit, parser='markdown', target='browser'):
        settings = sublime.load_settings('MarkdownPreview.sublime-settings')

        # backup parser+target for later saves
        self.view.settings().set('parser', parser)
        self.view.settings().set('target', target)

        html, body = compiler.run(self.view, parser)

        if target in ['disk', 'browser']:
            # check if LiveReload ST2 extension installed and add its script to the resulting HTML
            livereload_installed = ('LiveReload'
                                    in os.listdir(sublime.packages_path()))
            # build the html
            if livereload_installed:
                port = sublime.load_settings(
                    'LiveReload.sublime-settings').get('port', 35729)
                html += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':%d/livereload.js?snipver=1"></\' + \'script>\')</script>' % port
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            save_utf8(tmp_fullpath, html)
            # now opens in browser if needed
            if target == 'browser':
                config_browser = settings.get('browser')
                if config_browser and config_browser != 'default':
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == 'darwin':
                        cmd = "open -a %s" % cmd
                    elif sys.platform == 'linux2':
                        cmd += ' &'
                    elif sys.platform == 'win32':
                        cmd = 'start "" %s' % cmd
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message(
                            'cannot execute "%s" Please check your Markdown Preview settings'
                            % config_browser)
                    else:
                        sublime.status_message(
                            'Markdown preview launched in %s' % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message(
                        'Markdown preview launched in default html viewer')
        elif target == 'sublime':
            # create a new buffer and paste the output HTML
            embed_css = settings.get('embed_css_for_sublime_output', True)
            if embed_css:
                new_scratch_view(self.view.window(), html)
            else:
                new_scratch_view(self.view.window(), body)
            sublime.status_message('Markdown preview launched in sublime')
        elif target == 'clipboard':
            # clipboard copy the full HTML
            sublime.set_clipboard(html)
            sublime.status_message('Markdown export copied to clipboard')
Ejemplo n.º 33
0
	def run(self, edit, open=True):
		temp = encodeFilePath(getTempPreviewPath(self.view))
		source = encodeFilePath(self.view.file_name())
		retcode = subprocess.call(['blockdiag', source, '-o', temp])
		if retcode < 0:
			msg = 'Blockdiag process is failed!'
			print msg
			sublime.status_message(msg)
		elif open:
			desktop.open(temp)
Ejemplo n.º 34
0
 def run(self, edit, open=True):
     temp = encodeFilePath(getTempPreviewPath(self.view))
     source = encodeFilePath(self.view.file_name())
     retcode = subprocess.call(['blockdiag', source, '-o', temp])
     if retcode < 0:
         msg = 'Blockdiag process is failed!'
         print msg
         sublime.status_message(msg)
     elif open:
         desktop.open(temp)
    def run(self, edit, parser="markdown", target="browser"):
        settings = sublime.load_settings("MarkdownPreview.sublime-settings")

        # backup parser+target for later saves
        self.view.settings().set("parser", parser)
        self.view.settings().set("target", target)

        html, body = compiler.run(self.view, parser)

        if target in ["disk", "browser"]:
            # check if LiveReload ST2 extension installed and add its script to the resulting HTML
            livereload_installed = "LiveReload" in os.listdir(sublime.packages_path())
            # build the html
            if livereload_installed:
                port = sublime.load_settings("LiveReload.sublime-settings").get("port")
                html += (
                    "<script>document.write('<script src=\"http://' + (location.host || 'localhost').split(':')[0] + ':%d/livereload.js?snipver=1\"></' + 'script>')</script>"
                    % port
                )
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            save_utf8(tmp_fullpath, html)
            # now opens in browser if needed
            if target == "browser":
                config_browser = settings.get("browser")
                if config_browser and config_browser != "default":
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == "darwin":
                        cmd = "open -a %s" % cmd
                    elif sys.platform == "linux2":
                        cmd += " &"
                    elif sys.platform == "win32":
                        cmd = 'start "" %s' % cmd
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message(
                            'cannot execute "%s" Please check your Markdown Preview settings' % config_browser
                        )
                    else:
                        sublime.status_message("Markdown preview launched in %s" % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message("Markdown preview launched in default html viewer")
        elif target == "sublime":
            # create a new buffer and paste the output HTML
            embed_css = settings.get("embed_css_for_sublime_output", True)
            if embed_css:
                new_scratch_view(self.view.window(), html)
            else:
                new_scratch_view(self.view.window(), body)
            sublime.status_message("Markdown preview launched in sublime")
        elif target == "clipboard":
            # clipboard copy the full HTML
            sublime.set_clipboard(html)
            sublime.status_message("Markdown export copied to clipboard")
    def open(self):
        if sublime.platform() == "osx":
            import subprocess

            subprocess.Popen(["open", "-a", self.nameSystem()], cwd=self.dirnameSystem())
        elif sublime.platform() == "windows":
            import subprocess

            subprocess.Popen([self.nameSystem()], cwd=self.dirnameSystem(), shell=True)
        else:
            desktop.open(self.path())
Ejemplo n.º 37
0
    def try_open(self, window, maybe_path):
        global cache

        debug_info('Trying to open: ' + maybe_path)

        path_normalized = normalize(maybe_path)
        if path_normalized in cache['checked']:
            return False
        cache['checked'][path_normalized] = True

        if maybe_path.startswith('http') or maybe_path.startswith('//'):
            # HTTP URL
            if BINARY.search(maybe_path) or s.get("open_http_in_browser",
                                                  False):
                if maybe_path.startswith('//'):
                    maybe_path = "http:" + maybe_path

                sublime.status_message("Opening in Browser " + maybe_path)

                import webbrowser
                webbrowser.open_new_tab(maybe_path)
            else:
                sublime.status_message("Opening URL " + maybe_path)
                # Create thread to download url in background
                threading.Thread(target=self.read_url,
                                 args=(maybe_path, )).start()

        elif os_is_file(maybe_path):
            sublime.status_message("Opening File " + normalize(maybe_path))
            if IMAGE.search(maybe_path):
                self.open(window, maybe_path)
            elif BINARY.search(maybe_path):
                try:
                    import desktop
                except:
                    from . import desktop
                desktop.open(maybe_path)
            else:
                # Open within ST
                self.open(window, maybe_path)

        elif maybe_path and (
                os_is_dir(maybe_path) or os_is_dir('\\' + maybe_path)
        ) and not cache['folder'] and cache['folder_save']:
            # Walkaround for UNC path
            if maybe_path and maybe_path[0] == '\\':
                maybe_path = '\\' + maybe_path
            cache['folder'] = maybe_path
            return False

        else:
            return False

        return True
Ejemplo n.º 38
0
 def onMaiButtonClicked(self, *args):
     if self.config.glob['overrideMail'] == '':
         try:
             desktop.open(self.controller.hotmail.getLoginPage())
         except OSError:
             dialog.error(_('Couldn\'t launch the default browser'))
     else:
         try:
             subprocess.Popen(self.config.glob['overrideMail'])
         except:
             dialog.error(_('Couldn\'t launch the e-mail client'))
Ejemplo n.º 39
0
 def onMaiButtonClicked(self, *args):
     if self.config.glob['overrideMail'] == '':
         try:
             desktop.open(self.controller.hotmail.getLoginPage())
         except OSError:
             dialog.error(_('Couldn\'t launch the default browser'))
     else:
         try:
             subprocess.Popen(self.config.glob['overrideMail'])
         except:
             dialog.error(_('Couldn\'t launch the e-mail client'))
Ejemplo n.º 40
0
 def tvOpen():
     s = tv.selection()
     missions = [cid_index[i] for i in s]
     for mission in missions:
         savepath = mission.module.config["savepath"]
         folder = os.path.join(savepath,
                               safefilepath(mission.title))
         folder = os.path.expanduser(folder)
         if not os.path.isdir(folder):
             os.makedirs(folder)
         desktop.open(folder)
Ejemplo n.º 41
0
 def openMail(self, params):
     if self.config.glob['overrideMail'] == '':
         try:
             desktop.open(self.controller.hotmail.getLoginPage\
                 (params[0], params[1], params[2]))
         except OSError:
             dialog.error(_('Couldn\'t launch the default browser'))
     else:
         try:
             subprocess.Popen(self.config.glob['overrideMail'])
         except:
             dialog.error(_('Couldn\'t launch the e-mail client'))
	def open(self):
		import sys
		if sys.platform == 'darwin':
			import subprocess
			subprocess.Popen(['open', '-a', self.nameSystem()], cwd=self.dirnameSystem())
		elif sys.platform == 'win32':
			import subprocess
			subprocess.Popen([self.nameSystem()], cwd=self.dirnameSystem(), shell=True)
		else:
			sys.path.append(os.path.join(sublime.packages_path(), 'SideBarEnhancements'))
			import desktop
			desktop.open(self.path())
Ejemplo n.º 43
0
def send_to_browser(html):
    """Create a temp file containing html and open it in the default web browser."""
    tmp_html = tempfile.NamedTemporaryFile(delete=False, suffix='.html')
    tmp_html.write(html)
    tmp_html.close()
    PTbaseDir = os.path.expanduser('~\Documents\Poseidon Tools\\')
    PTExportDir = PTbaseDir + 'TEMP\\'
    sourceFile = tmp_html.name
    sourceFile = sourceFile.replace(tempfile.tempdir + "\\", "")
    finalDest = PTExportDir + sourceFile
    shutil.move(tmp_html.name, finalDest)
    # logger(tmp_html.name + "copied to "  + finalDest)
    desktop.open(finalDest)
Ejemplo n.º 44
0
	def open(self):
		if sublime.platform() == 'osx':
			import subprocess
			subprocess.Popen(['open', '-a', self.nameSystem()], cwd=self.dirnameSystem())
		elif sublime.platform() == 'windows':
			import subprocess
			subprocess.Popen([self.nameSystem()], cwd=self.dirnameSystem(), shell=True)
		else:
			import sys
			path = os.path.join(sublime.packages_path(), 'SideBarEnhancements')
			if path not in sys.path:
				sys.path.append(path)
			import desktop
			desktop.open(self.path())
    def view_image(self, dir_name, file_name = ""):
        '''View image with default OS viewer'''

        full_name = dir_name + "/" + file_name if file_name else dir_name

        if (os.path.isfile(full_name)):
            desktop.open(full_name)

        else:
            full_name2 = dir_name + "../" + file_name
            if (os.path.isfile(full_name2)):
                desktop.open(full_name2)
            else:
                sublime.error_message("Image-Viewer\n\nERROR: File not found:\n\n" + full_name)
Ejemplo n.º 46
0
    def run(self, edit, parser='markdown', target='browser'):
        settings = sublime.load_settings('MarkdownPreview.sublime-settings')

        # backup parser+target for later saves
        self.view.settings().set('parser', parser)
        self.view.settings().set('target', target)

        html, body = compiler.run(self.view, parser)

        if target in ['disk', 'browser']:
            # check if LiveReload ST2 extension installed and add its script to the resulting HTML
            livereload_installed = ('LiveReload' in os.listdir(sublime.packages_path()))
            # build the html
            if livereload_installed:
                port = sublime.load_settings('LiveReload.sublime-settings').get('port', 35729)
                html += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':%d/livereload.js?snipver=1"></\' + \'script>\')</script>' % port
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            save_utf8(tmp_fullpath, html)
            # now opens in browser if needed
            if target == 'browser':
                config_browser = settings.get('browser')
                if config_browser and config_browser != 'default':
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == 'darwin':
                        cmd = "open -a %s" % cmd
                    elif sys.platform == 'linux2':
                        cmd += ' &'
                    elif sys.platform == 'win32':
                        cmd = 'start "" %s' % cmd
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message('cannot execute "%s" Please check your Markdown Preview settings' % config_browser)
                    else:
                        sublime.status_message('Markdown preview launched in %s' % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message('Markdown preview launched in default html viewer')
        elif target == 'sublime':
            # create a new buffer and paste the output HTML
            embed_css = settings.get('embed_css_for_sublime_output', True)
            if embed_css:
                new_scratch_view(self.view.window(), html)
            else:
                new_scratch_view(self.view.window(), body)
            sublime.status_message('Markdown preview launched in sublime')
        elif target == 'clipboard':
            # clipboard copy the full HTML
            sublime.set_clipboard(html)
            sublime.status_message('Markdown export copied to clipboard')
Ejemplo n.º 47
0
    def view_image(self, dir_name, file_name=""):
        '''View image with default OS viewer'''

        full_name = dir_name + "/" + file_name if file_name else dir_name

        if (os.path.isfile(full_name)):
            desktop.open(full_name)

        else:
            full_name2 = dir_name + "../" + file_name
            if (os.path.isfile(full_name2)):
                desktop.open(full_name2)
            else:
                sublime.error_message(
                    "Image-Viewer\n\nERROR: File not found:\n\n" + full_name)
Ejemplo n.º 48
0
    def run(self, edit, target='external', output_type='html'):
        output_type = output_type if output_type in FORMATS else 'html'
        platform = desktop.get_desktop()

        # html clipboard output on windows should not be self-contained
        win = all([platform == 'Windows', output_type == 'html',
            target == 'clipboard'])
        full = False if win else settings.get('full', True)

        pygmented = self.highlight(output_type, full)

        if target == 'external':
            filename = '%s.%s' % (self.view.id(), output_type,)
            tmp_file = self.write_file(filename, pygmented)
            sublime.status_message(u'Written %s preview file: %s'
                                   % (output_type.upper(), tmp_file))
            if platform == 'Mac OS X':
                # for some reason desktop.open is broken under OSX Lion
                subprocess.call("open %s" % tmp_file, shell=True)
            else:
                desktop.open(tmp_file)
        elif target == 'clipboard':
            if platform == 'Mac OS X':
                # on mac osx we have `pbcopy` :)
                filename = '%s.%s' % (self.view.id(), output_type,)
                tmp_file = self.write_file(filename, pygmented)
                subprocess.call("cat %s | pbcopy -Prefer %s"
                                % (tmp_file, output_type,), shell=True)
                os.remove(tmp_file)
            elif platform == 'Windows':
                if self.view.line_endings != 'Windows':
                    pygmented = WIN_CR_RE.sub("\r\n", pygmented)
                    plaintext = WIN_CR_RE.sub("\r\n", self.code)
                else:
                    plaintext = self.code
                winclip.Paste(pygmented, output_type, plaintext)
            else:
                sublime.set_clipboard(pygmented)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            if output_type == 'html':
                new_view.set_syntax_file('Packages/HTML/HTML.tmLanguage')
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, pygmented)
            new_view.end_edit(new_edit)
        else:
            sublime.error_message(u'Unsupported target "%s"' % target)
Ejemplo n.º 49
0
    def try_open(self, window, maybe_path):
        global cache

        debug_info('Trying to open: ' + maybe_path)

        path_normalized = normalize(maybe_path)
        if path_normalized in cache['checked']:
            return False
        cache['checked'][path_normalized] = True

        if maybe_path.startswith('http'):
            # HTTP URL
            if BINARY.search(maybe_path) or s.get("open_http_in_browser", False):
                sublime.status_message("Opening in Browser " + maybe_path)

                import webbrowser
                webbrowser.open_new_tab(maybe_path)
            else:
                sublime.status_message("Opening URL " + maybe_path)
                # Create thread to download url in background
                threading.Thread(target=self.read_url, args=(maybe_path,)).start()

        elif os_is_file(maybe_path):
            sublime.status_message("Opening File " + normalize(maybe_path))
            if IMAGE.search(maybe_path):
                self.open(window, maybe_path)
            elif BINARY.search(maybe_path):
                try:
                    import desktop
                except:
                    from . import desktop
                desktop.open(maybe_path)
            else:
                # Open within ST
                self.open(window, maybe_path)

        elif maybe_path and ( os_is_dir(maybe_path) or os_is_dir('\\' + maybe_path) ) and not cache['folder'] and cache['folder_save']:
            # Walkaround for UNC path
            if maybe_path and maybe_path[0] == '\\':
                maybe_path = '\\' + maybe_path
            cache['folder'] = maybe_path
            return False

        else:
            return False

        return True
    def run(self, edit, target='browser'):
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == 'Undefined':
            encoding = 'utf-8'
        elif encoding == 'Western (Windows 1252)':
            encoding = 'windows-1252'
        contents = self.view.substr(region)

        # convert the markdown
        markdown_html = markdown.markdown(contents)

        # postprocess the html
        markdown_html = self.postprocessor(markdown_html)
        # check if LiveReload ST2 extension installed
        livereload_installed = ('LiveReload' in os.listdir(sublime.packages_path()))

        # build the html
        html_contents = u'<!DOCTYPE html>'
        html_contents += '<html><head><meta charset="%s">' % encoding
        styles = self.getCSS()
        html_contents += '<style>%s</style>' % styles
        html_contents += '<link rel="stylesheet" href="http://yandex.st/highlightjs/5.16/styles/default.min.css">'
        html_contents += '<script src="http://yandex.st/highlightjs/5.16/highlight.min.js"></script>'
        if livereload_installed:
            html_contents += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>'
        html_contents += '</head><body>'
        html_contents += markdown_html
        html_contents += '<script type="text/javascript">hljs.tabReplace = \'  \'; hljs.initHighlightingOnLoad();</script>'
        html_contents += '</body>'

        if target in ['disk', 'browser']:
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, 'w')
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            # todo : livereload ?
            if target == 'browser':
                desktop.open(tmp_fullpath)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
        print 'markdown converted'
Ejemplo n.º 51
0
 def open(self):
     if sublime.platform() == 'osx':
         import subprocess
         subprocess.Popen(['open', '-a', self.nameSystem()],
                          cwd=self.dirnameSystem())
     elif sublime.platform() == 'windows':
         import subprocess
         subprocess.Popen([self.nameSystem()],
                          cwd=self.dirnameSystem(),
                          shell=True)
     else:
         import sys
         path = os.path.join(sublime.packages_path(), 'SideBarEnhancements')
         if path not in sys.path:
             sys.path.append(path)
         import desktop
         desktop.open(self.path())
    def run(self, edit, target='browser'):
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == 'Undefined':
            encoding = 'utf-8'
        elif encoding == 'Western (Windows 1252)':
            encoding = 'windows-1252'
        contents = self.view.substr(region)

        # convert the markdown
        markdown_html = markdown2.markdown(contents,
                                           extras=['footnotes', 'toc'])

        # postprocess the html
        markdown_html = self.postprocessor(markdown_html)

        # check if LiveReload ST2 extension installed
        livereload_installed = ('LiveReload'
                                in os.listdir(sublime.packages_path()))

        # build the html
        html_contents = u'<!DOCTYPE html>'
        html_contents += '<html><head><meta charset="%s">' % encoding
        styles = self.getCSS()
        html_contents += '<style>%s</style>' % styles
        if livereload_installed:
            html_contents += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>'
        html_contents += '</head><body>'
        html_contents += markdown_html
        html_contents += '</body>'

        if target in ['disk', 'browser']:
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, 'w')
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            # todo : livereload ?
            if target == 'browser':
                desktop.open(tmp_fullpath)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
        print 'markdown converted'
Ejemplo n.º 53
0
    def open(self):
        import sys

        if sys.platform == "darwin":
            import subprocess

            subprocess.Popen(["open", "-a", self.nameSystem()], cwd=self.dirnameSystem())
        elif sys.platform == "win32":
            import subprocess

            subprocess.Popen([self.nameSystem()], cwd=self.dirnameSystem(), shell=True)
        else:
            path = os.path.join(sublime.packages_path(), "SideBarEnhancements")
            if path not in sys.path:
                sys.path.append(path)
            import desktop

            desktop.open(self.path())
Ejemplo n.º 54
0
            def start_explorer(event=None):
                if event:
                    mission = table.identify_row(event.y)
                    if not mission:
                        # click on header
                        return
                    missions = [mission]
                else:
                    missions = table.selected()

                for mission in missions:
                    savepath = profile(mission.module.config["savepath"])
                    folder = os.path.join(savepath,
                                          safefilepath(mission.title))
                    folder = os.path.expanduser(folder)
                    if not os.path.isdir(folder):
                        os.makedirs(folder)
                    desktop.open(folder)
Ejemplo n.º 55
0
    def select_subdir(self, treeview, o1, o2):
        selection = treeview.get_selection()
        liststore, rows = selection.get_selected_rows()

        if self.selected_backup:
            focus_dir = self.backup.parent_backup_dir + '/' + self.selected_backup.strftime(
                BACKUP_DIR_DATE_FORMAT) + self.cur_dir
        else:
            focus_dir = self.cur_dir
#        print 'focus_dir', focus_dir

        local_file = liststore[rows[0]][0].rstrip('/')

        new_file = focus_dir.rstrip('/') + '/' + local_file
        #        print 'new_file', new_file
        if os.path.isdir(new_file):
            self.cur_dir = self.cur_dir.rstrip('/') + '/' + local_file
            self.xml.get_widget('location_field').set_text(self.cur_dir)
        else:
            print 'not a dir:', new_file
            desktop.open(new_file)
        self.refresh_file_list()
Ejemplo n.º 56
0
    def run(self, edit, target='external', output_type='html'):
        output_type = output_type if output_type in FORMATS else 'html'
        pygmented = self.highlight(output_type)

        if target == 'external':
            filename = '%s.%s' % (
                self.view.id(),
                output_type,
            )
            tmp_file = self.write_file(filename, pygmented)
            sublime.status_message(tmp_file)
            desktop.open(tmp_file)
        elif target == 'clipboard':
            sublime.set_clipboard(pygmented)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            if output_type == 'html':
                new_view.set_syntax_file('Packages/HTML/HTML.tmLanguage')
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, pygmented)
            new_view.end_edit(new_edit)
        else:
            sublime.error_message(u'Unsupported target "%s"' % target)
Ejemplo n.º 57
0
    def playEpisode(self, episode):
        """Open the player and open the episode."""
        command = Config.config['command_open']
        if episode.path:
            path = os.path.normpath(episode.path)
            player = int(Config.config['player'])
            if player == 1:
                desktop.open(path)
            elif player == 2:
                self.playIntegratedPlayer(episode)
            elif player == 3:
                if command is None:
                    desktop.open(path)
                else:
                    self.commandOpen.startDetached(command, [path])
            else:
                desktop.open(path)

            self.markAsView(episode)
            self.refreshCount()
    def run(self, edit, target='browser'):
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == 'Undefined':
            encoding = 'utf-8'
        elif encoding == 'Western (Windows 1252)':
            encoding = 'windows-1252'
        elif encoding == 'UTF-8 with BOM':
            encoding = 'utf-8'
        contents = self.view.substr(region)

        config_parser = settings.get('parser')

        markdown_html = u'cannot convert markdown'
        if config_parser and config_parser == 'github':
            sublime.status_message('converting markdown with github API...')
            try:
                #contents = contents.replace('%', '')    # see https://gist.github.com/3742011
                data = json.dumps({"text": contents, "mode": "gfm"})
                url = "https://api.github.com/markdown"
                request = urllib2.Request(url, data, {'Content-Type': 'application/json'})
                markdown_html = urllib2.urlopen(request).read().decode('utf-8')
            except urllib2.HTTPError:
                sublime.error_message('github API responded in an unfashion way :/')
            except urllib2.URLError:
                sublime.error_message('cannot use github API to convert markdown. SSL is not included in your Python installation')
            except:
                sublime.error_message('cannot use github API to convert markdown. Please check your settings.')
            else:
                sublime.status_message('converted markdown with github API successfully')
        else:
            # convert the markdown
            markdown_html = markdown2.markdown(contents, extras=['footnotes', 'toc', 'fenced-code-blocks', 'cuddled-lists'])
            toc_html = markdown_html.toc_html
            if toc_html:
                toc_markers = ['[toc]', '[TOC]', '<!--TOC-->']
                for marker in toc_markers:
                    markdown_html = markdown_html.replace(marker, toc_html)

            # postprocess the html
            markdown_html = self.postprocessor(markdown_html)

        # check if LiveReload ST2 extension installed
        livereload_installed = ('LiveReload' in os.listdir(sublime.packages_path()))

        if target in ['disk', 'browser']:
            # build the html
            html_contents = u'<!DOCTYPE html>'
            html_contents += '<html><head><meta charset="%s">' % encoding
            html_contents += self.getCSS()
            if livereload_installed:
                html_contents += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>'
            html_contents += '</head><body>'
            html_contents += markdown_html
            html_contents += '</body>'

            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, 'w')
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            # todo : livereload ?
            if target == 'browser':
                config_browser = settings.get('browser')
                if config_browser and config_browser != 'default':
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == 'darwin':
                        cmd = "open -a %s" % cmd
                    print "Markdown Preview: executing", cmd
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message('cannot execute "%s" Please check your Markdown Preview settings' % config_browser)
                    else:
                        sublime.status_message('Markdown preview launched in %s' % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message('Markdown preview launched in default html viewer')
        elif target == 'sublime':
            # build the html
            html_contents = markdown_html
            new_view = self.view.window().new_file()
            new_view.set_scratch(True)
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
            sublime.status_message('Markdown preview launched in sublime')
Ejemplo n.º 59
0
 def open(self):
     if self.full_text and os.path.isfile(self.full_text.path):
         desktop.open(self.full_text.path)
         self.read_count = self.read_count + 1
         self.save()