Example #1
0
    def run(self, **args):
        pdffile = None
        if 'file' in args:
            pdffile = args.pop('file', None)
        else:
            view = self.window.active_view()

            root = getTeXRoot.get_tex_root(view)
            file_name = get_jobname(root)

            output_directory = get_output_directory(view)
            if output_directory is None:
                root = getTeXRoot.get_tex_root(view)
                pdffile = os.path.join(os.path.dirname(root),
                                       file_name + u'.pdf')
            else:
                pdffile = os.path.join(output_directory, file_name + u'.pdf')

                if not os.path.exists(pdffile):
                    pdffile = os.path.join(os.path.dirname(root),
                                           file_name + u'.pdf')

        pdffile = os.path.normpath(pdffile)
        if not os.path.exists(pdffile):
            print("Expected PDF file {0} not found".format(pdffile))
            return

        pdffile = os.path.realpath(pdffile)

        # since we potentially accept an argument, add some extra
        # safety checks
        if pdffile is None:
            print('No PDF file found.')
            return
        elif not os.path.exists(pdffile):
            print(u'PDF file "{0}" does not exist.'.format(pdffile))
            sublime.error_message(
                u'PDF file "{0}" does not exist.'.format(pdffile))
            return

        try:
            viewer = get_viewer()
        except NoViewerException:
            return

        try:
            viewer.view_file(pdffile, keep_focus=False)
        except (AttributeError, NotImplementedError):
            traceback.print_exception()
            sublime.error_message(
                'Viewer ' + viewer_name +
                ' does not appear to be a proper LaTeXTools viewer plugin.' +
                ' Please contact the plugin author.')
            return
Example #2
0
	def run(self):
		s = sublime.load_settings("LaTeXTools Preferences.sublime-settings")
		prefs_keep_focus = s.get("keep_focus", True)
		prefs_lin = s.get("linux")

		view = self.window.active_view()
		texFile, texExt = os.path.splitext(view.file_name())
		if texExt.upper() != ".TEX":
			sublime.error_message("%s is not a TeX source file: cannot view." % (os.path.basename(view.file_name()),))
			return
		quotes = ""# \"" MUST CHECK WHETHER WE NEED QUOTES ON WINDOWS!!!
		root = getTeXRoot.get_tex_root(view)

		rootFile, rootExt = os.path.splitext(root)
		pdfFile = quotes + rootFile + '.pdf' + quotes
		s = platform.system()
		script_path = None
		if s == "Darwin":
			# for inverse search, set up a "Custom" sync profile, using
			# "subl" as command and "%file:%line" as argument
			# you also have to put a symlink to subl somewhere on your path
			# Also check the box "check for file changes"
			viewercmd = ["open", "-a", "Skim"]
		elif s == "Windows":
			# with new version of SumatraPDF, can set up Inverse 
			# Search in the GUI: under Settings|Options...
			# Under "Set inverse search command-line", set:
			# sublime_text "%f":%l
			viewercmd = ["SumatraPDF", "-reuse-instance"]		
		elif s == "Linux":
Example #3
0
    def run(self):
        # Retrieve root file and dirname.
        view = self.window.active_view()

        root_file = getTeXRoot.get_tex_root(view)
        if root_file is None:
            sublime.status_message(
                'Could not find TEX root. Please ensure that either you have configured a TEX root in your project settings or have a LaTeX document open.'
            )
            print(
                'Could not find TEX root. Please ensure that either you have configured a TEX root in your project settings or have a LaTeX document open.'
            )
            return

        if not os.path.isfile(root_file):
            message = "Could not find TEX root {0}.".format(root_file)
            sublime.status_message(message)
            print(message)
            return

        # clear the cache
        try:
            cache.delete_local_cache(root_file)
        except:
            print('Error while trying to delete local cache')
            traceback.print_exc()

        path = os.path.dirname(root_file)

        # Load the files to delete from the settings
        temp_files_exts = get_setting('temp_files_exts', [
            '.blg', '.bbl', '.aux', '.log', '.brf', '.nlo', '.out', '.dvi',
            '.ps', '.lof', '.toc', '.fls', '.fdb_latexmk', '.pdfsync',
            '.synctex.gz', '.ind', '.ilg', '.idx'
        ])

        ignored_folders = get_setting('temp_files_ignored_folders',
                                      ['.git', '.svn', '.hg'])
        ignored_folders = set(ignored_folders)

        for dir_path, dir_names, file_names in os.walk(path):
            dir_names[:] = [d for d in dir_names if d not in ignored_folders]
            for file_name in file_names:
                for ext in temp_files_exts:
                    if file_name.endswith(ext):
                        file_name_to_del = os.path.join(dir_path, file_name)
                        if os.path.exists(file_name_to_del):
                            try:
                                os.remove(file_name_to_del)
                            except OSError:
                                # basically here for locked files in Windows,
                                # but who knows what we might find?
                                print(
                                    'Error while trying to delete {0}'.format(
                                        file_name_to_del))
                                traceback.print_exc()
                        # exit extension
                        break

        sublime.status_message("Deleted temp files")
Example #4
0
    def run(self, edit, **args):
        tex_root = get_tex_root(self.view)

        if not os.path.exists(tex_root):
            sublime.error_message(
                'Tried to run TeXCount on non-existent file. Please ensure '
                'all files are saved before invoking TeXCount.')
            return

        sub_level = args.get('sub_level',
                             get_setting('word_count_sub_level', 'none'))

        if sub_level not in ['none', 'part', 'chapter', 'section']:
            sub_level = 'none'

        if sub_level == 'none':
            command = ['texcount', '-total', '-merge', '-utf8']
        else:
            command = ['texcount', '-merge', '-sub=' + sub_level, '-utf8']
        cwd = os.path.dirname(tex_root)
        command.append(os.path.basename(tex_root))

        try:
            result = check_output(command, cwd=cwd)
            res_split = result.splitlines()
            self.view.window().show_quick_panel(res_split[1:4] + res_split[9:],
                                                None)
        except CalledProcessError as e:
            sublime.error_message('Error while running TeXCount: {0}'.format(
                e.output or e))
        except OSError:
            sublime.error_message(
                'Could not run texcount. Please ensure that TeXcount is '
                'installed and that your texpath setting includes the path '
                'containing the TeXcount executable.')
Example #5
0
	def run(self):
		view = self.window.active_view()
		texFile, texExt = os.path.splitext(view.file_name())
		if texExt.upper() != ".TEX":
			sublime.error_message("%s is not a TeX source file: cannot view." % (os.path.basename(view.fileName()),))
			return
		quotes = ""# \"" MUST CHECK WHETHER WE NEED QUOTES ON WINDOWS!!!
		root = getTeXRoot.get_tex_root(view)

		rootFile, rootExt = os.path.splitext(root)
		pdfFile = quotes + rootFile + '.pdf' + quotes
		s = platform.system()
		if s == "Darwin":
			# for inverse search, set up a "Custom" sync profile, using
			# "subl" as command and "%file:%line" as argument
			# you also have to put a symlink to subl somewhere on your path
			# Also check the box "check for file changes"
			viewercmd = ["open", "-a", "Skim"]
		elif s == "Windows":
			# with new version of SumatraPDF, can set up Inverse 
			# Search in the GUI: under Settings|Options...
			# Under "Set inverse search command-line", set:
			# sublime_text "%f":%l
			viewercmd = ["SumatraPDF", "-reuse-instance"]		
		else:
			sublime.error_message("Platform as yet unsupported. Sorry!")
			return	
		print viewercmd + [pdfFile]
		try:
			# this works on OSX but not Windows, and in any case it's old-fashioned
			#os.system(viewercmd + pdfFile)
			# better:
			Popen(viewercmd + [pdfFile])
		except OSError:
			sublime.error_message("Cannot launch Viewer. Make sure it is on your PATH.")
Example #6
0
    def get_completions(self, view, prefix, line):
        completions = parse_completions(view, line)

        if len(completions) == 0:
            return
        elif not type(completions[0]) is tuple:
            return completions
        else:
            tex_root = getTeXRoot.get_tex_root(view)
            if tex_root:
                root_path = os.path.dirname(tex_root)
            else:
                print("Can't find TeXroot. "
                      "Assuming current directory is {0}".format(os.curdir))
                root_path = os.curdir

            formatted_completions = []
            normal_completions = []
            for relpath, filename in completions:
                latex_formatted = os.path.normpath(
                    os.path.join(relpath, filename)).replace('\\', '/')

                formatted_completions.append([
                    latex_formatted,
                    os.path.normpath(os.path.join(root_path, relpath,
                                                  filename))
                ])

                normal_completions.append(latex_formatted)

            return formatted_completions, normal_completions
Example #7
0
	def run(self, cmd="", file_regex="", path=""):
		
		# Try to handle killing
		if hasattr(self, 'proc') and self.proc: # if we are running, try to kill running process
			self.output("\n\n### Got request to terminate compilation ###")
			self.proc.kill()
			self.proc = None
			return
		else: # either it's the first time we run, or else we have no running processes
			self.proc = None
		
		view = self.window.active_view()
		self.file_name = getTeXRoot.get_tex_root(view.file_name())
		# self.file_name = view.file_name()
		self.tex_base, self.tex_ext = os.path.splitext(self.file_name)
		# On OSX, change to file directory, or latexmk will spew stuff into root!
		tex_dir = os.path.dirname(self.file_name)
		
		# Extra paths
		self.path = path
			
		# Output panel: from exec.py
		if not hasattr(self, 'output_view'):
			self.output_view = self.window.get_output_panel("exec")

		# Dumb, but required for the moment for the output panel to be picked
        # up as the result buffer
		self.window.get_output_panel("exec")

		self.output_view.settings().set("result_file_regex", "^([^:\n\r]*):([0-9]+):?([0-9]+)?:? (.*)$")
		# self.output_view.settings().set("result_line_regex", line_regex)
		self.output_view.settings().set("result_base_dir", tex_dir)

		self.window.run_command("show_panel", {"panel": "output.exec"})

		# Get parameters from sublime-build file:
		self.make_cmd = cmd
		self.output_view.settings().set("result_file_regex", file_regex)

		if view.is_dirty():
			print "saving..."
			view.run_command('save') # call this on view, not self.window
		
		if self.tex_ext.upper() != ".TEX":
			sublime.error_message("%s is not a TeX source file: cannot compile." % (os.path.basename(view.fileName()),))
			return
		
		s = platform.system()
		if s == "Darwin":
			self.encoding = "UTF-8"
		elif s == "Windows":
			self.encoding = getOEMCP()
		else:
			sublime.error_message("Platform as yet unsupported. Sorry!")
			return	
		print self.make_cmd + [self.file_name]
		
		os.chdir(tex_dir)
		CmdThread(self).start()
		print threading.active_count()
Example #8
0
	def run(self, **args):
		pdffile = None
		if 'file' in args:
			pdffile = args.pop('file', None)
		else:
			view = self.window.active_view()
			root = getTeXRoot.get_tex_root(view)
			print("!TEX root = ", repr(root))
			pdffile = os.path.splitext(root)[0] + '.pdf'

		# since we potentially accept an argument, add some extra
		# safety checks
		if pdffile is None:
			print('No PDF file found.')
			return
		elif not os.path.exists(pdffile):
			print('PDF file "' + pdffile + '" does not exist.')
			sublime.error_message(
				'PDF file "' + pdffile + '" does not exist.'
			)
			return

		try:
			viewer = get_viewer()
		except NoViewerException:
			return

		try:
			viewer.view_file(pdffile, keep_focus=False)
		except (AttributeError, NotImplementedError):
			traceback.print_exception()
			sublime.error_message('Viewer ' + viewer_name + 
					' does not appear to be a proper LaTeXTools viewer plugin.' +
					' Please contact the plugin author.')
			return
Example #9
0
	def run(self, edit):

		# get the root filename
		self.file_name = getTeXRoot.get_tex_root(self.view)
		if not os.path.isfile(self.file_name):
			sublime.error_message(self.file_name + ": file not found.")
			return

		self.tex_base, self.tex_ext = os.path.splitext(self.file_name)

		# load the output settings
		output_settings = sublime.load_settings("LaTeXTools.sublime-settings").get("output_settings")

		# root directory path
		dir_path = os.path.dirname(self.file_name)

		for move_entry in output_settings:
			move_path = move_entry.get("path")
			move_exts = move_entry.get("exts")
			if move_path!=None and move_exts!=None:
				# destination folder
				dest_dir = os.path.normpath(os.path.join(dir_path,move_path))
				# create destionation folder if not already exists
				if not os.path.exists(dest_dir):
					os.mkdir(dest_dir)
				for ext in move_exts:
					# move files specified in the extension settings if existing
					file_to_move = self.tex_base + ext
					if os.path.exists(file_to_move):
						file_name_to_move = os.path.basename(file_to_move)
						dest_path = os.path.normpath(os.path.join(dir_path,move_path,file_name_to_move))
						print("moving file "+file_to_move+"->"+dest_path)
						shutil.move(file_to_move,dest_path)
Example #10
0
def _jumpto_ref(view, com_reg, pos):
    label_id = _get_selected_arg(view, com_reg, pos)
    if not label_id:
        return
    sublime.status_message(
        "Scanning document for label '{0}'...".format(label_id))
    tex_root = get_tex_root(view)
    ana = analysis.analyze_document(tex_root)
    if ana is None:
        return

    def is_correct_label(c):
        return c.command == "label" and c.args == label_id
    labels = ana.filter_commands(is_correct_label)
    try:
        label = labels[0]
    except:
        message = "No matching label found for '{0}'.".format(label_id)
        print(message)
        sublime.status_message(message)
        return
    label_region = label.region
    message = "Jumping to label '{0}'.".format(label_id)
    print(message)
    sublime.status_message(message)
    utils.open_and_select_region(view, label.file_name, label_region)
def get_cite_completions(view):
    root = getTeXRoot.get_tex_root(view)

    if root is None:
        # This is an unnamed, unsaved file
        # FIXME: should probably search the buffer instead of giving up
        raise NoBibFilesError()

    print(u"TEX root: " + repr(root))
    bib_files = []
    find_bib_files(os.path.dirname(root), root, bib_files)
    # remove duplicate bib files
    bib_files = list(set(bib_files))
    print("Bib files found: ")
    print(repr(bib_files))

    if not bib_files:
        # sublime.error_message("No bib files found!") # here we can!
        raise NoBibFilesError()

    bib_files = ([x.strip() for x in bib_files])

    completions = run_plugin_command('get_entries', *bib_files)

    return completions
Example #12
0
    def run(self):
        # Retrieve file and dirname.
        view = self.window.active_view()
        self.file_name = getTeXRoot.get_tex_root(view)
        if not os.path.isfile(self.file_name):
            sublime.error_message(self.file_name + ": file not found.")
            return

        self.path = os.path.dirname(self.file_name)

        # Delete the files.
        temp_exts = set([
            '.blg', '.bbl', '.aux', '.log', '.brf', '.nlo', '.out', '.dvi',
            '.ps', '.lof', '.toc', '.fls', '.fdb_latexmk', '.pdfsync',
            '.synctex.gz', '.ind', '.ilg', '.idx'
        ])

        for dir_path, dir_names, file_names in os.walk(self.path):
            for file_name in file_names:
                for ext in temp_exts:
                    if file_name.endswith(ext):
                        file_name_to_del = os.path.join(dir_path, file_name)
                        if os.path.exists(file_name_to_del):
                            os.remove(file_name_to_del)

        sublime.status_message("Deleted temp files")
Example #13
0
    def run(self):
        # Retrieve file and dirname.
        view = self.window.active_view()
        self.file_name = getTeXRoot.get_tex_root(view)
        if not os.path.isfile(self.file_name):
            sublime.error_message(self.file_name + ": file not found.")
            return

        self.tex_base, self.tex_ext = os.path.splitext(self.file_name)

        # Delete the files.
        temp_exts = [
            '.blg', '.bbl', '.aux', '.log', '.brf', '.nlo', '.out', '.dvi',
            '.ps', '.lof', '.toc', '.fls', '.fdb_latexmk', '.pdfsync',
            '.synctex.gz', '.ind', '.ilg', '.idx'
        ]

        for temp_ext in temp_exts:
            file_name_to_del = self.tex_base + temp_ext
            #print file_name_to_del
            if os.path.exists(file_name_to_del):
                #print ' deleted '
                os.remove(file_name_to_del)

        sublime.status_message("Deleted the temp files")
Example #14
0
	def run(self, **args):
		pdffile = None
		if 'file' in args:
			pdffile = args.pop('file', None)
		else:
			view = self.window.active_view()
			root = getTeXRoot.get_tex_root(view)
			print("!TEX root = ", repr(root))
			pdffile = os.path.splitext(root)[0] + '.pdf'

		# since we potentially accept an argument, add some extra
		# safety checks
		if pdffile is None:
			print('No PDF file found.')
			return
		elif not os.path.exists(pdffile):
			print('PDF file "' + pdffile + '" does not exist.')
			sublime.error_message(
				'PDF file "' + pdffile + '" does not exist.'
			)
			return

		try:
			viewer = get_viewer()
		except NoViewerException:
			return

		try:
			viewer.view_file(pdffile, keep_focus=False)
		except (AttributeError, NotImplementedError):
			traceback.print_exception()
			sublime.error_message('Viewer ' + viewer_name + 
					' does not appear to be a proper LaTeXTools viewer plugin.' +
					' Please contact the plugin author.')
			return
def _jumpto_ref(view, com_reg, pos):
    label_id = _get_selected_arg(view, com_reg, pos)
    if not label_id:
        return
    sublime.status_message(
        "Scanning document for label '{0}'...".format(label_id))
    tex_root = get_tex_root(view)
    ana = analysis.analyze_document(tex_root)
    if ana is None:
        return

    def is_correct_label(c):
        return c.command == "label" and c.args == label_id

    labels = ana.filter_commands(is_correct_label)
    try:
        label = labels[0]
    except:
        message = "No matching label found for '{0}'.".format(label_id)
        print(message)
        sublime.status_message(message)
        return
    label_region = label.region
    message = "Jumping to label '{0}'.".format(label_id)
    print(message)
    sublime.status_message(message)
    utils.open_and_select_region(view, label.file_name, label_region)
Example #16
0
	def run(self):
		# Retrieve file and dirname.
		view = self.window.active_view()
		self.file_name = getTeXRoot.get_tex_root(view)
		if not os.path.isfile(self.file_name):
			sublime.error_message(self.file_name + ": file not found.")
			return

		self.tex_base, self.tex_ext = os.path.splitext(self.file_name)
		self.out_root = getTeXRoot.get_out_root(view)
		self.out_base = os.path.join(self.out_root,os.path.basename(self.tex_base))

		if os.path.normpath(self.out_root) != os.path.normpath(os.path.dirname(self.tex_base)):
			if os.path.isdir(self.out_root): shutil.rmtree(self.out_root)

		# Delete the files with specified extensions.
		temp_exts = ['.blg','.bbl','.aux','.log','.brf','.nlo','.out','.dvi','.ps',
			     '.lof','.toc','.fls','.fdb_latexmk','.pdfsync','.synctex.gz','.ind','.ilg','.idx']

		for temp_ext in temp_exts:
			file_name_to_del = self.tex_base + temp_ext
			#print file_name_to_del
			if os.path.exists(file_name_to_del):
				#print ' deleted '
				os.remove(file_name_to_del)

		sublime.status_message("Deleted the temp files")
    def get_completions(self, view, prefix, line):
        completions = parse_completions(view, line)

        if len(completions) == 0:
            return
        elif not type(completions[0]) is tuple:
            return completions
        else:
            tex_root = getTeXRoot.get_tex_root(view)
            if tex_root:
                root_path = os.path.dirname(tex_root)
            else:
                print(
                    "Can't find TeXroot. "
                    "Assuming current directory is {0}".format(os.curdir)
                )
                root_path = os.curdir

            formatted_completions = []
            normal_completions = []
            for relpath, filename in completions:
                latex_formatted = os.path.normpath(os.path.join(
                    relpath, filename)).replace('\\', '/')

                formatted_completions.append([
                    latex_formatted,
                    os.path.normpath(os.path.join(
                        root_path, relpath, filename)
                    )
                ])

                normal_completions.append(latex_formatted)

            return formatted_completions, normal_completions
    def get_packages(self):
        packages = get_setting('cwl_list', [
            "latex-document.cwl", "tex.cwl", "latex-dev.cwl", "latex-209.cwl",
            "latex-l2tabu.cwl", "latex-mathsymbols.cwl"
        ])

        # autoload packages by scanning the document
        if get_setting('cwl_autoload', True):
            root = get_tex_root(sublime.active_window().active_view())
            if root is not None:
                doc = analysis.get_analysis(root)

                # really, there should only be one documentclass
                packages.extend([
                    'class-{0}'.format(documentclass.args)
                    for documentclass in doc.filter_commands(
                        'documentclass', analysis.ONLY_PREAMBLE
                        | analysis.ONLY_COMMANDS_WITH_ARGS)
                ])

                packages.extend([
                    package.args for package in doc.filter_commands(
                        'usepackage', analysis.ONLY_PREAMBLE
                        | analysis.ONLY_COMMANDS_WITH_ARGS)
                ])
            # TODO - Attempt to read current buffer

        return packages
def get_cite_completions(view):
    root = getTeXRoot.get_tex_root(view)

    if root is None:
        # This is an unnamed, unsaved file
        # FIXME: should probably search the buffer instead of giving up
        raise NoBibFilesError()

    print(u"TEX root: " + repr(root))
    bib_files = []
    find_bib_files(os.path.dirname(root), root, bib_files)
    # remove duplicate bib files
    bib_files = list(set(bib_files))
    print("Bib files found: ")
    print(repr(bib_files))

    if not bib_files:
        # sublime.error_message("No bib files found!") # here we can!
        raise NoBibFilesError()

    bib_files = ([x.strip() for x in bib_files])

    completions = run_plugin_command('get_entries', *bib_files)

    return completions
    def run(self):
        # Retrieve root file and dirname.
        view = self.window.active_view()

        root_file = getTeXRoot.get_tex_root(view)
        if root_file is None:
            msg = \
             'Could not find TEX root. Please ensure that either you ' + \
             'have configured a TEX root in your project settings or ' + \
             'have a LaTeX document open.'
            sublime.status_message(msg)
            print(msg)
            return

        if not os.path.isfile(root_file):
            message = "Could not find TEX root {0}.".format(root_file)
            sublime.status_message(message)
            print(message)
            return

        # clear the cache
        try:
            cache.delete_local_cache(root_file)
        except:
            print('Error while trying to delete local cache')
            traceback.print_exc()

        aux_directory, aux_directory_setting = get_aux_directory(
            root_file, return_setting=True)

        output_directory, output_directory_setting = get_output_directory(
            root_file, return_setting=True)

        if aux_directory is not None:
            # we cannot delete the output directory on Windows in case
            # Sumatra is holding a reference to it
            if (sublime.platform() != 'windows'
                    or aux_directory != output_directory):
                if aux_directory_setting.startswith('<<'):
                    self._rmtree(aux_directory)
                else:
                    self.delete_temp_files(aux_directory)

        if output_directory is not None:
            if output_directory_setting.startswith('<<'):
                # we cannot delete the output directory on Windows in case
                # Sumatra is holding a reference to it
                if sublime.platform() == 'windows':
                    self._clear_dir(output_directory)
                else:
                    self._rmtree(output_directory)
            else:
                self.delete_temp_files(output_directory)
        else:
            # if there is no output directory, we may need to clean files
            # in the main directory, even if aux_directory is used
            self.delete_temp_files(os.path.dirname(root_file))

        sublime.status_message("Deleted temp files")
Example #21
0
    def run(self):
        view = self.window.active_view()
        tex_root = get_tex_root(view)
        if not tex_root:
            return
        ana = analysis.analyze_document(tex_root)

        show_toc_quickpanel(ana)
Example #22
0
    def run(self):
        view = self.window.active_view()
        tex_root = get_tex_root(view)
        if not tex_root:
            return
        ana = analysis.analyze_document(tex_root)

        show_toc_quickpanel(ana)
Example #23
0
    def run(self, only_current_file=False):
        view = self.window.active_view()
        tex_root = get_tex_root(view)
        if not tex_root:
            return
        ana = analysis.analyze_document(tex_root)

        only_file = None if not only_current_file else view.file_name()
        show_toc_quickpanel(ana, only_file=only_file)
def parse_completions(view, line):
    # reverse line, copied from latex_cite_completions, very cool :)
    line = line[::-1]

    search = None
    # search dynamic entries
    dyn_entries, dyn_regex = _get_dyn_entries()
    if dyn_regex:
        search = dyn_regex.match(line)
        entries = dyn_entries

    # search static entries if no dynamic matches found
    if not search:
        search = TEX_INPUT_FILE_REGEX.match(line)
        entries = _fillall_entries

    # if no regex matched, cancel completions
    if not search:
        return "", []

    try:
        # extract the first group and the prefix from the maching regex
        group, prefix = next((i, v) for i, v in enumerate(search.groups())
                             if v is not None)
        entry = entries[group]
        prefix = prefix[::-1]
    except Exception as e:
        print("Error occurred while extracting entry from matching group.")
        print(e)
        return "", []

    # adjust the prefix (don't include commas)
    if "," in prefix:
        prefix = prefix[prefix.rindex(",") + 1:]
    completions = []

    if entry["type"] == "input":
        root = getTeXRoot.get_tex_root(view)
        if root:
            output_directory = get_output_directory(root)
            aux_directory = get_aux_directory(root)
            completions = get_file_list(
                root, entry["extensions"],
                entry.get("strip_extensions", []),
                output_directory, aux_directory
            )
        else:
            # file is unsaved
            completions = []
    elif entry["type"] == "cached":
        cache = _get_cache()
        if cache is not None:
            completions = cache.get(entry["cache_name"])
    else:
        print("Unknown entry type {0}.".format(entry["type"]))

    return prefix, completions
Example #25
0
    def run(self, only_current_file=False):
        view = self.window.active_view()
        tex_root = get_tex_root(view)
        if not tex_root:
            return
        ana = analysis.analyze_document(tex_root)

        only_file = None if not only_current_file else view.file_name()
        show_toc_quickpanel(ana, only_file=only_file)
Example #26
0
	def run(self, edit, **args):
		texFile, texExt = os.path.splitext(self.view.file_name())
		if texExt.upper() != ".TEX":
			sublime.error_message("%s is not a TeX source file: cannot jump." % (os.path.basename(view.fileName()),))
			return
		quotes = "\""
		srcfile = texFile + u'.tex'
		root = getTeXRoot.get_tex_root(self.view.file_name())
		print "!TEX root = ", root
		rootName, rootExt = os.path.splitext(root)
		pdffile = rootName + u'.pdf'
		(line, col) = self.view.rowcol(self.view.sel()[0].end())
		print "Jump to: ", line,col
		# column is actually ignored up to 0.94
		# HACK? It seems we get better results incrementing line
		line += 1

		# Query view settings to see if we need to keep focus or let the PDF viewer grab it
		# By default, we keep it
		keep_focus = self.view.settings().get("keep focus",True)
		print keep_focus

		# platform-specific code:
		plat = sublime_plugin.sys.platform
		if plat == 'darwin':
			options = ["-r","-g"] if keep_focus else ["-r"]
			subprocess.Popen(["/Applications/Skim.app/Contents/SharedSupport/displayline"] + 
								options + [str(line), pdffile, srcfile])
		elif plat == 'win32':
			# determine if Sumatra is running, launch it if not
			print "Windows, Calling Sumatra"
			# hide console
			startupinfo = subprocess.STARTUPINFO()
			startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
			tasks = subprocess.Popen(["tasklist"], stdout=subprocess.PIPE,
					startupinfo=startupinfo).communicate()[0]
			# Popen returns a byte stream, i.e. a single line. So test simply:
			if "SumatraPDF.exe" not in tasks:
				print "Sumatra not running, launch it"
				self.view.window().run_command("view_pdf")
				time.sleep(0.5) # wait 1/2 seconds so Sumatra comes up
			setfocus = 0 if keep_focus else 1
			# First send an open command forcing reload, or ForwardSearch won't 
			# reload if the file is on a network share
			command = u'[Open(\"%s\",0,%d,1)]' % (pdffile,setfocus)
			print command
			self.view.run_command("send_dde",
					{ "service": "SUMATRA", "topic": "control", "command": command})
			# Now send ForwardSearch command
			command = "[ForwardSearch(\"%s\",\"%s\",%d,%d,0,%d)]" \
						% (pdffile, srcfile, line, col, setfocus)
			print command
			self.view.run_command("send_dde",
					{ "service": "SUMATRA", "topic": "control", "command": command})
		else: # Linux
			# self.view.window().run_command("view_pdf")
			subprocess.Popen(["okular", "--unique", "%s#src:%d%s" % (pdffile, line, srcfile)])
Example #27
0
    def run(self,
            edit,
            auto_create_missing_folders=True,
            auto_insert_root=True,
            position=None):
        view = self.view
        window = view.window()
        tex_root = get_tex_root(view)
        if tex_root is None:
            sublime.status_message("Save your current file first")
            return

        if position is None:
            selections = list(view.sel())
        else:
            selections = [sublime.Region(position, position)]

        for sel in selections:
            line_r = view.line(sel)
            line = view.substr(line_r)

            def is_inside(g):
                """check whether the selection is inside the command"""
                if g is None:
                    return False
                b = line_r.begin()
                # the region, which should contain the selection
                reg = g.regs[0]
                return reg[0] <= sel.begin() - b and sel.end() - b <= reg[1]

            for g in filter(is_inside, INPUT_REG.finditer(line)):
                file_name = g.group("file")
                print("Jumpto tex file '{0}'".format(file_name))
                _jumpto_tex_file(view, window, tex_root, file_name,
                                 auto_create_missing_folders, auto_insert_root)

            for g in filter(is_inside, IMPORT_REG.finditer(line)):
                if not g.group("file"):
                    continue
                file_name = os.path.join(g.group("path"), g.group("file"))
                print("Jumpto tex file '{0}'".format(file_name))
                _jumpto_tex_file(view, window, tex_root, file_name,
                                 auto_create_missing_folders, auto_insert_root)

            for g in filter(is_inside, BIB_REG.finditer(line)):
                file_group = g.group("file")
                file_names = _split_bib_args(file_group)
                for file_name in file_names:
                    print("Jumpto bib file '{0}'".format(file_name))
                    _jumpto_bib_file(view, window, tex_root, file_name,
                                     auto_create_missing_folders)

            for g in filter(is_inside, IMAGE_REG.finditer(line)):
                file_name = g.group("file")
                print("Jumpto image file '{0}'".format(file_name))
                _jumpto_image_file(view, window, tex_root, file_name)
Example #28
0
    def run(self, edit, **args):
        tex_root = get_tex_root(self.view)

        if not os.path.exists(tex_root):
            sublime.error_message(
                'Tried to run TeXCount on non-existent file. Please ensure '
                'all files are saved before invoking TeXCount.')
            return

        texpath = get_texpath() or os.environ['PATH']
        env = dict(os.environ)
        env['PATH'] = texpath

        sub_level = args.get('sub_level',
                             get_setting('word_count_sub_level', 'none'))

        if sub_level not in ['none', 'part', 'chapter', 'section']:
            sub_level = 'none'

        if sub_level == 'none':
            command = ['texcount', '-total', '-merge', '-utf8']
        else:
            command = ['texcount', '-merge', '-sub=' + sub_level, '-utf8']
        cwd = os.path.dirname(tex_root)
        command.append(os.path.basename(tex_root))

        try:
            startupinfo = None
            shell = False
            if sublime.platform() == 'windows':
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                shell = True

            print('Running {0}'.format(' '.join(command)))
            p = Popen(command,
                      stdout=PIPE,
                      stderr=PIPE,
                      startupinfo=startupinfo,
                      shell=shell,
                      env=env,
                      cwd=cwd)

            result = p.communicate()[0].decode('utf-8').strip()
            if p.returncode == 0:
                res_split = result.splitlines()
                self.view.window().show_quick_panel(
                    res_split[1:4] + res_split[9:], None)
            else:
                sublime.error_message(
                    'Error while running TeXCount: {0}'.format(str(p.stderr)))
        except OSError:
            sublime.error_message(
                'Could not run texcount. Please ensure that TeXcount is '
                'installed and that your texpath setting includes the path '
                'containing the TeXcount executable.')
Example #29
0
	def run(self, edit, **args):
		texFile, texExt = os.path.splitext(self.view.file_name())
		if texExt.upper() != ".TEX":
			sublime.error_message("%s is not a TeX source file: cannot jump." % (os.path.basename(view.fileName()),))
			return
		quotes = "\""
		srcfile = texFile + u'.tex'
		root = getTeXRoot.get_tex_root(self.view.file_name())
		print "!TEX root = ", root
		rootName, rootExt = os.path.splitext(root)
		pdffile = rootName + u'.pdf'
		(line, col) = self.view.rowcol(self.view.sel()[0].end())
		print "Jump to: ", line,col
		# column is actually ignored up to 0.94
		# HACK? It seems we get better results incrementing line
		line += 1

		# Query view settings to see if we need to keep focus or let the PDF viewer grab it
		# By default, we keep it
		keep_focus = self.view.settings().get("keep focus",True)
		print keep_focus

		# platform-specific code:
		plat = sublime_plugin.sys.platform
		if plat == 'darwin':
			options = ["-r","-g"] if keep_focus else ["-r"]
			subprocess.Popen(["/Applications/Skim.app/Contents/SharedSupport/displayline"] + 
								options + [str(line), pdffile, srcfile])
		elif plat == 'win32':
			# determine if Sumatra is running, launch it if not
			print "Windows, Calling Sumatra"
			# hide console
			startupinfo = subprocess.STARTUPINFO()
			startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
			tasks = subprocess.Popen(["tasklist"], stdout=subprocess.PIPE,
					startupinfo=startupinfo).communicate()[0]
			# Popen returns a byte stream, i.e. a single line. So test simply:
			if "SumatraPDF.exe" not in tasks:
				print "Sumatra not running, launch it"
				self.view.window().run_command("view_pdf")
				time.sleep(0.5) # wait 1/2 seconds so Sumatra comes up
			setfocus = 0 if keep_focus else 1
			# First send an open command forcing reload, or ForwardSearch won't 
			# reload if the file is on a network share
			command = u'[Open(\"%s\",0,%d,1)]' % (pdffile,setfocus)
			print command
			self.view.run_command("send_dde",
					{ "service": "SUMATRA", "topic": "control", "command": command})
			# Now send ForwardSearch command
			command = "[ForwardSearch(\"%s\",\"%s\",%d,%d,0,%d)]" \
						% (pdffile, srcfile, line, col, setfocus)
			print command
			self.view.run_command("send_dde",
					{ "service": "SUMATRA", "topic": "control", "command": command})
		else: # Linux
			pass
Example #30
0
    def run(self, commands):
        window = self.window
        view = window.active_view()
        tex_root = get_tex_root(view)

        ana = analysis.analyze_document(tex_root)
        entries = ana.filter_commands(commands, flags=analysis.ALL_COMMANDS)

        captions = [_make_caption(ana, e) for e in entries]
        quickpanel.show_quickpanel(captions, entries)
Example #31
0
def get_own_env_completion(view):
    tex_root = get_tex_root(view)
    if not tex_root:
        return []

    def make_completions():
        ana = analysis.get_analysis(tex_root)
        return _make_own_env_completion(ana)

    return cache.cache(tex_root, "own_env_completion", make_completions)
Example #32
0
    def run(self):
        view = self.window.active_view()

        tex_root = getTeXRoot.get_tex_root(view)
        if tex_root:
            try:
                cache.delete_local_cache(tex_root)
            except:
                print('Error while trying to delete local cache')
                traceback.print_exc()
def get_own_env_completion(view):
    tex_root = get_tex_root(view)
    if not tex_root:
        return []

    def make_completions():
        ana = analysis.get_analysis(tex_root)
        return _make_own_env_completion(ana)

    return cache.cache(tex_root, "own_env_completion", make_completions)
	def run(self):
		view = self.window.active_view()

		tex_root = getTeXRoot.get_tex_root(view)
		if tex_root:
			try:
				cache.delete_local_cache(tex_root)
			except:
				print('Error while trying to delete local cache')
				traceback.print_exc()
    def run(self, commands):
        window = self.window
        view = window.active_view()
        tex_root = get_tex_root(view)

        ana = analysis.analyze_document(tex_root)
        entries = ana.filter_commands(commands, flags=analysis.ALL_COMMANDS)

        captions = [_make_caption(ana, e) for e in entries]
        quickpanel.show_quickpanel(captions, entries)
Example #36
0
	def run(self):
		s = sublime.load_settings("LaTeXTools.sublime-settings")
		prefs_keep_focus = s.get("keep_focus", True)
		prefs_lin = s.get("linux")

		view = self.window.active_view()
		texFile, texExt = os.path.splitext(view.file_name())
		if texExt.upper() != ".TEX":
			sublime.error_message("%s is not a TeX source file: cannot view." % (os.path.basename(view.file_name()),))
			return
		quotes = ""# \"" MUST CHECK WHETHER WE NEED QUOTES ON WINDOWS!!!
		root = getTeXRoot.get_tex_root(view)
		out_dir="bin/"
		file_lines=codecs.open(root, "r", "UTF-8", "ignore").readlines()
		if file_lines[1].startswith('%?'):
			print(file_lines[1])
			outs=re.match(r"%\?([a-z0-9]+)\s*$", file_lines[1])
			print("outs"+outs.group(1))
			if outs:
				self.out_setting=outs.group(1)
				out_dir=s.get("output").get(self.out_setting, "bin")+"/"
				print("\nout_set: "+out_dir+"\n")

		rootFile, rootExt = os.path.splitext(root)
		pdfFile = quotes + os.path.dirname(root) + "/" + out_dir + os.path.basename(rootFile) + '.pdf' + quotes
		s = platform.system()
		script_path = None
		if s == "Darwin":
			# for inverse search, set up a "Custom" sync profile, using
			# "subl" as command and "%file:%line" as argument
			# you also have to put a symlink to subl somewhere on your path
			# Also check the box "check for file changes"
			viewercmd = ["open", "-a", "Skim"]
		elif s == "Windows":
			# with new version of SumatraPDF, can set up Inverse 
			# Search in the GUI: under Settings|Options...
			# Under "Set inverse search command-line", set:
			# sublime_text "%f":%l
			viewercmd = ["SumatraPDF", "-reuse-instance"]		
		elif s == "Linux":
			# the required scripts are in the 'evince' subdir
			script_path = os.path.join(sublime.packages_path(), 'Bacon tools', 'evince')
			ev_sync_exec = os.path.join(script_path, 'evince_sync') # so we get inverse search
			# Get python binary if set in preferences:
			py_binary = prefs_lin["python2"] or 'python'
			sb_binary = prefs_lin["sublime"] or 'sublime-text'
			viewercmd = ['sh', ev_sync_exec, py_binary, sb_binary]
		else:
			sublime.error_message("Platform as yet unsupported. Sorry!")
			return	
		print (viewercmd + [pdfFile])
		try:
			Popen(viewercmd + [pdfFile], cwd=script_path)
		except OSError:
			sublime.error_message("Cannot launch Viewer. Make sure it is on your PATH.")
Example #37
0
def parse_completions(view, line):
    # reverse line, copied from latex_cite_completions, very cool :)
    line = line[::-1]

    search = None
    # search dynamic entries
    dyn_entries, dyn_regex = _get_dyn_entries()
    if dyn_regex:
        search = dyn_regex.match(line)
        entries = dyn_entries

    # search static entries if no dynamic matches found
    if not search:
        search = TEX_INPUT_FILE_REGEX.match(line)
        entries = _fillall_entries

    # if no regex matched, cancel completions
    if not search:
        return "", []

    try:
        # extract the first group and the prefix from the maching regex
        group, prefix = next(
            (i, v) for i, v in enumerate(search.groups()) if v is not None)
        entry = entries[group]
        prefix = prefix[::-1]
    except Exception as e:
        print("Error occurred while extracting entry from matching group.")
        print(e)
        return "", []

    # adjust the prefix (don't include commas)
    if "," in prefix:
        prefix = prefix[prefix.rindex(",") + 1:]
    completions = []

    if entry["type"] == "input":
        root = getTeXRoot.get_tex_root(view)
        if root:
            output_directory = get_output_directory(root)
            aux_directory = get_aux_directory(root)
            completions = get_file_list(root, entry["extensions"],
                                        entry.get("strip_extensions", []),
                                        output_directory, aux_directory)
        else:
            # file is unsaved
            completions = []
    elif entry["type"] == "cached":
        cache = _get_cache()
        if cache is not None:
            completions = cache.get(entry["cache_name"])
    else:
        print("Unknown entry type {0}.".format(entry["type"]))

    return prefix, completions
def get_own_env_completion(view):
    tex_root = get_tex_root(view)
    if not tex_root:
        return []

    def make_completions():
        ana = analysis.get_analysis(tex_root)
        return _make_own_env_completion(ana)

    return list(cache.LocalCache(tex_root).cache(
        "own_env_completion", make_completions) or [])
Example #39
0
	def run(self, **args):
		pdffile = None
		if 'file' in args:
			pdffile = args.pop('file', None)
		else:
			view = self.window.active_view()

			root = getTeXRoot.get_tex_root(view)
			file_name = get_jobname(root)

			output_directory = get_output_directory(view)
			if output_directory is None:
				pdffile = os.path.join(
					os.path.dirname(root),
					file_name + u'.pdf'
				)
			else:
				pdffile = os.path.join(
					output_directory,
					file_name + u'.pdf'
				)

				if not os.path.exists(pdffile):
					pdffile = os.path.join(
						os.path.dirname(root),
						file_name + u'.pdf'
					)

		# since we potentially accept an argument, add some extra
		# safety checks
		if pdffile is None:
			print('No PDF file found.')
			return
		elif not os.path.exists(pdffile):
			print(u'PDF file "{0}" does not exist.'.format(pdffile))
			sublime.error_message(
				u'PDF file "{0}" does not exist.'.format(pdffile)
			)
			return

		try:
			viewer = get_viewer()
		except NoViewerException:
			return

		try:
			viewer.view_file(pdffile, keep_focus=False)
		except (AttributeError, NotImplementedError):
			traceback.print_exception()
			sublime.error_message('Viewer ' + viewer_name + 
					' does not appear to be a proper LaTeXTools viewer plugin.' +
					' Please contact the plugin author.')
			return
def get_own_env_completion(view):
    tex_root = get_tex_root(view)
    if not tex_root:
        return []

    def make_completions():
        ana = analysis.get_analysis(tex_root)
        return _make_own_env_completion(ana)

    return list(
        cache.LocalCache(tex_root).cache("own_env_completion",
                                         make_completions) or [])
Example #41
0
	def run(self):
		# Retrieve root file and dirname.
		view = self.window.active_view()

		root_file = getTeXRoot.get_tex_root(view)
		if root_file is None:
			sublime.status_message('Could not find TEX root. Please ensure that either you have configured a TEX root in your project settings or have a LaTeX document open.')
			print('Could not find TEX root. Please ensure that either you have configured a TEX root in your project settings or have a LaTeX document open.')
			return

		if not os.path.isfile(root_file):
			message = "Could not find TEX root {0}.".format(root_file)
			sublime.status_message(message)
			print(message)
			return

		# clear the cache
		try:
			cache.delete_local_cache(root_file)
		except:
			print('Error while trying to delete local cache')
			traceback.print_exc()

		path = os.path.dirname(root_file)

		# Load the files to delete from the settings
		temp_files_exts = get_setting('temp_files_exts',
			['.blg', '.bbl', '.aux', '.log', '.brf', '.nlo', '.out', '.dvi',
			 '.ps', '.lof', '.toc', '.fls', '.fdb_latexmk', '.pdfsync',
			 '.synctex.gz', '.ind', '.ilg', '.idx'])

		ignored_folders = get_setting('temp_files_ignored_folders',
			['.git', '.svn', '.hg'])
		ignored_folders = set(ignored_folders)

		for dir_path, dir_names, file_names in os.walk(path):
			dir_names[:] = [d for d in dir_names if d not in ignored_folders]
			for file_name in file_names:
				for ext in temp_files_exts:
					if file_name.endswith(ext):
						file_name_to_del = os.path.join(dir_path, file_name)
						if os.path.exists(file_name_to_del):
							try:
								os.remove(file_name_to_del)
							except OSError:
								# basically here for locked files in Windows,
								# but who knows what we might find?
								print('Error while trying to delete {0}'.format(file_name_to_del))
								traceback.print_exc()
						# exit extension
						break

		sublime.status_message("Deleted temp files")
Example #42
0
    def run(self, edit, auto_create_missing_folders=True,
            auto_insert_root=True, position=None):
        view = self.view
        window = view.window()
        tex_root = get_tex_root(view)
        if tex_root is None:
            sublime.status_message("Save your current file first")
            return

        if position is None:
            selections = list(view.sel())
        else:
            selections = [sublime.Region(position, position)]

        for sel in selections:
            line_r = view.line(sel)
            line = view.substr(line_r)

            def is_inside(g):
                """check whether the selection is inside the command"""
                if g is None:
                    return False
                b = line_r.begin()
                # the region, which should contain the selection
                reg = g.regs[0]
                return reg[0] <= sel.begin() - b and sel.end() - b <= reg[1]

            for g in filter(is_inside, INPUT_REG.finditer(line)):
                file_name = g.group("file")
                print("Jumpto tex file '{0}'".format(file_name))
                _jumpto_tex_file(view, window, tex_root, file_name,
                                 auto_create_missing_folders, auto_insert_root)

            for g in filter(is_inside, IMPORT_REG.finditer(line)):
                if not g.group("file"):
                    continue
                file_name = os.path.join(g.group("path"), g.group("file"))
                print("Jumpto tex file '{0}'".format(file_name))
                _jumpto_tex_file(view, window, tex_root, file_name,
                                 auto_create_missing_folders, auto_insert_root)

            for g in filter(is_inside, BIB_REG.finditer(line)):
                file_group = g.group("file")
                file_names = _split_bib_args(file_group)
                for file_name in file_names:
                    print("Jumpto bib file '{0}'".format(file_name))
                    _jumpto_bib_file(view, window, tex_root, file_name,
                                     auto_create_missing_folders)

            for g in filter(is_inside, IMAGE_REG.finditer(line)):
                file_name = g.group("file")
                print("Jumpto image file '{0}'".format(file_name))
                _jumpto_image_file(view, window, tex_root, file_name)
    def run(self):
        s = sublime.load_settings("LaTeXTools Preferences.sublime-settings")
        prefs_keep_focus = s.get("keep_focus", True)
        prefs_lin = s.get("linux")

        view = self.window.active_view()
        texFile, texExt = os.path.splitext(view.file_name())
        if texExt.upper() != ".TEX":
            sublime.error_message("%s is not a TeX source file: cannot view." % (os.path.basename(view.fileName()),))
            return
        quotes = ""  # \"" MUST CHECK WHETHER WE NEED QUOTES ON WINDOWS!!!
        root = getTeXRoot.get_tex_root(view)

        rootFile, rootExt = os.path.splitext(root)

        ## BEGIN modification by lawlist.
        # 		pdfFile = quotes + rootFile + '.pdf' + quotes
        path, filename = os.path.split(root)
        prefix, suffix = os.path.splitext(filename)
        pdfFile = quotes + "/tmp/" + prefix + ".pdf" + quotes
        ## END modification by lawlist.

        s = platform.system()
        script_path = None
        if s == "Darwin":
            # for inverse search, set up a "Custom" sync profile, using
            # "subl" as command and "%file:%line" as argument
            # you also have to put a symlink to subl somewhere on your path
            # Also check the box "check for file changes"
            viewercmd = ["open", "-a", "Skim"]
        elif s == "Windows":
            # with new version of SumatraPDF, can set up Inverse
            # Search in the GUI: under Settings|Options...
            # Under "Set inverse search command-line", set:
            # sublime_text "%f":%l
            viewercmd = ["SumatraPDF", "-reuse-instance"]
        elif s == "Linux":
            # the required scripts are in the 'evince' subdir
            script_path = os.path.join(sublime.packages_path(), "LaTeXTools", "evince")
            ev_sync_exec = os.path.join(script_path, "evince_sync")  # so we get inverse search
            # Get python binary if set in preferences:
            py_binary = prefs_lin["python2"] or "python"
            sb_binary = prefs_lin["sublime"] or "sublime-text"
            viewercmd = ["sh", ev_sync_exec, py_binary, sb_binary]
        else:
            sublime.error_message("Platform as yet unsupported. Sorry!")
            return
        print viewercmd + [pdfFile]
        try:
            Popen(viewercmd + [pdfFile], cwd=script_path)
        except OSError:
            sublime.error_message("Cannot launch Viewer. Make sure it is on your PATH.")
Example #44
0
	def run(self):
		s = sublime.load_settings("LaTeXTools Preferences.sublime-settings")
		prefs_keep_focus = s.get("keep_focus", True)
		prefs_lin = s.get("linux")

		view = self.window.active_view()
		texFile, texExt = os.path.splitext(view.file_name())
		if texExt.upper() != ".TEX":
			sublime.error_message("%s is not a TeX source file: cannot view." % (os.path.basename(view.file_name()),))
			return
		quotes = ""# \"" MUST CHECK WHETHER WE NEED QUOTES ON WINDOWS!!!
		root = getTeXRoot.get_tex_root(view)

		rootFile, rootExt = os.path.splitext(root)
		pdfFile = quotes + rootFile + '.pdf' + quotes
		s = platform.system()
		script_path = None
		if s == "Darwin":
			# for inverse search, set up a "Custom" sync profile, using
			# "subl" as command and "%file:%line" as argument
			# you also have to put a symlink to subl somewhere on your path
			# Also check the box "check for file changes"
			viewercmd = ["open", "-a", "Skim"]
		elif s == "Windows":
			# with new version of SumatraPDF, can set up Inverse 
			# Search in the GUI: under Settings|Options...
			# Under "Set inverse search command-line", set:
			# sublime_text "%f":%l
			viewercmd = ["SumatraPDF", "-reuse-instance"]
		elif s == "Linux":
			if subprocess.call(['which', 'okular']) == 0:
				# for inverse search: Settings|Configure Okular|Editor ...
				# Under "Command" set: sublime_text" "%f":%l
				viewercmd = ["okular", "--unique"]
			else:
				# the required scripts are in the 'evince' subdir
				script_path = os.path.join(sublime.packages_path(), 'LaTeXTools', 'evince')
				ev_sync_exec = os.path.join(script_path, 'evince_sync') # so we get inverse search
				# Get python binary if set in preferences:
				py_binary = prefs_lin["python2"] or 'python'
				sb_binary = prefs_lin["sublime"] or 'sublime-text'
				viewercmd = ['sh', ev_sync_exec, py_binary, sb_binary]
		else:
			sublime.error_message("Platform as yet unsupported. Sorry!")
			return	
		print('Executing: {0}'.format(' '.join(viewercmd + [pdfFile])))
		try:
			Popen(viewercmd + [pdfFile], cwd=script_path)
		except OSError:
			sublime.error_message("Cannot launch Viewer. Make sure it is on your PATH.")
	def run(self):
		view = self.window.active_view()

		if view is None or not bool(view.score_selector(0, "text.tex.latex")):
			return

		tex_root = getTeXRoot.get_tex_root(view)
		if tex_root:
			# clear the cache
			try:
				cache.LocalCache(tex_root).invalidate()
			except:
				print('Error while trying to delete local cache')
				traceback.print_exc()
    def run(self):
        view = self.window.active_view()

        if view is None or not bool(view.score_selector(0, "text.tex.latex")):
            return

        tex_root = getTeXRoot.get_tex_root(view)
        if tex_root:
            # clear the cache
            try:
                cache.LocalCache(tex_root).invalidate()
            except:
                print('Error while trying to delete local cache')
                traceback.print_exc()
Example #47
0
    def run(self, commands, only_current_file=False):
        window = self.window
        view = window.active_view()
        tex_root = get_tex_root(view)

        ana = analysis.analyze_document(tex_root)
        entries = ana.filter_commands(commands, flags=analysis.ALL_COMMANDS)

        if only_current_file:
            file_name = view.file_name()
            entries = [e for e in entries if e.file_name == file_name]

        captions = [_make_caption(ana, e) for e in entries]
        quickpanel.show_quickpanel(captions, entries)
Example #48
0
    def run(self, commands, only_current_file=False):
        window = self.window
        view = window.active_view()
        tex_root = get_tex_root(view)

        ana = analysis.analyze_document(tex_root)
        entries = ana.filter_commands(commands, flags=analysis.ALL_COMMANDS)

        if only_current_file:
            file_name = view.file_name()
            entries = [e for e in entries if e.file_name == file_name]

        captions = [_make_caption(ana, e) for e in entries]
        quickpanel.show_quickpanel(captions, entries)
Example #49
0
    def run(self):
        s = sublime.load_settings("LaTeXTools Preferences.sublime-settings")
        prefs_keep_focus = s.get("keep_focus", True)
        prefs_lin = s.get("linux")

        view = self.window.active_view()
        texFile, texExt = os.path.splitext(view.file_name())
        if texExt.upper() != ".TEX":
            sublime.error_message("%s is not a TeX source file: cannot view." %
                                  (os.path.basename(view.fileName()), ))
            return
        quotes = ""  # \"" MUST CHECK WHETHER WE NEED QUOTES ON WINDOWS!!!
        root = getTeXRoot.get_tex_root(view)

        rootFile, rootExt = os.path.splitext(root)
        pdfFile = quotes + rootFile + '.pdf' + quotes
        s = platform.system()
        script_path = None
        if s == "Darwin":
            # for inverse search, set up a "Custom" sync profile, using
            # "subl" as command and "%file:%line" as argument
            # you also have to put a symlink to subl somewhere on your path
            # Also check the box "check for file changes"
            viewercmd = ["open", "-a", "Skim"]
        elif s == "Windows":
            # with new version of SumatraPDF, can set up Inverse
            # Search in the GUI: under Settings|Options...
            # Under "Set inverse search command-line", set:
            # sublime_text "%f":%l
            viewercmd = ["SumatraPDF", "-reuse-instance"]
        elif s == "Linux":
            # the required scripts are in the 'evince' subdir
            script_path = os.path.join(sublime.packages_path(), 'LaTeXTools',
                                       'evince')
            ev_sync_exec = os.path.join(
                script_path, 'evince_sync')  # so we get inverse search
            # Get python binary if set in preferences:
            py_binary = prefs_lin["python2"] or 'python'
            sb_binary = prefs_lin["sublime"] or 'sublime-text'
            viewercmd = ['sh', ev_sync_exec, py_binary, sb_binary]
        else:
            sublime.error_message("Platform as yet unsupported. Sorry!")
            return
        print viewercmd + [pdfFile]
        try:
            Popen(viewercmd + [pdfFile], cwd=script_path)
        except OSError:
            sublime.error_message(
                "Cannot launch Viewer. Make sure it is on your PATH.")
Example #50
0
    def run(self, edit, **args):
        tex_root = get_tex_root(self.view)

        if not os.path.exists(tex_root):
            sublime.error_message(
                "Tried to run TeXCount on non-existent file. Please ensure "
                "all files are saved before invoking TeXCount."
            )
            return

        texpath = get_texpath() or os.environ["PATH"]
        env = dict(os.environ)
        env["PATH"] = texpath

        sub_level = args.get("sub_level", get_setting("word_count_sub_level", "none"))

        if sub_level not in ["none", "part", "chapter", "section"]:
            sub_level = "none"

        if sub_level == "none":
            command = ["texcount", "-total", "-merge", "-utf8"]
        else:
            command = ["texcount", "-merge", "-sub=" + sub_level, "-utf8"]
        cwd = os.path.dirname(tex_root)
        command.append(os.path.basename(tex_root))

        try:
            startupinfo = None
            shell = False
            if sublime.platform() == "windows":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                shell = True

            print("Running {0}".format(" ".join(command)))
            p = Popen(command, stdout=PIPE, stderr=PIPE, startupinfo=startupinfo, shell=shell, env=env, cwd=cwd)

            result = p.communicate()[0].decode("utf-8").strip()
            if p.returncode == 0:
                res_split = result.splitlines()
                self.view.window().show_quick_panel(res_split[1:4] + res_split[9:], None)
            else:
                sublime.error_message("Error while running TeXCount: {0}".format(str(p.stderr)))
        except OSError:
            sublime.error_message(
                "Could not run texcount. Please ensure that TeXcount is "
                "installed and that your texpath setting includes the path "
                "containing the TeXcount executable."
            )
Example #51
0
def get_ref_completions(view):
    completions = []
    # Check the file buffer first:
    #    1) in case there are unsaved changes
    #    2) if this file is unnamed and unsaved, get_tex_root will fail
    view.find_all(r'\\label\{([^\{\}]+)\}', 0, '\\1', completions)

    root = getTeXRoot.get_tex_root(view)
    if root:
        print("TEX root: " + repr(root))
        find_labels_in_files(os.path.dirname(root), root, completions)

    # remove duplicates
    completions = list(set(completions))

    return completions
def get_ref_completions(view):
    completions = []
    # Check the file buffer first:
    #    1) in case there are unsaved changes
    #    2) if this file is unnamed and unsaved, get_tex_root will fail
    view.find_all(r'\\label\{([^\{\}]+)\}', 0, '\\1', completions)

    root = getTeXRoot.get_tex_root(view)
    if root:
        print(u"TEX root: " + repr(root))
        find_labels_in_files(root, completions)

    # remove duplicates
    completions = list(set(completions))

    return completions
Example #53
0
	def run(self):
		# Retrieve file and dirname.
		view = self.window.active_view()
		self.file_name = getTeXRoot.get_tex_root(view)
		if not os.path.isfile(self.file_name):
			sublime.error_message(self.file_name + ": file not found.")
			return

		self.path = os.path.dirname(self.file_name)

		# Delete the files.
		temp_exts = set([
			'.acn',
			'.acr',
			'.alg',
			'.aux',
			'.bbl',
			'.bcf',
			'.blg',
			'.brf',
			'.dvi',
			'.fdb_latexmk',
			'.fls',
			'.idx',
			'.ilg',
			'.ind',
			'.lof',
			'.log',
			'.nlo',
			'.out',
			'.pdfsync',
			'.ps',
			'.run.xml',
			'.synctex.gz',
			'.toc',
			'.xdy'
		])

		for dir_path, dir_names, file_names in os.walk(self.path):
			for file_name in file_names:
				file_base, file_ext = os.path.splitext(file_name)
				if file_ext in temp_exts:
					file_name_to_del = os.path.join(dir_path, file_name)
					if os.path.exists(file_name_to_del):
						os.remove(file_name_to_del)

		sublime.status_message("Deleted temp files")
    def run(self, edit):

        view = self.view
        point = view.sel()[0].b
        # Only trigger within LaTeX
        # Note using score_selector rather than match_selector
        if not view.score_selector(point,
                "text.tex.latex"):
            return

        prefix, completions = parse_completions(view, point)

        if len(completions) != 0 and not type(completions[0]) is tuple:
            result = completions
        else:
            root_path = os.path.dirname(getTeXRoot.get_tex_root(self.view))
            
            # Process path separators on Windows platform
            plat = sublime.platform()
            if plat == 'windows':
                result = []
                for relpath, filename in completions:
                    converted_path = os.path.normpath('%s/%s'%(relpath, filename))
                    converted_path = converted_path.replace('\\', '/')
                    result.append([converted_path, os.path.normpath('%s/%s/%s'%(root_path, relpath, filename))])
            else:
                result = [[os.path.normpath('%s/%s'%(relpath, filename)), 
                    os.path.normpath('%s/%s/%s'%(root_path, relpath, filename))] for relpath, filename in completions]



        def on_done(i):
            # Doing Nothing
            if i < 0:
                return
            if type(result[i]) is list: # if result[i] is a list, it comes from input, include and includegraphics
                key = result[i][0]
            else:
                key = result[i]
            startpos = point - len(prefix)
            view.run_command("latex_tools_replace", {"a": startpos, "b": point, "replacement": key})
            caret = view.sel()[0].b
            view.sel().subtract(view.sel()[0])
            view.sel().add(sublime.Region(caret, caret))

        view.window().show_quick_panel(result, on_done)
Example #55
0
    def run(self, edit, auto_create_missing_folders=True,
            auto_insert_root=True):
        view = self.view
        window = view.window()
        tex_root = get_tex_root(view)
        if tex_root is None:
            sublime.status_message("Save your current file first")
            return

        for sel in view.sel():
            line_r = view.line(sel)
            line = view.substr(line_r)

            def is_inside(g):
                """check whether the selection is inside the command"""
                if g is None:
                    return False
                b = line_r.begin()
                # the region, which should contain the selection
                reg = g.regs[0]
                return reg[0] <= sel.begin() - b and sel.end() - b <= reg[1]

            for g in filter(is_inside, _INPUT_REG.finditer(line)):
                file_name = g.group("file")
                print("Jumpto tex file '{0}'".format(file_name))
                _jumpto_tex_file(view, window, tex_root, file_name,
                                 auto_create_missing_folders, auto_insert_root)

            for g in filter(is_inside, _BIB_REG.finditer(line)):
                file_group = g.group("file")
                if "," in file_group:
                    file_names = file_group.split(",")
                    file_names = [f.strip() for f in file_names]
                    print("Bib files: {0}".format(file_names))
                else:
                    file_names = [file_group]
                for file_name in file_names:
                    print("Jumpto bib file '{0}'".format(file_name))
                    _jumpto_bib_file(view, window, tex_root, file_name,
                                     auto_create_missing_folders)

            for g in filter(is_inside, _IMAGE_REG.finditer(line)):
                file_name = g.group("file")
                print("Jumpto image file '{0}'".format(file_name))
                _jumpto_image_file(view, window, tex_root, file_name)
Example #56
0
def get_own_command_completion(view):
    tex_root = get_tex_root(view)
    if not tex_root:
        return []

    # use special handling (additional completions) for math mode
    math_selector = ("string.other.math.tex, "
                     "string.other.math.latex, "
                     "string.other.math.block.environment.latex")
    is_math = bool(view.score_selector(view.sel()[0].b, math_selector))

    def make_completions():
        ana = analysis.get_analysis(tex_root)
        return _make_own_command_completion(ana, is_math)

    cache_name = "own_command_completion"
    if is_math:
        cache_name += "_math"
    return cache.cache(tex_root, cache_name, make_completions)
    def run(self):
        view = self.window.active_view()

        if view is None:
            return

        is_tex_file = bool(view.score_selector(0, "text.tex.latex"))
        if not (is_tex_file or is_bib_buffer(view)):
            return

        # find the instance of LatextoolsCacheUpdateListener, if any
        cache_listener = None
        for callback in sublime_plugin.all_callbacks['on_close']:
            try:
                instance = get_self(callback)
            except:
                continue

            if instance.__class__.__name__ == 'LatextoolsCacheUpdateListener':
                cache_listener = instance
                break

        if cache_listener is None:
            return

        # if run from a TeX file, clear all bib caches associated with this
        # document
        if is_tex_file:
            tex_root = getTeXRoot.get_tex_root(view)
            for bib_cache in cache_listener._BIB_CACHES.get(tex_root, []):
                bib_cache.invalidate()
        # if run from a bib file, clear all bib caches that reflect this
        # document
        else:
            file_name = view.file_name()
            if not file_name:
                return

            for bib_caches in cache_listener._BIB_CACHES.values():
                for bib_cache in bib_caches:
                    if bib_cache.bib_file == file_name:
                        bib_cache.invalidate()
Example #58
0
def get_cite_completions(view):
    root = getTeXRoot.get_tex_root(view)

    if root is None:
        # This is an unnamed, unsaved file
        # FIXME: should probably search the buffer instead of giving up
        raise NoBibFilesError()

    print(u"TEX root: " + repr(root))
    bib_files = find_bib_files(root)
    print("Bib files found: ")
    print(repr(bib_files))

    if not bib_files:
        # sublime.error_message("No bib files found!") # here we can!
        raise NoBibFilesError()

    completions = run_plugin_command('get_entries', *bib_files)

    return completions
def _jumpto_cite(view, com_reg, pos):
    tex_root = get_tex_root(view)
    bib_key = _get_selected_arg(view, com_reg, pos)
    if tex_root is None or not bib_key:
        return
    message = "Scanning bibliography files for key '{0}'...".format(bib_key)
    print(message)
    sublime.status_message(message)
    base_dir = os.path.dirname(tex_root)
    ana = analysis.get_analysis(tex_root)

    bib_commands = ana.filter_commands(
        ["bibliography", "nobibliography", "addbibresource"])
    for bib_command in bib_commands:
        for bib_file in jumpto_tex_file._split_bib_args(bib_command.args):
            if not os.path.splitext(bib_file)[1]:
                bib_file += ".bib"
            bib_file = os.path.join(base_dir, bib_file)
            try:
                file_content = utils.read_file_unix_endings(bib_file)
                start = file_content.find(bib_key)
                end = start + len(bib_key)
                # check that we found the entry and we are not inside a word
                if (start == -1 or file_content[start - 1:start].isalnum()
                        or file_content[end:end + 1].isalnum()):
                    continue
                region = sublime.Region(start, end)
                message = "Jumping to bibliography key '{0}'.".format(bib_key)
                print(message)
                sublime.status_message(message)
                utils.open_and_select_region(view, bib_file, region)
                return
            except Exception as e:
                print("Error occurred opening file {0}".format(bib_file))
                print(e)
                continue
    message = "Entry '{0}' not found in bibliography.".format(bib_key)
    print(message)
    sublime.status_message(message)