Пример #1
0
def start():

  global mainPlugin

  if sublime.platform() == 'windows':
    print(sublime.platform())
    sublime.error_message("Windows is not supported by this plugin for now.")
    return

  if platform.architecture()[0] != "64bit":
    print(platform.architecture())
    sublime.error_message("Your architecture is not supported by this plugin. This plugin supports only 64bit architectures.")
    return

  try:
    sys.modules["TerminalView"]
  except Exception as err:
    response = sublime.yes_no_cancel_dialog("TerminalView plugin is missing. TerminalView is required to be able to use \"JavaScript Enhancements\" plugin.\n\nDo you want open the github repo of it?", "Yes, open it", "No")
    if response == sublime.DIALOG_YES:
      sublime.active_window().run_command("open_url", args={"url": "https://github.com/Wramberg/TerminalView"})
    return

  try:
    sys.modules["JavaScript Completions"]
    sublime.error_message("Please uninstall/disable JavaScript Completions plugin.")
    return
  except Exception as err:
    pass

  node = NodeJS(check_local=True)
  try:
    print(node.getCurrentNodeJSVersion())
  except Exception as err: 
    print(err)
    response = sublime.yes_no_cancel_dialog("Error during installation: \"node.js\" seems not installed on your system. Node.js and npm are required to be able to use JavaScript Enhancements plugin.\n\nIf you are using \"nvm\" or you have a different path for node.js and npm, please then change the path on:\n\nPreferences > Package Settings > JavaScript Enhancements > Settings\n\nand restart Sublime Text.\n\nIf this doesn't work then try also to add the path of their binaries in the PATH key-value on the same JavaScript Enhancements settings file. This variable will be used to add them in the $PATH environment variable, so put the symbol \":\" in front of your path.\n\nDo you want open the website of node.js?", "Yes, open it", "Or use nvm")
    if response == sublime.DIALOG_YES:
      sublime.active_window().run_command("open_url", args={"url": "https://nodejs.org"})
    elif response == sublime.DIALOG_NO:
      sublime.active_window().run_command("open_url", args={"url": "https://github.com/creationix/nvm"})
    return

  npm = NPM(check_local=True)
  try:
    print(npm.getCurrentNPMVersion())
  except Exception as err: 
    print(err)
    response = sublime.yes_no_cancel_dialog("Error during installation: \"npm\" seems not installed on your system. Node.js and npm are required to be able to use JavaScript Enhancements plugin.\n\nIf you are using \"nvm\" or you have a different path for node.js and npm, please change their custom path on:\n\nPreferences > Package Settings > JavaScript Enhancements > Settings\n\nand restart Sublime Text.\n\nIf this doesn't work then try also to add the path of their binaries in the PATH key-value on the same JavaScript Enhancements settings file. This variable will be used to add them in the $PATH environment variable, so put the symbol \":\" in front of your path.\n\nDo you want open the website of node.js?", "Yes, open it", "Or use nvm")
    if response == sublime.DIALOG_YES:
      sublime.active_window().run_command("open_url", args={"url": "https://nodejs.org"})
    elif response == sublime.DIALOG_NO:
      sublime.active_window().run_command("open_url", args={"url": "https://github.com/creationix/nvm"})
    return

  mainPlugin.init()
Пример #2
0
    def run(self, **kwargs):
        """ Save this window's workspace

        Keyword Arguments:
            filename        = workspace file to save
            promptOverwrite = indicates if we should prompt before overwriting a file
            promptSave      = indicates if we should prompt before saving a new file
        """
        super().run(**kwargs)

        # are we saving a new workspace?
        isNewWorkspace = self.window.id(
        ) not in EasyWorkspaceCommand._openWorkspaceFiles
        noFileProvided = kwargs.get('filename', None) == None

        if isNewWorkspace and noFileProvided:
            # use save-as to get the filename!
            self.window.run_command("save_as_easy_workspace", kwargs)

        else:
            self.window.status_message("Saving workspace...")

            ws = EasyWorkspace()
            ws.buildFromWindow(self.window)

            # resolve the full filepath
            fullFilePath = self.getWorkspaceFilepath(
                kwargs.get(
                    'filename',
                    EasyWorkspaceCommand._openWorkspaceFiles.get(
                        self.window.id())))

            # prompt for overwrite or create new
            doSaveDialogResult = sublime.DIALOG_YES
            if (kwargs.get("promptOverwrite", False)
                    and os.path.isfile(fullFilePath)):
                doSaveDialogResult = sublime.yes_no_cancel_dialog(
                    "Overwrite Easy Workspace?\n\n{}".format(fullFilePath))
            elif (kwargs.get("promptSave", False)):
                doSaveDialogResult = sublime.yes_no_cancel_dialog(
                    "Save New Workspace?\n\n{}".format(fullFilePath))

            # save if not cancelled
            if doSaveDialogResult != sublime.DIALOG_YES:
                self.window.status_message("Canceled")
            else:
                ws.saveToFile(fullFilePath)
                EasyWorkspaceCommand._openWorkspaceFiles[
                    self.window.id()] = fullFilePath
                self.window.status_message("Saved " + fullFilePath)
Пример #3
0
		def on_done(index):
			if index == -1: return
			select = folder[index]
			# print(select)
			exist = []
			overwrite = 'none' # none all file system
			for file in workflowFiles:
				result = os.path.exists(os.path.abspath(os.path.join(select, file)))
				exist.append(result)

			if os.path.exists(self.window.project_file_name()):
				with open (self.window.project_file_name(), 'r+', encoding='utf8') as project:
					projectData = project.readlines()
					exist.append('\t"build_systems":\n' in projectData)
			else:
				sublime.message_dialog("請先建立project\nProject -> Save Project As...")
			
			if True in exist:
				while exist.count(True) == len(exist):
					if sublime.yes_no_cancel_dialog(
						'build tool 已建立\n是否要更新為最新版本', '全部更新', '指定更新'
						) == sublime.DIALOG_NO:
						if sublime.yes_no_cancel_dialog(
							'請選擇要更新的項目', '更新 task 及 package.json', '更新 build system'
							) == sublime.DIALOG_YES:
							overwrite = 'file'
						elif sublime.DIALOG_NO:
							overwrite = 'system'
						elif sublime.DIALOG_CANCEL:
							return None
					elif sublime.DIALOG_YES:
						overwrite = 'all'
					elif sublime.DIALOG_CANCEL:
						 return None
					break
				while overwrite == 'none' and exist.index(True) < len(exist) - 1:
					if not sublime.ok_cancel_dialog('task 和 package 已建立\n是否需要更新為最新版本', '更新'):
						overwrite = 'system'
					else:
						overwrite = 'file'
					break
				while overwrite == 'none' and exist.index(True) == len(exist) - 1:
					if not sublime.ok_cancel_dialog('build system 已建立\n是否需要更新為最新版本', '更新'):
						overwrite = 'file'
					break	

			# print('overwrite '+ overwrite)
			copyFiles(select, copied, overwrite)
Пример #4
0
    def create_and_upload_request():
      d = description if description != '' else ''
      files = Manager.get_files_content()

      if len(files) > 0:
        try:
          data = {'files': files}
          api = Manager.gist_api()

          if d != '': data.update({'description': d})
          if api is not None:
            result = api.create(data)
            dialog_message = ''.join([
              'Sync Settings: \n',
              'Your gist was created successfully\n',
              'Do you want update the gist_id property in the configuration file?'
            ])

            Manager.show_message_and_log('Gist created, id = ' + result.get('id'), False)
            if sublime.yes_no_cancel_dialog(dialog_message) == sublime.DIALOG_YES:
              Manager.settings('gist_id', result.get('id'))
              sublime.save_settings(Manager.get_settings_filename())
              Manager.show_message_and_log('Gist id updated successfully!', False)
        except Exception as e:
          Manager.show_message_and_log(e)
      else:
        Manager.show_message_and_log('There are not enough files to create the gist', False)
Пример #5
0
    def on_done_reason(self, reason):
        self.reason = reason

        message = '''
        Old name: "%s"
        New name: "%s"
        Reason: %s

        Leave a redirect behind?
        ''' % (self.title, self.new_title, self.reason)

        is_make_redirect = sublime.yes_no_cancel_dialog(message, 'Yes', 'No')

        if is_make_redirect != sublime.DIALOG_CANCEL:
            no_redirect = True if is_make_redirect == sublime.DIALOG_NO else False
            utils.api.page_move(self.page, self.new_title, self.reason, no_redirect)
            utils.status_message('Page [[%s]] was moved successfully to [[%s]], leave redirect: %s' % (self.title, self.new_title, not no_redirect))

            if not no_redirect:
                utils.status_message('Refreshing old page (redirect): [[%s]]' % self.title)
                self.view.window().run_command(utils.cmd('reopen_page'))
            else:
                utils.status_message('Closing old page: [[%s]]' % self.title)
                self.view.close()

            utils.status_message('Opening new page: [[%s]]' % self.new_title)
            sublime.set_timeout(
                lambda: sublime.active_window().run_command(utils.cmd('page'), {
                    'action': utils.cmd('show_page'),
                    'action_params': {'title': self.new_title, 'new_tab': True}
                }), 2)
Пример #6
0
  def __create_and_upload_request(self, description):
    d = description if description != '' else ''
    files = SyncManager.get_files_content()

    if len(files):
      try:
        data = {'files': files}
        api = SyncManager.gist_api()

        if d != '': data.update({'description': d})
        if api is not None:
          gist_data = api.create(data)
          dialog_message = ''.join([
            'Sync Settings:\n\n',
            'Do you want overwrite the current `gist_id` property?'
          ])

          if sublime.yes_no_cancel_dialog(dialog_message) == sublime.DIALOG_YES:
            SyncManager.settings('gist_id', gist_data.get('id')).save_settings()
            SyncVersion.upgrade(gist_data)

          SyncLogger.log('Your settings were correctly backed', SyncLogger.LOG_LEVEL_SUCCESS)

      except Exception as e:
        SyncLogger.log(e, SyncLogger.LOG_LEVEL_ERROR)
    else:
      SyncLogger.log(
        'There are not enough files to create a backup',
        SyncLogger.LOG_LEVEL_WARNING
      )
def start_onboarding():
    """Attempts to open the live onboarding file. If fetching the file fails,
    then a help dialog is shown instead.

    This function returns whether or not the help prompt should be suppressed
    in future startups. The help prompt should be suppressed if fetching the
    live onboarding file succeeds or if the user clicked on the "No" button
    in the help dialog.
    """

    url = 'http://localhost:46624/clientapi/plugins/onboarding_file'
    resp = requests.get(url)

    if resp.status_code != 200:
        res = sublime.yes_no_cancel_dialog(
            'Sublime Text is now integrated with Kite.\n\n' +
            'Kite is an AI-powered programming assistant that shows you ' +
            'the right information at the right time to keep you in the ' +
            'flow.\n\n' + 'Would you like to learn how to use Kite?\n',
            yes_title='Show me what Kite can do',
            no_title='Hide forever')
        if res == sublime.DIALOG_YES:
            link_opener.open_browser_url(
                'https://github.com/kiteco/KiteSublime/blob/master/README.md')
        return res == sublime.DIALOG_NO

    file_name = resp.json()
    sublime.active_window().open_file(file_name)
    return True
Пример #8
0
 def on_done(text):
     text = text.replace("/", "\\")
     text = os.path.join(path, text)
     if text.endswith("\\"):
         os.makedirs(text, exist_ok = True)
     else:
         new_path = os.path.dirname(text)
         os.makedirs(new_path, exist_ok = True)
         if not os.path.exists(text):
             open(text, "w").close()
             sublime.active_window().open_file(text)
         else:
             if os.path.isdir(text):
                 sublime.error_message(
                     'Folder: "{}" has already existed!'.format(text))
             else:
                 res_dialog = sublime.yes_no_cancel_dialog(
                     'File: "{}" has already existed!'.format(text),
                     "Overwrite It!", "Open It")
                 if res_dialog == sublime.DIALOG_YES:
                     open(text, "w").close()
                     sublime.active_window().open_file(text)
                 elif res_dialog == sublime.DIALOG_NO:
                     sublime.active_window().open_file(text)
                 else:
                     pass
Пример #9
0
    def run(self, **args):
        self.args = args
        self.get_files()
        if not (self.filepaths):
            return

        if self.debug:
            print("checkout requested for these files")
            self.pp.pprint(self.filepaths)

        dialog_message = ''.join([
            'xxxDo you really want to add these files to Clearcase?\n',
            '\n',
            '\n'.join(self.filepaths) + "\n",
        ])
        retval = sublime.yes_no_cancel_dialog(dialog_message)

        if retval == sublime.DIALOG_YES:
            self._cmd = [
                'cleartool',
                'mkelem',
                '-mkpath',
                '-nc',
                '-nco',
            ]
            self._cmd.extend(self.filepaths)

            self.run_cmd(self._cmd)
Пример #10
0
    def burn_firmware(self):
        """Burn firmware

        Uses esptool.py to burn the firmware
        """
        from ..tools.command import Command

        filename = self.url.split('/')[-1]
        firmware = join(self.firmwares, filename)

        options = self.get_board_options(self.board)
        options.append(firmware)

        caption = "Do you want to erase the flash memory?"
        answer = sublime.yes_no_cancel_dialog(caption, "Yes", "No")

        # stop
        if (answer == sublime.DIALOG_CANCEL):
            return

        # erase flash
        if (answer == sublime.DIALOG_YES):
            tools.erase_flash()

        options.insert(0, "--port " + self.port)

        if (not serial.check_port(self.port)):
            return

        if (self.port in serial.in_use):
            serial.serial_dict[self.port].close()

        Command().run(options, port=self.port)
Пример #11
0
def backup_with_prompt_on_done(path):
    global prompt_parameters

    if os.path.exists(path) == True:

        if sublime.version()[0] == "2":
            if sublime.ok_cancel_dialog(
                    "Backup already exists @ %s \nReplace it?" % path,
                    "Continue") == True:
                prompt_parameters["operation_to_perform"](path)

            else:
                tools.packagesync_cancelled()
        else:
            confirm_override = sublime.yes_no_cancel_dialog(
                "Backup already exists @ %s \nReplace it?" % path, "Continue")

            if confirm_override == sublime.DIALOG_YES:
                prompt_parameters["operation_to_perform"](path)
            elif sublime.version(
            )[0] == "3" and confirm_override == sublime.DIALOG_NO:
                prompt_parameters["initial_text"] = path
                prompt_for_location()
            else:
                tools.packagesync_cancelled()

    elif os.path.isabs(os.path.dirname(path)) == True:
        prompt_parameters["operation_to_perform"](path)

    else:
        sublime.error_message("Please provide a valid path for backup.")
        prompt_parameters["initial_text"] = path
        prompt_for_location()
Пример #12
0
    def run(self, **args):
        self.args = args
        self.get_files()
        if not (self.filepaths):
            return

        dialog_message = ''.join([
            'You are about to undo checkout of:\n',
            '\n',
            "\n".join(self.filepaths) + "\n",
            "\n",
            "Do you want to save a .keep file?\n",
        ])
        retval = sublime.yes_no_cancel_dialog(dialog_message)

        if retval == sublime.DIALOG_CANCEL:
            return

        if retval == sublime.DIALOG_YES:
            keep_switch = "-keep"
        else:
            keep_switch = "-rm"

        # keep_switch = (retval == sublime.DIALOG_YES) ? "-keep" : "-rm"

        self._cmd = [
            'cleartool',
            'unco',
            keep_switch,
        ]
        self._cmd.extend(self.filepaths)

        self.run_cmd(self._cmd)
Пример #13
0
 def on_navigate(self, href):
     global _IS_ENABLED
     if href == "check_system":
         self.view.window().run_command("latextools_system_check")
     elif href == "disable":
         answer = sublime.yes_no_cancel_dialog(
             "The math-live preview will be temporary disabled until "
             "you restart Sublime Text. If you want to disable it "
             "permanent open your LaTeXTools settings and set "
             "\"preview_math_mode\" to \"none\".",
             yes_title="Open LaTeXTools settings",
             no_title="Disable for this session"
         )
         if answer == sublime.DIALOG_CANCEL:
             # do nothing
             return
         _IS_ENABLED = False
         self.update_phantoms()
         if answer == sublime.DIALOG_YES:
             self.view.window().run_command("open_latextools_user_settings")
     elif href.startswith("report-"):
         file_path = href[len("report-"):]
         if not os.path.exists(file_path):
             sublime.error_message(
                 "Report file missing: {0}.".format(file_path)
             )
             return
         self.view.window().open_file(file_path)
Пример #14
0
def backup_with_prompt_on_done(path):
    global prompt_parameters

    if os.path.exists(path) == True:

        if sublime.version()[0] == "2":
            if sublime.ok_cancel_dialog(
                    "Backup already exists @ %s \nReplace it?" % path, "Continue") == True:
                prompt_parameters["operation_to_perform"](path)

            else:
                tools.packagesync_cancelled()
        else:
            confirm_override = sublime.yes_no_cancel_dialog(
                "Backup already exists @ %s \nReplace it?" % path, "Continue")

            if confirm_override == sublime.DIALOG_YES:
                prompt_parameters["operation_to_perform"](path)
            elif sublime.version()[0] == "3" and confirm_override == sublime.DIALOG_NO:
                prompt_parameters["initial_text"] = path
                prompt_for_location()
            else:
                tools.packagesync_cancelled()

    elif os.path.isabs(os.path.dirname(path)) == True:
        prompt_parameters["operation_to_perform"](path)

    else:
        sublime.error_message("Please provide a valid path for backup.")
        prompt_parameters["initial_text"] = path
        prompt_for_location()
Пример #15
0
def plugin_loaded():

  if int(sublime.version()) >= 3124 :

    if platform.system() == "Darwin" or platform.system() == "Linux":
      global fixPathSettings
      fixPathSettings = sublime.load_settings("Preferences.sublime-settings")
      fixPathSettings.clear_on_change('fixpath-reload')
      fixPathSettings.add_on_change('fixpath-reload', fixPath)

      # Save the original environ (particularly the original PATH) to restore later
      global fixPathOriginalEnv
      for key in os.environ:
        fixPathOriginalEnv[key] = os.environ[key]

      fixPath()

    debug_mode = javaScriptEnhancements.get("debug_mode")

    if debug_mode:
      print(os.environ)

    sublime.set_timeout_async(delete_temp_files)

    sublime.set_timeout_async(start, 1000)

  else:
    response = sublime.yes_no_cancel_dialog("JavaScript Enhancements plugin requires Sublime Text 3 (build 3124 or newer). Your build is: " + sublime.version() + ". Do you want open the download page?", "Yes, open it", "No")
    if response == sublime.DIALOG_YES:
      sublime.active_window().run_command("open_url", args={"url": "https://www.sublimetext.com/3"})
Пример #16
0
 def on_navigate(self, href):
     global _IS_ENABLED
     if href == "check_system":
         self.view.window().run_command("latextools_system_check")
     elif href == "disable":
         answer = sublime.yes_no_cancel_dialog(
             "The math-live preview will be temporary disabled until "
             "you restart Sublime Text. If you want to disable it "
             "permanent open your LaTeXTools settings and set "
             "\"preview_math_mode\" to \"none\".",
             yes_title="Open LaTeXTools settings",
             no_title="Disable for this session")
         if answer == sublime.DIALOG_CANCEL:
             # do nothing
             return
         _IS_ENABLED = False
         self.update_phantoms()
         if answer == sublime.DIALOG_YES:
             self.view.window().run_command("open_latextools_user_settings")
     elif href.startswith("report-"):
         file_path = href[len("report-"):]
         if not os.path.exists(file_path):
             sublime.error_message(
                 "Report file missing: {0}.".format(file_path))
             return
         self.view.window().open_file(file_path)
Пример #17
0
def queryWarning(test, view):
	answer = sublime.yes_no_cancel_dialog("The element pointed at " + test.locator + " has changed, potentially breaking your test. If you'd like to continue being warned about this test, hit cancel.", "Turn off warnings for this test.", "Undo changes")
	if answer == sublime.DIALOG_YES:
		test.warn = False
		test.broken = True
	if answer == sublime.DIALOG_NO:
		view.run_command("undo")
Пример #18
0
    def run(self, paths, current_file=False):
        if not self.is_enabled():
            return

        if paths is None and current_file:
            active_view = self.window.active_view()
            if active_view is None:
                msg.log(
                    'RemoveFromWorkspace: No active view found. Perhaps active tab is an image?'
                )
                return
            paths = [active_view.file_name()]

        if not hasattr(sublime, 'yes_no_cancel_dialog'):
            unlink = bool(
                sublime.ok_cancel_dialog(
                    'Delete? Select cancel to remove from the workspace without deleting.',
                    'Delete'))
        else:
            ret = sublime.yes_no_cancel_dialog(
                "What should I do with\n%s" % "\n".join(paths[:5]), "Delete!",
                "Just Remove from Workspace.")
            if ret == 0:
                return
            unlink = ret == 1

        for path in paths:
            G.AGENT.delete_buf(path, unlink)
Пример #19
0
    def __create_and_upload_request(self, description):
        d = description if description != '' else ''
        files = SyncManager.get_files_content()

        if len(files):
            try:
                data = {'files': files}
                api = SyncManager.gist_api()

                if d != '': data.update({'description': d})
                if api is not None:
                    gist_data = api.create(data)
                    dialog_message = ''.join([
                        'Sync Settings:\n\n',
                        'Do you want overwrite the current `gist_id` property?'
                    ])

                    if sublime.yes_no_cancel_dialog(
                            dialog_message) == sublime.DIALOG_YES:
                        SyncManager.settings(
                            'gist_id', gist_data.get('id')).save_settings()
                        SyncVersion.upgrade(gist_data)

                    SyncLogger.log('Your settings were correctly backed',
                                   SyncLogger.LOG_LEVEL_SUCCESS)

            except Exception as e:
                SyncLogger.log(e, SyncLogger.LOG_LEVEL_ERROR)
        else:
            SyncLogger.log('There are not enough files to create a backup',
                           SyncLogger.LOG_LEVEL_WARNING)
Пример #20
0
 def folder_selected(self, destination_folder):
     untitled_suffix = 1
     for occurrence in self.occurrences:
         filename = occurrence.filename
         # deal with untitled
         if occurrence.isuntitled:
             filename = "%s-%i" % (occurrence.filename, untitled_suffix)
             untitled_suffix += 1
         # assemble full paths
         file_path = os.path.join(destination_folder, filename)
         folder_path = os.path.dirname(file_path)
         # make parent directory (if filename contains a relative path)
         if not os.path.exists(folder_path):
             os.makedirs(folder_path)
         # ask to overwrite if file exists
         if os.path.exists(file_path):
             answer = sublime.yes_no_cancel_dialog(
                 "Do you want to overwrite %s?" % (file_path, ),
                 'Overwrite', 'Keep Existing')
             if answer == sublime.DIALOG_NO:
                 continue
             elif answer == sublime.DIALOG_CANCEL:
                 return
         with open(file_path, 'wb') as f:
             f.write(occurrence.unpacked)
Пример #21
0
 def run(self):
     """."""
     if stino.arduino_info['init_done']:
         msg = 'Beware: Please check your board type! Continue?'
         result = sublime.yes_no_cancel_dialog(msg)
         if result == sublime.DIALOG_YES:
             stino.bootloader.put()
 def add_some_projects(add_q, projli):
     """
     add_q is one of sublime.DIALOG_YES, _NO, or _CANCEL
     projli is of type [{'name': {}}]
     """
     if add_q == sublime.DIALOG_YES:
         for rel, absol in projli:
             if 'pretext_projects' not in projdata.keys():
                 projdata['pretext_projects'] = {}
             if not is_present(rel, projdata['pretext_projects']):
                 projdata['pretext_projects'].update({rel: {"path": absol, "name": rel, "root_file": ""}})
     elif add_q == sublime.DIALOG_CANCEL:
         sublime.message_dialog("No projects added.")
         return
     elif add_q == sublime.DIALOG_NO:
         for rel, absol in projli:
             add = sublime.yes_no_cancel_dialog(
                 "OK to add {} to PreTeXtual management? Select No to proceed to next project.".format(rel))
             if add == sublime.DIALOG_YES:
                 if 'pretext_projects' not in projdata.keys():
                     projdata['pretext_projects'] = {}
                 if not is_present(rel, projdata['pretext_projects']):
                     projdata['pretext_projects'].update({rel: {"path": absol, "name": rel, "root_file": ""}})
             elif add == sublime.DIALOG_CANCEL:
                 sublime.message_dialog("Project addition cancelled.")
                 return
             elif add == sublime.DIALOG_NO:
                 continue
             else:
                 sublime.message_dialog("Error 18: something bad happened")
                 raise VagrantException
     else:
         sublime.message_dialog("Error 16: something bad happened")
         raise VagrantException
Пример #23
0
def show_goodbye_message():
    ok_button_text = "Go back"
    no_button_text = "Skip this upgrade"

    lines = \
    [
        wrap_text( """\
        Do you want to cancel the {channel_name} {wizard}?

        If you would like to upgrade the {channel_name}, hit the `{ok_button}` button to go back and
        try again. Otherwise, hit the `Cancel` button to follow the {wizard} next time Sublime Text
        starts.

        If you would like to ignore this upgrade, hit the `{no_button}` button.
        """.format( ok_button=ok_button_text, no_button=no_button_text,
                wizard=g_installation_type, channel_name=CHANNEL_PACKAGE_NAME ), single_lines=True ),
    ]

    sublime_dialog = sublime.yes_no_cancel_dialog( "\n".join( lines ), ok_button_text, no_button_text )

    if sublime_dialog == sublime.DIALOG_YES: # "Go back"
        return True

    elif sublime_dialog == sublime.DIALOG_NO: # "Skip this upgrade"
        g_channelSettings['CHANNEL_UPGRADE_SKIP'] = True

    elif sublime_dialog == sublime.DIALOG_CANCEL:
        # When pressing escape key, it returns to DIALOG_CANCEL
        pass

    else:
        log(1, "Error: The option `%s` is a invalid return value from `sublime.yes_no_cancel_dialog`!", sublime_dialog )

    return False
Пример #24
0
    def on_done_reason(self, reason):
        self.reason = reason

        message = '''
        Old name: "%s"
        New name: "%s"
        Reason: %s

        Leave a redirect behind?
        ''' % (self.title, self.new_title, self.reason)

        is_make_redirect = sublime.yes_no_cancel_dialog(message, 'Yes', 'No')

        if is_make_redirect != sublime.DIALOG_CANCEL:
            no_redirect = True if is_make_redirect == sublime.DIALOG_NO else False
            mw.api.page_move(self.page, self.new_title, self.reason, no_redirect)
            mw.status_message('Page [[%s]] was moved successfully to [[%s]], leave redirect: %s' % (self.title, self.new_title, not no_redirect))

            if not no_redirect:
                mw.status_message('Refreshing old page (redirect): [[%s]]' % self.title)
                self.view.window().run_command(mw.cmd('reopen_page'))
            else:
                mw.status_message('Closing old page: [[%s]]' % self.title)
                self.view.close()

            mw.status_message('Opening new page: [[%s]]' % self.new_title)
            sublime.set_timeout(
                lambda: sublime.active_window().run_command(mw.cmd('page'), {
                    'action': mw.cmd('show_page'),
                    'action_params': {'title': self.new_title, 'new_tab': True}
                }), 2)
Пример #25
0
 def run(self, edit):
     if is_valid(self.view):
         region, module = line(self.view)
         reply = sublime.yes_no_cancel_dialog(
             'Remove "%s" module?' % module, 'Yes', 'No')
         if reply == 1:
             self.view.erase(edit, region)
             NpmExec(module, cwd(self.view), 'uninstall', self.view).start()
Пример #26
0
    def run(self, **kwargs):
        caption = kwargs.pop("caption", "Start the Build?")

        variables = self.window.extract_variables()
        caption = sublime.expand_variables(caption, variables)

        if sublime.yes_no_cancel_dialog(caption) == sublime.DIALOG_YES:
            self.window.run_command("exec", kwargs)
Пример #27
0
def plugin_loaded():
  
  if int(sublime.version()) >= 3124 :
    sublime.set_timeout_async(start, 1000)
  else:
    response = sublime.yes_no_cancel_dialog("JavaScript Enhancements plugin requires Sublime Text 3 (build 3124 or newer). Your build is: " + sublime.version() + ". Do you want open the download page?", "Yes, open it", "No")
    if response == sublime.DIALOG_YES:
      sublime.active_window().run_command("open_url", args={"url": "https://www.sublimetext.com/3"})
Пример #28
0
def show_update_dialog(on_yes=None):
    msg = ('Sync Settings:\n\n'
           'Your settings seem out of date.\n\n'
           'Do you want to download the latest version?')
    if sublime.yes_no_cancel_dialog(msg) == sublime.DIALOG_YES:
        # call download command
        if on_yes:
            on_yes()
Пример #29
0
def show_program_description():
    ok_button_text = "Edit upgrade"
    no_button_text = "Start upgrade"

    lines = [ "Welcome to the {channel} {wizard}.".format( channel=CHANNEL_PACKAGE_NAME, wizard=g_installation_type ), "", ]

    def format_packages_list(packages_list, maximum_length=500):
        length = 0
        contents = []

        for index, name in enumerate( packages_list ):
            contents.append( "%s. %s" % ( index + 1, name ) )
            length += len( contents[-1] )

            if length > maximum_length:
                remaining = len( packages_list ) - index - 1
                if remaining > 0: contents.append( "and more {} packages!".format( remaining ) )
                break

        return ", ".join( contents )

    if len( PACKAGES_TO_INSTALL ):
        lines.append( "The main {channel} upstream has added the following new packages: ".format( channel=CHANNEL_PACKAGE_NAME ) )
        lines.append( format_packages_list( PACKAGES_TO_INSTALL ) )
        lines.append( "" )

    if len( PACKAGES_TO_UNINSTALL ):
        lines.append( "The main {channel} upstream has removed the following installed packages: ".format( channel=CHANNEL_PACKAGE_NAME ) )
        lines.append( format_packages_list( PACKAGES_TO_UNINSTALL ) )
        lines.append( "" )

    if len( PACKAGES_TO_UNINSTALL ) < 1 and len( PACKAGES_TO_INSTALL ) < 1:
        lines.append( wrap_text( """\
                You removed all upgrade changes. If you would like the undo this, cancel the
                {wizard} and restart Sublime Text. Otherwise, hit the `{ok_button}` button to
                confirm the operation changes.
            """.format( wizard=g_installation_type, ok_button=no_button_text ), single_lines=True ) )

    else:
        global g_isFirstTime

        if g_isFirstTime:
            lines.append( wrap_text( """\
                    If you would like to remove packages from the upgrade list, choose the
                    `{ok_button}` button. Otherwise, choose the `{no_button}` button to start the
                    upgrade process.
                """.format( ok_button=ok_button_text, no_button=no_button_text), single_lines=True ) )

        else:
            lines.append( wrap_text( """\
                    If you would like revert your changes to the {wizard} package's list, just
                    cancel the {wizard} and restart Sublime Text. Then, on next time you start
                    Sublime Text, you will be able to start picking up packages again.
                """.format( wizard=g_installation_type ), single_lines=True ) )

        g_isFirstTime = False

    return sublime.yes_no_cancel_dialog( "\n".join( lines ), ok_button_text, no_button_text )
Пример #30
0
    def run(self, force=False):
        if not force:
            msg = "If you proceed, you will need to re-authenticate. Continue?"
            if sublime.yes_no_cancel_dialog(msg) == sublime.DIALOG_YES:
                sublime.run_command("youtube_editor_logout", {"force": True})

            return

        self.request("deauthorize", reason="Logging out")
Пример #31
0
def _double_custom_button_notify(title, body, buttons):
    first, second = buttons[0], buttons[1]

    res = sublime.yes_no_cancel_dialog(title + "\n\n" + body, first['text'],
                                       second['text'])
    if res == sublime.DIALOG_YES:
        _do_button_action(first)
    elif res == sublime.DIALOG_NO:
        _do_button_action(second)
def plugin_loaded():
    window = sublime.active_window()
    try:
        from package_control import events
        if events.install("PythonVoiceCodingPlugin"):
            if sublime.yes_no_cancel_dialog(greeting) != sublime.DIALOG_YES:
                return
            window.run_command("quick_install_python_voice_coding_plugin", {})
    except:
        pass
Пример #33
0
    def run( self, **kwargs ):
        if "Dual" in kwargs and kwargs["Dual"]==1:
            self.dual_mode=1

        if "action" in kwargs:
            self.action=kwargs["action"]

        (build_yaml_found,dirname)=self.build_yaml_is_present()

        if  self.action=="create-file":
            ##Ask if overwriting is in order
            if build_yaml_found:
                if sublime.yes_no_cancel_dialog("Found existing build.yaml file.\nDo you want to overwrite it?")!=1:
                    return
        elif self.action=="delete-file":
            if not build_yaml_found:
                sublime.error_message("build.yaml was not found at %s" % dirname)
                return
            os.remove(os.path.join(dirname, "build.yaml"))
            return
        elif self.action=="open-file":
            if not build_yaml_found: 
                sublime.error_message("build.yaml was not found at %s" % dirname)
                return     
            self.window.open_file(os.path.join(dirname, "build.yaml"))
            return 
        elif self.action=="clean":
            if not build_yaml_found:
                sublime.error_message("build.yaml was not found at %s" % dirname)
                return
            self.cmd=["panbuild","clean"]
            self.dirname=dirname
            self.invoke_panbuild_command()     
            return               
        else: ## Add-target...  
            if not build_yaml_found and sublime.yes_no_cancel_dialog("build.yaml was not found at %s.\nDo you want to create it?" % dirname) !=1:
                    return 

        if self.window.active_view():
            self.window.show_quick_panel(
                self.get_available_targets(),
                self.append_target)
def select_stable_or_developent_version():
    global g_version_to_install

    lines = \
    [
        wrap_text( """\
        {descriptions}
        It is recommended to use both Stable and Development Versions of the {channel_name}. For
        example, while you are at home, use the Development Version as you should have free time to
        work on it, fixing bugs and installing new packages. Elsewhere your are, use the Stable
        Version, because when you are elsewhere you have no time for fixing bugs or testing new
        things. Also because elsewhere you are, not always there will be enough free space required
        by the Development Version.
        """.format( descriptions=g_channelSettings['CHANNEL_VERSIONS_DESCRIPTIONS'],
                channel_name=CHANNEL_PACKAGE_NAME ), single_lines=True ),
    ]

    user_response = sublime.yes_no_cancel_dialog(
        "\n".join(lines), "Install the Stable Version",
        "Install the Development Version")

    if user_response == sublime.DIALOG_YES:
        g_version_to_install = "stable"

    elif user_response == sublime.DIALOG_NO:
        g_version_to_install = "development"

        command_line_interface = cmd.Cli(None, True)
        git_executable_path = command_line_interface.find_binary(
            "git.exe" if os.name == 'nt' else "git")

        if not git_executable_path:
            g_version_to_install = "stable"

            log(
                1,
                "Using the Stable Version instead of the Development Version as a valid `git`"
                "application could not be found")

            sublime.message_dialog(
                wrap_text("""\
                    Sorry, but the `git` application could not be found on your system. Hence the
                    Stable Version will be used instead. If you are sure there is a `git`
                    application installed on your system check your console for error messages.

                    You can also open an issue on the {channel_name} issue tracker at the address:
                    <{root_url}>, Just do not forget to save your Sublime Text Console output, as it
                    recorded everything which happened, and should be very helpful in finding the
                    solution for the problem.
                    """.format(channel_name=CHANNEL_PACKAGE_NAME,
                               root_url=g_channelSettings['CHANNEL_ROOT_URL']),
                          single_lines=True))

    return user_response != sublime.DIALOG_CANCEL, False
Пример #35
0
    def run(self, files):
        working_dir = self.window.folders()[0]

        settings = load_settings(working_dir)
        full_file_name = files[0]
        file_path = get_file_path(full_file_name)
        file_name = get_file_name(full_file_name)
        file_type = get_file_type(full_file_name)

        if file_name == "service-now.json" or file_type == "spec":
            return False

        table_settings = load_settings(file_path)

        if table_settings is False:
            return False

        sys_id = lookup_record_id(file_name, table_settings)

        if sys_id is not False:
            result = get_record(settings, table_settings['table'], sys_id)

            if result is not False:
                item = result[0]

                body_field = table_settings['body_field']

                doc = item[body_field]

                if os.path.exists(full_file_name):
                    diffs = diff_file_to_doc(full_file_name, doc)

                    if not diffs:
                        sublime.message_dialog('File is up to date.')
                    else:
                        action = sublime.yes_no_cancel_dialog(
                            "Server record is newer than local copy.",
                            "Overwrite Local", "View Differences")

                        if action == sublime.DIALOG_YES:
                            write_doc_file(full_file_name, doc)

                        if action == sublime.DIALOG_NO:
                            diffs = map(
                                lambda line: (line and line[-1] == "\n") and
                                line or line + "\n", diffs)
                            diffs = ''.join(diffs)
                            scratch = self.window.new_file()
                            scratch.set_scratch(True)
                            scratch.run_command('create_diff_scratch',
                                                {'content': diffs})

        else:
            return False
Пример #36
0
def ask_for_back_feedback(filename, feedback_filename, fromEvent = False):
	sublime.active_window().open_file(feedback_filename)
	resp = sublime.yes_no_cancel_dialog("Was this feedback helpful? Please answer Yes or No", "Yes", "No")
	if resp == sublime.DIALOG_YES:
		send_student_back_feedback(filename, "yes", feedback_filename)
	elif resp == sublime.DIALOG_NO:
		send_student_back_feedback(filename, "no", feedback_filename)
	elif resp == sublime.DIALOG_CANCEL:
		ask_for_back_feedback(filename, feedback_filename)
	if fromEvent == False:
		sublime.active_window().active_view().close()
 def _user_permission_dialog():
     message = ("Mousemap already exists. "
                "Do you want to overwrite or change it?")
     answer = sublime.yes_no_cancel_dialog(message, "Overwrite",
                                           "Change existing mousemap")
     if answer == sublime.DIALOG_YES:
         result = _OVERWRITE
     elif answer == sublime.DIALOG_NO:
         result = _CHANGE
     else:
         result = _CANCEL
     return result
Пример #38
0
  def run(self, create = True):
    if not (Manager.settings('access_token') and Manager.settings('gist_id')):
      error_msg = 'You need set the `access_token` and `gist_id` properties'
      Manager.show_message_and_log(error_msg, False)
    else:
      dialog_message = ''.join([
        'Sync Settings: \n',
        'Your Gist will be deleted, are you sure?\n',
        'This action is irreversible'
      ])

      if sublime.yes_no_cancel_dialog(dialog_message) == sublime.DIALOG_YES:
        ThreadProgress(lambda: self.delete_and_create_gist(create), 'Deleting gist')
    def run(self, files):
        working_dir = self.window.folders()[0]

        settings = load_settings(working_dir)
        full_file_name = files[0]
        file_path = get_file_path(full_file_name)
        file_name = get_file_name(full_file_name)
        file_type = get_file_type(full_file_name)

        if file_name == "service-now.json" or file_type == "spec":
            return False

        table_settings = load_settings(file_path)

        if table_settings is False:
            return False

        sys_id = lookup_record_id(file_name, table_settings)

        if sys_id is not False:
            result = get_record(settings, table_settings['table'], sys_id)

            if result is not False:
                item = result

                body_field = table_settings['body_field']
                name = full_file_name

                doc = item[body_field]

                if os.path.exists(full_file_name):
                    diffs = diff_file_to_doc(full_file_name, doc)

                    if not diffs:
                        sublime.message_dialog('File is up to date.')
                    else:
                        action = sublime.yes_no_cancel_dialog("Server record is newer than local copy.",
                                                              "Overwrite Local", "View Differences")

                        if action == sublime.DIALOG_YES:
                            write_doc_file(full_file_name, doc)

                        if action == sublime.DIALOG_NO:
                            diffs = map(lambda line: (line and line[-1] == "\n") and line or line + "\n", diffs)
                            diffs = ''.join(diffs)
                            scratch = self.window.new_file()
                            scratch.set_scratch(True)
                            scratch.run_command('create_diff_scratch', {'content': diffs})

        else:
            return False
Пример #40
0
    def run(self, create=True):
        if not (SyncManager.settings("access_token") and SyncManager.settings("gist_id")):
            SyncLogger.log("You need set the `access_token` and `gist_id` properties", SyncLogger.LOG_LEVEL_WARNING)
        else:
            dialog_message = "".join(
                [
                    "Sync Settings:\n",
                    "Your backup will be deleted, are you sure?\n\n",
                    "Warning: This action is irreversible",
                ]
            )

            if sublime.yes_no_cancel_dialog(dialog_message) == sublime.DIALOG_YES:
                ThreadProgress(lambda: self.__delete_and_create_gist(create), "Deleting backup")
Пример #41
0
	def onDone (self, description):
		d = description if description != "" else ""
		data = {
			'files': SyncSettingsManager.getContentFiles()
		}
		if d != "": data.update({"description": d})

		try:
			result = Gist(SyncSettingsManager.settings('access_token')).create(data)
			sublime.status_message('Sync Settings: Gist created, id = ' + result.get('id'))
			if sublime.yes_no_cancel_dialog('Sync Settings: \nYour gist was created successfully\nDo you want update the gist_id property in the config file?') == sublime.DIALOG_YES:
				SyncSettingsManager.settings('gist_id', result.get('id'))
				sublime.save_settings(SyncSettingsManager.getSettingsFilename())
				sublime.status_message('Sync Settings: Gist id updated successfully!')
		except Exception as e:
			sublime.status_message(str(e))
    def run(self, paths, current_file=False):
        if not self.is_enabled():
            return

        if paths is None and current_file:
            paths = [self.window.active_view().file_name()]

        if not hasattr(sublime, 'yes_no_cancel_dialog'):
            unlink = bool(sublime.ok_cancel_dialog('Delete? Select cancel to remove from the workspace without deleting.', 'Delete'))
        else:
            ret = sublime.yes_no_cancel_dialog("What should I do with\n%s" % "\n".join(paths[:5]), "Delete!", "Just Remove from Workspace.")
            if ret == 0:
                return
            unlink = ret == 1

        for path in paths:
            G.AGENT.delete_buf(path, unlink)
 def displaysentences(self, edit, sentences):
     allcontent = sublime.Region(0, self.view.size())
     toolong = []
     for index in range(len(sentences)):
         if len(sentences[index])>self.limit:
             toolong.append(index)
     newline = "\n";
     self.view.replace(edit, allcontent, newline.join( sentences ))
     if len(toolong)>0:
         action = sublime.yes_no_cancel_dialog('There are currently ' + str(len(toolong)) + ' lines that are over ' + str(self.limit), 'Best guess split long lines', 'Jump to next large line')
         if action == sublime.DIALOG_YES:
             self.bestguesssplit(edit, sentences)
         if action == sublime.DIALOG_NO:
             pt = self.view.text_point(toolong[0], 0);
             self.view.sel().clear()
             self.view.sel().add(sublime.Region(pt))
             self.view.show(pt, True)
Пример #44
0
    def enable_rle(self, edit, file_name):
        """Enable raw line ending mode."""

        if self.view.is_dirty():
            if convert_buffers():
                msg = (
                    "File has unsaved changes.  If you choose to 'continue' without a 'save', "
                    "the view buffer will be parsed as the source.\n\nSave?"
                )
            else:
                msg = (
                    "File has unsaved changes.  If you choose to 'continue' without a 'save', "
                    "changes will be discarded and the file will be parsed from disk.\n\nSave?"
                )
            value = sublime.yes_no_cancel_dialog(msg, "Save", "Continue")
            if value == sublime.DIALOG_YES:
                # Save the file
                self.view.run_command("save")
            elif value == sublime.DIALOG_NO:
                # Convert the unsaved buffer
                if convert_buffers():
                    self.enable_buffer_rle(edit, file_name)
                    return
                else:
                    if file_name is None:
                        error("File must exist on disk!")
                        return
                    else:
                        notify("Changes discarded.")
            else:
                return

        if file_name is None or not exists(file_name):
            if convert_buffers():
                self.enable_buffer_rle(edit)
            else:
                error("File must exist on disk!")
            return

        # Convert the file on disk to a raw line view
        encoding = get_encoding(self.view)
        try:
            self.show_rle(edit, file_name, encoding)
        except Exception:
            self.show_rle(edit, file_name, "utf-8")
Пример #45
0
def diff_and_confirm(full_file_name, remote_doc, local_doc):
    diffs = diff_file_to_doc(full_file_name, remote_doc)

    if diffs:
        diffs = diff_doc_to_doc(local_doc, remote_doc)
        if diffs:
            action = sublime.yes_no_cancel_dialog("Remote record does not match local.", "Overwrite Remote", "View Differences")

            if action == sublime.DIALOG_NO:
                diffs = map(lambda line: (line and line[-1] == "\n") and line or line + "\n", diffs)
                diffs = ''.join(diffs)
                scratch = view.window().new_file()
                scratch.set_scratch(True)
                scratch.run_command('create_diff_scratch', {'content': diffs})

                return False

    return True    
Пример #46
0
def show_python_not_found_error(python_detectors):
    global LAST_ERROR_TIME
    if LAST_ERROR_TIME is not None and (time.time() < LAST_ERROR_TIME + 10.0):
        return
    LAST_ERROR_TIME = time.time()

    msg = (
        "SublimePythonIDE: Could not find Python.\n"
        "Make sure Python is accessible via one of these methods:\n"
        "\n"
        " \xb7 From SublimePythonIDE settings:\n"
        "   %r\n"
        " \xb7 From venv settings:\n"
        "   %r\n"
        " \xb7 From #! (shebang) line in this file:\n"
        "   %r\n"
        " \xb7 From system Python (via $PATH):\n"
        "   %r\n"
        "\n"
        "We use the first non-None value and ensure that the path exists before proceeding.\n"
        % tuple(d() for d in python_detectors)
    )

    if not get_setting("suppress_python_not_found_error", False):
        result = sublime.yes_no_cancel_dialog(
            msg +
            "\n"
            "\"Do Not Show Again\" suppresses this dialog until next launch. "
            "\"More Info\" shows help for configuring Python or permanently suppressing this dialog.",
            "More Info", "Do Not Show Again"
        )
        # In case the user takes more than 10 seconds to react to the dialog
        LAST_ERROR_TIME = time.time()
        if result == sublime.DIALOG_YES:
            import webbrowser
            webbrowser.open("https://github.com/JulianEberius/SublimePythonIDE#configuration")
        elif result == sublime.DIALOG_NO:
            LAST_ERROR_TIME = float("inf")

    raise OSError(
        msg +
        "More info: https://github.com/JulianEberius/SublimePythonIDE#configuration"
    )
Пример #47
0
    def first_run(self):
        if len(self.get_repository_url()) == 0:
            sublime.error_message("Repository url is not set in settings file. Do it first, then run sync again")
            return

        if not self.get_setting('first_run'):
            return
        result = sublime.yes_no_cancel_dialog("Looks like it was first time You run Sublime Sync on this computer."
            + "\n\nRepository: "+ self.get_repository_url()
            + "\nBranch: "+ self.get_branch_name()
            + "\n\nWhat do you want to do first? ", "PULL (will overwrite current settings)",
            "PUSH (upload current settings to repository)")

        if result == sublime.DIALOG_CANCEL:
            return

        if result == sublime.DIALOG_YES:
            self.set_setting("first_run", False)
            git_pull()

        if result == sublime.DIALOG_NO:
            self.set_setting("first_run", False)
            git_push()
Пример #48
0
def load_multiple(settings, table_settings, file_dir, query):

    if settings!=False and table_settings!=False:
        fields = ['sys_id']
        if "display" in table_settings:
            fields.append(table_settings["display"])

        if "body_field" in table_settings:
            fields.append(table_settings["body_field"])

        if "fields" in table_settings:
            for field in table_settings["fields"]:
                fields.append(field['field'])                

        if 'multi' in table_settings:
            for child in os.listdir(file_dir):
                test_path = os.path.join(file_dir, child)
                if os.path.isdir(test_path):
                    fields.append(child)

        fields = ",".join(fields);

        items = get_list(settings, table_settings['table'], query, fields)
        
        action = sublime.yes_no_cancel_dialog("Action will add/change " + str(len(items)) + " files.  Continue?")
        
        if action!=sublime.DIALOG_YES:
            return


        if 'grouped' in table_settings:
            for item in items:
                name_field = table_settings['display']
                name = item[name_field]
                name = re.sub('[^-a-zA-Z0-9_.() ]+', '', name)

                grouped_dir = os.path.join(file_dir, name)

                if os.path.exists(grouped_dir):
                    grouped_dir = grouped_dir + "_" + item['sys_id']

                os.makedirs(grouped_dir)
                settings = json.loads('{}')
                settings['grouped_child'] = True
                settings['id'] = item['sys_id']
                save_settings(grouped_dir, settings)

                for child in table_settings['fields']:
                    child_name = child['name'];
                    child_field = child['field'];
                    extension = child['extension']
                    child_file = convert_file_name(child_name + "." + extension)
                    file_name = os.path.join(grouped_dir , child_file)

                    if os.path.exists(file_name):
                            if sublime.ok_cancel_dialog("File already exists.\nOverwrite?")==False:
                                return False

                    doc = item[child_field]
                    write_doc_file(file_name, doc)

        if 'multi' in table_settings:
            for item in items:
                for field in os.listdir(file_dir):
                    field_path = os.path.join(file_dir, field)

                    if os.path.isdir(field_path):
                        sub_settings = load_settings( field_path )
                        body_field = field
                        name_field = sub_settings['display']
                        extension = sub_settings['extension']
                        
                        name = convert_file_name(item[name_field] + "." + extension)
                        
                        
                        doc = item[body_field]

                        file_name = os.path.join(file_dir,field, name)

                        if os.path.exists(file_name):
                            if sublime.ok_cancel_dialog("File already exists.\nOverwrite?")==False:
                                return False

                        write_doc_file(file_name, doc)

                        add_file(field_path ,item['sys_id'],name)                        

        else:
            for item in items:
                body_field = table_settings['body_field']
                name_field = table_settings['display']
                extension  = table_settings['extension'] 
                name = convert_file_name(item[name_field] + "." + extension)

                doc = item[body_field]
                file_name = os.path.join(file_dir, name)

                if os.path.exists(file_name):
                    if sublime.ok_cancel_dialog(file_name + " already exists.\nOverwrite?")==False:
                        return False

                write_doc_file(file_name, doc)

                add_file(file_dir,item['sys_id'],name)

    return
Пример #49
0
    def run(self, edit, save_file=False, auto_format_prettier_config_path=None):
        view = self.view
        source_file_path = view.file_name()

        if source_file_path is None:
            #
            # Handle file must first be saved:
            if IS_ST3:
                # sublime text 3+: show dialog that includes a save option:
                result = sublime.yes_no_cancel_dialog(
                    '{0}\n\n'
                    'File must first be Saved.'.format(PLUGIN_NAME),
                    'Save...', "Don't Save")
                if result == sublime.DIALOG_YES:
                    view.run_command('save')
            else:
                # sublime text 2x: limited dialog support, just show error:
                return sublime.error_message(
                    '{0} Error\n\n'
                    'File must first be saved.'.format(PLUGIN_NAME))

        #
        # set paths
        if source_file_path is None:
            # Re-check if file was saved, in case user canceled or closed the save dialog:
            return st_status_message('Save canceled.')

        #
        # Max file size check
        if self.exceeds_max_file_size_limit(source_file_path):
            return st_status_message('Maximum file size reached.')

        source_file_dir = get_file_abs_dir(source_file_path)
        st_project_path = str(get_st_project_path())

        #
        # cd to the active sublime text project dir:
        os.chdir(st_project_path)

        #
        # if a `--config <path>` option is set in 'additional_cli_args',
        # no action is necessary. otherwise, try to sniff the config
        # file path:
        parsed_additional_cli_args = parse_additional_cli_args(self.additional_cli_args)
        has_custom_config_defined = parsed_additional_cli_args.count('--config') > 0
        has_no_config_defined = parsed_additional_cli_args.count('--no-config') > 0
        has_config_precedence_defined = parsed_additional_cli_args.count('--config-precedence') > 0

        prettier_config_path = None
        if not has_no_config_defined:
            if save_file and auto_format_prettier_config_path and os.path.exists(auto_format_prettier_config_path):
                prettier_config_path = auto_format_prettier_config_path
            if not prettier_config_path:
                resolved_prettier_config = self.try_find_prettier_config(view)
                if resolved_prettier_config and os.path.exists(resolved_prettier_config):
                    prettier_config_path = resolved_prettier_config
        if not prettier_config_path or not os.path.exists(prettier_config_path):
            prettier_config_path = ''
            has_custom_config_defined = False

        #
        # Get node and prettier command paths:
        node_path = self.node_path
        prettier_cli_path = resolve_prettier_cli_path(view, PLUGIN_PATH, st_project_path)
        if not prettier_cli_path:
            log_error(
                "Ensure 'prettier' is installed in your environment PATH, "
                "or manually specify an absolute path in your '{0}' file "
                "and the 'prettier_cli_path' setting.".format(SETTINGS_FILENAME))
            return st_status_message('Prettier not found. Open console for more details.')

        # try to find a '.prettierignore' file path in the project root
        # if the '--ignore-path' option isn't specified in 'additional_cli_args':
        prettier_ignore_filepath = None
        if not parsed_additional_cli_args.count('--ignore-path') > 0:
            prettier_ignore_filepath = resolve_prettier_ignore_path(source_file_dir, st_project_path)

        #
        # Parse prettier options:
        prettier_options = self.parse_prettier_options(
            view, parsed_additional_cli_args, prettier_config_path,
            has_custom_config_defined, has_no_config_defined,
            has_config_precedence_defined, prettier_ignore_filepath,
            source_file_path)

        #
        # Format entire file:
        if not has_selection(view) or save_file is True:
            region = sublime.Region(0, view.size())
            source = view.substr(region)
            if is_str_empty_or_whitespace_only(source):
                return st_status_message('Nothing to format in file.')

            transformed = self.format_code(source, node_path, prettier_cli_path, prettier_options, view)
            if self.has_error:
                self.format_console_error()
                return self.show_status_bar_error()

            # sanity check to ensure textual content was returned from cmd
            # stdout, not necessarily caught in OSError try/catch
            # exception handler
            if is_str_empty_or_whitespace_only(transformed):
                self.error_message = 'Empty content returned to stdout'
                return self.show_status_bar_error()

            source_modified = False
            transformed = trim_trailing_ws_and_lines(transformed)
            if transformed:
                if transformed == trim_trailing_ws_and_lines(source):
                    if self.ensure_newline_at_eof(view, edit) is True:
                        # no formatting changes applied, however, a line
                        # break was needed/inserted at the end of the file:
                        source_modified = True
                else:
                    view.replace(edit, region, transformed)
                    self.ensure_newline_at_eof(view, edit)
                    source_modified = True
            else:
                view.replace(edit, region, transformed)
                self.ensure_newline_at_eof(view, edit)
                source_modified = True

            if source_modified:
                st_status_message('File formatted.')
            else:
                st_status_message('File already formatted.')
            return

        #
        # Format each selection:
        for region in view.sel():
            if region.empty():
                continue

            source = view.substr(region)
            if is_str_empty_or_whitespace_only(source):
                st_status_message('Nothing to format in selection.')
                continue

            transformed = self.format_code(source, node_path, prettier_cli_path, prettier_options, view)
            if self.has_error:
                self.format_console_error()
                return self.show_status_bar_error()

            # sanity check to ensure textual content was returned from cmd
            # stdout, not necessarily caught in OSError try/catch
            # exception handler
            if is_str_empty_or_whitespace_only(transformed):
                self.error_message = 'Empty content returned to stdout'
                return self.show_status_bar_error()

            transformed = trim_trailing_ws_and_lines(transformed)
            if transformed and transformed == trim_trailing_ws_and_lines(source):
                st_status_message('Selection(s) already formatted.')
            else:
                view.replace(edit, region, transformed)
                st_status_message('Selection(s) formatted.')
Пример #50
0
 def run(self):
     if sublime.yes_no_cancel_dialog("Clear all bookmarks?") == sublime.DIALOG_YES:
         for view in sublime.active_window().views():
             view.erase_regions("bookmarks");
    def run(self):

        default_pretext_vagrant_root = r"C:\\PreTeXt"

        projdata = self.window.project_data()
        if projdata is None or "folders" not in projdata:
        # no open folder, setup defaults
            # test for existence of default folder
            if not os.access(default_pretext_vagrant_root, os.F_OK):
                create_folder_ok = sublime.ok_cancel_dialog("OK to create "
                    "default folder C:\\PreTeXt? (Cancel, create new folder, "
                    "add to project, and initialize again to override default)")
                if create_folder_ok:
                    os.mkdir(default_pretext_vagrant_root)
                else:
                    sublime.message_dialog("PreTeXt Vagrant initialization "
                    "cancelled.")
                    return
            projdata = {"folders": [{"path": r"C:\\PreTeXt"}]}
        elif len(projdata['folders']) > 1:
        # close all but top folder after user confirms
            remove_ok = sublime.ok_cancel_dialog("Multiple folders are open in "
                "the project. OK to remove all folders except {} and make {}"
                "the root PreTeXt folder?".format(projdata['folders'][0]))
            if remove_ok:
                projdata['folders'] = projdata['folders'][0:1]
                # ensure a list of length 1 is returned
            else:
                sublime.message_dialog("PreTeXt Vagrant initialization "
                    "cancelled.")
                return

        pretext_vagrant_root = projdata['folders'][0]['path']
        projdata['pretext_vagrant_root'] = pretext_vagrant_root
        self.window.set_project_data(projdata)

        pretext_vagrantfile = os.sep.join([pretext_vagrant_root,
            "Vagrantfile"])
        pretext_vagrant_root_exists = os.access(pretext_vagrant_root, os.F_OK)
        pretext_vagrantfile_exists = os.access(pretext_vagrantfile, os.F_OK)

        # print("pretext_vagrant_root: {}".format(self.pretext_vagrant_root))
        # print("pretext_vagrantfile: {}".format(self.pretext_vagrantfile))

        if not pretext_vagrant_root_exists:
            # this should never happen since either we created the default
            # or the user added an existing folder
            sublime.message_dialog("Error 14: something bad happened")
            raise VagrantException

            # try:
            #     os.mkdir(self.pretext_vagrant_root)
            # except FileExistsError as e:
            #     sublime.message_dialog("Error 6: Directory already exists; continuing")

        # now get the rest of the settings in place to manage projects

        projdata = self.window.project_data()
        projdata['pretext_vagrant_root'] = pretext_vagrant_root
        projdata['pretext_vagrantfile'] = pretext_vagrantfile
        ls = os.listdir(pretext_vagrant_root)

        def is_project(dirnm):
            dotted = dirnm[0] == '.'
            isdir = os.path.isdir(os.path.join(pretext_vagrant_root, dirnm))
            return not dotted and isdir

        def is_present(dirnm, projli):
            # projli is a list of dict with entries name and path
            # name is typically a relative path from the vagrant root
            for d in projli:
                if "name" in d and d['name'] == dirnm:
                    return True
            return False

        projlist = [(d, os.path.join(pretext_vagrant_root, d))
            for d in ls if is_project(d) and d != "mathbook"]

        # Add all or some project folders to the settings file, converting to absolute paths
        # so projlist is a list of pairs of paths

        if len(projlist) > 0:
            add_all = sublime.yes_no_cancel_dialog(
                "OK to add {} writing projects to PreTeXtual "
                "management? (Select No to add one by one.)".format(
                    len(projlist)
                )
            )
        else:
            sublime.message_dialog("No subfolders detected. See "
                "documentation for details on adding projects.")

        def add_some_projects(add_q, projli):
            """
            add_q is one of sublime.DIALOG_YES, _NO, or _CANCEL
            projli is of type [{'name': {}}]
            """
            if add_q == sublime.DIALOG_YES:
                for rel, absol in projli:
                    if 'pretext_projects' not in projdata.keys():
                        projdata['pretext_projects'] = {}
                    if not is_present(rel, projdata['pretext_projects']):
                        projdata['pretext_projects'].update({rel: {"path": absol, "name": rel, "root_file": ""}})
            elif add_q == sublime.DIALOG_CANCEL:
                sublime.message_dialog("No projects added.")
                return
            elif add_q == sublime.DIALOG_NO:
                for rel, absol in projli:
                    add = sublime.yes_no_cancel_dialog(
                        "OK to add {} to PreTeXtual management? Select No to proceed to next project.".format(rel))
                    if add == sublime.DIALOG_YES:
                        if 'pretext_projects' not in projdata.keys():
                            projdata['pretext_projects'] = {}
                        if not is_present(rel, projdata['pretext_projects']):
                            projdata['pretext_projects'].update({rel: {"path": absol, "name": rel, "root_file": ""}})
                    elif add == sublime.DIALOG_CANCEL:
                        sublime.message_dialog("Project addition cancelled.")
                        return
                    elif add == sublime.DIALOG_NO:
                        continue
                    else:
                        sublime.message_dialog("Error 18: something bad happened")
                        raise VagrantException
            else:
                sublime.message_dialog("Error 16: something bad happened")
                raise VagrantException

        if len(projlist) > 0:
            add_some_projects(add_all, projlist)

        self.window.set_project_data(projdata)
        if 'pretext_projects' in projdata.keys():
            pretext_projects = projdata['pretext_projects']
        else:
            pretext_projects = {}

        # print("About to set root files "
        #     + "with output_dict: {}".format(pretext_projects))

        # We need to ask one at a time or the input panels all
        # collide and we don't get to see the first n-1 of them.
        # Thanks to OdatNurd on the Sublime Text freenode chat
        # for this idea.
        # def set_root_file_keys(key_list, key_index, output_dict):
        #     print("srfk: {}, {}, {}".format(key_list, key_index, output_dict))
        #     key = key_list[key_index]
        #     self.window.show_input_panel("Enter full path to root "
        #         "file for project {}:".format(key),
        #         os.path.normpath(pretext_vagrant_root),
        #         lambda v: set_root_file_values(v, key_list, key_index,
        #             output_dict),
        #         None, None)

        # def set_root_file_values(key_value, key_list, key_index, output_dict):
        #     print("srfv: {}, {}, {}, {}".format(key_value, key_list, key_index, output_dict))
        #     key = key_list[key_index]
        #     output_dict[key].update({'root_file': os.path.normpath(key_value)})

        #     key_index += 1
        #     if key_index < len(key_list):
        #         set_root_file_keys(key_list, key_index, output_dict)
        #     else:
        #         print("Finished with: {}".format(output_dict))

        # # if 'pretext_projects' in projdata.keys():
        # if pretext_projects:
        #     set_root_files = sublime.ok_cancel_dialog("Set "
        #         "root files for the projects you just added?")

        #     if set_root_files:
        #         projnames = list(pretext_projects.keys())
        #         if projnames:
        #             set_root_file_keys(projnames, 0, pretext_projects)
        #         print("keys exhausted, new pretext_projects is {}".format(pretext_projects))
        #         projdata.update({'pretext_projects': pretext_projects})
        #         print("keys exhausted, new projdata is {}".format(projdata))
        #         self.window.set_project_data(projdata)
        #     else:
        #         sublime.message_dialog("No root files set. You can add these "
        #             "later in the user settings.")

        sublime.message_dialog("Make sure to check your User Settings"
            " and set root files for all the packages you have added."
            " Nothing will work unless you do this.")

        # projdata = self.window.project_data()
        usersettings = sublime.load_settings("Preferences.sublime-settings")
        if 'pretext_projects' in projdata.keys():
            print("updating user settings: setting 'pretext_projects' to {}".format(pretext_projects))
            usersettings.set('pretext_projects', pretext_projects)
            # usersettings.set('pretext_projects', projdata['pretext_projects'])
        else:
            usersettings.set('pretext_projects', {})
        sublime.save_settings("Preferences.sublime-settings")

        options = ["Install PreTeXt", "Install PreTeXt-lite",
            "Install PreTeXt-barebones", "Install PreTeXt-no-images"]

            # "A comprehensive kitchen-sink installation"
            # "Sufficient for most needs"
            # "If you only need HTML"
            # "For testing only, very limited"

        def on_done(n):
            self.acquire_vagrantfile(n, pretext_vagrant_root)

        if not pretext_vagrantfile_exists:
            sublime.message_dialog("Click OK to bring up a quick panel to select "
                "a PreTeXt installation. This step can take a long time, perhaps "
                "an hour or more. Be patient and do not worry if it seems like "
                "your system is hanging. Just watch and wait. If you don't know "
                "what you want, select PreTeXt-lite.")
            self.window.show_quick_panel(options, on_done)

        vagrantpath = get_setting('vagrantpath', r"C:\\HashiCorp\\Vagrant\\bin\\vagrant.exe")
        if vagrantpath:
            vp = get_setting('vagrant_path')
            settings = sublime.load_settings("Preferences.sublime-settings")
            settings.set('vagrant_path', vagrantpath)
            sublime.save_settings("Preferences.sublime-settings")