TDE core libraries
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

katejscript.cpp 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. /* This file is part of the KDE libraries
  2. Copyright (C) 2005 Christoph Cullmann <cullmann@kde.org>
  3. Copyright (C) 2005 Joseph Wenninger <jowenn@kde.org>
  4. This library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Library General Public
  6. License version 2 as published by the Free Software Foundation.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Library General Public License for more details.
  11. You should have received a copy of the GNU Library General Public License
  12. along with this library; see the file COPYING.LIB. If not, write to
  13. the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  14. Boston, MA 02110-1301, USA.
  15. */
  16. #include "katejscript.h"
  17. #include "katedocument.h"
  18. #include "kateview.h"
  19. #include "katefactory.h"
  20. #include "kateconfig.h"
  21. #include "kateautoindent.h"
  22. #include "katehighlight.h"
  23. #include "katetextline.h"
  24. #include "kateindentscriptabstracts.h"
  25. #include <sys/types.h>
  26. #include <sys/stat.h>
  27. #include <unistd.h>
  28. #include <kdebug.h>
  29. #include <kstandarddirs.h>
  30. #include <tdelocale.h>
  31. #include <tdemessagebox.h>
  32. #include <tdeconfig.h>
  33. #include <kjs/function_object.h>
  34. #include <kjs/interpreter.h>
  35. #include <kjs/lookup.h>
  36. #include <tqfile.h>
  37. #include <tqfileinfo.h>
  38. #include <tqpopupmenu.h>
  39. #include <tqregexp.h>
  40. #include <tqtextstream.h>
  41. namespace KJS {
  42. // taken from tdehtml
  43. // therefor thx to:
  44. // Copyright (C) 1999-2003 Harri Porten (porten@kde.org)
  45. // Copyright (C) 2001-2003 David Faure (faure@kde.org)
  46. // Copyright (C) 2003 Apple Computer, Inc.
  47. UString::UString(const TQString &d)
  48. {
  49. unsigned int len = d.length();
  50. UChar *dat = new UChar[len];
  51. memcpy(dat, d.unicode(), len * sizeof(UChar));
  52. rep = UString::Rep::create(dat, len);
  53. }
  54. TQString UString::qstring() const
  55. {
  56. return TQString((TQChar*) data(), size());
  57. }
  58. TQConstString UString::qconststring() const
  59. {
  60. return TQConstString((TQChar*) data(), size());
  61. }
  62. //BEGIN global methods
  63. class KateJSGlobalFunctions : public ObjectImp
  64. {
  65. public:
  66. KateJSGlobalFunctions(int i, int length);
  67. virtual bool implementsCall() const { return true; }
  68. virtual Value call(ExecState *exec, Object &thisObj, const List &args);
  69. enum {
  70. Debug
  71. };
  72. private:
  73. int id;
  74. };
  75. KateJSGlobalFunctions::KateJSGlobalFunctions(int i, int length) : ObjectImp(), id(i)
  76. {
  77. putDirect(lengthPropertyName,length,DontDelete|ReadOnly|DontEnum);
  78. }
  79. Value KateJSGlobalFunctions::call(ExecState *exec, Object &/*thisObj*/, const List &args)
  80. {
  81. switch (id) {
  82. case Debug:
  83. tqDebug("Kate (KJS Scripting): %s", args[0].toString(exec).ascii());
  84. return Undefined();
  85. default:
  86. break;
  87. }
  88. return Undefined();
  89. }
  90. //END global methods
  91. } // namespace KJS
  92. //BEGIN JS API STUFF
  93. class KateJSGlobal : public KJS::ObjectImp {
  94. public:
  95. virtual KJS::UString className() const { return "global"; }
  96. };
  97. class KateJSDocument : public KJS::ObjectImp
  98. {
  99. public:
  100. KateJSDocument (KJS::ExecState *exec, KateDocument *_doc);
  101. KJS::Value get( KJS::ExecState *exec, const KJS::Identifier &propertyName) const;
  102. KJS::Value getValueProperty(KJS::ExecState *exec, int token) const;
  103. void put(KJS::ExecState *exec, const KJS::Identifier &propertyName, const KJS::Value& value, int attr = KJS::None);
  104. void putValueProperty(KJS::ExecState *exec, int token, const KJS::Value& value, int attr);
  105. const KJS::ClassInfo* classInfo() const { return &info; }
  106. enum { FullText,
  107. Text,
  108. TextLine,
  109. Lines,
  110. Length,
  111. LineLength,
  112. SetText,
  113. Clear,
  114. InsertText,
  115. RemoveText,
  116. InsertLine,
  117. RemoveLine,
  118. EditBegin,
  119. EditEnd,
  120. IndentWidth,
  121. IndentMode,
  122. SpaceIndent,
  123. MixedIndent,
  124. HighlightMode,
  125. IsInWord,
  126. CanBreakAt,
  127. CanComment,
  128. CommentMarker,
  129. CommentStart,
  130. CommentEnd,
  131. Attribute
  132. };
  133. public:
  134. KateDocument *doc;
  135. static const KJS::ClassInfo info;
  136. };
  137. class KateJSView : public KJS::ObjectImp
  138. {
  139. public:
  140. KateJSView (KJS::ExecState *exec, KateView *_view);
  141. KJS::Value get( KJS::ExecState *exec, const KJS::Identifier &propertyName) const;
  142. KJS::Value getValueProperty(KJS::ExecState *exec, int token) const;
  143. void put(KJS::ExecState *exec, const KJS::Identifier &propertyName, const KJS::Value& value, int attr = KJS::None);
  144. void putValueProperty(KJS::ExecState *exec, int token, const KJS::Value& value, int attr);
  145. const KJS::ClassInfo* classInfo() const { return &info; }
  146. enum { CursorLine,
  147. CursorColumn,
  148. CursorColumnReal,
  149. SetCursorPosition,
  150. SetCursorPositionReal,
  151. Selection,
  152. HasSelection,
  153. SetSelection,
  154. RemoveSelectedText,
  155. SelectAll,
  156. ClearSelection,
  157. SelStartLine,
  158. SelStartCol,
  159. SelEndLine,
  160. SelEndCol
  161. };
  162. public:
  163. KateView *view;
  164. static const KJS::ClassInfo info;
  165. };
  166. class KateJSIndenter : public KJS::ObjectImp
  167. {
  168. public:
  169. KateJSIndenter (KJS::ExecState *exec);
  170. /*
  171. KJS::Value get( KJS::ExecState *exec, const KJS::Identifier &propertyName) const;
  172. KJS::Value getValueProperty(KJS::ExecState *exec, int token) const;
  173. void put(KJS::ExecState *exec, const KJS::Identifier &propertyName, const KJS::Value& value, int attr = KJS::None);
  174. void putValueProperty(KJS::ExecState *exec, int token, const KJS::Value& value, int attr);
  175. */
  176. const KJS::ClassInfo* classInfo() const { return &info; }
  177. enum { OnChar,
  178. OnLine,
  179. OnNewline,
  180. Dummy
  181. };
  182. public:
  183. static const KJS::ClassInfo info;
  184. };
  185. #include "katejscript.lut.h"
  186. //END
  187. KateJScript::KateJScript ()
  188. : m_global (new KJS::Object (new KateJSGlobal ()))
  189. , m_interpreter (new KJS::Interpreter (*m_global))
  190. , m_document (new KJS::Object(wrapDocument(m_interpreter->globalExec(), 0)))
  191. , m_view (new KJS::Object (wrapView(m_interpreter->globalExec(), 0)))
  192. {
  193. // put some stuff into env., this should stay for all executions, as we keep external
  194. // references to the inserted KJS::Objects, this should avoid any garbage collection
  195. m_interpreter->globalObject().put(m_interpreter->globalExec(), "document", *m_document);
  196. m_interpreter->globalObject().put(m_interpreter->globalExec(), "view", *m_view);
  197. m_interpreter->globalObject().put(m_interpreter->globalExec(), "debug",
  198. KJS::Object(new KateJSGlobalFunctions(KateJSGlobalFunctions::Debug,1)));
  199. }
  200. KateJScript::~KateJScript ()
  201. {
  202. delete m_view;
  203. delete m_document;
  204. delete m_interpreter;
  205. delete m_global;
  206. }
  207. KJS::ObjectImp *KateJScript::wrapDocument (KJS::ExecState *exec, KateDocument *doc)
  208. {
  209. return new KateJSDocument(exec, doc);
  210. }
  211. KJS::ObjectImp *KateJScript::wrapView (KJS::ExecState *exec, KateView *view)
  212. {
  213. return new KateJSView(exec, view);
  214. }
  215. bool KateJScript::execute (KateView *view, const TQString &script, TQString &errorMsg)
  216. {
  217. // no view, no fun
  218. if (!view)
  219. {
  220. errorMsg = i18n("Could not access view");
  221. return false;
  222. }
  223. // init doc & view with new pointers!
  224. static_cast<KateJSDocument *>( m_document->imp() )->doc = view->doc();
  225. static_cast<KateJSView *>( m_view->imp() )->view = view;
  226. // run the script for real
  227. KJS::Completion comp (m_interpreter->evaluate(script));
  228. if (comp.complType() == KJS::Throw)
  229. {
  230. KJS::ExecState *exec = m_interpreter->globalExec();
  231. KJS::Value exVal = comp.value();
  232. char *msg = exVal.toString(exec).ascii();
  233. int lineno = -1;
  234. if (exVal.type() == KJS::ObjectType)
  235. {
  236. KJS::Value lineVal = KJS::Object::dynamicCast(exVal).get(exec,"line");
  237. if (lineVal.type() == KJS::NumberType)
  238. lineno = int(lineVal.toNumber(exec));
  239. }
  240. errorMsg = i18n("Exception, line %1: %2").arg(lineno).arg(msg);
  241. return false;
  242. }
  243. return true;
  244. }
  245. //BEGIN KateJSDocument
  246. // -------------------------------------------------------------------------
  247. /* Source for KateJSDocumentProtoTable.
  248. @begin KateJSDocumentProtoTable 21
  249. #
  250. # edit interface stuff + editBegin/End, this is nice start
  251. #
  252. textFull KateJSDocument::FullText DontDelete|Function 0
  253. textRange KateJSDocument::Text DontDelete|Function 4
  254. textLine KateJSDocument::TextLine DontDelete|Function 1
  255. lines KateJSDocument::Lines DontDelete|Function 0
  256. length KateJSDocument::Length DontDelete|Function 0
  257. lineLength KateJSDocument::LineLength DontDelete|Function 1
  258. setText KateJSDocument::SetText DontDelete|Function 1
  259. clear KateJSDocument::Clear DontDelete|Function 0
  260. insertText KateJSDocument::InsertText DontDelete|Function 3
  261. removeText KateJSDocument::RemoveText DontDelete|Function 4
  262. insertLine KateJSDocument::InsertLine DontDelete|Function 2
  263. removeLine KateJSDocument::RemoveLine DontDelete|Function 1
  264. editBegin KateJSDocument::EditBegin DontDelete|Function 0
  265. editEnd KateJSDocument::EditEnd DontDelete|Function 0
  266. #
  267. # methods from highlight (and around)
  268. #
  269. isInWord KateJSDocument::IsInWord DontDelete|Function 2
  270. canBreakAt KateJSDocument::CanBreakAt DontDelete|Function 2
  271. canComment KateJSDocument::CanComment DontDelete|Function 2
  272. commentMarker KateJSDocument::CommentMarker DontDelete|Function 1
  273. commentStart KateJSDocument::CommentStart DontDelete|Function 1
  274. commentEnd KateJSDocument::CommentEnd DontDelete|Function 1
  275. attribute KateJSDocument::Attribute DontDelete|Function 2
  276. @end
  277. @begin KateJSDocumentTable 6
  278. #
  279. # Configuration properties
  280. #
  281. indentWidth KateJSDocument::IndentWidth DontDelete|ReadOnly
  282. indentMode KateJSDocument::IndentMode DontDelete|ReadOnly
  283. spaceIndent KateJSDocument::SpaceIndent DontDelete|ReadOnly
  284. mixedIndent KateJSDocument::MixedIndent DontDelete|ReadOnly
  285. highlightMode KateJSDocument::HighlightMode DontDelete|ReadOnly
  286. @end
  287. */
  288. DEFINE_PROTOTYPE("KateJSDocument",KateJSDocumentProto)
  289. IMPLEMENT_PROTOFUNC(KateJSDocumentProtoFunc)
  290. IMPLEMENT_PROTOTYPE(KateJSDocumentProto,KateJSDocumentProtoFunc)
  291. const KJS::ClassInfo KateJSDocument::info = { "KateJSDocument", 0, 0, 0 };
  292. KJS::Value KJS::KateJSDocumentProtoFunc::call(KJS::ExecState *exec, KJS::Object &thisObj, const KJS::List &args)
  293. {
  294. KJS_CHECK_THIS( KateJSDocument, thisObj );
  295. KateDocument *doc = static_cast<KateJSDocument *>( thisObj.imp() )->doc;
  296. if (!doc)
  297. return KJS::Undefined();
  298. switch (id)
  299. {
  300. case KateJSDocument::FullText:
  301. return KJS::String (doc->text());
  302. case KateJSDocument::Text:
  303. return KJS::String (doc->text(args[0].toUInt32(exec), args[1].toUInt32(exec), args[2].toUInt32(exec), args[3].toUInt32(exec)));
  304. case KateJSDocument::TextLine:
  305. return KJS::String (doc->textLine (args[0].toUInt32(exec)));
  306. case KateJSDocument::Lines:
  307. return KJS::Number (doc->numLines());
  308. case KateJSDocument::Length:
  309. return KJS::Number (doc->length());
  310. case KateJSDocument::LineLength:
  311. return KJS::Number (doc->lineLength(args[0].toUInt32(exec)));
  312. case KateJSDocument::SetText:
  313. return KJS::Boolean (doc->setText(args[0].toString(exec).qstring()));
  314. case KateJSDocument::Clear:
  315. return KJS::Boolean (doc->clear());
  316. case KateJSDocument::InsertText:
  317. return KJS::Boolean (doc->insertText (args[0].toUInt32(exec), args[1].toUInt32(exec), args[2].toString(exec).qstring()));
  318. case KateJSDocument::RemoveText:
  319. return KJS::Boolean (doc->removeText(args[0].toUInt32(exec), args[1].toUInt32(exec), args[2].toUInt32(exec), args[3].toUInt32(exec)));
  320. case KateJSDocument::InsertLine:
  321. return KJS::Boolean (doc->insertLine (args[0].toUInt32(exec), args[1].toString(exec).qstring()));
  322. case KateJSDocument::RemoveLine:
  323. return KJS::Boolean (doc->removeLine (args[0].toUInt32(exec)));
  324. case KateJSDocument::EditBegin:
  325. doc->editBegin();
  326. return KJS::Null ();
  327. case KateJSDocument::EditEnd:
  328. doc->editEnd ();
  329. return KJS::Null ();
  330. case KateJSDocument::IsInWord:
  331. return KJS::Boolean( doc->highlight()->isInWord( args[0].toString(exec).qstring().at(0), args[1].toUInt32(exec) ) );
  332. case KateJSDocument::CanBreakAt:
  333. return KJS::Boolean( doc->highlight()->canBreakAt( args[0].toString(exec).qstring().at(0), args[1].toUInt32(exec) ) );
  334. case KateJSDocument::CanComment:
  335. return KJS::Boolean( doc->highlight()->canComment( args[0].toUInt32(exec), args[1].toUInt32(exec) ) );
  336. case KateJSDocument::CommentMarker:
  337. return KJS::String( doc->highlight()->getCommentSingleLineStart( args[0].toUInt32(exec) ) );
  338. case KateJSDocument::CommentStart:
  339. return KJS::String( doc->highlight()->getCommentStart( args[0].toUInt32(exec) ) );
  340. case KateJSDocument::CommentEnd:
  341. return KJS::String( doc->highlight()->getCommentEnd( args[0].toUInt32(exec) ) );
  342. case KateJSDocument::Attribute:
  343. return KJS::Number( doc->kateTextLine(args[0].toUInt32(exec))->attribute(args[1].toUInt32(exec)) );
  344. }
  345. return KJS::Undefined();
  346. }
  347. KJS::Value KateJSDocument::get( KJS::ExecState *exec, const KJS::Identifier &propertyName) const
  348. {
  349. return KJS::lookupGetValue<KateJSDocument,KJS::ObjectImp>(exec, propertyName, &KateJSDocumentTable, this );
  350. }
  351. KJS::Value KateJSDocument::getValueProperty(KJS::ExecState *exec, int token) const
  352. {
  353. if (!doc)
  354. return KJS::Undefined ();
  355. switch (token) {
  356. case KateJSDocument::IndentWidth:
  357. return KJS::Number( doc->config()->indentationWidth() );
  358. case KateJSDocument::IndentMode:
  359. return KJS::String( KateAutoIndent::modeName( doc->config()->indentationMode() ) );
  360. case KateJSDocument::SpaceIndent:
  361. return KJS::Boolean( doc->config()->configFlags() & KateDocumentConfig::cfSpaceIndent );
  362. case KateJSDocument::MixedIndent:
  363. return KJS::Boolean( doc->config()->configFlags() & KateDocumentConfig::cfMixedIndent );
  364. case KateJSDocument::HighlightMode:
  365. return KJS::String( doc->hlModeName( doc->hlMode() ) );
  366. }
  367. return KJS::Undefined ();
  368. }
  369. void KateJSDocument::put(KJS::ExecState *exec, const KJS::Identifier &propertyName, const KJS::Value& value, int attr)
  370. {
  371. KJS::lookupPut<KateJSDocument,KJS::ObjectImp>(exec, propertyName, value, attr, &KateJSDocumentTable, this );
  372. }
  373. void KateJSDocument::putValueProperty(KJS::ExecState *exec, int token, const KJS::Value& value, int attr)
  374. {
  375. if (!doc)
  376. return;
  377. }
  378. KateJSDocument::KateJSDocument (KJS::ExecState *exec, KateDocument *_doc)
  379. : KJS::ObjectImp (KateJSDocumentProto::self(exec))
  380. , doc (_doc)
  381. {
  382. }
  383. //END
  384. //BEGIN KateJSView
  385. // -------------------------------------------------------------------------
  386. /* Source for KateJSViewProtoTable.
  387. @begin KateJSViewProtoTable 14
  388. cursorLine KateJSView::CursorLine DontDelete|Function 0
  389. cursorColumn KateJSView::CursorColumn DontDelete|Function 0
  390. cursorColumnReal KateJSView::CursorColumnReal DontDelete|Function 0
  391. setCursorPosition KateJSView::SetCursorPosition DontDelete|Function 2
  392. setCursorPositionReal KateJSView::SetCursorPositionReal DontDelete|Function 2
  393. selection KateJSView::Selection DontDelete|Function 0
  394. hasSelection KateJSView::HasSelection DontDelete|Function 0
  395. setSelection KateJSView::SetSelection DontDelete|Function 4
  396. removeSelectedText KateJSView::RemoveSelectedText DontDelete|Function 0
  397. selectAll KateJSView::SelectAll DontDelete|Function 0
  398. clearSelection KateJSView::ClearSelection DontDelete|Function 0
  399. @end
  400. */
  401. /* Source for KateJSViewTable.
  402. @begin KateJSViewTable 5
  403. selectionStartLine KateJSView::SelStartLine DontDelete|ReadOnly
  404. selectionStartColumn KateJSView::SelStartCol DontDelete|ReadOnly
  405. selectionEndLine KateJSView::SelEndLine DontDelete|ReadOnly
  406. selectionEndColumn KateJSView::SelEndCol DontDelete|ReadOnly
  407. @end
  408. */
  409. DEFINE_PROTOTYPE("KateJSView",KateJSViewProto)
  410. IMPLEMENT_PROTOFUNC(KateJSViewProtoFunc)
  411. IMPLEMENT_PROTOTYPE(KateJSViewProto,KateJSViewProtoFunc)
  412. const KJS::ClassInfo KateJSView::info = { "KateJSView", 0, &KateJSViewTable, 0 };
  413. KJS::Value KJS::KateJSViewProtoFunc::call(KJS::ExecState *exec, KJS::Object &thisObj, const KJS::List &args)
  414. {
  415. KJS_CHECK_THIS( KateJSView, thisObj );
  416. KateView *view = static_cast<KateJSView *>( thisObj.imp() )->view;
  417. if (!view)
  418. return KJS::Undefined();
  419. switch (id)
  420. {
  421. case KateJSView::CursorLine:
  422. return KJS::Number (view->cursorLine());
  423. case KateJSView::CursorColumn:
  424. return KJS::Number (view->cursorColumn());
  425. case KateJSView::CursorColumnReal:
  426. return KJS::Number (view->cursorColumnReal());
  427. case KateJSView::SetCursorPosition:
  428. return KJS::Boolean( view->setCursorPosition( args[0].toUInt32(exec), args[1].toUInt32(exec) ) );
  429. case KateJSView::SetCursorPositionReal:
  430. return KJS::Boolean( view->setCursorPositionReal( args[0].toUInt32(exec), args[1].toUInt32(exec) ) );
  431. // SelectionInterface goes in the view, in anticipation of the future
  432. case KateJSView::Selection:
  433. return KJS::String( view->selection() );
  434. case KateJSView::HasSelection:
  435. return KJS::Boolean( view->hasSelection() );
  436. case KateJSView::SetSelection:
  437. return KJS::Boolean( view->setSelection(args[0].toUInt32(exec),
  438. args[1].toUInt32(exec),
  439. args[2].toUInt32(exec),
  440. args[3].toUInt32(exec)) );
  441. case KateJSView::RemoveSelectedText:
  442. return KJS::Boolean( view->removeSelectedText() );
  443. case KateJSView::SelectAll:
  444. return KJS::Boolean( view->selectAll() );
  445. case KateJSView::ClearSelection:
  446. return KJS::Boolean( view->clearSelection() );
  447. }
  448. return KJS::Undefined();
  449. }
  450. KateJSView::KateJSView (KJS::ExecState *exec, KateView *_view)
  451. : KJS::ObjectImp (KateJSViewProto::self(exec))
  452. , view (_view)
  453. {
  454. }
  455. KJS::Value KateJSView::get( KJS::ExecState *exec, const KJS::Identifier &propertyName) const
  456. {
  457. return KJS::lookupGetValue<KateJSView,KJS::ObjectImp>(exec, propertyName, &KateJSViewTable, this );
  458. }
  459. KJS::Value KateJSView::getValueProperty(KJS::ExecState *exec, int token) const
  460. {
  461. if (!view)
  462. return KJS::Undefined ();
  463. switch (token) {
  464. case KateJSView::SelStartLine:
  465. return KJS::Number( view->selStartLine() );
  466. case KateJSView::SelStartCol:
  467. return KJS::Number( view->selStartCol() );
  468. case KateJSView::SelEndLine:
  469. return KJS::Number( view->selEndLine() );
  470. case KateJSView::SelEndCol:
  471. return KJS::Number( view->selEndCol() );
  472. }
  473. return KJS::Undefined ();
  474. }
  475. void KateJSView::put(KJS::ExecState *exec, const KJS::Identifier &propertyName, const KJS::Value& value, int attr)
  476. {
  477. KJS::lookupPut<KateJSView,KJS::ObjectImp>(exec, propertyName, value, attr, &KateJSViewTable, this );
  478. }
  479. void KateJSView::putValueProperty(KJS::ExecState *exec, int token, const KJS::Value& value, int attr)
  480. {
  481. if (!view)
  482. return;
  483. }
  484. //END
  485. //BEGIN KateJScriptManager
  486. KateJScriptManager::KateJScriptManager ()
  487. {
  488. m_scripts.setAutoDelete (true);
  489. collectScripts ();
  490. }
  491. KateJScriptManager::~KateJScriptManager ()
  492. {
  493. }
  494. void KateJScriptManager::collectScripts (bool force)
  495. {
  496. // If there's something in myModeList the Mode List was already built so, don't do it again
  497. if (!m_scripts.isEmpty())
  498. return;
  499. // We'll store the scripts list in this config
  500. TDEConfig config("katepartjscriptrc", false, false);
  501. // figure out if the kate install is too new
  502. config.setGroup ("General");
  503. if (config.readNumEntry ("Version") > config.readNumEntry ("CachedVersion"))
  504. {
  505. config.writeEntry ("CachedVersion", config.readNumEntry ("Version"));
  506. force = true;
  507. }
  508. // Let's get a list of all the .js files
  509. TQStringList list = TDEGlobal::dirs()->findAllResources("data","katepart/scripts/*.js",false,true);
  510. // Let's iterate through the list and build the Mode List
  511. for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it )
  512. {
  513. // Each file has a group called:
  514. TQString Group="Cache "+ *it;
  515. // Let's go to this group
  516. config.setGroup(Group);
  517. // stat the file
  518. struct stat sbuf;
  519. memset (&sbuf, 0, sizeof(sbuf));
  520. stat(TQFile::encodeName(*it), &sbuf);
  521. // If the group exist and we're not forced to read the .js file, let's build myModeList for katepartjscriptrc
  522. if (!force && config.hasGroup(Group) && (sbuf.st_mtime == config.readNumEntry("lastModified")))
  523. {
  524. }
  525. else
  526. {
  527. kdDebug (13050) << "add script: " << *it << endl;
  528. TQString desktopFile = (*it).left((*it).length()-2).append ("desktop");
  529. kdDebug (13050) << "add script (desktop file): " << desktopFile << endl;
  530. TQFileInfo dfi (desktopFile);
  531. if (dfi.exists())
  532. {
  533. TDEConfig df (desktopFile, true, false);
  534. df.setDesktopGroup ();
  535. // get cmdname, fallback to baseName, if it is empty, therefor not use the tdeconfig fallback
  536. TQString cmdname = df.readEntry ("X-Kate-Command");
  537. if (cmdname.isEmpty())
  538. {
  539. TQFileInfo fi (*it);
  540. cmdname = fi.baseName();
  541. }
  542. if (m_scripts[cmdname])
  543. continue;
  544. KateJScriptManager::Script *s = new KateJScriptManager::Script ();
  545. s->name = cmdname;
  546. s->filename = *it;
  547. s->desktopFileExists = true;
  548. m_scripts.insert (s->name, s);
  549. }
  550. else // no desktop file around, fall back to scriptfilename == commandname
  551. {
  552. kdDebug (13050) << "add script: fallback, no desktop file around!" << endl;
  553. TQFileInfo fi (*it);
  554. if (m_scripts[fi.baseName()])
  555. continue;
  556. KateJScriptManager::Script *s = new KateJScriptManager::Script ();
  557. s->name = fi.baseName();
  558. s->filename = *it;
  559. s->desktopFileExists = false;
  560. m_scripts.insert (s->name, s);
  561. }
  562. }
  563. }
  564. // Syncronize with the file katepartjscriptrc
  565. config.sync();
  566. }
  567. bool KateJScriptManager::exec( Kate::View *view, const TQString &_cmd, TQString &errorMsg )
  568. {
  569. // cast it hardcore, we know that it is really a kateview :)
  570. KateView *v = (KateView*) view;
  571. if ( !v )
  572. {
  573. errorMsg = i18n("Could not access view");
  574. return false;
  575. }
  576. //create a list of args
  577. TQStringList args( TQStringList::split( TQRegExp("\\s+"), _cmd ) );
  578. TQString cmd ( args.first() );
  579. args.remove( args.first() );
  580. kdDebug(13050) << "try to exec: " << cmd << endl;
  581. if (!m_scripts[cmd])
  582. {
  583. errorMsg = i18n("Command not found");
  584. return false;
  585. }
  586. TQFile file (m_scripts[cmd]->filename);
  587. if ( !file.open( IO_ReadOnly ) )
  588. {
  589. errorMsg = i18n("JavaScript file not found");
  590. return false;
  591. }
  592. TQTextStream stream( &file );
  593. stream.setEncoding (TQTextStream::UnicodeUTF8);
  594. TQString source = stream.read ();
  595. file.close();
  596. return KateFactory::self()->jscript()->execute(v, source, errorMsg);
  597. }
  598. bool KateJScriptManager::help( Kate::View *, const TQString &cmd, TQString &msg )
  599. {
  600. if (!m_scripts[cmd] || !m_scripts[cmd]->desktopFileExists)
  601. return false;
  602. TDEConfig df (m_scripts[cmd]->desktopFilename(), true, false);
  603. df.setDesktopGroup ();
  604. msg = df.readEntry ("X-Kate-Help");
  605. if (msg.isEmpty())
  606. return false;
  607. return true;
  608. }
  609. TQStringList KateJScriptManager::cmds()
  610. {
  611. TQStringList l;
  612. TQDictIterator<KateJScriptManager::Script> it( m_scripts );
  613. for( ; it.current(); ++it )
  614. l << it.current()->name;
  615. return l;
  616. }
  617. //END
  618. //BEGIN KateJSIndenter
  619. // -------------------------------------------------------------------------
  620. /* Source for KateJSIndenterProtoTable.
  621. @begin KateJSIndenterProtoTable 1
  622. Dummy KateJSIndenter::Dummy DontDelete
  623. @end
  624. */
  625. /* Source for KateJSIndenterTable.
  626. @begin KateJSIndenterTable 3
  627. onchar KateJSIndenter::OnChar DontDelete
  628. onnewline KateJSIndenter::OnNewline DontDelete
  629. online KateJSIndenter::OnLine DontDelete
  630. @end
  631. */
  632. KateJSIndenter::KateJSIndenter (KJS::ExecState *exec)
  633. : KJS::ObjectImp (KateJSViewProto::self(exec))
  634. {
  635. }
  636. DEFINE_PROTOTYPE("KateJSIndenter",KateJSIndenterProto)
  637. IMPLEMENT_PROTOFUNC(KateJSIndenterProtoFunc)
  638. IMPLEMENT_PROTOTYPE(KateJSIndenterProto,KateJSIndenterProtoFunc)
  639. const KJS::ClassInfo KateJSIndenter::info = { "KateJSIndenter", 0, &KateJSIndenterTable, 0 };
  640. KJS::Value KJS::KateJSIndenterProtoFunc::call(KJS::ExecState *exec, KJS::Object &thisObj, const KJS::List &args)
  641. {
  642. KJS_CHECK_THIS( KateJSIndenter, thisObj );
  643. return KJS::Undefined();
  644. }
  645. //END
  646. //BEGIN KateIndentJScriptImpl
  647. KateIndentJScriptImpl::KateIndentJScriptImpl(const TQString& internalName,
  648. const TQString &filePath, const TQString &niceName,
  649. const TQString &copyright, double version):
  650. KateIndentScriptImplAbstract(internalName,filePath,niceName,copyright,version),m_interpreter(0),m_indenter(0)
  651. {
  652. }
  653. KateIndentJScriptImpl::~KateIndentJScriptImpl()
  654. {
  655. deleteInterpreter();
  656. }
  657. void KateIndentJScriptImpl::decRef()
  658. {
  659. KateIndentScriptImplAbstract::decRef();
  660. if (refCount()==0)
  661. {
  662. deleteInterpreter();
  663. }
  664. }
  665. void KateIndentJScriptImpl::deleteInterpreter()
  666. {
  667. m_docWrapper=0;
  668. m_viewWrapper=0;
  669. delete m_indenter;
  670. m_indenter=0;
  671. delete m_interpreter;
  672. m_interpreter=0;
  673. }
  674. bool KateIndentJScriptImpl::setupInterpreter(TQString &errorMsg)
  675. {
  676. if (!m_interpreter)
  677. {
  678. kdDebug(13050)<<"Setting up interpreter"<<endl;
  679. m_interpreter=new KJS::Interpreter(KJS::Object(new KateJSGlobal()));
  680. m_docWrapper=new KateJSDocument(m_interpreter->globalExec(),0);
  681. m_viewWrapper=new KateJSView(m_interpreter->globalExec(),0);
  682. m_indenter=new KJS::Object(new KateJSIndenter(m_interpreter->globalExec()));
  683. m_interpreter->globalObject().put(m_interpreter->globalExec(),"document",KJS::Object(m_docWrapper),KJS::DontDelete | KJS::ReadOnly);
  684. m_interpreter->globalObject().put(m_interpreter->globalExec(),"view",KJS::Object(m_viewWrapper),KJS::DontDelete | KJS::ReadOnly);
  685. m_interpreter->globalObject().put(m_interpreter->globalExec(),"debug", KJS::Object(new
  686. KateJSGlobalFunctions(KateJSGlobalFunctions::Debug,1)));
  687. m_interpreter->globalObject().put(m_interpreter->globalExec(),"indenter",*m_indenter,KJS::DontDelete | KJS::ReadOnly);
  688. TQFile file (filePath());
  689. if ( !file.open( IO_ReadOnly ) )
  690. {
  691. errorMsg = i18n("JavaScript file not found");
  692. deleteInterpreter();
  693. return false;
  694. }
  695. TQTextStream stream( &file );
  696. stream.setEncoding (TQTextStream::UnicodeUTF8);
  697. TQString source = stream.read ();
  698. file.close();
  699. KJS::Completion comp (m_interpreter->evaluate(source));
  700. if (comp.complType() == KJS::Throw)
  701. {
  702. KJS::ExecState *exec = m_interpreter->globalExec();
  703. KJS::Value exVal = comp.value();
  704. char *msg = exVal.toString(exec).ascii();
  705. int lineno = -1;
  706. if (exVal.type() == KJS::ObjectType)
  707. {
  708. KJS::Value lineVal = KJS::Object::dynamicCast(exVal).get(exec,"line");
  709. if (lineVal.type() == KJS::NumberType)
  710. lineno = int(lineVal.toNumber(exec));
  711. }
  712. errorMsg = i18n("Exception, line %1: %2").arg(lineno).arg(msg);
  713. deleteInterpreter();
  714. return false;
  715. } else {
  716. return true;
  717. }
  718. } else return true;
  719. }
  720. inline static bool KateIndentJScriptCall(Kate::View *view, TQString &errorMsg, KateJSDocument *docWrapper, KateJSView *viewWrapper,
  721. KJS::Interpreter *interpreter, KJS::Object lookupobj,const KJS::Identifier& func,KJS::List params)
  722. {
  723. // no view, no fun
  724. if (!view)
  725. {
  726. errorMsg = i18n("Could not access view");
  727. return false;
  728. }
  729. KateView *v=(KateView*)view;
  730. KJS::Object o=lookupobj.get(interpreter->globalExec(),func).toObject(interpreter->globalExec());
  731. if (interpreter->globalExec()->hadException())
  732. {
  733. errorMsg=interpreter->globalExec()->exception().toString(interpreter->globalExec()).qstring();
  734. kdDebug(13050)<<"Exception(1):"<<errorMsg<<endl;
  735. interpreter->globalExec()->clearException();
  736. return false;
  737. }
  738. // init doc & view with new pointers!
  739. docWrapper->doc = v->doc();
  740. viewWrapper->view = v;
  741. /*kdDebug(13050)<<"Call Object:"<<o.toString(interpreter->globalExec()).ascii()<<endl;*/
  742. o.call(interpreter->globalExec(),interpreter->globalObject(),params);
  743. if (interpreter->globalExec()->hadException())
  744. {
  745. errorMsg=interpreter->globalExec()->exception().toString(interpreter->globalExec()).ascii();
  746. kdDebug(13050)<<"Exception(2):"<<errorMsg<<endl;
  747. interpreter->globalExec()->clearException();
  748. return false;
  749. }
  750. return true;
  751. }
  752. bool KateIndentJScriptImpl::processChar(Kate::View *view, TQChar c, TQString &errorMsg )
  753. {
  754. kdDebug(13050)<<"KateIndentJScriptImpl::processChar"<<endl;
  755. if (!setupInterpreter(errorMsg)) return false;
  756. KJS::List params;
  757. params.append(KJS::String(TQString(c)));
  758. return KateIndentJScriptCall(view,errorMsg,m_docWrapper,m_viewWrapper,m_interpreter,*m_indenter,KJS::Identifier("onchar"),params);
  759. }
  760. bool KateIndentJScriptImpl::processLine(Kate::View *view, const KateDocCursor &line, TQString &errorMsg )
  761. {
  762. kdDebug(13050)<<"KateIndentJScriptImpl::processLine"<<endl;
  763. if (!setupInterpreter(errorMsg)) return false;
  764. return KateIndentJScriptCall(view,errorMsg,m_docWrapper,m_viewWrapper,m_interpreter,*m_indenter,KJS::Identifier("online"),KJS::List());
  765. }
  766. bool KateIndentJScriptImpl::processNewline( class Kate::View *view, const KateDocCursor &begin, bool needcontinue, TQString &errorMsg )
  767. {
  768. kdDebug(13050)<<"KateIndentJScriptImpl::processNewline"<<endl;
  769. if (!setupInterpreter(errorMsg)) return false;
  770. return KateIndentJScriptCall(view,errorMsg,m_docWrapper,m_viewWrapper,m_interpreter,*m_indenter,KJS::Identifier("onnewline"),KJS::List());
  771. }
  772. //END
  773. //BEGIN KateIndentJScriptManager
  774. KateIndentJScriptManager::KateIndentJScriptManager():KateIndentScriptManagerAbstract()
  775. {
  776. m_scripts.setAutoDelete (true);
  777. collectScripts ();
  778. }
  779. KateIndentJScriptManager::~KateIndentJScriptManager ()
  780. {
  781. }
  782. void KateIndentJScriptManager::collectScripts (bool force)
  783. {
  784. // If there's something in myModeList the Mode List was already built so, don't do it again
  785. if (!m_scripts.isEmpty())
  786. return;
  787. // We'll store the scripts list in this config
  788. TDEConfig config("katepartindentjscriptrc", false, false);
  789. #if 0
  790. // figure out if the kate install is too new
  791. config.setGroup ("General");
  792. if (config.readNumEntry ("Version") > config.readNumEntry ("CachedVersion"))
  793. {
  794. config.writeEntry ("CachedVersion", config.readNumEntry ("Version"));
  795. force = true;
  796. }
  797. #endif
  798. // Let's get a list of all the .js files
  799. TQStringList list = TDEGlobal::dirs()->findAllResources("data","katepart/scripts/indent/*.js",false,true);
  800. // Let's iterate through the list and build the Mode List
  801. for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it )
  802. {
  803. // Each file has a group ed:
  804. TQString Group="Cache "+ *it;
  805. // Let's go to this group
  806. config.setGroup(Group);
  807. // stat the file
  808. struct stat sbuf;
  809. memset (&sbuf, 0, sizeof(sbuf));
  810. stat(TQFile::encodeName(*it), &sbuf);
  811. // If the group exist and we're not forced to read the .js file, let's build myModeList for katepartjscriptrc
  812. bool readnew=false;
  813. if (!force && config.hasGroup(Group) && (sbuf.st_mtime == config.readNumEntry("lastModified")))
  814. {
  815. config.setGroup(Group);
  816. TQString filePath=*it;
  817. TQString internalName=config.readEntry("internlName","KATE-ERROR");
  818. if (internalName=="KATE-ERROR") readnew=true;
  819. else
  820. {
  821. TQString niceName=config.readEntry("niceName",internalName);
  822. TQString copyright=config.readEntry("copyright",i18n("(Unknown)"));
  823. double version=config.readDoubleNumEntry("version",0.0);
  824. KateIndentJScriptImpl *s=new KateIndentJScriptImpl(
  825. internalName,filePath,niceName,copyright,version);
  826. m_scripts.insert (internalName, s);
  827. }
  828. }
  829. else readnew=true;
  830. if (readnew)
  831. {
  832. TQFileInfo fi (*it);
  833. if (m_scripts[fi.baseName()])
  834. continue;
  835. TQString internalName=fi.baseName();
  836. TQString filePath=*it;
  837. TQString niceName=internalName;
  838. TQString copyright=i18n("(Unknown)");
  839. double version=0.0;
  840. parseScriptHeader(filePath,&niceName,&copyright,&version);
  841. /*save the information for retrieval*/
  842. config.setGroup(Group);
  843. config.writeEntry("lastModified",sbuf.st_mtime);
  844. config.writeEntry("internalName",internalName);
  845. config.writeEntry("niceName",niceName);
  846. config.writeEntry("copyright",copyright);
  847. config.writeEntry("version",version);
  848. KateIndentJScriptImpl *s=new KateIndentJScriptImpl(
  849. internalName,filePath,niceName,copyright,version);
  850. m_scripts.insert (internalName, s);
  851. }
  852. }
  853. // Syncronize with the file katepartjscriptrc
  854. config.sync();
  855. }
  856. KateIndentScript KateIndentJScriptManager::script(const TQString &scriptname) {
  857. KateIndentJScriptImpl *s=m_scripts[scriptname];
  858. kdDebug(13050)<<scriptname<<"=="<<s<<endl;
  859. return KateIndentScript(s);
  860. }
  861. void KateIndentJScriptManager::parseScriptHeader(const TQString &filePath,
  862. TQString *niceName,TQString *copyright,double *version)
  863. {
  864. TQFile f(TQFile::encodeName(filePath));
  865. if (!f.open(IO_ReadOnly) ) {
  866. kdDebug(13050)<<"Header could not be parsed, because file could not be opened"<<endl;
  867. return;
  868. }
  869. TQTextStream st(&f);
  870. st.setEncoding (TQTextStream::UnicodeUTF8);
  871. if (!st.readLine().upper().startsWith("/**KATE")) {
  872. kdDebug(13050)<<"No header found"<<endl;
  873. f.close();
  874. return;
  875. }
  876. // here the real parsing begins
  877. kdDebug(13050)<<"Parsing indent script header"<<endl;
  878. enum {NOTHING=0,COPYRIGHT=1} currentState=NOTHING;
  879. TQString line;
  880. TQString tmpblockdata="";
  881. TQRegExp endExpr("[\\s\\t]*\\*\\*\\/[\\s\\t]*$");
  882. TQRegExp keyValue("[\\s\\t]*\\*\\s*(.+):(.*)$");
  883. TQRegExp blockContent("[\\s\\t]*\\*(.*)$");
  884. while ((line=st.readLine())!=TQString::null) {
  885. if (endExpr.exactMatch(line)) {
  886. kdDebug(13050)<<"end of config block"<<endl;
  887. if (currentState==NOTHING) break;
  888. if (currentState==COPYRIGHT) {
  889. *copyright=tmpblockdata;
  890. break;
  891. }
  892. Q_ASSERT(0);
  893. }
  894. if (currentState==NOTHING)
  895. {
  896. if (keyValue.exactMatch(line)) {
  897. TQStringList sl=keyValue.capturedTexts();
  898. kdDebug(13050)<<"key:"<<sl[1]<<endl<<"value:"<<sl[2]<<endl;
  899. kdDebug(13050)<<"key-length:"<<sl[1].length()<<endl<<"value-length:"<<sl[2].length()<<endl;
  900. TQString key=sl[1];
  901. TQString value=sl[2];
  902. if (key=="NAME") (*niceName)=value.stripWhiteSpace();
  903. else if (key=="VERSION") (*version)=value.stripWhiteSpace().toDouble(0);
  904. else if (key=="COPYRIGHT")
  905. {
  906. tmpblockdata="";
  907. if (value.stripWhiteSpace().length()>0) tmpblockdata=value;
  908. currentState=COPYRIGHT;
  909. } else kdDebug(13050)<<"ignoring key"<<endl;
  910. }
  911. } else {
  912. if (blockContent.exactMatch(line))
  913. {
  914. TQString bl=blockContent.capturedTexts()[1];
  915. //kdDebug(13050)<<"block content line:"<<bl<<endl<<bl.length()<<" "<<bl.isEmpty()<<endl;
  916. if (bl.isEmpty())
  917. {
  918. (*copyright)=tmpblockdata;
  919. kdDebug(13050)<<"Copyright block:"<<endl<<(*copyright)<<endl;
  920. currentState=NOTHING;
  921. } else tmpblockdata=tmpblockdata+"\n"+bl;
  922. }
  923. }
  924. }
  925. f.close();
  926. }
  927. //END
  928. // kate: space-indent on; indent-width 2; replace-tabs on;