PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/sztools/python/jde.py

https://code.google.com/p/vim-sztool/
Python | 1794 lines | 1791 code | 3 blank | 0 comment | 3 complexity | ab10c048be5ec4f7c335482d83afd900 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. import socket
  2. import vim
  3. import os.path
  4. import time
  5. import re
  6. import traceback
  7. import StringIO
  8. import shutil
  9. from subprocess import Popen
  10. from string import Template
  11. import difflib
  12. from common import output,SzToolsConfig,MiscUtil,VimUtil,BasicTalker,ZipUtil
  13. from pyparsing import *
  14. from xml.etree.ElementTree import *
  15. HOST = 'localhost'
  16. PORT = 9527
  17. END_TOKEN = "==end=="
  18. MAX_CPT_COUNT = 200
  19. bp_data = {}
  20. lastProjectRoot = None
  21. class ProjectManager(object):
  22. @staticmethod
  23. def getProjectRoot(filePath, useLastRoot = True):
  24. global lastProjectRoot
  25. projectRoot = None
  26. parent = filePath
  27. if not filePath :
  28. return None
  29. while True :
  30. tmpdir = os.path.dirname(parent)
  31. if tmpdir == "" or tmpdir == "/" or tmpdir == parent :
  32. break
  33. parent = tmpdir
  34. fullname = lambda name : os.path.join(parent,name)
  35. prj_names =[fullname(name) for name in [".project",".classpath"]]
  36. if os.path.exists(prj_names[0]) and os.path.exists(prj_names[1]):
  37. projectRoot = parent
  38. break
  39. if projectRoot != None :
  40. lastProjectRoot = projectRoot
  41. elif useLastRoot :
  42. projectRoot = lastProjectRoot
  43. return projectRoot
  44. @staticmethod
  45. def getSrcLocations(filePath):
  46. tree = ElementTree()
  47. classpathXml = ProjectManager.getClassPathXml(filePath)
  48. if os.path.isdir(classpathXml) :
  49. return [ classpathXml ]
  50. project_root = ProjectManager.getProjectRoot(filePath)
  51. tree.parse(classpathXml)
  52. entries = tree.findall("classpathentry")
  53. src_locs = []
  54. for entry in entries :
  55. if entry.get("kind") == "src" :
  56. abpath = os.path.normpath(os.path.join(project_root,entry.get("path")))
  57. src_locs.append(abpath)
  58. return src_locs
  59. @staticmethod
  60. def getClassPathXml(filePath):
  61. projectRoot = ProjectManager.getProjectRoot(filePath)
  62. if not projectRoot :
  63. parent = os.path.dirname(filePath)
  64. return parent
  65. return os.path.join(projectRoot,".classpath")
  66. @staticmethod
  67. def getAntBuildXml(filePath):
  68. projectRoot = ProjectManager.getProjectRoot(filePath)
  69. if not projectRoot : return None
  70. antBuildXml = os.path.join(projectRoot,"build.xml")
  71. if os.path.exists(antBuildXml):
  72. return antBuildXml
  73. return None
  74. @staticmethod
  75. def projectInit():
  76. pwd = os.getcwd()
  77. projectName = os.path.basename(os.getcwd())
  78. examples_dir = os.path.join(SzToolsConfig.getShareHome(),"examples")
  79. projectInitXml = os.path.join(examples_dir,"project.xml")
  80. classpathInitXml = os.path.join(examples_dir,"classpath.xml")
  81. jdeInitXml = os.path.join(examples_dir,"jde.xml")
  82. if not os.path.exists("src") :
  83. os.mkdir("src")
  84. if not os.path.exists("lib") :
  85. os.mkdir("lib")
  86. if not os.path.exists("dst") :
  87. os.mkdir("dst")
  88. lines = open(projectInitXml).readlines()
  89. f = open(".project","w")
  90. for line in lines :
  91. line=line.replace("test",projectName)
  92. f.write(line)
  93. f.close()
  94. shutil.copy2(classpathInitXml, "./.classpath")
  95. shutil.copy2(jdeInitXml, "./.jde")
  96. print "project initialized in current dir succeed."
  97. @staticmethod
  98. def projectClean():
  99. vim_buffer = vim.current.buffer
  100. current_file_name = vim_buffer.name
  101. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  102. Talker.projectClean(classPathXml)
  103. @staticmethod
  104. def projectOpen():
  105. classPathXml = os.path.join(os.getcwd(),".classpath")
  106. if not os.path.exists(classPathXml) :
  107. vim_buffer = vim.current.buffer
  108. current_file_name = vim_buffer.name
  109. if current_file_name != None and os.path.exists(current_file_name):
  110. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  111. else :
  112. classPathXml = ProjectManager.getClassPathXml(os.getcwd())
  113. #if we can't find .classpath, defer the project init process later .
  114. if classPathXml.endswith(".classpath") :
  115. Talker.projectOpen(classPathXml)
  116. @staticmethod
  117. def loadJarMeta():
  118. vim_buffer = vim.current.buffer
  119. current_file_name = vim_buffer.name
  120. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  121. Talker.loadJarMeta(classPathXml)
  122. class Talker(BasicTalker):
  123. @staticmethod
  124. def getPackageList(pkgname,xmlPath):
  125. params = dict()
  126. params["cmd"]="completion"
  127. params["completionType"] = "package"
  128. params["pkgname"] = pkgname
  129. params["classPathXml"] = xmlPath
  130. data = Talker.send(params)
  131. return data
  132. @staticmethod
  133. def getClassList(classNameStart,xmlPath,ignoreCase="false"):
  134. params = dict()
  135. params["cmd"]="completion"
  136. params["completionType"] = "class"
  137. params["className"] = classNameStart
  138. params["classPathXml"] = xmlPath
  139. params["ignoreCase"] = ignoreCase
  140. data = Talker.send(params)
  141. return data
  142. @staticmethod
  143. def locateSource(className, xmlPath, sourceType="declare"):
  144. "sourceType in { 'declare', 'impl] }"
  145. params = dict()
  146. params["cmd"]="locateSource"
  147. params["className"] = className
  148. params["classPathXml"] = xmlPath
  149. params["sourceType"] = sourceType
  150. data = Talker.send(params)
  151. return data
  152. @staticmethod
  153. def getMemberList(args):
  154. params = dict()
  155. sourceFile ,classnameList,xmlPath,memberType,expTokens = args
  156. params["cmd"]="completion"
  157. params["sourceFile"] = sourceFile
  158. params["completionType"] = memberType
  159. params["classnames"] = ",".join(classnameList)
  160. params["classPathXml"] = xmlPath
  161. params["expTokens"] = ",".join(expTokens)
  162. data = Talker.send(params)
  163. return data
  164. @staticmethod
  165. def getMethodDefs(args):
  166. "print all methods of a variable"
  167. params = dict()
  168. sourceFile ,classnameList,xmlPath,expTokens,memberName= args
  169. params["cmd"]="getMethodDefs"
  170. params["sourceFile"] = sourceFile
  171. params["classnames"] = ",".join(classnameList)
  172. params["classPathXml"] = xmlPath
  173. params["expTokens"] = ",".join(expTokens)
  174. params["memberName"] = memberName
  175. data = Talker.send(params)
  176. return data
  177. @staticmethod
  178. def getMethodDefClass(args):
  179. "get whic class defines a method"
  180. params = dict()
  181. sourceFile ,classnameList,xmlPath,expTokens,memberName,sourceType= args
  182. params["cmd"]="getMethodDefClass"
  183. params["sourceFile"] = sourceFile
  184. params["classnames"] = ",".join(classnameList)
  185. params["classPathXml"] = xmlPath
  186. params["expTokens"] = ",".join(expTokens)
  187. params["memberName"] = memberName
  188. params["sourceType"] = sourceType
  189. data = Talker.send(params)
  190. return data
  191. @staticmethod
  192. def searchRef(xmlPath,sourceFile,memberDesc):
  193. params = dict()
  194. params["cmd"]="searchRef"
  195. params["classPathXml"] = xmlPath
  196. params["sourceFile"] = sourceFile
  197. params["memberDesc"] = memberDesc
  198. data = Talker.send(params)
  199. return data
  200. @staticmethod
  201. def getConstructDefs(sourceFile,classnameList,xmlPath):
  202. params = dict()
  203. params["cmd"]="getConstructDefs"
  204. params["sourceFile"] = sourceFile
  205. params["classnames"] = ",".join(classnameList)
  206. params["classPathXml"] = xmlPath
  207. data = Talker.send(params)
  208. return data
  209. @staticmethod
  210. def compileFile(xmlPath,sourceFile):
  211. params = dict()
  212. params["cmd"]="compile"
  213. params["classPathXml"] = xmlPath
  214. params["sourceFile"] = sourceFile
  215. data = Talker.send(params)
  216. return data
  217. @staticmethod
  218. def typeHierarchy(xmlPath,sourceFile):
  219. params = dict()
  220. params["cmd"]="typeHierarchy"
  221. params["classPathXml"] = xmlPath
  222. params["sourceFile"] = sourceFile
  223. data = Talker.send(params)
  224. return data
  225. @staticmethod
  226. def copyResource(xmlPath,sourceFile):
  227. params = dict()
  228. params["cmd"]="copyResource"
  229. params["classPathXml"] = xmlPath
  230. params["sourceFile"] = sourceFile
  231. data = Talker.send(params)
  232. return data
  233. @staticmethod
  234. def runFile(xmlPath,sourceFile,vimServer,bufname,runCmd="run"):
  235. params = dict()
  236. params["cmd"]=runCmd
  237. params["classPathXml"] = xmlPath
  238. params["sourceFile"] = sourceFile
  239. params["vimServer"] = vimServer
  240. params["bufname"] = bufname
  241. data = Talker.send(params)
  242. return data
  243. @staticmethod
  244. def autoImport(xmlPath,varNames,pkgName):
  245. params = dict()
  246. params["cmd"]="autoimport"
  247. params["classPathXml"] = xmlPath
  248. params["varNames"] = varNames
  249. params["pkgName"] = pkgName
  250. data = Talker.send(params)
  251. return data
  252. @staticmethod
  253. def dumpClass(xmlPath,classnameList):
  254. params = dict()
  255. params["cmd"]="dumpClass"
  256. params["classPathXml"] = xmlPath
  257. params["dumpClassNames"] = ",".join(classnameList)
  258. data = Talker.send(params)
  259. return data
  260. @staticmethod
  261. def overideMethod(xmlPath,varNames):
  262. params = dict()
  263. params["cmd"]="overide"
  264. params["classPathXml"] = xmlPath
  265. params["varNames"] = ",".join(varNames)
  266. data = Talker.send(params)
  267. return data
  268. @staticmethod
  269. def runAntBuild(vimServer,cmdName,runInShell):
  270. params = dict()
  271. params["cmd"]="runSys"
  272. params["vimServer"] = vimServer
  273. params["cmdName"] = cmdName
  274. params["runInShell"] = runInShell
  275. data = Talker.send(params)
  276. return data
  277. @staticmethod
  278. def projectClean(xmlPath):
  279. params = dict()
  280. params["cmd"]="projectClean"
  281. params["classPathXml"] = xmlPath
  282. data = Talker.send(params)
  283. return data
  284. @staticmethod
  285. def projectOpen(xmlPath):
  286. params = dict()
  287. params["cmd"]="projectOpen"
  288. params["classPathXml"] = xmlPath
  289. data = Talker.send(params)
  290. return data
  291. @staticmethod
  292. def loadJarMeta(xmlPath):
  293. params = dict()
  294. params["cmd"]="loadJarMeta"
  295. params["classPathXml"] = xmlPath
  296. data = Talker.send(params)
  297. return data
  298. class EditUtil(object):
  299. @staticmethod
  300. def createSkeleton():
  301. vim_buffer = vim.current.buffer
  302. if len(vim_buffer) > 10 :
  303. return
  304. buf_content = "\n".join(vim_buffer)
  305. if not re.match("^\s*$",buf_content) :
  306. return
  307. cur_file = vim_buffer.name
  308. if cur_file.startswith("jar:"):
  309. return
  310. if os.path.exists(cur_file) :
  311. file_content ="\n".join(open(cur_file,"r").readlines())
  312. if not re.match("^\s*$",file_content) :
  313. return
  314. cur_path = os.path.dirname(cur_file)
  315. prj_root = ProjectManager.getProjectRoot(cur_file)
  316. src_locs = ProjectManager.getSrcLocations(cur_file)
  317. pkg = ""
  318. for abs_src in src_locs :
  319. if cur_path.startswith(abs_src) :
  320. pkg = cur_path[ len(abs_src)+1 : ]
  321. if pkg != "" :
  322. vim_buffer.append("package %s;" % pkg.replace(os.path.sep,"."))
  323. vim_buffer.append("")
  324. class_name = os.path.splitext(os.path.basename(cur_file))[0]
  325. s = Template("public class $name {\n\n}")
  326. skeleton = s.substitute(name=class_name)
  327. for line in skeleton.split("\n"):
  328. vim_buffer.append(line)
  329. del vim_buffer[0]
  330. @staticmethod
  331. def generateGseter():
  332. jdef_parser = Parser.getJavaVarDefParser(None,False)
  333. statement = OneOrMore(Group(jdef_parser))
  334. statement.ignore( javaStyleComment )
  335. startCol,endCol,startLine,endLine=MiscUtil.getVisualArea()
  336. vim_buffer = vim.current.buffer
  337. selectedText = "\n".join(vim_buffer[startLine-1:endLine])
  338. results = statement.parseString(selectedText)
  339. template = """
  340. public void set$1($2 $3) {
  341. this.$3=$3;
  342. }
  343. public $2 get$1() {
  344. return this.$3;
  345. }
  346. """
  347. sb = []
  348. for item in results :
  349. tmp = []
  350. for type_token in item[0]:
  351. if type_token not in "<>[]" :
  352. if len(tmp) > 0 and tmp[-1] not in "<>[]":
  353. tmp.append(",")
  354. tmp.append(type_token)
  355. vartype = "".join(tmp)
  356. varname = item[1]
  357. result = template.replace("$1",varname[0].upper() + varname[1:])
  358. result = result.replace("$2",vartype)
  359. result = result.replace("$3",varname)
  360. sb.append(result)
  361. if sb == [] :
  362. return
  363. endline = Parser.parseClassEnd()
  364. del vim_buffer[endline]
  365. output(sb,append=True)
  366. output("}",append=True)
  367. #format the getter,setter code
  368. vim.command("normal %sGV200j=" % endline)
  369. @staticmethod
  370. def overideMethod():
  371. vim_buffer = vim.current.buffer
  372. current_file_name = vim_buffer.name
  373. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  374. if not classPathXml : return
  375. allFullClassNames = Parser.getAllSuperClassFullNames()
  376. resultText = Talker.overideMethod(classPathXml,allFullClassNames)
  377. VimUtil.writeToSzToolBuffer("JdeConsole",resultText)
  378. @staticmethod
  379. def locateDefinition(sourceType):
  380. (row,col) = vim.current.window.cursor
  381. vim_buffer = vim.current.buffer
  382. line = vim_buffer[row-1]
  383. current_file_name = vim_buffer.name
  384. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  385. dotExpParser = Parser.getJavaDotExpParser()
  386. tokenEndCol = col
  387. for char in line[col:] :
  388. if not re.match("\w",char) :
  389. break
  390. tokenEndCol += 1
  391. #if current line starts with "." or last line ends with "." . join the line
  392. if re.match(r"^\s*\..*", line) or re.match(r".*\.$",vim_buffer[row-2]) :
  393. line = vim_buffer[row-2].strip() + line[0:tokenEndCol+1]
  394. tokenEndCol = len(line) - 1
  395. #if locate the class source
  396. classNamePat = r".*\b(?P<name>[A-Z]\w+)$"
  397. searchResult = re.search(classNamePat, line[0:tokenEndCol])
  398. if searchResult :
  399. className = searchResult.group("name")
  400. tmpLine = line[0:tokenEndCol]
  401. #check if the exp is some member name started with uppercase letter.
  402. if tmpLine[len(tmpLine) - len(className) - 1] != "." :
  403. classNameList = Parser.getFullClassNames(className)
  404. for className in classNameList :
  405. sourcePath = Talker.locateSource(className, classPathXml,sourceType)
  406. if sourcePath != "None" :
  407. sourcePath, className = sourcePath.split("\n")
  408. matchedLine = EditUtil.searchClassDefLineNum(className, sourcePath)
  409. vim.command("edit +%s %s" % (matchedLine, sourcePath ))
  410. break
  411. return
  412. #locate the member of class
  413. expTokens = dotExpParser.searchString(line[0:tokenEndCol])[0]
  414. if not expTokens :
  415. return
  416. varName = expTokens[0]
  417. endTokenIndex = 0 if len(expTokens)==1 else -1
  418. if len(expTokens) == 1 or (len(expTokens) == 3 and varName == "this"):
  419. if len(expTokens) ==1 :
  420. memberName = expTokens[0]
  421. else :
  422. memberName = expTokens[2]
  423. #search in visible scope(only upward)
  424. var_type, var_type_row = Parser.getVarTypeInfo(memberName,row-1)
  425. if var_type != None :
  426. vim.command("let @/='\<%s\>'" % memberName)
  427. vim.command("normal %sG" % str(var_type_row + 1))
  428. return
  429. #search in class member info
  430. members = Parser.parseAllMemberInfo(vim_buffer)
  431. for name,mtype,rtntype,param,lineNum in members :
  432. if name == memberName :
  433. matched_row = lineNum
  434. vim.command("let @/='\<%s\>'" % memberName)
  435. vim.command("normal %sG" % str(matched_row))
  436. return
  437. else :
  438. expTokens = expTokens[1:]
  439. memberName = expTokens[-1]
  440. if line[tokenEndCol] == "(":
  441. expTokens[endTokenIndex] = expTokens[endTokenIndex] + "()"
  442. superClass = Parser.getSuperClass()
  443. if varName[0].isupper():
  444. classname = varName
  445. elif varName == "this" :
  446. classname = "this"
  447. elif varName.endswith("()") :
  448. classname = "this"
  449. expTokens.insert(0,varName)
  450. elif varName == "super" :
  451. classname = superClass
  452. else :
  453. classname = Parser.getVarType(varName,row-1)
  454. if not classname :
  455. if not superClass : return
  456. expTokens.insert(0,varName)
  457. classname = superClass
  458. classNameList = Parser.getFullClassNames(classname)
  459. expTokens = expTokens[:-1]
  460. tmpName = memberName + "()" if line[tokenEndCol] == "(" else memberName
  461. #get the param count of method, match method by name and count of param first
  462. param_count = -1
  463. if line[tokenEndCol] == "(":
  464. matched_count = -1
  465. param_names = None
  466. for index, ch in enumerate(line[tokenEndCol+1:]) :
  467. if "(" == ch :
  468. matched_count = matched_count - 1
  469. if ")" == ch :
  470. matched_count = matched_count + 1
  471. if matched_count == 0 :
  472. param_names = line[tokenEndCol+1 : tokenEndCol+1+index]
  473. break
  474. if param_names != None :
  475. param_count = len(param_names.split(",")) if param_names.strip() != "" else 0
  476. params =(current_file_name,classNameList,classPathXml,expTokens,tmpName,sourceType)
  477. sourcePath = Talker.getMethodDefClass(params)
  478. if sourcePath != "None" :
  479. matchedLine = EditUtil.searchMemeberLineNum(memberName, sourcePath,param_count)
  480. vim.command("let @/='\<%s\>'" % memberName)
  481. vim.command("edit +%s %s" % (matchedLine, sourcePath ))
  482. else :
  483. print "cant' locate the source code"
  484. return
  485. @staticmethod
  486. def reprDictInDoubleQuote(dic):
  487. pairs = []
  488. for item in dic.keys() :
  489. value = re.escape(dic[item])
  490. pair = '"'+str(item)+'"'+":"+'"'+value+'"'
  491. pairs.append(pair)
  492. return "{"+",".join(pairs)+"}"
  493. @staticmethod
  494. def searchRef():
  495. (row,col) = vim.current.window.cursor
  496. vim_buffer = vim.current.buffer
  497. line = vim_buffer[row-1]
  498. current_file_name = vim_buffer.name
  499. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  500. result = Parser.parseCurrentMethod()
  501. if result == None :
  502. print "current line not contains a method declaration."
  503. return
  504. rtntype,name,param = result
  505. memberDesc = rtntype + " " + name + "(" + param +")"
  506. resultText = Talker.searchRef(classPathXml,current_file_name,memberDesc)
  507. hltype = "R"
  508. HighlightManager.removeHighlightType(hltype)
  509. qflist = []
  510. for line in resultText.split("\n"):
  511. if line.strip() == "" : continue
  512. try :
  513. filename,lnum,text= line.split("::")
  514. bufnr=str(vim.eval("bufnr('%')"))
  515. absname = os.path.normpath(filename)
  516. filename = Compiler.relpath(absname)
  517. if filename != Compiler.relpath(current_file_name) :
  518. qfitem = dict(filename=filename,lnum=lnum,text=text)
  519. else :
  520. qfitem = dict(bufnr=bufnr,lnum=lnum,text=text)
  521. lstart = text.find(name)
  522. lend = lstart + len(name) + 2
  523. HighlightManager.addHighlightInfo(absname,lnum,hltype,text,lstart, lend)
  524. qflist.append(qfitem)
  525. except Exception , e:
  526. fp = StringIO.StringIO()
  527. traceback.print_exc(file=fp)
  528. message = fp.getvalue()
  529. logging.debug(message)
  530. HighlightManager.highlightCurrentBuf()
  531. if len(qflist) > 0 :
  532. #since vim use single quote string as literal string, the escape char will not
  533. #been handled, so repr the dict in a double quoted string
  534. qflist_str = "[" + ",".join([EditUtil.reprDictInDoubleQuote(item) for item in qflist])+"]"
  535. vim.command("call setqflist(%s)" % qflist_str)
  536. vim.command("cwindow")
  537. else :
  538. print "can't find any reference location."
  539. @staticmethod
  540. def searchMemeberLineNum(memberName,sourcePath,paramCount = -1):
  541. if sourcePath.startswith("jar:") :
  542. lines = ZipUtil.read_zip_entry(sourcePath)
  543. else :
  544. lines = open(sourcePath).readlines()
  545. matched_row = 1
  546. members = Parser.parseAllMemberInfo(lines)
  547. nameMatches = [1]
  548. gotExactMatch = False
  549. for name,mtype,rtntype,param,lineNum in members :
  550. if name == memberName :
  551. tmp_count = len(param.split(",")) if param.strip() != "" else 0
  552. if paramCount == -1 or paramCount == tmp_count :
  553. matched_row = lineNum
  554. gotExactMatch = True
  555. break
  556. else :
  557. nameMatches.append(lineNum)
  558. if gotExactMatch :
  559. return str(matched_row)
  560. else :
  561. return str(nameMatches[-1])
  562. @staticmethod
  563. def searchClassDefLineNum(className, sourcePath):
  564. if sourcePath.startswith("jar:") :
  565. lines = ZipUtil.read_zip_entry(sourcePath)
  566. else :
  567. lines = open(sourcePath).readlines()
  568. matched_row = 1
  569. clsPat = re.compile(r"\s*((public|private|protected)\s+)?"
  570. "((abstract|static|final|strictfp)\s+)?"
  571. "(class|interface)\s"+className+r"\b")
  572. for index,line in enumerate(lines):
  573. if clsPat.match(line):
  574. matched_row = index + 1
  575. break
  576. return str(matched_row)
  577. @staticmethod
  578. def searchAndEdit(current_file_name, className,memberName, mode="local",param_count=-1):
  579. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  580. sourcePath = Talker.locateSource(className, classPathXml)
  581. if mode == "local" :
  582. editCmd="edit"
  583. elif mode == "buffer" :
  584. vim.command("split")
  585. elif mode == "tab" :
  586. vim.command("tabnew")
  587. if sourcePath != "None" :
  588. sourcePath, className = sourcePath.split("\n")
  589. if memberName.strip() != "" :
  590. matchedLine = EditUtil.searchMemeberLineNum(memberName, sourcePath,param_count)
  591. else :
  592. matchedLine = EditUtil.searchClassDefLineNum(className, sourcePath)
  593. vim.command("edit +%s %s" % (matchedLine, sourcePath ))
  594. return
  595. @staticmethod
  596. def tipMethodParameter():
  597. (row,col) = vim.current.window.cursor
  598. vim_buffer = vim.current.buffer
  599. line = vim_buffer[row-1]
  600. current_file_name = vim_buffer.name
  601. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  602. tokenEndCol = line[0:col+1].rfind("(")
  603. if tokenEndCol < 0 : return
  604. newClassPat = r".*\bnew\s+(?P<name>[A-Z]\w+)$"
  605. searchResult = re.search(newClassPat, line[0:tokenEndCol])
  606. if searchResult :
  607. className = searchResult.group("name")
  608. classNameList = Parser.getFullClassNames(className)
  609. constructDefs = Talker.getConstructDefs(current_file_name,classNameList,classPathXml)
  610. if constructDefs == "" : return
  611. VimUtil.writeToSzToolBuffer("JdeConsole",constructDefs)
  612. return
  613. dotExpParser = Parser.getJavaDotExpParser()
  614. expTokens = dotExpParser.searchString(line[0:tokenEndCol])[0]
  615. if not expTokens : return
  616. varName = expTokens[0]
  617. endTokenIndex = 0 if len(expTokens)==1 else -1
  618. if len(expTokens) == 1 or (len(expTokens) == 3 and varName == "this"):
  619. if len(expTokens) ==1 :
  620. memberName = expTokens[0]
  621. else :
  622. memberName = expTokens[2]
  623. members = Parser.parseAllMemberInfo(vim_buffer)
  624. for name,mtype,rtntype,param,lineNum in members :
  625. if name == memberName :
  626. matched_row = lineNum
  627. vim.command("normal %sG" % str(matched_row))
  628. return
  629. else :
  630. expTokens = expTokens[1:]
  631. memberName = expTokens[-1]
  632. if varName[0].isupper():
  633. classname = varName
  634. elif varName == "this" :
  635. classname = "this"
  636. else :
  637. classname = Parser.getVarType(varName,row-1)
  638. superClass = Parser.getSuperClass()
  639. if not classname :
  640. if not superClass : return
  641. expTokens.insert(0,varName)
  642. classname = superClass
  643. classNameList = Parser.getFullClassNames(classname)
  644. expTokens = expTokens[:-1]
  645. params =(current_file_name,classNameList,classPathXml,expTokens,memberName)
  646. methodDefs = Talker.getMethodDefs(params)
  647. if methodDefs == "" :
  648. return
  649. VimUtil.writeToSzToolBuffer("JdeConsole",methodDefs)
  650. return
  651. @staticmethod
  652. def dumpClassInfo():
  653. classname = vim.eval("expand('<cword>')")
  654. if classname == "" : return
  655. vim_buffer = vim.current.buffer
  656. current_file_name = vim_buffer.name
  657. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  658. if not classPathXml : return
  659. classNameList = Parser.getFullClassNames(classname)
  660. result = Talker.dumpClass(classPathXml,classNameList)
  661. VimUtil.writeToSzToolBuffer("JdeConsole",result)
  662. @staticmethod
  663. def toggleBreakpoint():
  664. global bp_data
  665. file_name = vim.current.buffer.name
  666. (row,col) = vim.current.window.cursor
  667. bp_set = bp_data.get(file_name)
  668. if bp_set == None :
  669. bp_set = set()
  670. mainClassName = Parser.getMainClass()
  671. class_path_xml = ProjectManager.getClassPathXml(file_name)
  672. serverName = vim.eval("v:servername")
  673. bufnr=str(vim.eval("bufnr('%')"))
  674. if row in bp_set :
  675. cmdline = "breakpoint_remove %s %s" % (mainClassName,row)
  676. data = JdbTalker.submit(cmdline,class_path_xml,serverName)
  677. if data == "success" :
  678. bp_set.remove(row)
  679. HighlightManager.removeSign(file_name,row,"B")
  680. else :
  681. print "remove breakpoint error : msgs "+data
  682. else :
  683. cmdline = "breakpoint_add %s %s" % (mainClassName,row)
  684. data = JdbTalker.submit(cmdline,class_path_xml,serverName)
  685. if data == "success" :
  686. HighlightManager.addSign(file_name,row, "B")
  687. bp_set.add(row)
  688. bp_data[file_name] = bp_set
  689. else :
  690. print "can't create breakpoint here"
  691. @staticmethod
  692. def addConditionalBreakpoint(lineNum):
  693. global bp_data
  694. file_name = vim.current.buffer.name
  695. (row,col) = vim.current.window.cursor
  696. bp_set = bp_data.get(file_name)
  697. if bp_set == None :
  698. bp_set = set()
  699. HighlightManager.addSign(file_name,lineNum, "B")
  700. bp_set.add(row)
  701. bp_data[file_name] = bp_set
  702. @staticmethod
  703. def syncBreakpointInfo():
  704. global bp_data
  705. current_file = vim.current.buffer.name
  706. bp_set = bp_data.get(current_file)
  707. if bp_set :
  708. for row_num in bp_set :
  709. HighlightManager.removeSign(current_file,row_num,"B")
  710. source_file_path = vim.current.buffer.name
  711. serverName = vim.eval("v:servername")
  712. class_path_xml = ProjectManager.getClassPathXml(source_file_path)
  713. data = JdbTalker.submit("syncbps",class_path_xml,serverName)
  714. bp_data = {}
  715. if data :
  716. for line in data.split("\n"):
  717. if line.strip() == "" or line.find(" ") < 0 :
  718. continue
  719. class_name, line_num = line.split(" ")
  720. rlt_path = class_name.replace(".", os.path.sep)+".java"
  721. src_locs = ProjectManager.getSrcLocations(source_file_path)
  722. matched_file = None
  723. for src_loc in src_locs :
  724. abs_path = os.path.normpath(os.path.join(src_loc, rlt_path))
  725. if os.path.exists(abs_path) :
  726. matched_file = abs_path
  727. break
  728. if matched_file != None :
  729. bp_set = bp_data.get(matched_file)
  730. if bp_set == None :
  731. bp_set = set()
  732. bp_set.add(int(line_num))
  733. bp_data[matched_file] = bp_set
  734. if matched_file == vim.current.buffer.name :
  735. HighlightManager.addSign(matched_file,line_num,"B")
  736. @staticmethod
  737. def getTypeHierarchy():
  738. (row,col) = vim.current.window.cursor
  739. vim_buffer = vim.current.buffer
  740. line = vim_buffer[row-1]
  741. current_file_name = vim_buffer.name
  742. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  743. if not classPathXml :
  744. return
  745. resultText = Talker.typeHierarchy(classPathXml,current_file_name)
  746. return resultText
  747. class HighlightManager(object):
  748. class Info(object):
  749. def __init__(self,msg,lstart,lend,hltype):
  750. self.msg = msg
  751. self.lstart = lstart
  752. self.lend = lend
  753. self.hltype = hltype
  754. def __str__(self):
  755. return "(%s,%s)" % (self.hltype,self.msg)
  756. def __repr__(self):
  757. return "(%s,%s)" % (self.hltype,self.msg)
  758. @staticmethod
  759. def removeHighlightType(removed_hltype):
  760. global all_hl_info
  761. all_hl_info = globals().get("all_hl_info")
  762. if all_hl_info == None :
  763. return
  764. empty_buf = []
  765. for file_path in all_hl_info :
  766. buf_hl_info = all_hl_info.get(file_path)
  767. empty_line =[]
  768. for line_num in buf_hl_info :
  769. infos = [info for info in buf_hl_info.get(line_num) if info.hltype != removed_hltype]
  770. if len(infos) > 0 :
  771. buf_hl_info[line_num] = infos
  772. else :
  773. empty_line.append(line_num)
  774. for line_num in empty_line:
  775. del buf_hl_info[line_num]
  776. if len(buf_hl_info) == 0 :
  777. empty_buf.append(file_path)
  778. for file_path in empty_buf :
  779. del all_hl_info[file_path]
  780. @staticmethod
  781. def addHighlightInfo(abs_path,lnum,hltype,msg="",lstart=-1,lend=-1):
  782. global all_hl_info
  783. lnum=int(lnum)
  784. all_hl_info = globals().get("all_hl_info")
  785. if all_hl_info == None :
  786. all_hl_info = {}
  787. buf_hl_info = all_hl_info.get(abs_path)
  788. if buf_hl_info == None :
  789. buf_hl_info = {}
  790. cur_hl_info = HighlightManager.Info(msg,lstart,lend,hltype)
  791. line_hl_info = buf_hl_info.get(lnum)
  792. if line_hl_info == None :
  793. line_hl_info = []
  794. line_hl_info.append(cur_hl_info)
  795. buf_hl_info[lnum] = line_hl_info
  796. all_hl_info[abs_path] = buf_hl_info
  797. @staticmethod
  798. def addSign(abs_path, lnum,hltype,bufnr=None):
  799. lnum=int(lnum)
  800. HighlightManager.addHighlightInfo(abs_path,lnum,hltype)
  801. if bufnr == None :
  802. bufnr=str(vim.eval("bufnr('%')"))
  803. global all_hl_info
  804. all_hl_info = globals().get("all_hl_info")
  805. buf_hl_info = all_hl_info.get(abs_path)
  806. line_hl_info = buf_hl_info.get(lnum)
  807. hltypes = "".join([info.hltype for info in line_hl_info])
  808. group = HighlightManager._getGroupName(hltypes)
  809. HighlightManager._signErrorGroup(lnum,group,bufnr)
  810. @staticmethod
  811. def removeSign(abs_path, lnum, hltype,bufnr = None):
  812. global all_hl_info
  813. lnum = int(lnum)
  814. all_hl_info = globals().get("all_hl_info")
  815. if all_hl_info == None :
  816. return
  817. buf_hl_info = all_hl_info.get(abs_path)
  818. if buf_hl_info == None :
  819. return
  820. line_hl_info = buf_hl_info.get(lnum)
  821. if line_hl_info == None :
  822. return
  823. line_hl_info = [info for info in line_hl_info if info.hltype != hltype]
  824. if bufnr == None :
  825. bufnr=str(vim.eval("bufnr('%')"))
  826. unsigncmd = "sign unplace %s buffer=%s" % (str(lnum),bufnr)
  827. unsigncmd = "sign unplace %s buffer=%s" % (str(lnum),bufnr)
  828. vim.command(unsigncmd)
  829. if len(line_hl_info) == 0 :
  830. del buf_hl_info[lnum]
  831. else :
  832. buf_hl_info[lnum] = line_hl_info
  833. hltypes = "".join([info.hltype for info in line_hl_info])
  834. group = HighlightManager._getGroupName(hltypes)
  835. signcmd=Template("sign place ${id} line=${lnum} name=${name} buffer=${nr}")
  836. signcmd =signcmd.substitute(id=lnum,lnum=lnum,name=group, nr=bufnr)
  837. vim.command(signcmd)
  838. @staticmethod
  839. def displayMsg():
  840. global all_hl_info
  841. all_hl_info = globals().get("all_hl_info")
  842. if all_hl_info == None :
  843. return
  844. vim_buffer = vim.current.buffer
  845. buf_hl_info = all_hl_info.get(vim_buffer.name)
  846. if buf_hl_info == None :
  847. return
  848. (row,col) = vim.current.window.cursor
  849. if buf_hl_info.get(row) != None :
  850. fist_hl_info = buf_hl_info.get(row)[0]
  851. msg = fist_hl_info.msg
  852. vim.command("call DisplayMsg('%s')" % msg)
  853. else :
  854. vim.command("call DisplayMsg('%s')" % "")
  855. @staticmethod
  856. def highlightCurrentBuf():
  857. global all_hl_info
  858. HighlightManager._clearHighlightInVim()
  859. all_hl_info = globals().get("all_hl_info")
  860. if all_hl_info == None :
  861. return
  862. file_name = vim.current.buffer.name
  863. buf_hl_info = all_hl_info.get(file_name)
  864. if buf_hl_info == None :
  865. return
  866. bufnr=str(vim.eval("bufnr('%')"))
  867. for lnum in buf_hl_info :
  868. hltypes =[]
  869. for info in buf_hl_info.get(lnum) :
  870. group = HighlightManager._getGroupName(info.hltype)
  871. HighlightManager._highlightErrorGroup(lnum,info.lstart,info.lend,group)
  872. hltypes.append(info.hltype)
  873. group = HighlightManager._getGroupName("".join(hltypes))
  874. HighlightManager._signErrorGroup(lnum,group,bufnr)
  875. @staticmethod
  876. def _getGroupName(highlightType):
  877. infos = {"W":"SzjdeWarning","E":"SzjdeError","R":"SzjdeReference",\
  878. "B":"SzjdeBreakPoint","S":"SuspendLine", "SB":"SuspendLineBP"}
  879. if "S" in highlightType and "B" in highlightType :
  880. group = "SuspendLineBP"
  881. elif "S" in highlightType:
  882. group = "SuspendLine"
  883. elif "B" in highlightType:
  884. group = "SzjdeBreakPoint"
  885. elif "E" in highlightType:
  886. group = "SzjdeError"
  887. elif "W" in highlightType :
  888. group = "SzjdeWarning"
  889. elif "R" in highlightType:
  890. group = "SzjdeReference"
  891. return group
  892. @staticmethod
  893. def _highlightErrorGroup(errorRow,start,end,group):
  894. errorRow,start,end = int(errorRow), int(start), int(end)
  895. if start < 0 or end < 0 or errorRow < 0 :
  896. return
  897. vim_buffer = vim.current.buffer
  898. charCount = 0
  899. fileformat = vim.eval("&fileformat")
  900. newLineCount =1
  901. if fileformat == "dos" :
  902. newLineCount = 2
  903. if group=="SzjdeError" or group == "SzjdeWarning" :
  904. for row in vim_buffer[0:errorRow-1] :
  905. charCount += len(unicode(row)) + newLineCount
  906. rowStart = 0 if start - charCount < 0 else start - charCount
  907. #TODO : shit! where does that magic number come from ? don't fucing rember.
  908. rowEnd = end - charCount + 3
  909. if rowEnd < 0 :
  910. rowEnd = rowStart + len(unicode(vim_buffer[errorRow]))
  911. else :
  912. rowStart = start
  913. rowEnd = end
  914. syncmd = """syn match %s "\%%%sl\%%>%sc.\%%<%sc" """ %(group, errorRow, rowStart, rowEnd)
  915. vim.command(syncmd)
  916. @staticmethod
  917. def _signErrorGroup(errorRow,group,bufnr):
  918. signcmd=Template("sign place ${id} line=${lnum} name=${name} buffer=${nr}")
  919. signcmd =signcmd.substitute(id=errorRow,lnum=errorRow,name=group, nr=bufnr)
  920. vim.command(signcmd)
  921. @staticmethod
  922. def initBreakpointSign():
  923. HighlightManager.highlightCurrentBuf()
  924. return
  925. @staticmethod
  926. def _clearHighlightInVim():
  927. vim.command("syntax clear SzjdeError")
  928. vim.command("syntax clear SzjdeWarning")
  929. vim.command("syntax clear SzjdeReference")
  930. pat = re.compile(r".*id=(?P<name>\d+)\b.*$")
  931. bufnr=str(vim.eval("bufnr('%')"))
  932. vim.command("redir => g:current_signplace")
  933. vim.command("silent sign place buffer=%s" % bufnr )
  934. vim.command("redir END")
  935. output = vim.eval("g:current_signplace")
  936. lines = output.split("\n")
  937. for line in lines :
  938. sign_ids = pat.findall(line)
  939. if (len(sign_ids) == 1 ) :
  940. vim.command("silent sign unplace %s buffer=%s" % (sign_ids[0], bufnr ))
  941. class Compiler(object):
  942. @staticmethod
  943. def relpath(path):
  944. if path.startswith(os.getcwd()) :
  945. return os.path.relpath(path)
  946. else :
  947. return path
  948. @staticmethod
  949. def compileCurrentFile(buildProject = False):
  950. (row,col) = vim.current.window.cursor
  951. vim_buffer = vim.current.buffer
  952. line = vim_buffer[row-1]
  953. current_file_name = vim_buffer.name
  954. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  955. if not classPathXml :
  956. return
  957. need_compiled = False
  958. src_locs = ProjectManager.getSrcLocations(current_file_name)
  959. for abs_src in src_locs :
  960. if current_file_name.startswith(abs_src) :
  961. need_compiled = True
  962. break
  963. if not need_compiled :
  964. return
  965. if buildProject :
  966. current_file_name = "All"
  967. print "build project can take a while, please wait....."
  968. resultText = Talker.compileFile(classPathXml,current_file_name)
  969. allsrcFiles, errorMsgList = resultText.split("$$$$$")
  970. allsrcFiles = allsrcFiles.split("\n")
  971. errorMsgList = errorMsgList.split("\n")
  972. qflist = []
  973. #clear highlight type E and W
  974. HighlightManager.removeHighlightType("E")
  975. HighlightManager.removeHighlightType("W")
  976. error_files = []
  977. for line in errorMsgList:
  978. if line.strip() == "" : continue
  979. try :
  980. errorType,filename,lnum,text,lstart,lend = line.split("::")
  981. if errorType == "E" :
  982. error_files.append(filename)
  983. bufnr=str(vim.eval("bufnr('%')"))
  984. absname = os.path.normpath(filename)
  985. filename = Compiler.relpath(absname)
  986. if filename != Compiler.relpath(current_file_name) :
  987. qfitem = dict(filename=filename,lnum=lnum,text=text,type=errorType)
  988. else :
  989. qfitem = dict(bufnr=bufnr,lnum=lnum,text=text,type=errorType)
  990. HighlightManager.addHighlightInfo(absname,lnum,errorType,text,lstart,lend)
  991. qflist.append(qfitem)
  992. except Exception , e:
  993. fp = StringIO.StringIO()
  994. traceback.print_exc(file=fp)
  995. message = fp.getvalue()
  996. logging.debug(message)
  997. EditUtil.syncBreakpointInfo()
  998. HighlightManager.highlightCurrentBuf()
  999. pathflags =[(filename.replace("\n",""),False) for filename in allsrcFiles]
  1000. pathflags.extend([(filename,True) for filename in error_files])
  1001. Compiler.set_error_flags(pathflags)
  1002. vim.command("call setqflist(%s)" % qflist)
  1003. if len(error_files) > 0 :
  1004. vim.command("cwindow")
  1005. else :
  1006. vim.command("cclose")
  1007. @staticmethod
  1008. def set_error_flags(pathflags):
  1009. if "projectTree" not in globals() :
  1010. return
  1011. for path,flag in pathflags :
  1012. node = projectTree.find_node(path)
  1013. if node != None :
  1014. node.set_error_flag(flag)
  1015. if not VimUtil.isSzToolBufferVisible('ProjectTree'):
  1016. return
  1017. vim.command("call SwitchToSzToolView('ProjectTree')" )
  1018. (row,col) = vim.current.window.cursor
  1019. projectTree.render_tree()
  1020. vim.current.window.cursor = (row,col)
  1021. vim.command("exec 'wincmd w'")
  1022. @staticmethod
  1023. def copyResource():
  1024. vim_buffer = vim.current.buffer
  1025. current_file_name = vim_buffer.name
  1026. if not current_file_name : return
  1027. if current_file_name.endswith(".java") : return
  1028. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  1029. if not classPathXml : return
  1030. resultText = Talker.copyResource(classPathXml,current_file_name)
  1031. VimUtil.writeToSzToolBuffer("JdeConsole",resultText)
  1032. class Runner(object):
  1033. @staticmethod
  1034. def runCurrentFile(runCmd="run"):
  1035. (row,col) = vim.current.window.cursor
  1036. vim_buffer = vim.current.buffer
  1037. line = vim_buffer[row-1]
  1038. current_file_name = vim_buffer.name
  1039. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  1040. if not classPathXml : return
  1041. serverName = vim.eval("v:servername")
  1042. resultText = Talker.runFile(classPathXml,current_file_name,serverName,"JdeConsole",runCmd)
  1043. VimUtil.writeToSzToolBuffer("JdeConsole",resultText)
  1044. @staticmethod
  1045. def runAntBuild(target=None):
  1046. serverName = vim.eval("v:servername")
  1047. vim_buffer = vim.current.buffer
  1048. current_file_name = vim_buffer.name
  1049. antBuildXml = ProjectManager.getAntBuildXml(current_file_name)
  1050. if antBuildXml :
  1051. cmdName = "ant -file "+antBuildXml
  1052. runInShell = "false"
  1053. if os.name == "nt" :
  1054. runInShell = "true"
  1055. resultText = Talker.runAntBuild(serverName,cmdName,runInShell)
  1056. else :
  1057. print "can't find the build.xml."
  1058. @staticmethod
  1059. def fetchResult(guid):
  1060. resultText = BasicTalker.fetchResult(guid)
  1061. lines = resultText.split("\n")
  1062. VimUtil.writeToSzToolBuffer("JdeConsole",lines)
  1063. class AutoImport(object):
  1064. @staticmethod
  1065. def getImportInsertLocation():
  1066. vim_buffer = vim.current.buffer
  1067. pkgLocation = 0
  1068. impLocation = -1
  1069. for index,line in enumerate(vim_buffer):
  1070. if line.strip().startswith("import "):
  1071. impLocation = index
  1072. break
  1073. if impLocation > -1 :
  1074. return impLocation
  1075. for index,line in enumerate(vim_buffer):
  1076. if line.strip().startswith("package") :
  1077. pkgLocation = index + 1
  1078. break
  1079. return pkgLocation
  1080. @staticmethod
  1081. def addImportDef(line):
  1082. if line.strip() == "" : return
  1083. vim_buffer_text ="\n".join(vim.current.buffer)
  1084. tmpDefs = line[:-1].split(";")
  1085. hadImported = False
  1086. for tmpDef in tmpDefs :
  1087. pat = r"import\s+%s\b|import\s+%s" % (tmpDef, tmpDef[0:tmpDef.rfind(".")]+"\.\*")
  1088. if re.search(pat,vim_buffer_text) :
  1089. hadImported = True
  1090. break
  1091. if not hadImported :
  1092. location = AutoImport.getImportInsertLocation()
  1093. if ( len(tmpDefs) == 1 ) :
  1094. insertText = "import %s;" % tmpDefs[0]
  1095. vim.command("call append(%s,'%s')" %(str(location),insertText))
  1096. else :
  1097. selectedIndex = VimUtil.inputOption(tmpDefs)
  1098. if (selectedIndex) :
  1099. insertText = "import %s;" % tmpDefs[int(selectedIndex)]
  1100. vim.command("call append(%s,'%s')" %(str(location),insertText))
  1101. @staticmethod
  1102. def autoImportVar():
  1103. AutoImport.removeUnusedImport()
  1104. vim_buffer = vim.current.buffer
  1105. current_file_name = vim_buffer.name
  1106. classPathXml = ProjectManager.getClassPathXml(current_file_name)
  1107. if not classPathXml : return
  1108. currentPackage = Parser.getPackage()
  1109. if not currentPackage :
  1110. currentPackage = ""
  1111. searchText = "\n".join(vim_buffer)
  1112. #remove comments
  1113. commentPat = re.compile(r"(\/\*.*?\*\/)|((\/\/.*?)(?=\n))", re.DOTALL)
  1114. searchText = commentPat.sub("",searchText)
  1115. strliteralPat = re.compile(r'"(\\"|[^"])*"')
  1116. searchText = strliteralPat.sub("",searchText)
  1117. dclClassNamePat = re.compile(r"(?<=class)\b\W\w+\b")
  1118. dclClassNames =[item.strip() for item in dclClassNamePat.findall(searchText)]
  1119. # upercase words except preceded by "."
  1120. classNamePat = re.compile(r"\b(?<!\.)[A-Z]\w+\b")
  1121. var_type_set=set(classNamePat.findall(searchText))
  1122. for clsName in dclClassNames :
  1123. var_type_set.discard(clsName)
  1124. varNames=",".join(var_type_set)
  1125. resultText = Talker.autoImport(classPathXml,varNames,currentPackage)
  1126. lines = resultText.split("\n")
  1127. for line in lines :
  1128. AutoImport.addImportDef(line)
  1129. location = AutoImport.getImportInsertLocation()
  1130. if location > 0 and vim_buffer[location-1].strip() != "" :
  1131. vim.command("call append(%s,'')" %(str(location)))
  1132. @staticmethod
  1133. def removeUnusedImport():
  1134. vim_buffer = vim.current.buffer
  1135. rowIndex = 0
  1136. while True :
  1137. line = vim_buffer[rowIndex].strip()
  1138. if line.startswith("import") :
  1139. lastName = line[7:-1].split(".")[-1]
  1140. if lastName == "*" :
  1141. del vim_buffer[rowIndex]
  1142. continue
  1143. groups = re.findall(r"\b%s\b" % lastName, "\n".join(vim_buffer))
  1144. if len(groups) <= 1 :
  1145. del vim_buffer[rowIndex]
  1146. continue
  1147. rowIndex += 1
  1148. if rowIndex > len(vim_buffer) -1 :
  1149. break
  1150. class Parser(object):
  1151. @staticmethod
  1152. def parseClassEnd():
  1153. vim_buffer = vim.current.buffer
  1154. row_count = len(vim_buffer)
  1155. end_line = 0
  1156. for lineNum in range(row_count-1,-1,-1):
  1157. line = vim_buffer[lineNum]
  1158. if line.endswith("}") :
  1159. end_line = lineNum
  1160. break
  1161. return end_line
  1162. @staticmethod
  1163. def parseCurrentMethod():
  1164. (row,col) = vim.current.window.cursor
  1165. vim_buffer = vim.current.buffer
  1166. fullDeclLine = vim_buffer[row-1]
  1167. methodPat = re.compile(r"(?P<rtntype>[\w<>,]+)\s+(?P<name>\w+)\s*\((?P<param>.*)\)")
  1168. if "(" in fullDeclLine :
  1169. startLine = row
  1170. while True :
  1171. if ")" in fullDeclLine :
  1172. break
  1173. fullDeclLine = fullDeclLine +vim_buffer[startLine].replace("\t"," ")
  1174. startLine = startLine + 1
  1175. result = methodPat.search(fullDeclLine)
  1176. if result == None : return None
  1177. name = result.group("name")
  1178. rtntype = result.group("rtntype")
  1179. param = result.group("param")
  1180. return rtntype,name,param
  1181. @staticmethod
  1182. def parseCurrentMethodName():
  1183. result = Parser.parseCurrentMethod()
  1184. if result == None :
  1185. return "", None
  1186. rtntype,name,param = result
  1187. return name,param
  1188. @staticmethod
  1189. def parseAllMemberInfo(lines):
  1190. memberInfo = []
  1191. scopeCount = 0
  1192. methodPat = re.compile(r"(?P<rtntype>[\w<>\[\],]+)\s+(?P<name>\w+)\s*\((?P<param>.*)\)")
  1193. assignPat = re.compile("(?P<rtntype>[\w<>\[\],]+)\s+(?P<name>\w+)\s*=")
  1194. defPat = re.compile("(?P<rtntype>[\w<>\[\],]+)\s+(?P<name>\w+)\s*;")
  1195. commentLine = False
  1196. for lineNum,line in enumerate(lines) :
  1197. line = line.strip()
  1198. if (line.startswith("/*") and not line.endswith("*/") ) :
  1199. commentLine = True
  1200. continue
  1201. if line.endswith("*/"):
  1202. commentLine = False
  1203. continue
  1204. if commentLine == True or line.startswith("//"):
  1205. continue
  1206. if scopeCount == 1 :
  1207. fullDeclLine = line
  1208. if "=" in line :
  1209. pat = assignPat
  1210. mtype = "field"
  1211. elif "(" in line :
  1212. startLine = lineNum + 1
  1213. while True :
  1214. if ")" in fullDeclLine or startLine >= len(lines) :

Large files files are truncated, but you can click here to view the full file