script_text_editor.cpp 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700
  1. /**************************************************************************/
  2. /* script_text_editor.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "script_text_editor.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/json.h"
  33. #include "core/math/expression.h"
  34. #include "core/os/keyboard.h"
  35. #include "editor/debugger/editor_debugger_node.h"
  36. #include "editor/editor_command_palette.h"
  37. #include "editor/editor_help.h"
  38. #include "editor/editor_node.h"
  39. #include "editor/editor_settings.h"
  40. #include "editor/editor_string_names.h"
  41. #include "editor/gui/editor_toaster.h"
  42. #include "editor/plugins/editor_context_menu_plugin.h"
  43. #include "editor/themes/editor_scale.h"
  44. #include "scene/gui/menu_button.h"
  45. #include "scene/gui/rich_text_label.h"
  46. #include "scene/gui/split_container.h"
  47. void ConnectionInfoDialog::ok_pressed() {
  48. }
  49. void ConnectionInfoDialog::popup_connections(const String &p_method, const Vector<Node *> &p_nodes) {
  50. method->set_text(p_method);
  51. tree->clear();
  52. TreeItem *root = tree->create_item();
  53. for (int i = 0; i < p_nodes.size(); i++) {
  54. List<Connection> all_connections;
  55. p_nodes[i]->get_signals_connected_to_this(&all_connections);
  56. for (const Connection &connection : all_connections) {
  57. if (connection.callable.get_method() != p_method) {
  58. continue;
  59. }
  60. TreeItem *node_item = tree->create_item(root);
  61. node_item->set_text(0, Object::cast_to<Node>(connection.signal.get_object())->get_name());
  62. node_item->set_icon(0, EditorNode::get_singleton()->get_object_icon(connection.signal.get_object(), "Node"));
  63. node_item->set_selectable(0, false);
  64. node_item->set_editable(0, false);
  65. node_item->set_text(1, connection.signal.get_name());
  66. Control *p = Object::cast_to<Control>(get_parent());
  67. node_item->set_icon(1, p->get_editor_theme_icon(SNAME("Slot")));
  68. node_item->set_selectable(1, false);
  69. node_item->set_editable(1, false);
  70. node_item->set_text(2, Object::cast_to<Node>(connection.callable.get_object())->get_name());
  71. node_item->set_icon(2, EditorNode::get_singleton()->get_object_icon(connection.callable.get_object(), "Node"));
  72. node_item->set_selectable(2, false);
  73. node_item->set_editable(2, false);
  74. }
  75. }
  76. popup_centered(Size2(600, 300) * EDSCALE);
  77. }
  78. ConnectionInfoDialog::ConnectionInfoDialog() {
  79. set_title(TTR("Connections to method:"));
  80. VBoxContainer *vbc = memnew(VBoxContainer);
  81. vbc->set_anchor_and_offset(SIDE_LEFT, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  82. vbc->set_anchor_and_offset(SIDE_TOP, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  83. vbc->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -8 * EDSCALE);
  84. vbc->set_anchor_and_offset(SIDE_BOTTOM, Control::ANCHOR_END, -8 * EDSCALE);
  85. add_child(vbc);
  86. method = memnew(Label);
  87. method->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  88. vbc->add_child(method);
  89. tree = memnew(Tree);
  90. tree->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  91. tree->set_columns(3);
  92. tree->set_hide_root(true);
  93. tree->set_column_titles_visible(true);
  94. tree->set_column_title(0, TTR("Source"));
  95. tree->set_column_title(1, TTR("Signal"));
  96. tree->set_column_title(2, TTR("Target"));
  97. vbc->add_child(tree);
  98. tree->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  99. tree->set_allow_rmb_select(true);
  100. }
  101. ////////////////////////////////////////////////////////////////////////////////
  102. Vector<String> ScriptTextEditor::get_functions() {
  103. CodeEdit *te = code_editor->get_text_editor();
  104. String text = te->get_text();
  105. List<String> fnc;
  106. if (script->get_language()->validate(text, script->get_path(), &fnc)) {
  107. //if valid rewrite functions to latest
  108. functions.clear();
  109. for (const String &E : fnc) {
  110. functions.push_back(E);
  111. }
  112. }
  113. return functions;
  114. }
  115. void ScriptTextEditor::apply_code() {
  116. if (script.is_null()) {
  117. return;
  118. }
  119. script->set_source_code(code_editor->get_text_editor()->get_text());
  120. script->update_exports();
  121. code_editor->get_text_editor()->get_syntax_highlighter()->update_cache();
  122. }
  123. Ref<Resource> ScriptTextEditor::get_edited_resource() const {
  124. return script;
  125. }
  126. void ScriptTextEditor::set_edited_resource(const Ref<Resource> &p_res) {
  127. ERR_FAIL_COND(script.is_valid());
  128. ERR_FAIL_COND(p_res.is_null());
  129. script = p_res;
  130. code_editor->get_text_editor()->set_text(script->get_source_code());
  131. code_editor->get_text_editor()->clear_undo_history();
  132. code_editor->get_text_editor()->tag_saved_version();
  133. emit_signal(SNAME("name_changed"));
  134. code_editor->update_line_and_column();
  135. }
  136. void ScriptTextEditor::enable_editor(Control *p_shortcut_context) {
  137. if (editor_enabled) {
  138. return;
  139. }
  140. editor_enabled = true;
  141. _enable_code_editor();
  142. _validate_script();
  143. if (p_shortcut_context) {
  144. for (int i = 0; i < edit_hb->get_child_count(); ++i) {
  145. Control *c = cast_to<Control>(edit_hb->get_child(i));
  146. if (c) {
  147. c->set_shortcut_context(p_shortcut_context);
  148. }
  149. }
  150. }
  151. }
  152. void ScriptTextEditor::_load_theme_settings() {
  153. CodeEdit *text_edit = code_editor->get_text_editor();
  154. Color updated_warning_line_color = EDITOR_GET("text_editor/theme/highlighting/warning_color");
  155. Color updated_marked_line_color = EDITOR_GET("text_editor/theme/highlighting/mark_color");
  156. Color updated_safe_line_number_color = EDITOR_GET("text_editor/theme/highlighting/safe_line_number_color");
  157. Color updated_folded_code_region_color = EDITOR_GET("text_editor/theme/highlighting/folded_code_region_color");
  158. bool warning_line_color_updated = updated_warning_line_color != warning_line_color;
  159. bool marked_line_color_updated = updated_marked_line_color != marked_line_color;
  160. bool safe_line_number_color_updated = updated_safe_line_number_color != safe_line_number_color;
  161. bool folded_code_region_color_updated = updated_folded_code_region_color != folded_code_region_color;
  162. if (safe_line_number_color_updated || warning_line_color_updated || marked_line_color_updated || folded_code_region_color_updated) {
  163. safe_line_number_color = updated_safe_line_number_color;
  164. for (int i = 0; i < text_edit->get_line_count(); i++) {
  165. if (warning_line_color_updated && text_edit->get_line_background_color(i) == warning_line_color) {
  166. text_edit->set_line_background_color(i, updated_warning_line_color);
  167. }
  168. if (marked_line_color_updated && text_edit->get_line_background_color(i) == marked_line_color) {
  169. text_edit->set_line_background_color(i, updated_marked_line_color);
  170. }
  171. if (safe_line_number_color_updated && text_edit->get_line_gutter_item_color(i, line_number_gutter) != default_line_number_color) {
  172. text_edit->set_line_gutter_item_color(i, line_number_gutter, safe_line_number_color);
  173. }
  174. if (folded_code_region_color_updated && text_edit->get_line_background_color(i) == folded_code_region_color) {
  175. text_edit->set_line_background_color(i, updated_folded_code_region_color);
  176. }
  177. }
  178. warning_line_color = updated_warning_line_color;
  179. marked_line_color = updated_marked_line_color;
  180. folded_code_region_color = updated_folded_code_region_color;
  181. }
  182. theme_loaded = true;
  183. if (script.is_valid()) {
  184. _set_theme_for_script();
  185. }
  186. }
  187. void ScriptTextEditor::_set_theme_for_script() {
  188. if (!theme_loaded) {
  189. return;
  190. }
  191. CodeEdit *text_edit = code_editor->get_text_editor();
  192. text_edit->get_syntax_highlighter()->update_cache();
  193. List<String> strings;
  194. script->get_language()->get_string_delimiters(&strings);
  195. text_edit->clear_string_delimiters();
  196. for (const String &string : strings) {
  197. String beg = string.get_slicec(' ', 0);
  198. String end = string.get_slice_count(" ") > 1 ? string.get_slicec(' ', 1) : String();
  199. if (!text_edit->has_string_delimiter(beg)) {
  200. text_edit->add_string_delimiter(beg, end, end.is_empty());
  201. }
  202. if (!end.is_empty() && !text_edit->has_auto_brace_completion_open_key(beg)) {
  203. text_edit->add_auto_brace_completion_pair(beg, end);
  204. }
  205. }
  206. text_edit->clear_comment_delimiters();
  207. List<String> comments;
  208. script->get_language()->get_comment_delimiters(&comments);
  209. for (const String &comment : comments) {
  210. String beg = comment.get_slicec(' ', 0);
  211. String end = comment.get_slice_count(" ") > 1 ? comment.get_slicec(' ', 1) : String();
  212. text_edit->add_comment_delimiter(beg, end, end.is_empty());
  213. if (!end.is_empty() && !text_edit->has_auto_brace_completion_open_key(beg)) {
  214. text_edit->add_auto_brace_completion_pair(beg, end);
  215. }
  216. }
  217. List<String> doc_comments;
  218. script->get_language()->get_doc_comment_delimiters(&doc_comments);
  219. for (const String &doc_comment : doc_comments) {
  220. String beg = doc_comment.get_slicec(' ', 0);
  221. String end = doc_comment.get_slice_count(" ") > 1 ? doc_comment.get_slicec(' ', 1) : String();
  222. text_edit->add_comment_delimiter(beg, end, end.is_empty());
  223. if (!end.is_empty() && !text_edit->has_auto_brace_completion_open_key(beg)) {
  224. text_edit->add_auto_brace_completion_pair(beg, end);
  225. }
  226. }
  227. }
  228. void ScriptTextEditor::_show_errors_panel(bool p_show) {
  229. errors_panel->set_visible(p_show);
  230. }
  231. void ScriptTextEditor::_show_warnings_panel(bool p_show) {
  232. warnings_panel->set_visible(p_show);
  233. }
  234. void ScriptTextEditor::_warning_clicked(const Variant &p_line) {
  235. if (p_line.get_type() == Variant::INT) {
  236. goto_line_centered(p_line.operator int64_t());
  237. } else if (p_line.get_type() == Variant::DICTIONARY) {
  238. Dictionary meta = p_line.operator Dictionary();
  239. const int line = meta["line"].operator int64_t() - 1;
  240. const String code = meta["code"].operator String();
  241. const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\"";
  242. CodeEdit *text_editor = code_editor->get_text_editor();
  243. String prev_line = line > 0 ? text_editor->get_line(line - 1) : "";
  244. if (prev_line.contains("@warning_ignore")) {
  245. const int closing_bracket_idx = prev_line.find_char(')');
  246. const String text_to_insert = ", " + code.quote(quote_style);
  247. text_editor->insert_text(text_to_insert, line - 1, closing_bracket_idx);
  248. } else {
  249. const int indent = text_editor->get_indent_level(line) / text_editor->get_indent_size();
  250. String annotation_indent;
  251. if (!text_editor->is_indent_using_spaces()) {
  252. annotation_indent = String("\t").repeat(indent);
  253. } else {
  254. annotation_indent = String(" ").repeat(text_editor->get_indent_size() * indent);
  255. }
  256. text_editor->insert_line_at(line, annotation_indent + "@warning_ignore(" + code.quote(quote_style) + ")");
  257. }
  258. _validate_script();
  259. }
  260. }
  261. void ScriptTextEditor::_error_clicked(const Variant &p_line) {
  262. if (p_line.get_type() == Variant::INT) {
  263. goto_line_centered(p_line.operator int64_t());
  264. } else if (p_line.get_type() == Variant::DICTIONARY) {
  265. Dictionary meta = p_line.operator Dictionary();
  266. const String path = meta["path"].operator String();
  267. const int line = meta["line"].operator int64_t();
  268. const int column = meta["column"].operator int64_t();
  269. if (path.is_empty()) {
  270. goto_line_centered(line, column);
  271. } else {
  272. Ref<Resource> scr = ResourceLoader::load(path);
  273. if (scr.is_null()) {
  274. EditorNode::get_singleton()->show_warning(TTR("Could not load file at:") + "\n\n" + path, TTR("Error!"));
  275. } else {
  276. int corrected_column = column;
  277. const String line_text = code_editor->get_text_editor()->get_line(line);
  278. const int indent_size = code_editor->get_text_editor()->get_indent_size();
  279. if (indent_size > 1) {
  280. const int tab_count = line_text.length() - line_text.lstrip("\t").length();
  281. corrected_column -= tab_count * (indent_size - 1);
  282. }
  283. ScriptEditor::get_singleton()->edit(scr, line, corrected_column);
  284. }
  285. }
  286. }
  287. }
  288. void ScriptTextEditor::reload_text() {
  289. ERR_FAIL_COND(script.is_null());
  290. CodeEdit *te = code_editor->get_text_editor();
  291. int column = te->get_caret_column();
  292. int row = te->get_caret_line();
  293. int h = te->get_h_scroll();
  294. int v = te->get_v_scroll();
  295. te->set_text(script->get_source_code());
  296. te->set_caret_line(row);
  297. te->set_caret_column(column);
  298. te->set_h_scroll(h);
  299. te->set_v_scroll(v);
  300. te->tag_saved_version();
  301. code_editor->update_line_and_column();
  302. if (editor_enabled) {
  303. _validate_script();
  304. }
  305. }
  306. void ScriptTextEditor::add_callback(const String &p_function, const PackedStringArray &p_args) {
  307. ScriptLanguage *language = script->get_language();
  308. if (!language->can_make_function()) {
  309. return;
  310. }
  311. code_editor->get_text_editor()->begin_complex_operation();
  312. code_editor->get_text_editor()->remove_secondary_carets();
  313. code_editor->get_text_editor()->deselect();
  314. String code = code_editor->get_text_editor()->get_text();
  315. int pos = language->find_function(p_function, code);
  316. if (pos == -1) {
  317. // Function does not exist, create it at the end of the file.
  318. int last_line = code_editor->get_text_editor()->get_line_count() - 1;
  319. String func = language->make_function("", p_function, p_args);
  320. code_editor->get_text_editor()->insert_text("\n\n" + func, last_line, code_editor->get_text_editor()->get_line(last_line).length());
  321. pos = last_line + 3;
  322. }
  323. // Put caret on the line after the function, after the indent.
  324. int indent_column = 1;
  325. if (EDITOR_GET("text_editor/behavior/indent/type")) {
  326. indent_column = EDITOR_GET("text_editor/behavior/indent/size");
  327. }
  328. code_editor->get_text_editor()->set_caret_line(pos, true, true, -1);
  329. code_editor->get_text_editor()->set_caret_column(indent_column);
  330. code_editor->get_text_editor()->end_complex_operation();
  331. }
  332. bool ScriptTextEditor::show_members_overview() {
  333. return true;
  334. }
  335. void ScriptTextEditor::update_settings() {
  336. code_editor->get_text_editor()->set_gutter_draw(connection_gutter, EDITOR_GET("text_editor/appearance/gutters/show_info_gutter"));
  337. code_editor->update_editor_settings();
  338. }
  339. bool ScriptTextEditor::is_unsaved() {
  340. const bool unsaved =
  341. code_editor->get_text_editor()->get_version() != code_editor->get_text_editor()->get_saved_version() ||
  342. script->get_path().is_empty(); // In memory.
  343. return unsaved;
  344. }
  345. Variant ScriptTextEditor::get_edit_state() {
  346. return code_editor->get_edit_state();
  347. }
  348. void ScriptTextEditor::set_edit_state(const Variant &p_state) {
  349. code_editor->set_edit_state(p_state);
  350. Dictionary state = p_state;
  351. if (state.has("syntax_highlighter")) {
  352. int idx = highlighter_menu->get_item_idx_from_text(state["syntax_highlighter"]);
  353. if (idx >= 0) {
  354. _change_syntax_highlighter(idx);
  355. }
  356. }
  357. if (editor_enabled) {
  358. #ifndef ANDROID_ENABLED
  359. ensure_focus();
  360. #endif
  361. }
  362. }
  363. Variant ScriptTextEditor::get_navigation_state() {
  364. return code_editor->get_navigation_state();
  365. }
  366. Variant ScriptTextEditor::get_previous_state() {
  367. return code_editor->get_previous_state();
  368. }
  369. void ScriptTextEditor::store_previous_state() {
  370. return code_editor->store_previous_state();
  371. }
  372. void ScriptTextEditor::_convert_case(CodeTextEditor::CaseStyle p_case) {
  373. code_editor->convert_case(p_case);
  374. }
  375. void ScriptTextEditor::trim_trailing_whitespace() {
  376. code_editor->trim_trailing_whitespace();
  377. }
  378. void ScriptTextEditor::trim_final_newlines() {
  379. code_editor->trim_final_newlines();
  380. }
  381. void ScriptTextEditor::insert_final_newline() {
  382. code_editor->insert_final_newline();
  383. }
  384. void ScriptTextEditor::convert_indent() {
  385. code_editor->get_text_editor()->convert_indent();
  386. }
  387. void ScriptTextEditor::tag_saved_version() {
  388. code_editor->get_text_editor()->tag_saved_version();
  389. edited_file_data.last_modified_time = FileAccess::get_modified_time(edited_file_data.path);
  390. }
  391. void ScriptTextEditor::goto_line(int p_line, int p_column) {
  392. code_editor->goto_line(p_line, p_column);
  393. }
  394. void ScriptTextEditor::goto_line_selection(int p_line, int p_begin, int p_end) {
  395. code_editor->goto_line_selection(p_line, p_begin, p_end);
  396. }
  397. void ScriptTextEditor::goto_line_centered(int p_line, int p_column) {
  398. code_editor->goto_line_centered(p_line, p_column);
  399. }
  400. void ScriptTextEditor::set_executing_line(int p_line) {
  401. code_editor->set_executing_line(p_line);
  402. }
  403. void ScriptTextEditor::clear_executing_line() {
  404. code_editor->clear_executing_line();
  405. }
  406. void ScriptTextEditor::ensure_focus() {
  407. code_editor->get_text_editor()->grab_focus();
  408. }
  409. String ScriptTextEditor::get_name() {
  410. String name;
  411. name = script->get_path().get_file();
  412. if (name.is_empty()) {
  413. // This appears for newly created built-in scripts before saving the scene.
  414. name = TTR("[unsaved]");
  415. } else if (script->is_built_in()) {
  416. const String &script_name = script->get_name();
  417. if (!script_name.is_empty()) {
  418. // If the built-in script has a custom resource name defined,
  419. // display the built-in script name as follows: `ResourceName (scene_file.tscn)`
  420. name = vformat("%s (%s)", script_name, name.get_slice("::", 0));
  421. }
  422. }
  423. if (is_unsaved()) {
  424. name += "(*)";
  425. }
  426. return name;
  427. }
  428. Ref<Texture2D> ScriptTextEditor::get_theme_icon() {
  429. if (get_parent_control()) {
  430. String icon_name = script->get_class();
  431. if (script->is_built_in()) {
  432. icon_name += "Internal";
  433. }
  434. if (get_parent_control()->has_theme_icon(icon_name, EditorStringName(EditorIcons))) {
  435. return get_parent_control()->get_editor_theme_icon(icon_name);
  436. } else if (get_parent_control()->has_theme_icon(script->get_class(), EditorStringName(EditorIcons))) {
  437. return get_parent_control()->get_editor_theme_icon(script->get_class());
  438. }
  439. }
  440. return Ref<Texture2D>();
  441. }
  442. void ScriptTextEditor::_validate_script() {
  443. CodeEdit *te = code_editor->get_text_editor();
  444. String text = te->get_text();
  445. List<String> fnc;
  446. warnings.clear();
  447. errors.clear();
  448. depended_errors.clear();
  449. safe_lines.clear();
  450. if (!script->get_language()->validate(text, script->get_path(), &fnc, &errors, &warnings, &safe_lines)) {
  451. List<ScriptLanguage::ScriptError>::Element *E = errors.front();
  452. while (E) {
  453. List<ScriptLanguage::ScriptError>::Element *next_E = E->next();
  454. if ((E->get().path.is_empty() && !script->get_path().is_empty()) || E->get().path != script->get_path()) {
  455. depended_errors[E->get().path].push_back(E->get());
  456. E->erase();
  457. }
  458. E = next_E;
  459. }
  460. if (errors.size() > 0) {
  461. // TRANSLATORS: Script error pointing to a line and column number.
  462. String error_text = vformat(TTR("Error at (%d, %d):"), errors.front()->get().line, errors.front()->get().column) + " " + errors.front()->get().message;
  463. code_editor->set_error(error_text);
  464. code_editor->set_error_pos(errors.front()->get().line - 1, errors.front()->get().column - 1);
  465. }
  466. script_is_valid = false;
  467. } else {
  468. code_editor->set_error("");
  469. if (!script->is_tool()) {
  470. script->set_source_code(text);
  471. script->update_exports();
  472. te->get_syntax_highlighter()->update_cache();
  473. }
  474. functions.clear();
  475. for (const String &E : fnc) {
  476. functions.push_back(E);
  477. }
  478. script_is_valid = true;
  479. }
  480. _update_connected_methods();
  481. _update_errors();
  482. _update_warnings();
  483. emit_signal(SNAME("name_changed"));
  484. emit_signal(SNAME("edited_script_changed"));
  485. }
  486. void ScriptTextEditor::_update_warnings() {
  487. int warning_nb = warnings.size();
  488. warnings_panel->clear();
  489. bool has_connections_table = false;
  490. // Add missing connections.
  491. if (GLOBAL_GET("debug/gdscript/warnings/enable")) {
  492. Node *base = get_tree()->get_edited_scene_root();
  493. if (base && missing_connections.size() > 0) {
  494. has_connections_table = true;
  495. warnings_panel->push_table(1);
  496. for (const Connection &connection : missing_connections) {
  497. String base_path = base->get_name();
  498. String source_path = base == connection.signal.get_object() ? base_path : base_path + "/" + base->get_path_to(Object::cast_to<Node>(connection.signal.get_object()));
  499. String target_path = base == connection.callable.get_object() ? base_path : base_path + "/" + base->get_path_to(Object::cast_to<Node>(connection.callable.get_object()));
  500. warnings_panel->push_cell();
  501. warnings_panel->push_color(warnings_panel->get_theme_color(SNAME("warning_color"), EditorStringName(Editor)));
  502. warnings_panel->add_text(vformat(TTR("Missing connected method '%s' for signal '%s' from node '%s' to node '%s'."), connection.callable.get_method(), connection.signal.get_name(), source_path, target_path));
  503. warnings_panel->pop(); // Color.
  504. warnings_panel->pop(); // Cell.
  505. }
  506. warnings_panel->pop(); // Table.
  507. warning_nb += missing_connections.size();
  508. }
  509. }
  510. code_editor->set_warning_count(warning_nb);
  511. if (has_connections_table) {
  512. warnings_panel->add_newline();
  513. }
  514. // Add script warnings.
  515. warnings_panel->push_table(3);
  516. for (const ScriptLanguage::Warning &w : warnings) {
  517. Dictionary ignore_meta;
  518. ignore_meta["line"] = w.start_line;
  519. ignore_meta["code"] = w.string_code.to_lower();
  520. warnings_panel->push_cell();
  521. warnings_panel->push_meta(ignore_meta);
  522. warnings_panel->push_color(
  523. warnings_panel->get_theme_color(SNAME("accent_color"), EditorStringName(Editor)).lerp(warnings_panel->get_theme_color(SNAME("mono_color"), EditorStringName(Editor)), 0.5f));
  524. warnings_panel->add_text(TTR("[Ignore]"));
  525. warnings_panel->pop(); // Color.
  526. warnings_panel->pop(); // Meta ignore.
  527. warnings_panel->pop(); // Cell.
  528. warnings_panel->push_cell();
  529. warnings_panel->push_meta(w.start_line - 1);
  530. warnings_panel->push_color(warnings_panel->get_theme_color(SNAME("warning_color"), EditorStringName(Editor)));
  531. warnings_panel->add_text(vformat(TTR("Line %d (%s):"), w.start_line, w.string_code));
  532. warnings_panel->pop(); // Color.
  533. warnings_panel->pop(); // Meta goto.
  534. warnings_panel->pop(); // Cell.
  535. warnings_panel->push_cell();
  536. warnings_panel->add_text(w.message);
  537. warnings_panel->add_newline();
  538. warnings_panel->pop(); // Cell.
  539. }
  540. warnings_panel->pop(); // Table.
  541. if (warning_line_color.a != 0.0) {
  542. CodeEdit *te = code_editor->get_text_editor();
  543. for (int i = 0; i < te->get_line_count(); i++) {
  544. for (const ScriptLanguage::Warning &W : warnings) {
  545. if (i >= W.start_line - 1 && i < W.end_line) {
  546. te->set_line_background_color(i, warning_line_color);
  547. break;
  548. }
  549. }
  550. }
  551. }
  552. }
  553. void ScriptTextEditor::_update_errors() {
  554. code_editor->set_error_count(errors.size());
  555. errors_panel->clear();
  556. errors_panel->push_table(2);
  557. for (const ScriptLanguage::ScriptError &err : errors) {
  558. Dictionary click_meta;
  559. click_meta["line"] = err.line;
  560. click_meta["column"] = err.column;
  561. errors_panel->push_cell();
  562. errors_panel->push_meta(err.line - 1);
  563. errors_panel->push_color(warnings_panel->get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
  564. errors_panel->add_text(vformat(TTR("Line %d:"), err.line));
  565. errors_panel->pop(); // Color.
  566. errors_panel->pop(); // Meta goto.
  567. errors_panel->pop(); // Cell.
  568. errors_panel->push_cell();
  569. errors_panel->add_text(err.message);
  570. errors_panel->add_newline();
  571. errors_panel->pop(); // Cell.
  572. }
  573. errors_panel->pop(); // Table
  574. for (const KeyValue<String, List<ScriptLanguage::ScriptError>> &KV : depended_errors) {
  575. Dictionary click_meta;
  576. click_meta["path"] = KV.key;
  577. click_meta["line"] = 1;
  578. errors_panel->add_newline();
  579. errors_panel->add_newline();
  580. errors_panel->push_meta(click_meta);
  581. errors_panel->add_text(vformat(R"(%s:)", KV.key));
  582. errors_panel->pop(); // Meta goto.
  583. errors_panel->add_newline();
  584. errors_panel->push_indent(1);
  585. errors_panel->push_table(2);
  586. String filename = KV.key.get_file();
  587. for (const ScriptLanguage::ScriptError &err : KV.value) {
  588. click_meta["line"] = err.line;
  589. click_meta["column"] = err.column;
  590. errors_panel->push_cell();
  591. errors_panel->push_meta(click_meta);
  592. errors_panel->push_color(errors_panel->get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
  593. errors_panel->add_text(vformat(TTR("Line %d:"), err.line));
  594. errors_panel->pop(); // Color.
  595. errors_panel->pop(); // Meta goto.
  596. errors_panel->pop(); // Cell.
  597. errors_panel->push_cell();
  598. errors_panel->add_text(err.message);
  599. errors_panel->pop(); // Cell.
  600. }
  601. errors_panel->pop(); // Table
  602. errors_panel->pop(); // Indent.
  603. }
  604. CodeEdit *te = code_editor->get_text_editor();
  605. bool highlight_safe = EDITOR_GET("text_editor/appearance/gutters/highlight_type_safe_lines");
  606. bool last_is_safe = false;
  607. for (int i = 0; i < te->get_line_count(); i++) {
  608. if (errors.is_empty()) {
  609. bool is_folded_code_region = te->is_line_code_region_start(i) && te->is_line_folded(i);
  610. te->set_line_background_color(i, is_folded_code_region ? folded_code_region_color : Color(0, 0, 0, 0));
  611. } else if (marked_line_color.a != 0) {
  612. for (const ScriptLanguage::ScriptError &E : errors) {
  613. bool error_line = i == E.line - 1;
  614. te->set_line_background_color(i, error_line ? marked_line_color : Color(0, 0, 0, 0));
  615. if (error_line) {
  616. break;
  617. }
  618. }
  619. }
  620. if (highlight_safe) {
  621. if (safe_lines.has(i + 1)) {
  622. te->set_line_gutter_item_color(i, line_number_gutter, safe_line_number_color);
  623. last_is_safe = true;
  624. } else if (last_is_safe && (te->is_in_comment(i) != -1 || te->get_line(i).strip_edges().is_empty())) {
  625. te->set_line_gutter_item_color(i, line_number_gutter, safe_line_number_color);
  626. } else {
  627. te->set_line_gutter_item_color(i, line_number_gutter, default_line_number_color);
  628. last_is_safe = false;
  629. }
  630. } else {
  631. te->set_line_gutter_item_color(i, 1, default_line_number_color);
  632. }
  633. }
  634. }
  635. void ScriptTextEditor::_update_bookmark_list() {
  636. bookmarks_menu->clear();
  637. bookmarks_menu->reset_size();
  638. bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_bookmark"), BOOKMARK_TOGGLE);
  639. bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/remove_all_bookmarks"), BOOKMARK_REMOVE_ALL);
  640. bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_bookmark"), BOOKMARK_GOTO_NEXT);
  641. bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_bookmark"), BOOKMARK_GOTO_PREV);
  642. PackedInt32Array bookmark_list = code_editor->get_text_editor()->get_bookmarked_lines();
  643. if (bookmark_list.size() == 0) {
  644. return;
  645. }
  646. bookmarks_menu->add_separator();
  647. for (int i = 0; i < bookmark_list.size(); i++) {
  648. // Strip edges to remove spaces or tabs.
  649. // Also replace any tabs by spaces, since we can't print tabs in the menu.
  650. String line = code_editor->get_text_editor()->get_line(bookmark_list[i]).replace("\t", " ").strip_edges();
  651. // Limit the size of the line if too big.
  652. if (line.length() > 50) {
  653. line = line.substr(0, 50);
  654. }
  655. bookmarks_menu->add_item(String::num_int64(bookmark_list[i] + 1) + " - `" + line + "`");
  656. bookmarks_menu->set_item_metadata(-1, bookmark_list[i]);
  657. }
  658. }
  659. void ScriptTextEditor::_bookmark_item_pressed(int p_idx) {
  660. if (p_idx < 4) { // Any item before the separator.
  661. _edit_option(bookmarks_menu->get_item_id(p_idx));
  662. } else {
  663. code_editor->goto_line_centered(bookmarks_menu->get_item_metadata(p_idx));
  664. }
  665. }
  666. static Vector<Node *> _find_all_node_for_script(Node *p_base, Node *p_current, const Ref<Script> &p_script) {
  667. Vector<Node *> nodes;
  668. if (p_current->get_owner() != p_base && p_base != p_current) {
  669. return nodes;
  670. }
  671. Ref<Script> c = p_current->get_script();
  672. if (c == p_script) {
  673. nodes.push_back(p_current);
  674. }
  675. for (int i = 0; i < p_current->get_child_count(); i++) {
  676. Vector<Node *> found = _find_all_node_for_script(p_base, p_current->get_child(i), p_script);
  677. nodes.append_array(found);
  678. }
  679. return nodes;
  680. }
  681. static Node *_find_node_for_script(Node *p_base, Node *p_current, const Ref<Script> &p_script) {
  682. if (p_current->get_owner() != p_base && p_base != p_current) {
  683. return nullptr;
  684. }
  685. Ref<Script> c = p_current->get_script();
  686. if (c == p_script) {
  687. return p_current;
  688. }
  689. for (int i = 0; i < p_current->get_child_count(); i++) {
  690. Node *found = _find_node_for_script(p_base, p_current->get_child(i), p_script);
  691. if (found) {
  692. return found;
  693. }
  694. }
  695. return nullptr;
  696. }
  697. static void _find_changed_scripts_for_external_editor(Node *p_base, Node *p_current, HashSet<Ref<Script>> &r_scripts) {
  698. if (p_current->get_owner() != p_base && p_base != p_current) {
  699. return;
  700. }
  701. Ref<Script> c = p_current->get_script();
  702. if (c.is_valid()) {
  703. r_scripts.insert(c);
  704. }
  705. for (int i = 0; i < p_current->get_child_count(); i++) {
  706. _find_changed_scripts_for_external_editor(p_base, p_current->get_child(i), r_scripts);
  707. }
  708. }
  709. void ScriptEditor::_update_modified_scripts_for_external_editor(Ref<Script> p_for_script) {
  710. bool use_external_editor = bool(EDITOR_GET("text_editor/external/use_external_editor"));
  711. ERR_FAIL_NULL(get_tree());
  712. HashSet<Ref<Script>> scripts;
  713. Node *base = get_tree()->get_edited_scene_root();
  714. if (base) {
  715. _find_changed_scripts_for_external_editor(base, base, scripts);
  716. }
  717. for (const Ref<Script> &E : scripts) {
  718. Ref<Script> scr = E;
  719. if (!use_external_editor && !scr->get_language()->overrides_external_editor()) {
  720. continue; // We're not using an external editor for this script.
  721. }
  722. if (p_for_script.is_valid() && p_for_script != scr) {
  723. continue;
  724. }
  725. if (scr->is_built_in()) {
  726. continue; //internal script, who cares, though weird
  727. }
  728. uint64_t last_date = scr->get_last_modified_time();
  729. uint64_t date = FileAccess::get_modified_time(scr->get_path());
  730. if (last_date != date) {
  731. Ref<Script> rel_scr = ResourceLoader::load(scr->get_path(), scr->get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE);
  732. ERR_CONTINUE(rel_scr.is_null());
  733. scr->set_source_code(rel_scr->get_source_code());
  734. scr->set_last_modified_time(rel_scr->get_last_modified_time());
  735. scr->update_exports();
  736. trigger_live_script_reload(scr->get_path());
  737. }
  738. }
  739. }
  740. void ScriptTextEditor::_code_complete_scripts(void *p_ud, const String &p_code, List<ScriptLanguage::CodeCompletionOption> *r_options, bool &r_force) {
  741. ScriptTextEditor *ste = (ScriptTextEditor *)p_ud;
  742. ste->_code_complete_script(p_code, r_options, r_force);
  743. }
  744. void ScriptTextEditor::_code_complete_script(const String &p_code, List<ScriptLanguage::CodeCompletionOption> *r_options, bool &r_force) {
  745. if (color_panel->is_visible()) {
  746. return;
  747. }
  748. Node *base = get_tree()->get_edited_scene_root();
  749. if (base) {
  750. base = _find_node_for_script(base, base, script);
  751. }
  752. String hint;
  753. Error err = script->get_language()->complete_code(p_code, script->get_path(), base, r_options, r_force, hint);
  754. if (err == OK) {
  755. code_editor->get_text_editor()->set_code_hint(hint);
  756. }
  757. }
  758. void ScriptTextEditor::_update_breakpoint_list() {
  759. breakpoints_menu->clear();
  760. breakpoints_menu->reset_size();
  761. breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_breakpoint"), DEBUG_TOGGLE_BREAKPOINT);
  762. breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/remove_all_breakpoints"), DEBUG_REMOVE_ALL_BREAKPOINTS);
  763. breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_breakpoint"), DEBUG_GOTO_NEXT_BREAKPOINT);
  764. breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_breakpoint"), DEBUG_GOTO_PREV_BREAKPOINT);
  765. PackedInt32Array breakpoint_list = code_editor->get_text_editor()->get_breakpointed_lines();
  766. if (breakpoint_list.size() == 0) {
  767. return;
  768. }
  769. breakpoints_menu->add_separator();
  770. for (int i = 0; i < breakpoint_list.size(); i++) {
  771. // Strip edges to remove spaces or tabs.
  772. // Also replace any tabs by spaces, since we can't print tabs in the menu.
  773. String line = code_editor->get_text_editor()->get_line(breakpoint_list[i]).replace("\t", " ").strip_edges();
  774. // Limit the size of the line if too big.
  775. if (line.length() > 50) {
  776. line = line.substr(0, 50);
  777. }
  778. breakpoints_menu->add_item(String::num_int64(breakpoint_list[i] + 1) + " - `" + line + "`");
  779. breakpoints_menu->set_item_metadata(-1, breakpoint_list[i]);
  780. }
  781. }
  782. void ScriptTextEditor::_breakpoint_item_pressed(int p_idx) {
  783. if (p_idx < 4) { // Any item before the separator.
  784. _edit_option(breakpoints_menu->get_item_id(p_idx));
  785. } else {
  786. code_editor->goto_line_centered(breakpoints_menu->get_item_metadata(p_idx));
  787. }
  788. }
  789. void ScriptTextEditor::_breakpoint_toggled(int p_row) {
  790. EditorDebuggerNode::get_singleton()->set_breakpoint(script->get_path(), p_row + 1, code_editor->get_text_editor()->is_line_breakpointed(p_row));
  791. }
  792. void ScriptTextEditor::_on_caret_moved() {
  793. if (code_editor->is_previewing_navigation_change()) {
  794. return;
  795. }
  796. int current_line = code_editor->get_text_editor()->get_caret_line();
  797. if (Math::abs(current_line - previous_line) >= 10) {
  798. Dictionary nav_state = get_navigation_state();
  799. nav_state["row"] = previous_line;
  800. nav_state["scroll_position"] = -1;
  801. emit_signal(SNAME("request_save_previous_state"), nav_state);
  802. store_previous_state();
  803. }
  804. previous_line = current_line;
  805. }
  806. void ScriptTextEditor::_lookup_symbol(const String &p_symbol, int p_row, int p_column) {
  807. Node *base = get_tree()->get_edited_scene_root();
  808. if (base) {
  809. base = _find_node_for_script(base, base, script);
  810. }
  811. ScriptLanguage::LookupResult result;
  812. String code_text = code_editor->get_text_editor()->get_text_with_cursor_char(p_row, p_column);
  813. Error lc_error = script->get_language()->lookup_code(code_text, p_symbol, script->get_path(), base, result);
  814. if (ScriptServer::is_global_class(p_symbol)) {
  815. EditorNode::get_singleton()->load_resource(ScriptServer::get_global_class_path(p_symbol));
  816. } else if (p_symbol.is_resource_file() || p_symbol.begins_with("uid://")) {
  817. EditorNode::get_singleton()->load_scene_or_resource(p_symbol);
  818. } else if (lc_error == OK) {
  819. _goto_line(p_row);
  820. if (!result.class_name.is_empty() && EditorHelp::get_doc_data()->class_list.has(result.class_name) && !EditorHelp::get_doc_data()->class_list[result.class_name].is_script_doc) {
  821. switch (result.type) {
  822. case ScriptLanguage::LOOKUP_RESULT_CLASS: {
  823. emit_signal(SNAME("go_to_help"), "class_name:" + result.class_name);
  824. } break;
  825. case ScriptLanguage::LOOKUP_RESULT_CLASS_CONSTANT: {
  826. StringName cname = result.class_name;
  827. while (ClassDB::class_exists(cname)) {
  828. if (ClassDB::has_integer_constant(cname, result.class_member, true)) {
  829. result.class_name = cname;
  830. break;
  831. }
  832. cname = ClassDB::get_parent_class(cname);
  833. }
  834. emit_signal(SNAME("go_to_help"), "class_constant:" + result.class_name + ":" + result.class_member);
  835. } break;
  836. case ScriptLanguage::LOOKUP_RESULT_CLASS_PROPERTY: {
  837. StringName cname = result.class_name;
  838. while (ClassDB::class_exists(cname)) {
  839. if (ClassDB::has_property(cname, result.class_member, true)) {
  840. result.class_name = cname;
  841. break;
  842. }
  843. cname = ClassDB::get_parent_class(cname);
  844. }
  845. emit_signal(SNAME("go_to_help"), "class_property:" + result.class_name + ":" + result.class_member);
  846. } break;
  847. case ScriptLanguage::LOOKUP_RESULT_CLASS_METHOD: {
  848. StringName cname = result.class_name;
  849. while (ClassDB::class_exists(cname)) {
  850. if (ClassDB::has_method(cname, result.class_member, true)) {
  851. result.class_name = cname;
  852. break;
  853. }
  854. cname = ClassDB::get_parent_class(cname);
  855. }
  856. emit_signal(SNAME("go_to_help"), "class_method:" + result.class_name + ":" + result.class_member);
  857. } break;
  858. case ScriptLanguage::LOOKUP_RESULT_CLASS_SIGNAL: {
  859. StringName cname = result.class_name;
  860. while (ClassDB::class_exists(cname)) {
  861. if (ClassDB::has_signal(cname, result.class_member, true)) {
  862. result.class_name = cname;
  863. break;
  864. }
  865. cname = ClassDB::get_parent_class(cname);
  866. }
  867. emit_signal(SNAME("go_to_help"), "class_signal:" + result.class_name + ":" + result.class_member);
  868. } break;
  869. case ScriptLanguage::LOOKUP_RESULT_CLASS_ENUM: {
  870. StringName cname = result.class_name;
  871. while (ClassDB::class_exists(cname)) {
  872. if (ClassDB::has_enum(cname, result.class_member, true)) {
  873. result.class_name = cname;
  874. break;
  875. }
  876. cname = ClassDB::get_parent_class(cname);
  877. }
  878. emit_signal(SNAME("go_to_help"), "class_enum:" + result.class_name + ":" + result.class_member);
  879. } break;
  880. case ScriptLanguage::LOOKUP_RESULT_CLASS_ANNOTATION: {
  881. emit_signal(SNAME("go_to_help"), "class_annotation:" + result.class_name + ":" + result.class_member);
  882. } break;
  883. case ScriptLanguage::LOOKUP_RESULT_CLASS_TBD_GLOBALSCOPE: { // Deprecated.
  884. emit_signal(SNAME("go_to_help"), "class_global:" + result.class_name + ":" + result.class_member);
  885. } break;
  886. case ScriptLanguage::LOOKUP_RESULT_SCRIPT_LOCATION:
  887. case ScriptLanguage::LOOKUP_RESULT_LOCAL_CONSTANT:
  888. case ScriptLanguage::LOOKUP_RESULT_LOCAL_VARIABLE:
  889. case ScriptLanguage::LOOKUP_RESULT_MAX: {
  890. // Nothing to do.
  891. } break;
  892. }
  893. } else if (result.location >= 0) {
  894. if (result.script.is_valid()) {
  895. emit_signal(SNAME("request_open_script_at_line"), result.script, result.location - 1);
  896. } else {
  897. emit_signal(SNAME("request_save_history"));
  898. goto_line_centered(result.location - 1);
  899. }
  900. }
  901. } else if (ProjectSettings::get_singleton()->has_autoload(p_symbol)) {
  902. // Check for Autoload scenes.
  903. const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(p_symbol);
  904. if (info.is_singleton) {
  905. EditorNode::get_singleton()->load_scene(info.path);
  906. }
  907. } else if (p_symbol.is_relative_path()) {
  908. // Every symbol other than absolute path is relative path so keep this condition at last.
  909. String path = _get_absolute_path(p_symbol);
  910. if (FileAccess::exists(path)) {
  911. EditorNode::get_singleton()->load_scene_or_resource(path);
  912. }
  913. }
  914. }
  915. void ScriptTextEditor::_validate_symbol(const String &p_symbol) {
  916. CodeEdit *text_edit = code_editor->get_text_editor();
  917. Node *base = get_tree()->get_edited_scene_root();
  918. if (base) {
  919. base = _find_node_for_script(base, base, script);
  920. }
  921. ScriptLanguage::LookupResult result;
  922. String lc_text = code_editor->get_text_editor()->get_text_for_symbol_lookup();
  923. Error lc_error = script->get_language()->lookup_code(lc_text, p_symbol, script->get_path(), base, result);
  924. bool is_singleton = ProjectSettings::get_singleton()->has_autoload(p_symbol) && ProjectSettings::get_singleton()->get_autoload(p_symbol).is_singleton;
  925. if (lc_error == OK || is_singleton || ScriptServer::is_global_class(p_symbol) || p_symbol.is_resource_file() || p_symbol.begins_with("uid://")) {
  926. text_edit->set_symbol_lookup_word_as_valid(true);
  927. } else if (p_symbol.is_relative_path()) {
  928. String path = _get_absolute_path(p_symbol);
  929. if (FileAccess::exists(path)) {
  930. text_edit->set_symbol_lookup_word_as_valid(true);
  931. } else {
  932. text_edit->set_symbol_lookup_word_as_valid(false);
  933. }
  934. } else {
  935. text_edit->set_symbol_lookup_word_as_valid(false);
  936. }
  937. }
  938. void ScriptTextEditor::_show_symbol_tooltip(const String &p_symbol, int p_row, int p_column) {
  939. if (!EDITOR_GET("text_editor/behavior/documentation/enable_tooltips").booleanize()) {
  940. return;
  941. }
  942. if (p_symbol.begins_with("res://") || p_symbol.begins_with("uid://")) {
  943. EditorHelpBitTooltip::show_tooltip(code_editor->get_text_editor(), "resource||" + p_symbol);
  944. return;
  945. }
  946. Node *base = get_tree()->get_edited_scene_root();
  947. if (base) {
  948. base = _find_node_for_script(base, base, script);
  949. }
  950. ScriptLanguage::LookupResult result;
  951. String doc_symbol;
  952. const String code_text = code_editor->get_text_editor()->get_text_with_cursor_char(p_row, p_column);
  953. const Error lc_error = script->get_language()->lookup_code(code_text, p_symbol, script->get_path(), base, result);
  954. if (lc_error == OK) {
  955. switch (result.type) {
  956. case ScriptLanguage::LOOKUP_RESULT_CLASS: {
  957. doc_symbol = "class|" + result.class_name + "|";
  958. } break;
  959. case ScriptLanguage::LOOKUP_RESULT_CLASS_CONSTANT: {
  960. StringName cname = result.class_name;
  961. while (ClassDB::class_exists(cname)) {
  962. if (ClassDB::has_integer_constant(cname, result.class_member, true)) {
  963. result.class_name = cname;
  964. break;
  965. }
  966. cname = ClassDB::get_parent_class(cname);
  967. }
  968. doc_symbol = "constant|" + result.class_name + "|" + result.class_member;
  969. } break;
  970. case ScriptLanguage::LOOKUP_RESULT_CLASS_PROPERTY: {
  971. StringName cname = result.class_name;
  972. while (ClassDB::class_exists(cname)) {
  973. if (ClassDB::has_property(cname, result.class_member, true)) {
  974. result.class_name = cname;
  975. break;
  976. }
  977. cname = ClassDB::get_parent_class(cname);
  978. }
  979. doc_symbol = "property|" + result.class_name + "|" + result.class_member;
  980. } break;
  981. case ScriptLanguage::LOOKUP_RESULT_CLASS_METHOD: {
  982. StringName cname = result.class_name;
  983. while (ClassDB::class_exists(cname)) {
  984. if (ClassDB::has_method(cname, result.class_member, true)) {
  985. result.class_name = cname;
  986. break;
  987. }
  988. cname = ClassDB::get_parent_class(cname);
  989. }
  990. doc_symbol = "method|" + result.class_name + "|" + result.class_member;
  991. } break;
  992. case ScriptLanguage::LOOKUP_RESULT_CLASS_SIGNAL: {
  993. StringName cname = result.class_name;
  994. while (ClassDB::class_exists(cname)) {
  995. if (ClassDB::has_signal(cname, result.class_member, true)) {
  996. result.class_name = cname;
  997. break;
  998. }
  999. cname = ClassDB::get_parent_class(cname);
  1000. }
  1001. doc_symbol = "signal|" + result.class_name + "|" + result.class_member;
  1002. } break;
  1003. case ScriptLanguage::LOOKUP_RESULT_CLASS_ENUM: {
  1004. StringName cname = result.class_name;
  1005. while (ClassDB::class_exists(cname)) {
  1006. if (ClassDB::has_enum(cname, result.class_member, true)) {
  1007. result.class_name = cname;
  1008. break;
  1009. }
  1010. cname = ClassDB::get_parent_class(cname);
  1011. }
  1012. doc_symbol = "enum|" + result.class_name + "|" + result.class_member;
  1013. } break;
  1014. case ScriptLanguage::LOOKUP_RESULT_CLASS_ANNOTATION: {
  1015. doc_symbol = "annotation|" + result.class_name + "|" + result.class_member;
  1016. } break;
  1017. case ScriptLanguage::LOOKUP_RESULT_LOCAL_CONSTANT:
  1018. case ScriptLanguage::LOOKUP_RESULT_LOCAL_VARIABLE: {
  1019. const String item_type = (result.type == ScriptLanguage::LOOKUP_RESULT_LOCAL_CONSTANT) ? "local_constant" : "local_variable";
  1020. Dictionary item_data;
  1021. item_data["description"] = result.description;
  1022. item_data["is_deprecated"] = result.is_deprecated;
  1023. item_data["deprecated_message"] = result.deprecated_message;
  1024. item_data["is_experimental"] = result.is_experimental;
  1025. item_data["experimental_message"] = result.experimental_message;
  1026. item_data["doc_type"] = result.doc_type;
  1027. item_data["enumeration"] = result.enumeration;
  1028. item_data["is_bitfield"] = result.is_bitfield;
  1029. item_data["value"] = result.value;
  1030. doc_symbol = item_type + "||" + p_symbol + "|" + JSON::stringify(item_data);
  1031. } break;
  1032. case ScriptLanguage::LOOKUP_RESULT_SCRIPT_LOCATION:
  1033. case ScriptLanguage::LOOKUP_RESULT_CLASS_TBD_GLOBALSCOPE: // Deprecated.
  1034. case ScriptLanguage::LOOKUP_RESULT_MAX: {
  1035. // Nothing to do.
  1036. } break;
  1037. }
  1038. }
  1039. // NOTE: See also `ScriptEditor::_get_debug_tooltip()` for documentation tooltips disabled.
  1040. String debug_value = EditorDebuggerNode::get_singleton()->get_var_value(p_symbol);
  1041. if (!debug_value.is_empty()) {
  1042. constexpr int DISPLAY_LIMIT = 1024;
  1043. if (debug_value.size() > DISPLAY_LIMIT) {
  1044. debug_value = debug_value.left(DISPLAY_LIMIT) + "... " + TTR("(truncated)");
  1045. }
  1046. debug_value = TTR("Current value: ") + debug_value.replace("[", "[lb]");
  1047. }
  1048. if (!doc_symbol.is_empty() || !debug_value.is_empty()) {
  1049. EditorHelpBitTooltip::show_tooltip(code_editor->get_text_editor(), doc_symbol, debug_value, true);
  1050. }
  1051. }
  1052. String ScriptTextEditor::_get_absolute_path(const String &rel_path) {
  1053. String base_path = script->get_path().get_base_dir();
  1054. String path = base_path.path_join(rel_path);
  1055. return path.replace("///", "//").simplify_path();
  1056. }
  1057. void ScriptTextEditor::update_toggle_scripts_button() {
  1058. code_editor->update_toggle_scripts_button();
  1059. }
  1060. void ScriptTextEditor::_update_connected_methods() {
  1061. CodeEdit *text_edit = code_editor->get_text_editor();
  1062. text_edit->set_gutter_width(connection_gutter, text_edit->get_line_height());
  1063. for (int i = 0; i < text_edit->get_line_count(); i++) {
  1064. text_edit->set_line_gutter_metadata(i, connection_gutter, Dictionary());
  1065. text_edit->set_line_gutter_icon(i, connection_gutter, nullptr);
  1066. text_edit->set_line_gutter_clickable(i, connection_gutter, false);
  1067. }
  1068. missing_connections.clear();
  1069. if (!script_is_valid) {
  1070. return;
  1071. }
  1072. Node *base = get_tree()->get_edited_scene_root();
  1073. if (!base) {
  1074. return;
  1075. }
  1076. // Add connection icons to methods.
  1077. Vector<Node *> nodes = _find_all_node_for_script(base, base, script);
  1078. HashSet<StringName> methods_found;
  1079. for (int i = 0; i < nodes.size(); i++) {
  1080. List<Connection> signal_connections;
  1081. nodes[i]->get_signals_connected_to_this(&signal_connections);
  1082. for (const Connection &connection : signal_connections) {
  1083. if (!(connection.flags & CONNECT_PERSIST)) {
  1084. continue;
  1085. }
  1086. // As deleted nodes are still accessible via the undo/redo system, check if they're still on the tree.
  1087. Node *source = Object::cast_to<Node>(connection.signal.get_object());
  1088. if (source && !source->is_inside_tree()) {
  1089. continue;
  1090. }
  1091. const StringName method = connection.callable.get_method();
  1092. if (methods_found.has(method)) {
  1093. continue;
  1094. }
  1095. if (!ClassDB::has_method(script->get_instance_base_type(), method)) {
  1096. int line = -1;
  1097. for (int j = 0; j < functions.size(); j++) {
  1098. String name = functions[j].get_slicec(':', 0);
  1099. if (name == method) {
  1100. Dictionary line_meta;
  1101. line_meta["type"] = "connection";
  1102. line_meta["method"] = method;
  1103. line = functions[j].get_slicec(':', 1).to_int() - 1;
  1104. text_edit->set_line_gutter_metadata(line, connection_gutter, line_meta);
  1105. text_edit->set_line_gutter_icon(line, connection_gutter, get_parent_control()->get_editor_theme_icon(SNAME("Slot")));
  1106. text_edit->set_line_gutter_clickable(line, connection_gutter, true);
  1107. methods_found.insert(method);
  1108. break;
  1109. }
  1110. }
  1111. if (line >= 0) {
  1112. continue;
  1113. }
  1114. // There is a chance that the method is inherited from another script.
  1115. bool found_inherited_function = false;
  1116. Ref<Script> inherited_script = script->get_base_script();
  1117. while (inherited_script.is_valid()) {
  1118. if (inherited_script->has_method(method)) {
  1119. found_inherited_function = true;
  1120. break;
  1121. }
  1122. inherited_script = inherited_script->get_base_script();
  1123. }
  1124. if (!found_inherited_function) {
  1125. missing_connections.push_back(connection);
  1126. }
  1127. }
  1128. }
  1129. }
  1130. // Add override icons to methods.
  1131. methods_found.clear();
  1132. for (int i = 0; i < functions.size(); i++) {
  1133. String raw_name = functions[i].get_slicec(':', 0);
  1134. StringName name = StringName(raw_name);
  1135. if (methods_found.has(name)) {
  1136. continue;
  1137. }
  1138. // Account for inner classes by stripping the class names from the method,
  1139. // starting from the right since our inner class might be inside of another inner class.
  1140. int pos = raw_name.rfind_char('.');
  1141. if (pos != -1) {
  1142. name = raw_name.substr(pos + 1);
  1143. }
  1144. String found_base_class;
  1145. StringName base_class = script->get_instance_base_type();
  1146. Ref<Script> inherited_script = script->get_base_script();
  1147. while (inherited_script.is_valid()) {
  1148. if (inherited_script->has_method(name)) {
  1149. found_base_class = "script:" + inherited_script->get_path();
  1150. break;
  1151. }
  1152. base_class = inherited_script->get_instance_base_type();
  1153. inherited_script = inherited_script->get_base_script();
  1154. }
  1155. if (found_base_class.is_empty()) {
  1156. while (base_class) {
  1157. List<MethodInfo> methods;
  1158. ClassDB::get_method_list(base_class, &methods, true);
  1159. for (const MethodInfo &mi : methods) {
  1160. if (mi.name == name) {
  1161. found_base_class = "builtin:" + base_class;
  1162. break;
  1163. }
  1164. }
  1165. ClassDB::ClassInfo *base_class_ptr = ClassDB::classes.getptr(base_class)->inherits_ptr;
  1166. if (base_class_ptr == nullptr) {
  1167. break;
  1168. }
  1169. base_class = base_class_ptr->name;
  1170. }
  1171. }
  1172. if (!found_base_class.is_empty()) {
  1173. int line = functions[i].get_slicec(':', 1).to_int() - 1;
  1174. Dictionary line_meta = text_edit->get_line_gutter_metadata(line, connection_gutter);
  1175. if (line_meta.is_empty()) {
  1176. // Add override icon to gutter.
  1177. line_meta["type"] = "inherits";
  1178. line_meta["method"] = name;
  1179. line_meta["base_class"] = found_base_class;
  1180. text_edit->set_line_gutter_icon(line, connection_gutter, get_parent_control()->get_editor_theme_icon(SNAME("MethodOverride")));
  1181. text_edit->set_line_gutter_clickable(line, connection_gutter, true);
  1182. } else {
  1183. // If method is also connected to signal, then merge icons and keep the click behavior of the slot.
  1184. text_edit->set_line_gutter_icon(line, connection_gutter, get_parent_control()->get_editor_theme_icon(SNAME("MethodOverrideAndSlot")));
  1185. }
  1186. methods_found.insert(StringName(raw_name));
  1187. }
  1188. }
  1189. }
  1190. void ScriptTextEditor::_update_gutter_indexes() {
  1191. for (int i = 0; i < code_editor->get_text_editor()->get_gutter_count(); i++) {
  1192. if (code_editor->get_text_editor()->get_gutter_name(i) == "connection_gutter") {
  1193. connection_gutter = i;
  1194. continue;
  1195. }
  1196. if (code_editor->get_text_editor()->get_gutter_name(i) == "line_numbers") {
  1197. line_number_gutter = i;
  1198. continue;
  1199. }
  1200. }
  1201. }
  1202. void ScriptTextEditor::_gutter_clicked(int p_line, int p_gutter) {
  1203. if (p_gutter != connection_gutter) {
  1204. return;
  1205. }
  1206. Dictionary meta = code_editor->get_text_editor()->get_line_gutter_metadata(p_line, p_gutter);
  1207. String type = meta.get("type", "");
  1208. if (type.is_empty()) {
  1209. return;
  1210. }
  1211. // All types currently need a method name.
  1212. String method = meta.get("method", "");
  1213. if (method.is_empty()) {
  1214. return;
  1215. }
  1216. if (type == "connection") {
  1217. Node *base = get_tree()->get_edited_scene_root();
  1218. if (!base) {
  1219. return;
  1220. }
  1221. Vector<Node *> nodes = _find_all_node_for_script(base, base, script);
  1222. connection_info_dialog->popup_connections(method, nodes);
  1223. } else if (type == "inherits") {
  1224. String base_class_raw = meta["base_class"];
  1225. PackedStringArray base_class_split = base_class_raw.split(":", true, 1);
  1226. if (base_class_split[0] == "script") {
  1227. // Go to function declaration.
  1228. Ref<Script> base_script = ResourceLoader::load(base_class_split[1]);
  1229. ERR_FAIL_COND(base_script.is_null());
  1230. emit_signal(SNAME("go_to_method"), base_script, method);
  1231. } else if (base_class_split[0] == "builtin") {
  1232. // Open method documentation.
  1233. emit_signal(SNAME("go_to_help"), "class_method:" + base_class_split[1] + ":" + method);
  1234. }
  1235. }
  1236. }
  1237. void ScriptTextEditor::_edit_option(int p_op) {
  1238. CodeEdit *tx = code_editor->get_text_editor();
  1239. tx->apply_ime();
  1240. switch (p_op) {
  1241. case EDIT_UNDO: {
  1242. tx->undo();
  1243. callable_mp((Control *)tx, &Control::grab_focus).call_deferred();
  1244. } break;
  1245. case EDIT_REDO: {
  1246. tx->redo();
  1247. callable_mp((Control *)tx, &Control::grab_focus).call_deferred();
  1248. } break;
  1249. case EDIT_CUT: {
  1250. tx->cut();
  1251. callable_mp((Control *)tx, &Control::grab_focus).call_deferred();
  1252. } break;
  1253. case EDIT_COPY: {
  1254. tx->copy();
  1255. callable_mp((Control *)tx, &Control::grab_focus).call_deferred();
  1256. } break;
  1257. case EDIT_PASTE: {
  1258. tx->paste();
  1259. callable_mp((Control *)tx, &Control::grab_focus).call_deferred();
  1260. } break;
  1261. case EDIT_SELECT_ALL: {
  1262. tx->select_all();
  1263. callable_mp((Control *)tx, &Control::grab_focus).call_deferred();
  1264. } break;
  1265. case EDIT_MOVE_LINE_UP: {
  1266. code_editor->get_text_editor()->move_lines_up();
  1267. } break;
  1268. case EDIT_MOVE_LINE_DOWN: {
  1269. code_editor->get_text_editor()->move_lines_down();
  1270. } break;
  1271. case EDIT_INDENT: {
  1272. Ref<Script> scr = script;
  1273. if (scr.is_null()) {
  1274. return;
  1275. }
  1276. tx->indent_lines();
  1277. } break;
  1278. case EDIT_UNINDENT: {
  1279. Ref<Script> scr = script;
  1280. if (scr.is_null()) {
  1281. return;
  1282. }
  1283. tx->unindent_lines();
  1284. } break;
  1285. case EDIT_DELETE_LINE: {
  1286. code_editor->get_text_editor()->delete_lines();
  1287. } break;
  1288. case EDIT_DUPLICATE_SELECTION: {
  1289. code_editor->get_text_editor()->duplicate_selection();
  1290. } break;
  1291. case EDIT_DUPLICATE_LINES: {
  1292. code_editor->get_text_editor()->duplicate_lines();
  1293. } break;
  1294. case EDIT_TOGGLE_FOLD_LINE: {
  1295. tx->toggle_foldable_lines_at_carets();
  1296. } break;
  1297. case EDIT_FOLD_ALL_LINES: {
  1298. tx->fold_all_lines();
  1299. tx->queue_redraw();
  1300. } break;
  1301. case EDIT_UNFOLD_ALL_LINES: {
  1302. tx->unfold_all_lines();
  1303. tx->queue_redraw();
  1304. } break;
  1305. case EDIT_CREATE_CODE_REGION: {
  1306. tx->create_code_region();
  1307. } break;
  1308. case EDIT_TOGGLE_COMMENT: {
  1309. _edit_option_toggle_inline_comment();
  1310. } break;
  1311. case EDIT_COMPLETE: {
  1312. tx->request_code_completion(true);
  1313. } break;
  1314. case EDIT_AUTO_INDENT: {
  1315. String text = tx->get_text();
  1316. Ref<Script> scr = script;
  1317. if (scr.is_null()) {
  1318. return;
  1319. }
  1320. tx->begin_complex_operation();
  1321. tx->begin_multicaret_edit();
  1322. int begin = tx->get_line_count() - 1, end = 0;
  1323. if (tx->has_selection()) {
  1324. // Auto indent all lines that have a caret or selection on it.
  1325. Vector<Point2i> line_ranges = tx->get_line_ranges_from_carets();
  1326. for (Point2i line_range : line_ranges) {
  1327. scr->get_language()->auto_indent_code(text, line_range.x, line_range.y);
  1328. if (line_range.x < begin) {
  1329. begin = line_range.x;
  1330. }
  1331. if (line_range.y > end) {
  1332. end = line_range.y;
  1333. }
  1334. }
  1335. } else {
  1336. // Auto indent entire text.
  1337. begin = 0;
  1338. end = tx->get_line_count() - 1;
  1339. scr->get_language()->auto_indent_code(text, begin, end);
  1340. }
  1341. // Apply auto indented code.
  1342. Vector<String> lines = text.split("\n");
  1343. for (int i = begin; i <= end; ++i) {
  1344. tx->set_line(i, lines[i]);
  1345. }
  1346. tx->end_multicaret_edit();
  1347. tx->end_complex_operation();
  1348. } break;
  1349. case EDIT_TRIM_TRAILING_WHITESAPCE: {
  1350. trim_trailing_whitespace();
  1351. } break;
  1352. case EDIT_TRIM_FINAL_NEWLINES: {
  1353. trim_final_newlines();
  1354. } break;
  1355. case EDIT_CONVERT_INDENT_TO_SPACES: {
  1356. code_editor->set_indent_using_spaces(true);
  1357. convert_indent();
  1358. } break;
  1359. case EDIT_CONVERT_INDENT_TO_TABS: {
  1360. code_editor->set_indent_using_spaces(false);
  1361. convert_indent();
  1362. } break;
  1363. case EDIT_PICK_COLOR: {
  1364. color_panel->popup();
  1365. } break;
  1366. case EDIT_TO_UPPERCASE: {
  1367. _convert_case(CodeTextEditor::UPPER);
  1368. } break;
  1369. case EDIT_TO_LOWERCASE: {
  1370. _convert_case(CodeTextEditor::LOWER);
  1371. } break;
  1372. case EDIT_CAPITALIZE: {
  1373. _convert_case(CodeTextEditor::CAPITALIZE);
  1374. } break;
  1375. case EDIT_EVALUATE: {
  1376. Expression expression;
  1377. tx->begin_complex_operation();
  1378. for (int caret_idx = 0; caret_idx < tx->get_caret_count(); caret_idx++) {
  1379. Vector<String> lines = tx->get_selected_text(caret_idx).split("\n");
  1380. PackedStringArray results;
  1381. for (int i = 0; i < lines.size(); i++) {
  1382. const String &line = lines[i];
  1383. String whitespace = line.substr(0, line.size() - line.strip_edges(true, false).size()); // Extract the whitespace at the beginning.
  1384. if (expression.parse(line) == OK) {
  1385. Variant result = expression.execute(Array(), Variant(), false, true);
  1386. if (expression.get_error_text().is_empty()) {
  1387. results.push_back(whitespace + result.get_construct_string());
  1388. } else {
  1389. results.push_back(line);
  1390. }
  1391. } else {
  1392. results.push_back(line);
  1393. }
  1394. }
  1395. tx->insert_text_at_caret(String("\n").join(results), caret_idx);
  1396. }
  1397. tx->end_complex_operation();
  1398. } break;
  1399. case EDIT_TOGGLE_WORD_WRAP: {
  1400. TextEdit::LineWrappingMode wrap = code_editor->get_text_editor()->get_line_wrapping_mode();
  1401. code_editor->get_text_editor()->set_line_wrapping_mode(wrap == TextEdit::LINE_WRAPPING_BOUNDARY ? TextEdit::LINE_WRAPPING_NONE : TextEdit::LINE_WRAPPING_BOUNDARY);
  1402. } break;
  1403. case SEARCH_FIND: {
  1404. code_editor->get_find_replace_bar()->popup_search();
  1405. } break;
  1406. case SEARCH_FIND_NEXT: {
  1407. code_editor->get_find_replace_bar()->search_next();
  1408. } break;
  1409. case SEARCH_FIND_PREV: {
  1410. code_editor->get_find_replace_bar()->search_prev();
  1411. } break;
  1412. case SEARCH_REPLACE: {
  1413. code_editor->get_find_replace_bar()->popup_replace();
  1414. } break;
  1415. case SEARCH_IN_FILES: {
  1416. String selected_text = tx->get_selected_text();
  1417. // Yep, because it doesn't make sense to instance this dialog for every single script open...
  1418. // So this will be delegated to the ScriptEditor.
  1419. emit_signal(SNAME("search_in_files_requested"), selected_text);
  1420. } break;
  1421. case REPLACE_IN_FILES: {
  1422. String selected_text = tx->get_selected_text();
  1423. emit_signal(SNAME("replace_in_files_requested"), selected_text);
  1424. } break;
  1425. case SEARCH_LOCATE_FUNCTION: {
  1426. quick_open->popup_dialog(get_functions());
  1427. quick_open->set_title(TTR("Go to Function"));
  1428. } break;
  1429. case SEARCH_GOTO_LINE: {
  1430. goto_line_popup->popup_find_line(code_editor);
  1431. } break;
  1432. case BOOKMARK_TOGGLE: {
  1433. code_editor->toggle_bookmark();
  1434. } break;
  1435. case BOOKMARK_GOTO_NEXT: {
  1436. code_editor->goto_next_bookmark();
  1437. } break;
  1438. case BOOKMARK_GOTO_PREV: {
  1439. code_editor->goto_prev_bookmark();
  1440. } break;
  1441. case BOOKMARK_REMOVE_ALL: {
  1442. code_editor->remove_all_bookmarks();
  1443. } break;
  1444. case DEBUG_TOGGLE_BREAKPOINT: {
  1445. Vector<int> sorted_carets = tx->get_sorted_carets();
  1446. int last_line = -1;
  1447. for (const int &c : sorted_carets) {
  1448. int from = tx->get_selection_from_line(c);
  1449. from += from == last_line ? 1 : 0;
  1450. int to = tx->get_selection_to_line(c);
  1451. if (to < from) {
  1452. continue;
  1453. }
  1454. // Check first if there's any lines with breakpoints in the selection.
  1455. bool selection_has_breakpoints = false;
  1456. for (int line = from; line <= to; line++) {
  1457. if (tx->is_line_breakpointed(line)) {
  1458. selection_has_breakpoints = true;
  1459. break;
  1460. }
  1461. }
  1462. // Set breakpoint on caret or remove all bookmarks from the selection.
  1463. if (!selection_has_breakpoints) {
  1464. if (tx->get_caret_line(c) != last_line) {
  1465. tx->set_line_as_breakpoint(tx->get_caret_line(c), true);
  1466. }
  1467. } else {
  1468. for (int line = from; line <= to; line++) {
  1469. tx->set_line_as_breakpoint(line, false);
  1470. }
  1471. }
  1472. last_line = to;
  1473. }
  1474. } break;
  1475. case DEBUG_REMOVE_ALL_BREAKPOINTS: {
  1476. PackedInt32Array bpoints = tx->get_breakpointed_lines();
  1477. for (int i = 0; i < bpoints.size(); i++) {
  1478. int line = bpoints[i];
  1479. bool dobreak = !tx->is_line_breakpointed(line);
  1480. tx->set_line_as_breakpoint(line, dobreak);
  1481. EditorDebuggerNode::get_singleton()->set_breakpoint(script->get_path(), line + 1, dobreak);
  1482. }
  1483. } break;
  1484. case DEBUG_GOTO_NEXT_BREAKPOINT: {
  1485. PackedInt32Array bpoints = tx->get_breakpointed_lines();
  1486. if (bpoints.size() <= 0) {
  1487. return;
  1488. }
  1489. int current_line = tx->get_caret_line();
  1490. int bpoint_idx = 0;
  1491. if (current_line < (int)bpoints[bpoints.size() - 1]) {
  1492. while (bpoint_idx < bpoints.size() && bpoints[bpoint_idx] <= current_line) {
  1493. bpoint_idx++;
  1494. }
  1495. }
  1496. code_editor->goto_line_centered(bpoints[bpoint_idx]);
  1497. } break;
  1498. case DEBUG_GOTO_PREV_BREAKPOINT: {
  1499. PackedInt32Array bpoints = tx->get_breakpointed_lines();
  1500. if (bpoints.size() <= 0) {
  1501. return;
  1502. }
  1503. int current_line = tx->get_caret_line();
  1504. int bpoint_idx = bpoints.size() - 1;
  1505. if (current_line > (int)bpoints[0]) {
  1506. while (bpoint_idx >= 0 && bpoints[bpoint_idx] >= current_line) {
  1507. bpoint_idx--;
  1508. }
  1509. }
  1510. code_editor->goto_line_centered(bpoints[bpoint_idx]);
  1511. } break;
  1512. case HELP_CONTEXTUAL: {
  1513. String text = tx->get_selected_text(0);
  1514. if (text.is_empty()) {
  1515. text = tx->get_word_under_caret(0);
  1516. }
  1517. if (!text.is_empty()) {
  1518. emit_signal(SNAME("request_help"), text);
  1519. }
  1520. } break;
  1521. case LOOKUP_SYMBOL: {
  1522. String text = tx->get_word_under_caret(0);
  1523. if (text.is_empty()) {
  1524. text = tx->get_selected_text(0);
  1525. }
  1526. if (!text.is_empty()) {
  1527. _lookup_symbol(text, tx->get_caret_line(0), tx->get_caret_column(0));
  1528. }
  1529. } break;
  1530. case EDIT_EMOJI_AND_SYMBOL: {
  1531. code_editor->get_text_editor()->show_emoji_and_symbol_picker();
  1532. } break;
  1533. default: {
  1534. if (p_op >= EditorContextMenuPlugin::BASE_ID) {
  1535. EditorContextMenuPluginManager::get_singleton()->activate_custom_option(EditorContextMenuPlugin::CONTEXT_SLOT_SCRIPT_EDITOR_CODE, p_op, tx);
  1536. }
  1537. }
  1538. }
  1539. }
  1540. void ScriptTextEditor::_edit_option_toggle_inline_comment() {
  1541. if (script.is_null()) {
  1542. return;
  1543. }
  1544. String delimiter = "#";
  1545. List<String> comment_delimiters;
  1546. script->get_language()->get_comment_delimiters(&comment_delimiters);
  1547. for (const String &script_delimiter : comment_delimiters) {
  1548. if (!script_delimiter.contains_char(' ')) {
  1549. delimiter = script_delimiter;
  1550. break;
  1551. }
  1552. }
  1553. code_editor->toggle_inline_comment(delimiter);
  1554. }
  1555. void ScriptTextEditor::add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) {
  1556. ERR_FAIL_COND(p_highlighter.is_null());
  1557. highlighters[p_highlighter->_get_name()] = p_highlighter;
  1558. highlighter_menu->add_radio_check_item(p_highlighter->_get_name());
  1559. }
  1560. void ScriptTextEditor::set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) {
  1561. ERR_FAIL_COND(p_highlighter.is_null());
  1562. HashMap<String, Ref<EditorSyntaxHighlighter>>::Iterator el = highlighters.begin();
  1563. while (el) {
  1564. int highlighter_index = highlighter_menu->get_item_idx_from_text(el->key);
  1565. highlighter_menu->set_item_checked(highlighter_index, el->value == p_highlighter);
  1566. ++el;
  1567. }
  1568. CodeEdit *te = code_editor->get_text_editor();
  1569. p_highlighter->_set_edited_resource(script);
  1570. te->set_syntax_highlighter(p_highlighter);
  1571. }
  1572. void ScriptTextEditor::_change_syntax_highlighter(int p_idx) {
  1573. set_syntax_highlighter(highlighters[highlighter_menu->get_item_text(p_idx)]);
  1574. }
  1575. void ScriptTextEditor::_notification(int p_what) {
  1576. switch (p_what) {
  1577. case NOTIFICATION_THEME_CHANGED:
  1578. if (!editor_enabled) {
  1579. break;
  1580. }
  1581. if (is_visible_in_tree()) {
  1582. _update_errors();
  1583. _update_warnings();
  1584. }
  1585. [[fallthrough]];
  1586. case NOTIFICATION_ENTER_TREE: {
  1587. code_editor->get_text_editor()->set_gutter_width(connection_gutter, code_editor->get_text_editor()->get_line_height());
  1588. } break;
  1589. }
  1590. }
  1591. Control *ScriptTextEditor::get_edit_menu() {
  1592. return edit_hb;
  1593. }
  1594. void ScriptTextEditor::clear_edit_menu() {
  1595. if (editor_enabled) {
  1596. memdelete(edit_hb);
  1597. }
  1598. }
  1599. void ScriptTextEditor::set_find_replace_bar(FindReplaceBar *p_bar) {
  1600. code_editor->set_find_replace_bar(p_bar);
  1601. }
  1602. void ScriptTextEditor::reload(bool p_soft) {
  1603. CodeEdit *te = code_editor->get_text_editor();
  1604. Ref<Script> scr = script;
  1605. if (scr.is_null()) {
  1606. return;
  1607. }
  1608. scr->set_source_code(te->get_text());
  1609. bool soft = p_soft || ClassDB::is_parent_class(scr->get_instance_base_type(), "EditorPlugin"); // Always soft-reload editor plugins.
  1610. scr->get_language()->reload_tool_script(scr, soft);
  1611. }
  1612. PackedInt32Array ScriptTextEditor::get_breakpoints() {
  1613. return code_editor->get_text_editor()->get_breakpointed_lines();
  1614. }
  1615. void ScriptTextEditor::set_breakpoint(int p_line, bool p_enabled) {
  1616. code_editor->get_text_editor()->set_line_as_breakpoint(p_line, p_enabled);
  1617. }
  1618. void ScriptTextEditor::clear_breakpoints() {
  1619. code_editor->get_text_editor()->clear_breakpointed_lines();
  1620. }
  1621. void ScriptTextEditor::set_tooltip_request_func(const Callable &p_toolip_callback) {
  1622. Variant args[1] = { this };
  1623. const Variant *argp[] = { &args[0] };
  1624. code_editor->get_text_editor()->set_tooltip_request_func(p_toolip_callback.bindp(argp, 1));
  1625. }
  1626. void ScriptTextEditor::set_debugger_active(bool p_active) {
  1627. }
  1628. Control *ScriptTextEditor::get_base_editor() const {
  1629. return code_editor->get_text_editor();
  1630. }
  1631. CodeTextEditor *ScriptTextEditor::get_code_editor() const {
  1632. return code_editor;
  1633. }
  1634. Variant ScriptTextEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
  1635. return Variant();
  1636. }
  1637. bool ScriptTextEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
  1638. Dictionary d = p_data;
  1639. if (d.has("type") &&
  1640. (String(d["type"]) == "resource" ||
  1641. String(d["type"]) == "files" ||
  1642. String(d["type"]) == "nodes" ||
  1643. String(d["type"]) == "obj_property" ||
  1644. String(d["type"]) == "files_and_dirs")) {
  1645. return true;
  1646. }
  1647. return false;
  1648. }
  1649. static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
  1650. // Check scripts only for the nodes belonging to the edited scene.
  1651. if (p_current_node == p_edited_scene || p_current_node->get_owner() == p_edited_scene) {
  1652. Ref<Script> scr = p_current_node->get_script();
  1653. if (scr.is_valid() && scr == script) {
  1654. return p_current_node;
  1655. }
  1656. }
  1657. // Traverse all children, even the ones not owned by the edited scene as they
  1658. // can still have child nodes added within the edited scene and thus owned by
  1659. // it (e.g. nodes added to subscene's root or to its editable children).
  1660. for (int i = 0; i < p_current_node->get_child_count(); i++) {
  1661. Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
  1662. if (n) {
  1663. return n;
  1664. }
  1665. }
  1666. return nullptr;
  1667. }
  1668. static String _quote_drop_data(const String &str) {
  1669. // This function prepares a string for being "dropped" into the script editor.
  1670. // The string can be a resource path, node path or property name.
  1671. const bool using_single_quotes = EDITOR_GET("text_editor/completion/use_single_quotes");
  1672. String escaped = str.c_escape();
  1673. // If string is double quoted, there is no need to escape single quotes.
  1674. // We can revert the extra escaping added in c_escape().
  1675. if (!using_single_quotes) {
  1676. escaped = escaped.replace("\\'", "\'");
  1677. }
  1678. return escaped.quote(using_single_quotes ? "'" : "\"");
  1679. }
  1680. static String _get_dropped_resource_line(const Ref<Resource> &p_resource, bool p_create_field, bool p_allow_uid) {
  1681. String path = p_resource->get_path();
  1682. if (p_allow_uid) {
  1683. ResourceUID::ID id = ResourceLoader::get_resource_uid(path);
  1684. if (id != ResourceUID::INVALID_ID) {
  1685. path = ResourceUID::get_singleton()->id_to_text(id);
  1686. }
  1687. }
  1688. const bool is_script = ClassDB::is_parent_class(p_resource->get_class(), "Script");
  1689. if (!p_create_field) {
  1690. return vformat("preload(%s)", _quote_drop_data(path));
  1691. }
  1692. String variable_name = p_resource->get_name();
  1693. if (variable_name.is_empty()) {
  1694. variable_name = p_resource->get_path().get_file().get_basename();
  1695. }
  1696. if (is_script) {
  1697. variable_name = variable_name.to_pascal_case().validate_unicode_identifier();
  1698. } else {
  1699. variable_name = variable_name.to_snake_case().to_upper().validate_unicode_identifier();
  1700. }
  1701. return vformat("const %s = preload(%s)", variable_name, _quote_drop_data(path));
  1702. }
  1703. void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  1704. Dictionary d = p_data;
  1705. CodeEdit *te = code_editor->get_text_editor();
  1706. Point2i pos = te->get_line_column_at_pos(p_point);
  1707. int drop_at_line = pos.y;
  1708. int drop_at_column = pos.x;
  1709. int selection_index = te->get_selection_at_line_column(drop_at_line, drop_at_column);
  1710. bool line_will_be_empty = false;
  1711. if (selection_index >= 0) {
  1712. // Dropped on a selection, it will be replaced.
  1713. drop_at_line = te->get_selection_from_line(selection_index);
  1714. drop_at_column = te->get_selection_from_column(selection_index);
  1715. line_will_be_empty = drop_at_column <= te->get_first_non_whitespace_column(drop_at_line) && te->get_selection_to_column(selection_index) == te->get_line(te->get_selection_to_line(selection_index)).length();
  1716. }
  1717. String text_to_drop;
  1718. const bool drop_modifier_pressed = Input::get_singleton()->is_key_pressed(Key::CMD_OR_CTRL);
  1719. const bool allow_uid = Input::get_singleton()->is_key_pressed(Key::SHIFT) != bool(EDITOR_GET("text_editor/behavior/files/drop_preload_resources_as_uid"));
  1720. const String &line = te->get_line(drop_at_line);
  1721. const bool is_empty_line = line_will_be_empty || line.is_empty() || te->get_first_non_whitespace_column(drop_at_line) == line.length();
  1722. const String type = d.get("type", "");
  1723. if (type == "resource") {
  1724. Ref<Resource> resource = d["resource"];
  1725. if (resource.is_null()) {
  1726. return;
  1727. }
  1728. const String &path = resource->get_path();
  1729. if (path.is_empty() || path.ends_with("::")) {
  1730. String warning = TTR("The resource does not have a valid path because it has not been saved.\nPlease save the scene or resource that contains this resource and try again.");
  1731. EditorToaster::get_singleton()->popup_str(warning, EditorToaster::SEVERITY_ERROR);
  1732. return;
  1733. }
  1734. if (drop_modifier_pressed) {
  1735. if (resource->is_built_in()) {
  1736. String warning = TTR("Preloading internal resources is not supported.");
  1737. EditorToaster::get_singleton()->popup_str(warning, EditorToaster::SEVERITY_ERROR);
  1738. } else {
  1739. text_to_drop = _get_dropped_resource_line(resource, is_empty_line, allow_uid);
  1740. }
  1741. } else {
  1742. text_to_drop = _quote_drop_data(path);
  1743. }
  1744. }
  1745. if (type == "files" || type == "files_and_dirs") {
  1746. const PackedStringArray files = d["files"];
  1747. PackedStringArray parts;
  1748. for (const String &path : files) {
  1749. if (drop_modifier_pressed && ResourceLoader::exists(path)) {
  1750. Ref<Resource> resource = ResourceLoader::load(path);
  1751. if (resource.is_null()) {
  1752. // Resource exists, but failed to load. We need only path and name, so we can use a dummy Resource instead.
  1753. resource.instantiate();
  1754. resource->set_path_cache(path);
  1755. }
  1756. parts.append(_get_dropped_resource_line(resource, is_empty_line, allow_uid));
  1757. } else {
  1758. parts.append(_quote_drop_data(path));
  1759. }
  1760. }
  1761. text_to_drop = String(is_empty_line ? "\n" : ", ").join(parts);
  1762. }
  1763. if (type == "nodes") {
  1764. Node *scene_root = get_tree()->get_edited_scene_root();
  1765. if (!scene_root) {
  1766. EditorNode::get_singleton()->show_warning(TTR("Can't drop nodes without an open scene."));
  1767. return;
  1768. }
  1769. if (!ClassDB::is_parent_class(script->get_instance_base_type(), "Node")) {
  1770. EditorToaster::get_singleton()->popup_str(vformat(TTR("Can't drop nodes because script '%s' does not inherit Node."), get_name()), EditorToaster::SEVERITY_WARNING);
  1771. return;
  1772. }
  1773. Node *sn = _find_script_node(scene_root, scene_root, script);
  1774. if (!sn) {
  1775. sn = scene_root;
  1776. }
  1777. Array nodes = d["nodes"];
  1778. if (drop_modifier_pressed) {
  1779. const bool use_type = EDITOR_GET("text_editor/completion/add_type_hints");
  1780. for (int i = 0; i < nodes.size(); i++) {
  1781. NodePath np = nodes[i];
  1782. Node *node = get_node(np);
  1783. if (!node) {
  1784. continue;
  1785. }
  1786. bool is_unique = false;
  1787. String path;
  1788. if (node->is_unique_name_in_owner()) {
  1789. path = node->get_name();
  1790. is_unique = true;
  1791. } else {
  1792. path = sn->get_path_to(node);
  1793. }
  1794. for (const String &segment : path.split("/")) {
  1795. if (!segment.is_valid_unicode_identifier()) {
  1796. path = _quote_drop_data(path);
  1797. break;
  1798. }
  1799. }
  1800. String variable_name = String(node->get_name()).to_snake_case().validate_unicode_identifier();
  1801. if (use_type) {
  1802. StringName class_name = node->get_class_name();
  1803. Ref<Script> node_script = node->get_script();
  1804. if (node_script.is_valid()) {
  1805. StringName global_node_script_name = node_script->get_global_name();
  1806. if (global_node_script_name != StringName()) {
  1807. class_name = global_node_script_name;
  1808. }
  1809. }
  1810. text_to_drop += vformat("@onready var %s: %s = %c%s\n", variable_name, class_name, is_unique ? '%' : '$', path);
  1811. } else {
  1812. text_to_drop += vformat("@onready var %s = %c%s\n", variable_name, is_unique ? '%' : '$', path);
  1813. }
  1814. }
  1815. } else {
  1816. for (int i = 0; i < nodes.size(); i++) {
  1817. if (i > 0) {
  1818. text_to_drop += ", ";
  1819. }
  1820. NodePath np = nodes[i];
  1821. Node *node = get_node(np);
  1822. if (!node) {
  1823. continue;
  1824. }
  1825. bool is_unique = false;
  1826. String path;
  1827. if (node->is_unique_name_in_owner()) {
  1828. path = node->get_name();
  1829. is_unique = true;
  1830. } else {
  1831. path = sn->get_path_to(node);
  1832. }
  1833. for (const String &segment : path.split("/")) {
  1834. if (!segment.is_valid_ascii_identifier()) {
  1835. path = _quote_drop_data(path);
  1836. break;
  1837. }
  1838. }
  1839. text_to_drop += (is_unique ? "%" : "$") + path;
  1840. }
  1841. }
  1842. }
  1843. if (type == "obj_property") {
  1844. bool add_literal = EDITOR_GET("text_editor/completion/add_node_path_literals");
  1845. text_to_drop = add_literal ? "^" : "";
  1846. // It is unclear whether properties may contain single or double quotes.
  1847. // Assume here that double-quotes may not exist. We are escaping single-quotes if necessary.
  1848. text_to_drop += _quote_drop_data(String(d["property"]));
  1849. }
  1850. if (text_to_drop.is_empty()) {
  1851. return;
  1852. }
  1853. // Remove drag caret before any actions so it is not included in undo.
  1854. te->remove_drag_caret();
  1855. te->begin_complex_operation();
  1856. if (selection_index >= 0) {
  1857. te->delete_selection(selection_index);
  1858. }
  1859. te->remove_secondary_carets();
  1860. te->deselect();
  1861. te->set_caret_line(drop_at_line);
  1862. te->set_caret_column(drop_at_column);
  1863. te->insert_text_at_caret(text_to_drop);
  1864. te->end_complex_operation();
  1865. te->grab_focus();
  1866. }
  1867. void ScriptTextEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) {
  1868. Ref<InputEventMouseButton> mb = ev;
  1869. Ref<InputEventKey> k = ev;
  1870. Point2 local_pos;
  1871. bool create_menu = false;
  1872. CodeEdit *tx = code_editor->get_text_editor();
  1873. if (mb.is_valid() && mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed()) {
  1874. local_pos = mb->get_global_position() - tx->get_global_position();
  1875. create_menu = true;
  1876. } else if (k.is_valid() && k->is_action("ui_menu", true)) {
  1877. tx->adjust_viewport_to_caret(0);
  1878. local_pos = tx->get_caret_draw_pos(0);
  1879. create_menu = true;
  1880. }
  1881. if (create_menu) {
  1882. tx->apply_ime();
  1883. Point2i pos = tx->get_line_column_at_pos(local_pos);
  1884. int mouse_line = pos.y;
  1885. int mouse_column = pos.x;
  1886. tx->set_move_caret_on_right_click_enabled(EDITOR_GET("text_editor/behavior/navigation/move_caret_on_right_click"));
  1887. int selection_clicked = -1;
  1888. if (tx->is_move_caret_on_right_click_enabled()) {
  1889. selection_clicked = tx->get_selection_at_line_column(mouse_line, mouse_column, true);
  1890. if (selection_clicked < 0) {
  1891. tx->deselect();
  1892. tx->remove_secondary_carets();
  1893. selection_clicked = 0;
  1894. tx->set_caret_line(mouse_line, false, false, -1);
  1895. tx->set_caret_column(mouse_column);
  1896. }
  1897. }
  1898. String word_at_pos = tx->get_word_at_pos(local_pos);
  1899. if (word_at_pos.is_empty()) {
  1900. word_at_pos = tx->get_word_under_caret(selection_clicked);
  1901. }
  1902. if (word_at_pos.is_empty()) {
  1903. word_at_pos = tx->get_selected_text(selection_clicked);
  1904. }
  1905. bool has_color = (word_at_pos == "Color");
  1906. bool foldable = tx->can_fold_line(mouse_line) || tx->is_line_folded(mouse_line);
  1907. bool open_docs = false;
  1908. bool goto_definition = false;
  1909. if (ScriptServer::is_global_class(word_at_pos) || word_at_pos.is_resource_file()) {
  1910. open_docs = true;
  1911. } else {
  1912. Node *base = get_tree()->get_edited_scene_root();
  1913. if (base) {
  1914. base = _find_node_for_script(base, base, script);
  1915. }
  1916. ScriptLanguage::LookupResult result;
  1917. if (script->get_language()->lookup_code(tx->get_text_for_symbol_lookup(), word_at_pos, script->get_path(), base, result) == OK) {
  1918. open_docs = true;
  1919. }
  1920. }
  1921. if (has_color) {
  1922. String line = tx->get_line(mouse_line);
  1923. color_position.x = mouse_line;
  1924. color_position.y = mouse_column;
  1925. int begin = -1;
  1926. int end = -1;
  1927. enum EXPRESSION_PATTERNS {
  1928. NOT_PARSED,
  1929. RGBA_PARAMETER, // Color(float,float,float) or Color(float,float,float,float)
  1930. COLOR_NAME, // Color.COLOR_NAME
  1931. } expression_pattern = NOT_PARSED;
  1932. for (int i = mouse_column; i < line.length(); i++) {
  1933. if (line[i] == '(') {
  1934. if (expression_pattern == NOT_PARSED) {
  1935. begin = i;
  1936. expression_pattern = RGBA_PARAMETER;
  1937. } else {
  1938. // Method call or '(' appearing twice.
  1939. expression_pattern = NOT_PARSED;
  1940. break;
  1941. }
  1942. } else if (expression_pattern == RGBA_PARAMETER && line[i] == ')' && end < 0) {
  1943. end = i + 1;
  1944. break;
  1945. } else if (expression_pattern == NOT_PARSED && line[i] == '.') {
  1946. begin = i;
  1947. expression_pattern = COLOR_NAME;
  1948. } else if (expression_pattern == COLOR_NAME && end < 0 && (line[i] == ' ' || line[i] == '\t')) {
  1949. // Including '.' and spaces.
  1950. continue;
  1951. } else if (expression_pattern == COLOR_NAME && !(line[i] == '_' || ('A' <= line[i] && line[i] <= 'Z'))) {
  1952. end = i;
  1953. break;
  1954. }
  1955. }
  1956. switch (expression_pattern) {
  1957. case RGBA_PARAMETER: {
  1958. color_args = line.substr(begin, end - begin);
  1959. String stripped = color_args.remove_chars(" \t()");
  1960. PackedFloat64Array color = stripped.split_floats(",");
  1961. if (color.size() > 2) {
  1962. float alpha = color.size() > 3 ? color[3] : 1.0f;
  1963. color_picker->set_pick_color(Color(color[0], color[1], color[2], alpha));
  1964. }
  1965. } break;
  1966. case COLOR_NAME: {
  1967. if (end < 0) {
  1968. end = line.length();
  1969. }
  1970. color_args = line.substr(begin, end - begin);
  1971. const String color_name = color_args.remove_chars(" \t.");
  1972. const int color_index = Color::find_named_color(color_name);
  1973. if (0 <= color_index) {
  1974. const Color color_constant = Color::get_named_color(color_index);
  1975. color_picker->set_pick_color(color_constant);
  1976. } else {
  1977. has_color = false;
  1978. }
  1979. } break;
  1980. default:
  1981. has_color = false;
  1982. break;
  1983. }
  1984. if (has_color) {
  1985. color_panel->set_position(get_screen_position() + local_pos);
  1986. }
  1987. }
  1988. _make_context_menu(tx->has_selection(), has_color, foldable, open_docs, goto_definition, local_pos);
  1989. }
  1990. }
  1991. void ScriptTextEditor::_color_changed(const Color &p_color) {
  1992. String new_args;
  1993. const int decimals = 3;
  1994. if (p_color.a == 1.0f) {
  1995. new_args = String("(" + String::num(p_color.r, decimals) + ", " + String::num(p_color.g, decimals) + ", " + String::num(p_color.b, decimals) + ")");
  1996. } else {
  1997. new_args = String("(" + String::num(p_color.r, decimals) + ", " + String::num(p_color.g, decimals) + ", " + String::num(p_color.b, decimals) + ", " + String::num(p_color.a, decimals) + ")");
  1998. }
  1999. String line = code_editor->get_text_editor()->get_line(color_position.x);
  2000. String line_with_replaced_args = line.replace(color_args, new_args);
  2001. color_args = new_args;
  2002. code_editor->get_text_editor()->begin_complex_operation();
  2003. code_editor->get_text_editor()->set_line(color_position.x, line_with_replaced_args);
  2004. code_editor->get_text_editor()->end_complex_operation();
  2005. }
  2006. void ScriptTextEditor::_prepare_edit_menu() {
  2007. const CodeEdit *tx = code_editor->get_text_editor();
  2008. PopupMenu *popup = edit_menu->get_popup();
  2009. popup->set_item_disabled(popup->get_item_index(EDIT_UNDO), !tx->has_undo());
  2010. popup->set_item_disabled(popup->get_item_index(EDIT_REDO), !tx->has_redo());
  2011. }
  2012. void ScriptTextEditor::_make_context_menu(bool p_selection, bool p_color, bool p_foldable, bool p_open_docs, bool p_goto_definition, Vector2 p_pos) {
  2013. context_menu->clear();
  2014. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_EMOJI_AND_SYMBOL_PICKER)) {
  2015. context_menu->add_item(TTR("Emoji & Symbols"), EDIT_EMOJI_AND_SYMBOL);
  2016. context_menu->add_separator();
  2017. }
  2018. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO);
  2019. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO);
  2020. context_menu->add_separator();
  2021. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT);
  2022. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY);
  2023. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE);
  2024. context_menu->add_separator();
  2025. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL);
  2026. context_menu->add_separator();
  2027. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent"), EDIT_INDENT);
  2028. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unindent"), EDIT_UNINDENT);
  2029. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_comment"), EDIT_TOGGLE_COMMENT);
  2030. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_bookmark"), BOOKMARK_TOGGLE);
  2031. if (p_selection) {
  2032. context_menu->add_separator();
  2033. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_uppercase"), EDIT_TO_UPPERCASE);
  2034. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_lowercase"), EDIT_TO_LOWERCASE);
  2035. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/evaluate_selection"), EDIT_EVALUATE);
  2036. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/create_code_region"), EDIT_CREATE_CODE_REGION);
  2037. }
  2038. if (p_foldable) {
  2039. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_fold_line"), EDIT_TOGGLE_FOLD_LINE);
  2040. }
  2041. if (p_color || p_open_docs || p_goto_definition) {
  2042. context_menu->add_separator();
  2043. if (p_open_docs) {
  2044. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_symbol"), LOOKUP_SYMBOL);
  2045. }
  2046. if (p_color) {
  2047. context_menu->add_item(TTR("Pick Color"), EDIT_PICK_COLOR);
  2048. }
  2049. }
  2050. const PackedStringArray paths = { code_editor->get_text_editor()->get_path() };
  2051. EditorContextMenuPluginManager::get_singleton()->add_options_from_plugins(context_menu, EditorContextMenuPlugin::CONTEXT_SLOT_SCRIPT_EDITOR_CODE, paths);
  2052. const CodeEdit *tx = code_editor->get_text_editor();
  2053. context_menu->set_item_disabled(context_menu->get_item_index(EDIT_UNDO), !tx->has_undo());
  2054. context_menu->set_item_disabled(context_menu->get_item_index(EDIT_REDO), !tx->has_redo());
  2055. context_menu->set_position(get_screen_position() + p_pos);
  2056. context_menu->reset_size();
  2057. context_menu->popup();
  2058. }
  2059. void ScriptTextEditor::_enable_code_editor() {
  2060. ERR_FAIL_COND(code_editor->get_parent());
  2061. VSplitContainer *editor_box = memnew(VSplitContainer);
  2062. add_child(editor_box);
  2063. editor_box->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  2064. editor_box->set_v_size_flags(SIZE_EXPAND_FILL);
  2065. editor_box->add_child(code_editor);
  2066. code_editor->connect("show_errors_panel", callable_mp(this, &ScriptTextEditor::_show_errors_panel));
  2067. code_editor->connect("show_warnings_panel", callable_mp(this, &ScriptTextEditor::_show_warnings_panel));
  2068. code_editor->connect("validate_script", callable_mp(this, &ScriptTextEditor::_validate_script));
  2069. code_editor->connect("load_theme_settings", callable_mp(this, &ScriptTextEditor::_load_theme_settings));
  2070. code_editor->get_text_editor()->connect("symbol_lookup", callable_mp(this, &ScriptTextEditor::_lookup_symbol));
  2071. code_editor->get_text_editor()->connect("symbol_hovered", callable_mp(this, &ScriptTextEditor::_show_symbol_tooltip));
  2072. code_editor->get_text_editor()->connect("symbol_validate", callable_mp(this, &ScriptTextEditor::_validate_symbol));
  2073. code_editor->get_text_editor()->connect("gutter_added", callable_mp(this, &ScriptTextEditor::_update_gutter_indexes));
  2074. code_editor->get_text_editor()->connect("gutter_removed", callable_mp(this, &ScriptTextEditor::_update_gutter_indexes));
  2075. code_editor->get_text_editor()->connect("gutter_clicked", callable_mp(this, &ScriptTextEditor::_gutter_clicked));
  2076. code_editor->get_text_editor()->connect(SceneStringName(gui_input), callable_mp(this, &ScriptTextEditor::_text_edit_gui_input));
  2077. code_editor->show_toggle_scripts_button();
  2078. _update_gutter_indexes();
  2079. editor_box->add_child(warnings_panel);
  2080. warnings_panel->add_theme_font_override(
  2081. "normal_font", EditorNode::get_singleton()->get_editor_theme()->get_font(SNAME("main"), EditorStringName(EditorFonts)));
  2082. warnings_panel->add_theme_font_size_override(
  2083. "normal_font_size", EditorNode::get_singleton()->get_editor_theme()->get_font_size(SNAME("main_size"), EditorStringName(EditorFonts)));
  2084. warnings_panel->connect("meta_clicked", callable_mp(this, &ScriptTextEditor::_warning_clicked));
  2085. editor_box->add_child(errors_panel);
  2086. errors_panel->add_theme_font_override(
  2087. "normal_font", EditorNode::get_singleton()->get_editor_theme()->get_font(SNAME("main"), EditorStringName(EditorFonts)));
  2088. errors_panel->add_theme_font_size_override(
  2089. "normal_font_size", EditorNode::get_singleton()->get_editor_theme()->get_font_size(SNAME("main_size"), EditorStringName(EditorFonts)));
  2090. errors_panel->connect("meta_clicked", callable_mp(this, &ScriptTextEditor::_error_clicked));
  2091. add_child(context_menu);
  2092. context_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2093. add_child(color_panel);
  2094. color_picker = memnew(ColorPicker);
  2095. color_picker->set_deferred_mode(true);
  2096. color_picker->connect("color_changed", callable_mp(this, &ScriptTextEditor::_color_changed));
  2097. color_panel->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(color_picker));
  2098. color_panel->add_child(color_picker);
  2099. quick_open = memnew(ScriptEditorQuickOpen);
  2100. quick_open->connect("goto_line", callable_mp(this, &ScriptTextEditor::_goto_line));
  2101. add_child(quick_open);
  2102. goto_line_popup = memnew(GotoLinePopup);
  2103. add_child(goto_line_popup);
  2104. add_child(connection_info_dialog);
  2105. edit_hb->add_child(edit_menu);
  2106. edit_menu->connect("about_to_popup", callable_mp(this, &ScriptTextEditor::_prepare_edit_menu));
  2107. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO);
  2108. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO);
  2109. edit_menu->get_popup()->add_separator();
  2110. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT);
  2111. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY);
  2112. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE);
  2113. edit_menu->get_popup()->add_separator();
  2114. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL);
  2115. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/duplicate_selection"), EDIT_DUPLICATE_SELECTION);
  2116. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/duplicate_lines"), EDIT_DUPLICATE_LINES);
  2117. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/evaluate_selection"), EDIT_EVALUATE);
  2118. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_word_wrap"), EDIT_TOGGLE_WORD_WRAP);
  2119. edit_menu->get_popup()->add_separator();
  2120. {
  2121. PopupMenu *sub_menu = memnew(PopupMenu);
  2122. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_up"), EDIT_MOVE_LINE_UP);
  2123. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_down"), EDIT_MOVE_LINE_DOWN);
  2124. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent"), EDIT_INDENT);
  2125. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unindent"), EDIT_UNINDENT);
  2126. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/delete_line"), EDIT_DELETE_LINE);
  2127. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_comment"), EDIT_TOGGLE_COMMENT);
  2128. sub_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2129. edit_menu->get_popup()->add_submenu_node_item(TTR("Line"), sub_menu);
  2130. }
  2131. {
  2132. PopupMenu *sub_menu = memnew(PopupMenu);
  2133. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_fold_line"), EDIT_TOGGLE_FOLD_LINE);
  2134. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/fold_all_lines"), EDIT_FOLD_ALL_LINES);
  2135. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unfold_all_lines"), EDIT_UNFOLD_ALL_LINES);
  2136. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/create_code_region"), EDIT_CREATE_CODE_REGION);
  2137. sub_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2138. edit_menu->get_popup()->add_submenu_node_item(TTR("Folding"), sub_menu);
  2139. }
  2140. edit_menu->get_popup()->add_separator();
  2141. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_completion_query"), EDIT_COMPLETE);
  2142. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/trim_trailing_whitespace"), EDIT_TRIM_TRAILING_WHITESAPCE);
  2143. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/trim_final_newlines"), EDIT_TRIM_FINAL_NEWLINES);
  2144. {
  2145. PopupMenu *sub_menu = memnew(PopupMenu);
  2146. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_spaces"), EDIT_CONVERT_INDENT_TO_SPACES);
  2147. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_tabs"), EDIT_CONVERT_INDENT_TO_TABS);
  2148. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/auto_indent"), EDIT_AUTO_INDENT);
  2149. sub_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2150. edit_menu->get_popup()->add_submenu_node_item(TTR("Indentation"), sub_menu);
  2151. }
  2152. edit_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2153. edit_menu->get_popup()->add_separator();
  2154. {
  2155. PopupMenu *sub_menu = memnew(PopupMenu);
  2156. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_uppercase"), EDIT_TO_UPPERCASE);
  2157. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_lowercase"), EDIT_TO_LOWERCASE);
  2158. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/capitalize"), EDIT_CAPITALIZE);
  2159. sub_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2160. edit_menu->get_popup()->add_submenu_node_item(TTR("Convert Case"), sub_menu);
  2161. }
  2162. edit_menu->get_popup()->add_submenu_node_item(TTR("Syntax Highlighter"), highlighter_menu);
  2163. highlighter_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_change_syntax_highlighter));
  2164. edit_hb->add_child(search_menu);
  2165. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find"), SEARCH_FIND);
  2166. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_next"), SEARCH_FIND_NEXT);
  2167. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_previous"), SEARCH_FIND_PREV);
  2168. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace"), SEARCH_REPLACE);
  2169. search_menu->get_popup()->add_separator();
  2170. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_in_files"), SEARCH_IN_FILES);
  2171. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace_in_files"), REPLACE_IN_FILES);
  2172. search_menu->get_popup()->add_separator();
  2173. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/contextual_help"), HELP_CONTEXTUAL);
  2174. search_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2175. _load_theme_settings();
  2176. edit_hb->add_child(goto_menu);
  2177. goto_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_function"), SEARCH_LOCATE_FUNCTION);
  2178. goto_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_line"), SEARCH_GOTO_LINE);
  2179. goto_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_symbol"), LOOKUP_SYMBOL);
  2180. goto_menu->get_popup()->add_separator();
  2181. goto_menu->get_popup()->add_submenu_node_item(TTR("Bookmarks"), bookmarks_menu);
  2182. _update_bookmark_list();
  2183. bookmarks_menu->connect("about_to_popup", callable_mp(this, &ScriptTextEditor::_update_bookmark_list));
  2184. bookmarks_menu->connect("index_pressed", callable_mp(this, &ScriptTextEditor::_bookmark_item_pressed));
  2185. goto_menu->get_popup()->add_submenu_node_item(TTR("Breakpoints"), breakpoints_menu);
  2186. _update_breakpoint_list();
  2187. breakpoints_menu->connect("about_to_popup", callable_mp(this, &ScriptTextEditor::_update_breakpoint_list));
  2188. breakpoints_menu->connect("index_pressed", callable_mp(this, &ScriptTextEditor::_breakpoint_item_pressed));
  2189. goto_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2190. }
  2191. ScriptTextEditor::ScriptTextEditor() {
  2192. code_editor = memnew(CodeTextEditor);
  2193. code_editor->set_toggle_list_control(ScriptEditor::get_singleton()->get_left_list_split());
  2194. code_editor->add_theme_constant_override("separation", 2);
  2195. code_editor->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  2196. code_editor->set_code_complete_func(_code_complete_scripts, this);
  2197. code_editor->set_v_size_flags(SIZE_EXPAND_FILL);
  2198. code_editor->get_text_editor()->set_draw_breakpoints_gutter(true);
  2199. code_editor->get_text_editor()->set_draw_executing_lines_gutter(true);
  2200. code_editor->get_text_editor()->connect("breakpoint_toggled", callable_mp(this, &ScriptTextEditor::_breakpoint_toggled));
  2201. code_editor->get_text_editor()->connect("caret_changed", callable_mp(this, &ScriptTextEditor::_on_caret_moved));
  2202. code_editor->connect("navigation_preview_ended", callable_mp(this, &ScriptTextEditor::_on_caret_moved));
  2203. connection_gutter = 1;
  2204. code_editor->get_text_editor()->add_gutter(connection_gutter);
  2205. code_editor->get_text_editor()->set_gutter_name(connection_gutter, "connection_gutter");
  2206. code_editor->get_text_editor()->set_gutter_draw(connection_gutter, false);
  2207. code_editor->get_text_editor()->set_gutter_overwritable(connection_gutter, true);
  2208. code_editor->get_text_editor()->set_gutter_type(connection_gutter, TextEdit::GUTTER_TYPE_ICON);
  2209. warnings_panel = memnew(RichTextLabel);
  2210. warnings_panel->set_custom_minimum_size(Size2(0, 100 * EDSCALE));
  2211. warnings_panel->set_h_size_flags(SIZE_EXPAND_FILL);
  2212. warnings_panel->set_meta_underline(true);
  2213. warnings_panel->set_selection_enabled(true);
  2214. warnings_panel->set_context_menu_enabled(true);
  2215. warnings_panel->set_focus_mode(FOCUS_CLICK);
  2216. warnings_panel->hide();
  2217. errors_panel = memnew(RichTextLabel);
  2218. errors_panel->set_custom_minimum_size(Size2(0, 100 * EDSCALE));
  2219. errors_panel->set_h_size_flags(SIZE_EXPAND_FILL);
  2220. errors_panel->set_meta_underline(true);
  2221. errors_panel->set_selection_enabled(true);
  2222. errors_panel->set_context_menu_enabled(true);
  2223. errors_panel->set_focus_mode(FOCUS_CLICK);
  2224. errors_panel->hide();
  2225. update_settings();
  2226. code_editor->get_text_editor()->set_symbol_lookup_on_click_enabled(true);
  2227. code_editor->get_text_editor()->set_symbol_tooltip_on_hover_enabled(true);
  2228. code_editor->get_text_editor()->set_context_menu_enabled(false);
  2229. context_menu = memnew(PopupMenu);
  2230. color_panel = memnew(PopupPanel);
  2231. edit_hb = memnew(HBoxContainer);
  2232. edit_menu = memnew(MenuButton);
  2233. edit_menu->set_text(TTR("Edit"));
  2234. edit_menu->set_switch_on_hover(true);
  2235. edit_menu->set_shortcut_context(this);
  2236. highlighter_menu = memnew(PopupMenu);
  2237. Ref<EditorPlainTextSyntaxHighlighter> plain_highlighter;
  2238. plain_highlighter.instantiate();
  2239. add_syntax_highlighter(plain_highlighter);
  2240. Ref<EditorStandardSyntaxHighlighter> highlighter;
  2241. highlighter.instantiate();
  2242. add_syntax_highlighter(highlighter);
  2243. set_syntax_highlighter(highlighter);
  2244. search_menu = memnew(MenuButton);
  2245. search_menu->set_text(TTR("Search"));
  2246. search_menu->set_switch_on_hover(true);
  2247. search_menu->set_shortcut_context(this);
  2248. goto_menu = memnew(MenuButton);
  2249. goto_menu->set_text(TTR("Go To"));
  2250. goto_menu->set_switch_on_hover(true);
  2251. goto_menu->set_shortcut_context(this);
  2252. bookmarks_menu = memnew(PopupMenu);
  2253. breakpoints_menu = memnew(PopupMenu);
  2254. connection_info_dialog = memnew(ConnectionInfoDialog);
  2255. SET_DRAG_FORWARDING_GCD(code_editor->get_text_editor(), ScriptTextEditor);
  2256. }
  2257. ScriptTextEditor::~ScriptTextEditor() {
  2258. highlighters.clear();
  2259. if (!editor_enabled) {
  2260. memdelete(code_editor);
  2261. memdelete(warnings_panel);
  2262. memdelete(errors_panel);
  2263. memdelete(context_menu);
  2264. memdelete(color_panel);
  2265. memdelete(edit_hb);
  2266. memdelete(edit_menu);
  2267. memdelete(highlighter_menu);
  2268. memdelete(search_menu);
  2269. memdelete(goto_menu);
  2270. memdelete(bookmarks_menu);
  2271. memdelete(breakpoints_menu);
  2272. memdelete(connection_info_dialog);
  2273. }
  2274. }
  2275. static ScriptEditorBase *create_editor(const Ref<Resource> &p_resource) {
  2276. if (Object::cast_to<Script>(*p_resource)) {
  2277. return memnew(ScriptTextEditor);
  2278. }
  2279. return nullptr;
  2280. }
  2281. void ScriptTextEditor::register_editor() {
  2282. ED_SHORTCUT("script_text_editor/move_up", TTRC("Move Up"), KeyModifierMask::ALT | Key::UP);
  2283. ED_SHORTCUT("script_text_editor/move_down", TTRC("Move Down"), KeyModifierMask::ALT | Key::DOWN);
  2284. ED_SHORTCUT("script_text_editor/delete_line", TTRC("Delete Line"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::K);
  2285. // Leave these at zero, same can be accomplished with tab/shift-tab, including selection.
  2286. // The next/previous in history shortcut in this case makes a lot more sense.
  2287. ED_SHORTCUT("script_text_editor/indent", TTRC("Indent"), Key::NONE);
  2288. ED_SHORTCUT("script_text_editor/unindent", TTRC("Unindent"), KeyModifierMask::SHIFT | Key::TAB);
  2289. ED_SHORTCUT_ARRAY("script_text_editor/toggle_comment", TTRC("Toggle Comment"), { int32_t(KeyModifierMask::CMD_OR_CTRL | Key::K), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::SLASH), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::KP_DIVIDE), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::NUMBERSIGN) });
  2290. ED_SHORTCUT("script_text_editor/toggle_fold_line", TTRC("Fold/Unfold Line"), KeyModifierMask::ALT | Key::F);
  2291. ED_SHORTCUT_OVERRIDE("script_text_editor/toggle_fold_line", "macos", KeyModifierMask::CTRL | KeyModifierMask::META | Key::F);
  2292. ED_SHORTCUT("script_text_editor/fold_all_lines", TTRC("Fold All Lines"), Key::NONE);
  2293. ED_SHORTCUT("script_text_editor/create_code_region", TTRC("Create Code Region"), KeyModifierMask::ALT | Key::R);
  2294. ED_SHORTCUT("script_text_editor/unfold_all_lines", TTRC("Unfold All Lines"), Key::NONE);
  2295. ED_SHORTCUT("script_text_editor/duplicate_selection", TTRC("Duplicate Selection"), KeyModifierMask::SHIFT | KeyModifierMask::CTRL | Key::D);
  2296. ED_SHORTCUT_OVERRIDE("script_text_editor/duplicate_selection", "macos", KeyModifierMask::SHIFT | KeyModifierMask::META | Key::C);
  2297. ED_SHORTCUT("script_text_editor/duplicate_lines", TTRC("Duplicate Lines"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::ALT | Key::DOWN);
  2298. ED_SHORTCUT_OVERRIDE("script_text_editor/duplicate_lines", "macos", KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::DOWN);
  2299. ED_SHORTCUT("script_text_editor/evaluate_selection", TTRC("Evaluate Selection"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::E);
  2300. ED_SHORTCUT("script_text_editor/toggle_word_wrap", TTRC("Toggle Word Wrap"), KeyModifierMask::ALT | Key::Z);
  2301. ED_SHORTCUT("script_text_editor/trim_trailing_whitespace", TTRC("Trim Trailing Whitespace"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::ALT | Key::T);
  2302. ED_SHORTCUT("script_text_editor/trim_final_newlines", TTRC("Trim Final Newlines"), Key::NONE);
  2303. ED_SHORTCUT("script_text_editor/convert_indent_to_spaces", TTRC("Convert Indent to Spaces"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::Y);
  2304. ED_SHORTCUT("script_text_editor/convert_indent_to_tabs", TTRC("Convert Indent to Tabs"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::I);
  2305. ED_SHORTCUT("script_text_editor/auto_indent", TTRC("Auto Indent"), KeyModifierMask::CMD_OR_CTRL | Key::I);
  2306. ED_SHORTCUT_AND_COMMAND("script_text_editor/find", TTRC("Find..."), KeyModifierMask::CMD_OR_CTRL | Key::F);
  2307. ED_SHORTCUT("script_text_editor/find_next", TTRC("Find Next"), Key::F3);
  2308. ED_SHORTCUT_OVERRIDE("script_text_editor/find_next", "macos", KeyModifierMask::META | Key::G);
  2309. ED_SHORTCUT("script_text_editor/find_previous", TTRC("Find Previous"), KeyModifierMask::SHIFT | Key::F3);
  2310. ED_SHORTCUT_OVERRIDE("script_text_editor/find_previous", "macos", KeyModifierMask::META | KeyModifierMask::SHIFT | Key::G);
  2311. ED_SHORTCUT_AND_COMMAND("script_text_editor/replace", TTRC("Replace..."), KeyModifierMask::CTRL | Key::R);
  2312. ED_SHORTCUT_OVERRIDE("script_text_editor/replace", "macos", KeyModifierMask::ALT | KeyModifierMask::META | Key::F);
  2313. ED_SHORTCUT("script_text_editor/find_in_files", TTRC("Find in Files..."), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::F);
  2314. ED_SHORTCUT("script_text_editor/replace_in_files", TTRC("Replace in Files..."), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::R);
  2315. ED_SHORTCUT("script_text_editor/contextual_help", TTRC("Contextual Help"), KeyModifierMask::ALT | Key::F1);
  2316. ED_SHORTCUT_OVERRIDE("script_text_editor/contextual_help", "macos", KeyModifierMask::ALT | KeyModifierMask::SHIFT | Key::SPACE);
  2317. ED_SHORTCUT("script_text_editor/toggle_bookmark", TTRC("Toggle Bookmark"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::ALT | Key::B);
  2318. ED_SHORTCUT("script_text_editor/goto_next_bookmark", TTRC("Go to Next Bookmark"), KeyModifierMask::CMD_OR_CTRL | Key::B);
  2319. ED_SHORTCUT_OVERRIDE("script_text_editor/goto_next_bookmark", "macos", KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | KeyModifierMask::ALT | Key::B);
  2320. ED_SHORTCUT("script_text_editor/goto_previous_bookmark", TTRC("Go to Previous Bookmark"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::B);
  2321. ED_SHORTCUT("script_text_editor/remove_all_bookmarks", TTRC("Remove All Bookmarks"), Key::NONE);
  2322. ED_SHORTCUT("script_text_editor/goto_function", TTRC("Go to Function..."), KeyModifierMask::ALT | KeyModifierMask::CTRL | Key::F);
  2323. ED_SHORTCUT_OVERRIDE("script_text_editor/goto_function", "macos", KeyModifierMask::CTRL | KeyModifierMask::META | Key::J);
  2324. ED_SHORTCUT("script_text_editor/goto_line", TTRC("Go to Line..."), KeyModifierMask::CMD_OR_CTRL | Key::L);
  2325. ED_SHORTCUT("script_text_editor/goto_symbol", TTRC("Lookup Symbol"));
  2326. ED_SHORTCUT("script_text_editor/toggle_breakpoint", TTRC("Toggle Breakpoint"), Key::F9);
  2327. ED_SHORTCUT_OVERRIDE("script_text_editor/toggle_breakpoint", "macos", KeyModifierMask::META | KeyModifierMask::SHIFT | Key::B);
  2328. ED_SHORTCUT("script_text_editor/remove_all_breakpoints", TTRC("Remove All Breakpoints"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::F9);
  2329. // Using Control for these shortcuts even on macOS because Command+Comma is taken for opening Editor Settings.
  2330. ED_SHORTCUT("script_text_editor/goto_next_breakpoint", TTRC("Go to Next Breakpoint"), KeyModifierMask::CTRL | Key::PERIOD);
  2331. ED_SHORTCUT("script_text_editor/goto_previous_breakpoint", TTRC("Go to Previous Breakpoint"), KeyModifierMask::CTRL | Key::COMMA);
  2332. ScriptEditor::register_create_script_editor_function(create_editor);
  2333. }
  2334. void ScriptTextEditor::validate() {
  2335. code_editor->validate_script();
  2336. }