def run(self, view, args):
		currsel = view.sel()[0]
		currword = view.word(currsel)
		k = view.substr(currword)
		if macros.has_key(k):
			view.replace(currword, macros[k])
		else:
			sublime.errorMessage("%s is not a valid TeX symbol shortcut" % (k,))
	def run(self, window, args):
		view = window.activeView()
		texFile, texExt = os.path.splitext(view.fileName())
		if texExt.upper() != ".TEX":
			sublime.errorMessage("%s is not a TeX source file: cannot view." % (os.path.basename(view.fileName()),))
			return
		quotes = "\""
		pdfFile = quotes + texFile + u'.pdf' + quotes
		sumatra = u'SumatraPDF -reuse-instance -inverse-search \"sublimetext \\\"%f\\\":%l\" '
		print sumatra + pdfFile
		try:
			Popen(sumatra + pdfFile)
		except WindowsError:
			sublime.errorMessage("Cannot launch SumatraPDF. Make sure it is on your PATH.")
	def run(self, window, args):
		print "Show tex errors"
		pname = "texify" if args else "" # just as extra precaution
		print "Panel name: " + pname
		texFile = os.path.splitext(window.activeView().fileName())[0]
		try:
			# Read it in as binary, as there may be NULLs
			# No need to close as we do not create a file object
			log = open(texFile + ".log", 'rb').read().decode(getOEMCP()).splitlines()
		except IOError:
			sublime.errorMessage("Cannot open log file %s!" % (texFile + ".log",))
			return
		panelContent = parseTeXlog(log) + \
							["","********************", "", "Last generated log file follows", \
							"", "********************","",""] + log
		window.showQuickPanel(pname, "gotoTeXError", panelContent, panelContent, sublime.QUICK_PANEL_MONOSPACE_FONT)
	def run(self, view, args):
		texFile, texExt = os.path.splitext(view.fileName())
		if texExt.upper() != ".TEX":
			sublime.errorMessage("%s is not a TeX source file: cannot jump." % (os.path.basename(view.fileName()),))
			return
		quotes = "\""
		srcfile = texFile + u'.tex'
		pdffile = texFile + u'.pdf'
		(line, col) = view.rowcol(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
		# the last params are flags. In part. the last is 0 if no focus, 1 to focus
		command = "[ForwardSearch(\"%s\",\"%s\",%d,%d,0,0)]" % (pdffile, srcfile, line, col)
		view.runCommand("sendDDEExecute",["SUMATRA","control",command])
Exemplo n.º 5
0
    def run(self, edit):
        for region in self.view.sel():
            if region.empty():
                region = self.view.line(region)

            p = subprocess.Popen(
                "namecase",
                shell   = True,
                bufsize = -1,
                stdout  = subprocess.PIPE,
                stderr  = subprocess.PIPE,
                stdin   = subprocess.PIPE)
     
            output, error = p.communicate(self.view.substr(region).encode('utf-8'))
     
            if error:
                sublime.errorMessage(error.decode('utf-8'))
            else:
                self.view.replace(edit, region, output.decode('utf-8'))
Exemplo n.º 6
0
    def run(self, view, args):
        if view.sel()[0].empty():
            # nothing selected: process the entire file
            region = sublime.Region(0L, view.size())
        else:
            # process only selected region
            region = view.line(view.sel()[0])

        p = subprocess.Popen(args,
                             shell=True,
                             bufsize=-1,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE)

        output, error = p.communicate(view.substr(region).encode('utf-8'))

        if error:
            sublime.errorMessage(error.decode('utf-8'))
        else:
            view.replace(region, output.decode('utf-8'))
  def run(self, window, args):
    curdir = os.getcwdu()
    view = window.activeView()
    for region in view.sel():
      s = view.substr(region)
      if(s != ''):
        f = curdir + '\\' + s

        if(os.path.exists(f)):
          window.openFile(f)
        else:
          sublime.errorMessage('The file under cursor does not exists in the directory of the current file')
      else:
        # f = curdir + '\\' + str(args[1])
        word_under_cursor = view.substr(view.word(view.sel()[0].begin()))
        dot_pos = view.find('\.',view.sel()[0].begin())
        if(dot_pos):
          f = view.substr(view.word(dot_pos))

      if(os.path.exists(f)):
        window.openFile(f)
      else:
        sublime.errorMessage('The file under cursor does not exists in the directory of the current file')
	def run(self, view, args):
		# get current point
		# assume no selection, or a singe selection (for now)
		currsel = view.sel()[0]
		point = currsel.b
		prefix = view.substr(view.word(point)).strip()
		print currsel, point, prefix,len(prefix)
		completions = []
		view.findAll('\\label\{([^\{]*)\}',0,'\\1',completions)
#		print completions
#		print "%d labels" % (len(completions),)
		# no prefix, or braces
		if not prefix in ["", "{}", "{", "}"]:
			fcompletions = [comp for comp in completions if prefix in comp]
		else:
			prefix = "" # in case it's {} or { or }
			fcompletions = completions
		# The drop-down completion menu contains at most 16 items, so
		# show selection panel if we have more.
		print prefix, len(fcompletions)
		if len(fcompletions) == 0:
			sublime.errorMessage("No references starting with %s!" % (prefix,))
			return
		if len(fcompletions) <= 16:
			view.showCompletions(point, prefix, fcompletions)
		else:
			def onSelect(i):
				# if we had an actual prefix, replace it with the label,
				# otherwise insert the label.
				# FIXME like TextMate, if you give e.g. thm:so as prefix
				# you may get thm:thm:something
				if prefix not in ["", "{}", "{", "}"]:
					view.replace(currword, fcompletions[i])
				else:
					view.insert(point, fcompletions[i])
			view.window().showSelectPanel(fcompletions, onSelect, None, 0)
		print "done"
 def run(self, view, args):
     pattern = r"\\(begin|end)\{[^\}]+\}"
     b = []
     currpoint = view.sel()[0].b
     point = 0
     r = view.find(pattern, point)
     while r and r.end() <= currpoint:
         be = view.substr(r)
         point = r.end()
         if "\\begin" == be[0:6]:
             b.append(be[6:])
         else:
             if be[4:] == b[-1]:
                 b.pop()
             else:
                 sublime.errorMessage("\\begin%s closed with %s on line %d" % (b[-1], be, view.rowcol(point)[0]))
                 return
         r = view.find(pattern, point)
         # now either b = [] or b[-1] is unmatched
     if b == []:
         sublime.errorMessage("Every environment is closed")
     else:
         # note the double escaping of \end
         view.runCommand('insertCharacters "\\\\end' + b[-1] + '\\n"')
	def run(self, window, args):
		# Save file if necessary
		view = window.activeView()
		texFile, texExt = os.path.splitext(view.fileName())
		if texExt.upper() != ".TEX":
			sublime.errorMessage("%s is not a TeX source file: cannot compile." % (os.path.basename(view.fileName()),))
			return
		if view.isDirty():
			print "saving..."
			window.runCommand('save')
		# --max-print-line makes sure that no line is truncated, or we would not catch
		# line numbers in some warnings
		texify = u'texify -b -p --tex-option=\"--synctex=1\" --tex-option=\"--max-print-line=200\" '
		cmd = texify + quotes + texFile + texExt + quotes
		print "\n\nTexify executing command:"

		pContents = ["Texify executing command:", cmd]
		window.showQuickPanel("texify", "", pContents)

		# Execute command in a thread
		# First, define class 

		class CmdThread ( threading.Thread ):

			# Use __init__ to pass things we need, including window
			# so we can get window.showQuickPanel
			def __init__ (self, cmd, pContent, texFile, window):
				self.cmd = cmd
				self.pContent = pContent
				self.texFile = texFile
				self.qp = window.showQuickPanel
				threading.Thread.__init__ ( self )

			def run ( self ):
				print "Welcome to the thread!"
				#print self.cmd
				#print self.pContent
				p = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
				stdoutdata, stderrdata = p.communicate()
				# display errors and warnings from last generated log file,
				# followed by the full output of the texify command
				# (if we only use the texify output, we get multiple errors/warnings, and also
				# warnings about e.g. references that are corrected in subsequent runs)
				texifyLog = stdoutdata.decode(getOEMCP()).splitlines()
				try:
					# Read it in as binary, as there may be NULLs
					# No need to close as we do not create a file object
					log = open(texFile + ".log", 'rb').read().decode(getOEMCP()).splitlines()
				except IOError:
					# if we cannot read the log file for any reason,
					# just use the texify output
					log = texifyLog
				pContent = self.pContent + ["",] + parseTeXlog(log) + \
							["","********************", "", "Full texify output follows", \
							"Remember: texify may run latex & friends many times; missing refs. etc. may get automatically fixed in later runs",\
							"", "********************", "", ""] + texifyLog
				sublime.setTimeout(functools.partial(self.qp,"texify","gotoTeXError", pContent), 0)
				print "returned from qp in thread"

				# if stderrdata and not("see log file" in str(stderrdata)):
				# 	sublime.errorMessage("Could not invoke texify. Got the following error:\n%s" % (str(stderrdata),) )
				# 	print "texify invocation error:" + str(stderrdata)
				# 	print len(stdoutdata),len(stderrdata)
				# else:	
				# 	window.runCommand('showTeXError')
		
		CmdThread(cmd, pContents, texFile, window).start()
	def run(self, view, args):
		print "entering texCite"
		# test only for now
		# get current point
		# assume no selection, or a singe selection (for now)
		currsel = view.sel()[0]
		point = currsel.b
		prefix = view.substr(view.word(point)).strip()
		print currsel, point, prefix,len(prefix)
		completions = []
		# For now we only get completions from bibtex file
		bibcmd = view.substr(view.find(r'\\bibliography\{(.+)\}',0))
		print bibcmd
		bibp = re.compile(r'\{(.+)\}')
		bibmatch = bibp.search(bibcmd)
		if not bibmatch:
			print "Cannot parse bibliography command: " + bibcmd
			return
		bibfname = bibmatch.group(1)
		print bibfname
		if bibfname[-4:] != ".bib":
			bibfname = bibfname + ".bib"
		texfiledir = os.path.dirname(view.fileName())
		bibfname = os.path.normpath(texfiledir + os.path.sep + bibfname)
		print bibfname 
		try:
			bibf = open(bibfname)
		except IOError:
			sublime.errorMessage("Cannot open bibliography file %s !" % (bibfname,))
			return
		else:
			bib = bibf.readlines()
			bibf.close()
		kp = re.compile(r'@[^\{]+\{(.+),')
		tp = re.compile(r'\btitle\s*=\s*(.+)', re.IGNORECASE)
		kp2 = re.compile(r'([^\t]+)\t*')
		keywords = [kp.search(line).group(1) for line in bib if line[0] == '@']
		titles = [tp.search(line).group(1) for line in bib if tp.search(line)]
		if len(keywords) != len(titles):
			print "Bibliography " + bibfname + " is broken!"
		completions = ["%s\t\t%s" % kt for kt in zip(keywords, titles)]
		# need ",}" for multiple citations
		# support is limited: this only OK if there is no prefix after the
		# comma.
		multicites = False
		if not prefix in ["", "{}", ",}"]:
			fcompletions = [comp for comp in completions if prefix in comp]
		else:
			if prefix == ",}":
				multicites = True
			prefix = "" # in case it's {}
			fcompletions = completions
		# are there any completions?
		if len(fcompletions) == 0:
			sublime.errorMessage("No bibliography keys start with %s!" % (prefix,))
			return
		
		def onSelect(i):
			key = kp2.search(fcompletions[i]).group(1)
			# if no selection, and current character is not space, 
			# extend to word
			# Note: we crash if currsel.a=0, but that means that we are trying
			# to enter a reference as the very first character of the file!
			if currsel.a == currsel.b and view.substr(currsel.a-1) != ' ': 
				newsel = view.word(point)
			else:
				newsel = currsel
			view.erase(newsel)
			# Use all-powerful insertInlineSnippet! woot!
			# Note: must escape '\' twice
			if not multicites:
				snippet = "\\\\${1:cite}{" + key + "} $0"
			else:
				snippet = "," + key + "}"
			view.runCommand('insertInlineSnippet', [snippet])
			
		if len(fcompletions) == 1:
			onSelect(0)
		else:
			view.window().showSelectPanel(fcompletions, onSelect, None, 0)
		print "done"