completion.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. /*
  2. ktigcc - TIGCC IDE for KDE
  3. Copyright (C) 2006-2007 Kevin Kofler
  4. Copyright (C) 2007 Konrad Meyer
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software Foundation,
  15. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. */
  17. #include <QString>
  18. #include <QLinkedList>
  19. #include <QPair>
  20. #include <QPoint>
  21. #include <QRegExp>
  22. #include <QFileInfo>
  23. #include <QDir>
  24. #include <QApplication>
  25. #include <QWidget>
  26. #include <QEvent>
  27. #include <Q3PopupMenu>
  28. #include <kmessagebox.h>
  29. #include <ktexteditor/view.h>
  30. #include <ktexteditor/document.h>
  31. #include <kconfig.h>
  32. #include <cstring>
  33. #include "completion.h"
  34. #include "parsing.h"
  35. #include "preferences.h"
  36. #include "mainform.h"
  37. #include "tpr.h"
  38. // Maps file name to a CompletionInfo.
  39. QMap<QString,CompletionInfo> systemHeaderCompletion, projectCompletion;
  40. static void resetSearchedFlags(void)
  41. {
  42. for (QMap<QString,CompletionInfo>::Iterator it=projectCompletion.begin();
  43. it!=projectCompletion.end(); ++it)
  44. (*it).searched=false;
  45. for (QMap<QString,CompletionInfo>::Iterator it=systemHeaderCompletion.begin();
  46. it!=systemHeaderCompletion.end(); ++it)
  47. (*it).searched=false;
  48. }
  49. static void findSymbolInSystemHeaders(const QString &symbol,
  50. const QStringList &systemHeaders,
  51. QString &symbolFile,
  52. unsigned &symbolLine,
  53. bool &systemHeader)
  54. {
  55. foreach (const QString &headerName, systemHeaders) {
  56. // Avoid infinite recursion.
  57. if (systemHeaderCompletion.contains(headerName)
  58. && !systemHeaderCompletion[headerName].searched) {
  59. CompletionInfo &completionInfo=systemHeaderCompletion[headerName];
  60. completionInfo.searched=true;
  61. if (completionInfo.lineNumbers.contains(symbol)) {
  62. symbolFile=headerName;
  63. symbolLine=completionInfo.lineNumbers[symbol];
  64. systemHeader=true;
  65. return;
  66. } else {
  67. findSymbolInSystemHeaders(symbol,completionInfo.includedSystem,
  68. symbolFile,symbolLine,systemHeader);
  69. if (!symbolFile.isNull()) return;
  70. }
  71. }
  72. }
  73. }
  74. static bool findSymbolInFileRecursive(const QString &symbol,
  75. const QString &fileText,
  76. const QString &fileName,
  77. MainForm *mainForm,
  78. QString &symbolFile,
  79. unsigned &symbolLine,
  80. bool &systemHeader)
  81. {
  82. symbolFile=QString::null;
  83. systemHeader=false;
  84. if (!projectCompletion.contains(fileName) || projectCompletion[fileName].dirty) {
  85. QFileInfo fileInfo(fileName);
  86. QString pathInProject=fileInfo.isRelative()?fileInfo.path():".";
  87. CompletionInfo completionInfo=parseFileCompletion(fileText,pathInProject);
  88. if (completionInfo.dirty) return false;
  89. projectCompletion.insert(fileName,completionInfo);
  90. }
  91. CompletionInfo &completionInfo=projectCompletion[fileName];
  92. // Avoid infinite recursion.
  93. if (completionInfo.searched) return true;
  94. completionInfo.searched=true;
  95. if (completionInfo.lineNumbers.contains(symbol)) {
  96. symbolFile=fileName;
  97. symbolLine=completionInfo.lineNumbers[symbol];
  98. return true;
  99. }
  100. foreach (const QString &headerName, completionInfo.included) {
  101. QString headerText=mainForm->textForHeader(headerName);
  102. if (!headerText.isNull()) {
  103. if (!findSymbolInFile(symbol,headerText,headerName,mainForm,symbolFile,
  104. symbolLine,systemHeader))
  105. return false;
  106. if (!symbolFile.isNull()) return true;
  107. }
  108. }
  109. findSymbolInSystemHeaders(symbol,completionInfo.includedSystem,symbolFile,
  110. symbolLine,systemHeader);
  111. return true;
  112. }
  113. bool findSymbolInFile(const QString &symbol,
  114. const QString &fileText,
  115. const QString &fileName,
  116. MainForm *mainForm,
  117. QString &symbolFile,
  118. unsigned &symbolLine,
  119. bool &systemHeader)
  120. {
  121. resetSearchedFlags();
  122. return findSymbolInFileRecursive(symbol,fileText,fileName,mainForm,symbolFile,
  123. symbolLine,systemHeader);
  124. }
  125. static void mergeCompletionEntries(QLinkedList<CompletionEntry> &dest,
  126. const QLinkedList<CompletionEntry> &src)
  127. {
  128. foreach (const CompletionEntry &entry, src) dest.append(entry);
  129. }
  130. static void completionEntriesForSystemHeaders(const QStringList &systemHeaders,
  131. QLinkedList<CompletionEntry> &result)
  132. {
  133. foreach (const QString &headerName, systemHeaders) {
  134. // Avoid infinite recursion.
  135. if (systemHeaderCompletion.contains(headerName)
  136. && !systemHeaderCompletion[headerName].searched) {
  137. CompletionInfo &completionInfo=systemHeaderCompletion[headerName];
  138. completionInfo.searched=true;
  139. mergeCompletionEntries(result,completionInfo.entries);
  140. completionEntriesForSystemHeaders(completionInfo.includedSystem,result);
  141. }
  142. }
  143. }
  144. static bool completionEntriesForFileRecursive(const QString &fileText,
  145. const QString &fileName,
  146. MainForm *mainForm,
  147. QLinkedList<CompletionEntry> &result)
  148. {
  149. if (!projectCompletion.contains(fileName) || projectCompletion[fileName].dirty) {
  150. QFileInfo fileInfo(fileName);
  151. QString pathInProject=fileInfo.isRelative()?fileInfo.path():".";
  152. CompletionInfo completionInfo=parseFileCompletion(fileText,pathInProject);
  153. if (completionInfo.dirty) return false;
  154. projectCompletion.insert(fileName,completionInfo);
  155. }
  156. CompletionInfo &completionInfo=projectCompletion[fileName];
  157. // Avoid infinite recursion.
  158. if (completionInfo.searched) return true;
  159. completionInfo.searched=true;
  160. mergeCompletionEntries(result,completionInfo.entries);
  161. completionEntriesForSystemHeaders(completionInfo.includedSystem,result);
  162. foreach (const QString &headerName, completionInfo.included) {
  163. QString headerText=mainForm->textForHeader(headerName);
  164. if (!headerText.isNull())
  165. if (!completionEntriesForFile(headerText,headerName,mainForm,result))
  166. return false;
  167. }
  168. return true;
  169. }
  170. bool completionEntriesForFile(const QString &fileText,
  171. const QString &fileName,
  172. MainForm *mainForm,
  173. QLinkedList<CompletionEntry> &result)
  174. {
  175. resetSearchedFlags();
  176. return completionEntriesForFileRecursive(fileText,fileName,mainForm,result);
  177. }
  178. static QLinkedList<CompletionEntry> sortCompletionEntries(
  179. const QLinkedList<CompletionEntry> &entries)
  180. {
  181. QMap<QString,QLinkedList<CompletionEntry> > map;
  182. foreach (const CompletionEntry &entry, entries) {
  183. QLinkedList<CompletionEntry> &list=map[entry.text];
  184. if (!list.contains(entry)) list.append(entry);
  185. }
  186. QLinkedList<CompletionEntry> result;
  187. foreach (const QLinkedList<CompletionEntry> &entries, map)
  188. mergeCompletionEntries(result,entries);
  189. return result;
  190. }
  191. static QStringList prototypesForIdentifier(const QString &identifier,
  192. const QLinkedList<CompletionEntry> &entries)
  193. {
  194. QStringList result;
  195. QStringList reservedIdentifiers=QString("__alignof__\n"
  196. "__asm__\n"
  197. "__attribute__\n"
  198. "__complex__\n"
  199. "__const__\n"
  200. "__extension__\n"
  201. "__imag__\n"
  202. "__inline__\n"
  203. "__label__\n"
  204. "__real__\n"
  205. "__typeof__\n"
  206. "asm\n"
  207. "auto\n"
  208. "break\n"
  209. "case\n"
  210. "char\n"
  211. "const\n"
  212. "continue\n"
  213. "default\n"
  214. "do\n"
  215. "double\n"
  216. "else\n"
  217. "enum\n"
  218. "extern\n"
  219. "float\n"
  220. "for\n"
  221. "goto\n"
  222. "if\n"
  223. "inline\n"
  224. "int\n"
  225. "long\n"
  226. "register\n"
  227. "return\n"
  228. "short\n"
  229. "signed\n"
  230. "sizeof\n"
  231. "static\n"
  232. "struct\n"
  233. "switch\n"
  234. "typedef\n"
  235. "typeof\n"
  236. "union\n"
  237. "unsigned\n"
  238. "void\n"
  239. "volatile\n"
  240. "while\n").split('\n',QString::SkipEmptyParts);
  241. if (!reservedIdentifiers.contains(identifier)) {
  242. foreach (const CompletionEntry &entry, entries) {
  243. if (entry.text==identifier) {
  244. QString prototype=entry.prefix+' '+entry.text+entry.postfix;
  245. if (result.find(prototype)==result.end()) result.append(prototype);
  246. }
  247. }
  248. if (result.isEmpty()) {
  249. // Try approximate matching.
  250. unsigned identifierLength=identifier.length();
  251. if (identifierLength>=4) {
  252. QString identifierUpper=identifier.toUpper();
  253. QLinkedList<unsigned> distances;
  254. foreach (const CompletionEntry &entry, entries) {
  255. QString entryText=entry.text;
  256. unsigned entryTextLength=entryText.length();
  257. unsigned minLength=qMin(identifierLength,entryTextLength);
  258. unsigned i=0;
  259. for (; i<minLength && identifierUpper[i]==entryText[i].toUpper(); i++);
  260. unsigned distance=minLength-i;
  261. if (distance<=(minLength>>1)) {
  262. QString prototype=entryText+"? "+entry.prefix+' '+entry.postfix;
  263. if (result.find(prototype)==result.end()) {
  264. // Sort by similarity. Smaller distances first.
  265. QStringList::Iterator it1=result.begin();
  266. QLinkedList<unsigned>::Iterator it2=distances.begin();
  267. for (; it2!=distances.end() && *it2<=distance; ++it1,++it2);
  268. result.insert(it1,prototype);
  269. distances.insert(it2,distance);
  270. }
  271. }
  272. }
  273. }
  274. }
  275. }
  276. return result;
  277. }
  278. bool parseHelpSources(QWidget *parent, const QString &directory,
  279. QMap<QString,CompletionInfo> &sysHdrCompletion)
  280. {
  281. QDir qdir(directory);
  282. QStringList headers=qdir.entryList("*.h",QDir::Dirs);
  283. foreach (const QString &header, headers) {
  284. CompletionInfo &completionInfo=sysHdrCompletion[header];
  285. QLinkedList<CompletionEntry> &entries=completionInfo.entries;
  286. QDir hdrQdir(QFileInfo(qdir,header).filePath());
  287. QStringList hsfs=hdrQdir.entryList("*.hsf *.ref",QDir::Files);
  288. foreach (const QString &hsf, hsfs) {
  289. QString fileText=loadFileText(QFileInfo(hdrQdir,hsf).filePath());
  290. if (fileText.isNull()) {
  291. KMessageBox::error(parent,QString("Can't open \'%1/%2\'.").arg(header)
  292. .arg(hsf));
  293. return false;
  294. }
  295. if (hsf.endsWith(".ref")) {
  296. QString realHeader=fileText.trimmed();
  297. QDir realHdrQdir(QFileInfo(qdir,realHeader).filePath());
  298. QString realHsf=hsf;
  299. realHsf.replace(realHsf.length()-3,3,"hsf");
  300. fileText=loadFileText(QFileInfo(realHdrQdir,realHsf).filePath());
  301. if (fileText.isNull()) {
  302. KMessageBox::error(parent,QString("Can't open \'%1/%2\'.").arg(realHeader)
  303. .arg(realHsf));
  304. return false;
  305. }
  306. }
  307. CompletionEntry entry;
  308. QStringList lines=fileText.split('\n');
  309. foreach (const QString &line, lines) {
  310. if (line.startsWith("Name=")) {
  311. entry.text=line.mid(5);
  312. break;
  313. }
  314. }
  315. bool isType=false;
  316. foreach (const QString &line, lines) {
  317. if (line.startsWith("Type=")) {
  318. QString hsfType=line.mid(5);
  319. if (hsfType=="Type") isType=true;
  320. entry.prefix=isType?"type"
  321. :(hsfType=="Function")?"func"
  322. :(hsfType=="Constant")?"const"
  323. :(hsfType=="Variable")?"var":hsfType;
  324. break;
  325. }
  326. }
  327. QRegExp comments("/\\*.*\\*/");
  328. comments.setMinimal(true);
  329. QString definition;
  330. foreach (const QString &line, lines) {
  331. if (line.startsWith("Definition=")) {
  332. definition=line.mid(11);
  333. definition.remove(comments);
  334. int pos=definition.find(entry.text);
  335. QString left=(pos>=0)?definition.left(pos).trimmed()
  336. :QString::null;
  337. QString right;
  338. if (left.startsWith("typedef")) {
  339. entry.postfix=left.mid(8).simplified();
  340. left=QString::null;
  341. } else if (left=="unknown_retval") left="?";
  342. else if (left=="#define") left=QString::null;
  343. if (!left.isEmpty()) {
  344. left.prepend(' ');
  345. entry.prefix+=left;
  346. }
  347. entry.postfix+=definition.mid(pos+entry.text.length()).simplified();
  348. break;
  349. }
  350. }
  351. QStringList::ConstIterator desc=lines.find("[Description]");
  352. QString description;
  353. if (desc!=lines.end() && ++desc!=lines.end()) description=*desc;
  354. description.remove(QRegExp("<A [^>]*>",FALSE)).remove("</A>",FALSE);
  355. if (description.isEmpty()) description=QString::null;
  356. entry.comment=description;
  357. if (isType) {
  358. foreach (const QString &line, lines) {
  359. if (line.startsWith("Subtype=")
  360. || (!line.isEmpty() && line[0]=='[' && line!="[Main]")) {
  361. if (line=="Subtype=Enumeration") {
  362. int pos1=definition.find('{');
  363. if (pos1>=0) {
  364. QString left=definition.left(pos1).trimmed();
  365. int pos2=definition.find('}',++pos1);
  366. if (pos2>=0) {
  367. QString itemList=definition.mid(pos1,pos2-pos1);
  368. if (itemList=="...") {
  369. foreach (const QString &line, lines) {
  370. if (line.startsWith("Real Definition=")) {
  371. QString realDefinition=line.mid(16);
  372. realDefinition.remove(comments);
  373. pos1=realDefinition.find('{');
  374. if (pos1>=0) {
  375. left=realDefinition.left(pos1).trimmed();
  376. pos2=realDefinition.find('}',++pos1);
  377. if (pos2>=0) {
  378. itemList=realDefinition.mid(pos1,pos2-pos1);
  379. goto foundDefinition;
  380. }
  381. }
  382. break;
  383. }
  384. }
  385. } else {
  386. foundDefinition:
  387. QStringList enumItems=itemList.split(',',QString::SkipEmptyParts);
  388. foreach (const QString &enumItem, enumItems) {
  389. CompletionEntry enumEntry;
  390. int pos=enumItem.find('=');
  391. if (pos>=0) {
  392. enumEntry.text=enumItem.left(pos).trimmed();
  393. enumEntry.postfix=enumItem.mid(pos+1).trimmed();
  394. } else enumEntry.text=enumItem.trimmed();
  395. enumEntry.prefix=left;
  396. enumEntry.comment=description;
  397. entries.append(enumEntry);
  398. }
  399. }
  400. }
  401. }
  402. }
  403. break;
  404. }
  405. }
  406. }
  407. if (entry.text.trimmed().isEmpty()) {
  408. // No function name, so use HSF name. Can happen for _ROM_CALL_*.
  409. if (!hsf.startsWith("_ROM_CALL_"))
  410. KMessageBox::sorry(parent,QString("No name found in %1/%2").arg(header)
  411. .arg(hsf),
  412. "Warning");
  413. entry.text=hsf.left(hsf.length()-4);
  414. }
  415. entries.append(entry);
  416. }
  417. }
  418. return true;
  419. }
  420. bool parseSystemHeaders(QWidget *parent, const QString &directory,
  421. QMap<QString,CompletionInfo> &sysHdrCompletion)
  422. {
  423. QDir qdir(directory);
  424. QStringList headers=qdir.entryList("*.h",QDir::Files);
  425. foreach (const QString &header, headers) {
  426. QString fileText=loadFileText(QFileInfo(qdir,header).filePath());
  427. if (fileText.isNull()) {
  428. KMessageBox::error(parent,QString("Can't open \'%1\'.").arg(header));
  429. return false;
  430. }
  431. sysHdrCompletion[header]=parseFileCompletion(fileText,QString::null,
  432. sysHdrCompletion[header]);
  433. if (sysHdrCompletion[header].dirty) return false;
  434. }
  435. return true;
  436. }
  437. void loadSystemHeaderCompletion(void)
  438. {
  439. #ifdef HAVE_KSHAREDCONFIG_H
  440. KConfig config("data","ktigcc/completion",KConfig::NoGlobals);
  441. #else
  442. KConfig config("ktigcc/completion",true,false,"data");
  443. #endif
  444. QStringList groupList=config.groupList();
  445. if (groupList.isEmpty()) {
  446. KMessageBox::queuedMessageBox(0,KMessageBox::Sorry,
  447. "<p>No completion data found for TIGCCLIB headers. KTIGCC will not be "
  448. "able to show completion entries for system headers. You have 2 options "
  449. "to fix this:</p>"
  450. "<p>1. Download ktigcc-completion-data from "
  451. "<a href=\"http://sourceforge.net/project/showfiles.php?group_id=31034"
  452. "&amp;package_id=200501\">http://sourceforge.net/project/showfiles.php?"
  453. "group_id=31034&amp;package_id=200501</a> (recommended).</p>"
  454. "<p>2. Regenerate the data yourself through File/Preferences/Coding "
  455. "(TIGCC source code required).</p>","No Completion Data",
  456. KMessageBox::Notify|KMessageBox::AllowLink);
  457. }
  458. systemHeaderCompletion.clear();
  459. foreach (const QString &key, groupList) {
  460. if (key.endsWith(" Lines")) continue;
  461. CompletionInfo completionInfo;
  462. config.setGroup(key);
  463. completionInfo.includedSystem=config.readListEntry("Included");
  464. unsigned numEntries=config.readUnsignedNumEntry("Num Entries");
  465. for (unsigned i=0; i<numEntries; i++) {
  466. CompletionEntry entry;
  467. entry.type=config.readEntry(QString("Entry %1 Type").arg(i));
  468. entry.text=config.readEntry(QString("Entry %1 Text").arg(i));
  469. entry.prefix=config.readEntry(QString("Entry %1 Prefix").arg(i));
  470. entry.postfix=config.readEntry(QString("Entry %1 Postfix").arg(i));
  471. entry.comment=config.readEntry(QString("Entry %1 Comment").arg(i));
  472. entry.userdata=config.readEntry(QString("Entry %1 User Data").arg(i));
  473. completionInfo.entries.append(entry);
  474. }
  475. QMap<QString,QString> entryMap=config.entryMap(key+" Lines");
  476. for (QMap<QString,QString>::ConstIterator it=entryMap.begin();
  477. it!=entryMap.end(); ++it)
  478. completionInfo.lineNumbers.insert(it.key(),(*it).toUInt());
  479. systemHeaderCompletion.insert(key,completionInfo);
  480. }
  481. }
  482. void saveSystemHeaderCompletion(void)
  483. {
  484. #ifdef HAVE_KSHAREDCONFIG_H
  485. KConfig config("data","ktigcc/completion",KConfig::NoGlobals);
  486. #else
  487. KConfig config("ktigcc/completion",false,false,"data");
  488. #endif
  489. for (QMap<QString,CompletionInfo>::ConstIterator it=systemHeaderCompletion.begin();
  490. it!=systemHeaderCompletion.end(); ++it) {
  491. const QString &key=it.key();
  492. const CompletionInfo &completionInfo=*it;
  493. config.setGroup(key);
  494. config.writeEntry("Included",completionInfo.includedSystem);
  495. unsigned i=0;
  496. foreach (const CompletionEntry &entry, completionInfo.entries) {
  497. config.writeEntry(QString("Entry %1 Type").arg(i),entry.type);
  498. config.writeEntry(QString("Entry %1 Text").arg(i),entry.text);
  499. config.writeEntry(QString("Entry %1 Prefix").arg(i),entry.prefix);
  500. config.writeEntry(QString("Entry %1 Postfix").arg(i),entry.postfix);
  501. config.writeEntry(QString("Entry %1 Comment").arg(i),entry.comment);
  502. config.writeEntry(QString("Entry %1 User Data").arg(i++),entry.userdata);
  503. }
  504. config.writeEntry("Num Entries",i);
  505. config.setGroup(key+" Lines");
  506. for (QMap<QString,unsigned>::ConstIterator it=completionInfo.lineNumbers.begin();
  507. it!=completionInfo.lineNumbers.end(); ++it)
  508. config.writeEntry(it.key(),*it);
  509. }
  510. config.sync();
  511. }
  512. TemplatePopup::TemplatePopup(KTextEditor::View *parent)
  513. : Q3PopupMenu(parent), view(parent)
  514. {
  515. connect(this,SIGNAL(activated(int)),this,SLOT(QPopupMenu_activated(int)));
  516. unsigned i=0;
  517. typedef const QPair<QString,QString> &StringPairConstRef;
  518. foreach (StringPairConstRef pair, preferences.templates)
  519. insertItem(pair.first, i++);
  520. QPoint pos=parent->cursorPositionCoordinates();
  521. if (pos.x()<0 || pos.y()<0) {
  522. // Cursor outside of the view, so center on view instead.
  523. QSize parentSize=parent->size();
  524. QSize popupSize=sizeHint();
  525. pos.setX((parentSize.width()-popupSize.width())>>1);
  526. pos.setY((parentSize.height()-popupSize.height())>>1);
  527. }
  528. exec(parent->mapToGlobal(pos));
  529. deleteLater();
  530. }
  531. void TemplatePopup::QPopupMenu_activated(int id)
  532. {
  533. KTextEditor::Document *doc=view->document();
  534. QString code=preferences.templates[id].second;
  535. QString indent=doc->line(view->cursorPosition().line());
  536. // Remove everything starting from the first non-whitespace character.
  537. indent=indent.remove(QRegExp("(?!\\s).*$"));
  538. indent.prepend('\n');
  539. code.replace('\n',indent);
  540. int cursorPos=code.find('|');
  541. if (cursorPos>=0) {
  542. QString left=code.left(cursorPos);
  543. QString right=code.mid(cursorPos+1);
  544. int row, col;
  545. doc->startEditing();
  546. view->insertText(left);
  547. view->cursorPosition().position(row,col);
  548. view->insertText(right);
  549. doc->endEditing();
  550. view->setCursorPosition(KTextEditor::Cursor(row,col));
  551. } else view->insertText(code);
  552. }
  553. CompletionPopup::CompletionPopup(KTextEditor::View *parent, const QString &fileName,
  554. MainForm *mainForm, QObject *receiver)
  555. : QObject(parent), done(false), completionPopup(0)
  556. {
  557. connect(this,SIGNAL(closed()),receiver,SLOT(completionPopup_closed()));
  558. QLinkedList<CompletionEntry> entries;
  559. if (!completionEntriesForFile(parent->document()->text(),fileName,mainForm,
  560. entries)) {
  561. emit closed();
  562. deleteLater();
  563. return;
  564. }
  565. entries=sortCompletionEntries(entries);
  566. KTextEditor::Cursor cursor=parent->cursorPosition();
  567. int column=cursor.column();
  568. int offset=0;
  569. if (column) {
  570. QString textLine=parent->document()->line(cursor.line());
  571. if (column<=textLine.length()) {
  572. while (column && (textLine[--column].isLetterOrNumber()
  573. || textLine[column]=='_' || textLine[column]=='$'))
  574. offset++;
  575. }
  576. }
  577. #if 0 // FIXME: Port completion.
  578. connect(parent,SIGNAL(completionAborted()),this,SLOT(slotDone()));
  579. connect(parent,SIGNAL(completionDone()),this,SLOT(slotDone()));
  580. parent->showCompletionBox(entries,offset);
  581. // Unfortunately, Kate doesn't always send the completionAborted or
  582. // completionDone event when it closes its popup. Work around that.
  583. QWidgetList *list=QApplication::topLevelWidgets();
  584. QWidgetListIt it(*list);
  585. while (QWidget *w=it.current()) {
  586. ++it;
  587. if (w->isVisible() && w->testWFlags(Qt::WType_Popup)
  588. && !std::strcmp(w->className(),"QVBox")) {
  589. completionPopup=w;
  590. break;
  591. }
  592. }
  593. delete list;
  594. if (completionPopup)
  595. completionPopup->installEventFilter(this);
  596. #else
  597. slotDone();
  598. #endif
  599. }
  600. void CompletionPopup::slotDone()
  601. {
  602. if (!done) {
  603. done=true;
  604. emit closed();
  605. deleteLater();
  606. }
  607. }
  608. bool CompletionPopup::eventFilter(QObject *o, QEvent *e)
  609. {
  610. if (!done && o==completionPopup && e->type()==QEvent::Hide) {
  611. done=true;
  612. emit closed();
  613. deleteLater();
  614. }
  615. return false;
  616. }
  617. ArgHintPopup::ArgHintPopup(KTextEditor::View *parent, const QString &fileName,
  618. MainForm *mainForm)
  619. : QObject(parent), done(false), argHintPopup(0)
  620. {
  621. QLinkedList<CompletionEntry> entries;
  622. if (!completionEntriesForFile(parent->document()->text(),fileName,mainForm,
  623. entries)) {
  624. nothingFound:
  625. deleteLater();
  626. return;
  627. }
  628. KTextEditor::Cursor cursor=parent->cursorPosition();
  629. int column=cursor.column();
  630. if (!column || !--column) goto nothingFound;
  631. QString textLine=parent->document()->line(cursor.line());
  632. if (column>textLine.length() || textLine[column]!='(') goto nothingFound;
  633. while (column && textLine[column-1].isSpace()) column--;
  634. if (!column) goto nothingFound;
  635. unsigned startColumn=column, endColumn=column;
  636. while (column && (textLine[--column].isLetterOrNumber()
  637. || textLine[column]=='_' || textLine[column]=='$'))
  638. startColumn--;
  639. if (startColumn==endColumn) goto nothingFound;
  640. QString identifier=textLine.mid(startColumn,endColumn-startColumn);
  641. QStringList prototypes=prototypesForIdentifier(identifier,entries);
  642. if (prototypes.isEmpty()) goto nothingFound;
  643. #if 0 // FIXME: Port completion.
  644. connect(parent,SIGNAL(argHintHidden()),this,SLOT(slotDone()));
  645. parent->showArgHint(prototypes,"()",",");
  646. // Unfortunately, Kate doesn't always send the argHintHidden event when it
  647. // closes its popup. Work around that.
  648. QWidgetList *list=QApplication::topLevelWidgets();
  649. QWidgetListIt it(*list);
  650. while (QWidget *w=it.current()) {
  651. ++it;
  652. if (w->isVisible() && w->testWFlags(Qt::WType_Popup)
  653. && !std::strcmp(w->className(),"KateArgHint")) {
  654. argHintPopup=w;
  655. break;
  656. }
  657. }
  658. delete list;
  659. if (argHintPopup)
  660. argHintPopup->installEventFilter(this);
  661. #else
  662. slotDone();
  663. #endif
  664. }
  665. void ArgHintPopup::slotDone()
  666. {
  667. if (!done) {
  668. done=true;
  669. deleteLater();
  670. }
  671. }
  672. bool ArgHintPopup::eventFilter(QObject *o, QEvent *e)
  673. {
  674. if (!done && o==argHintPopup && e->type()==QEvent::Hide) {
  675. done=true;
  676. deleteLater();
  677. }
  678. return false;
  679. }