1 /*
2 SPDX-FileCopyrightText: 2009 Milian Wolff <mail@milianw.de>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
7 #include "includefileitem.h"
8
9 #include <KTextEditor/Document>
10 #include <KTextEditor/View>
11
12 using namespace KTextEditor;
13
14 namespace Php {
15
execute(View * view,const Range & _word)16 void IncludeFileItem::execute(View* view, const Range& _word)
17 {
18 KTextEditor::Document *document = view->document();
19 Range word(_word);
20
21 QString newText;
22
23 if ( includeItem.isDirectory ) {
24 newText = includeItem.name + '/';
25 } else {
26 newText = includeItem.name;
27 }
28
29 // Add suffix
30 QChar closeChar;
31 {
32 const QString textBefore = document->text(Range(Cursor(0, 0), _word.start()));
33 QRegExp regexp("(?:include|require)(?:_once)?(\\s*)(\\(?)(\\s*)(?:dirname\\s*\\(\\s*__FILE__\\s*\\)\\s*\\.\\s*)?([\"'])", Qt::CaseInsensitive);
34
35 if ( regexp.lastIndexIn(textBefore) != -1 ) {
36 closeChar = regexp.cap(4).at(0);
37
38 newText.append(closeChar);
39 if ( !regexp.cap(2).isEmpty() ) {
40 newText.append(regexp.cap(3));
41 newText.append(')');
42 }
43 newText.append(';');
44 }
45 }
46
47 // Adapt range and replace existing stuff
48 {
49 const QString textAfter = document->text(Range(_word.end(), document->documentEnd()));
50 if ( !textAfter.isEmpty() ) {
51 int pos = 0;
52 for (; pos < textAfter.length(); ++pos ) {
53 if ( textAfter[pos].isSpace() ) {
54 break;
55 } else if ( textAfter[pos] == closeChar ) {
56 // remove close char
57 ++pos;
58 // find semicolon (if existing)
59 for (int i = pos; i < textAfter.length(); ++i ) {
60 if ( textAfter[i] == ';' ) {
61 // remove semicolon
62 pos = i + 1;
63 break;
64 } else if ( !textAfter[i].isSpace() && textAfter[i] != ')' ) {
65 break;
66 }
67 }
68 break;
69 }
70 }
71 if ( pos > 0 ) {
72 word.setEnd(word.end() + Cursor(0, pos));
73 }
74 }
75 }
76
77 document->replaceText(word, newText);
78
79 // when we complete a directory, move the cursor behind it so we can continue with auto-completion
80 if ( includeItem.isDirectory ) {
81 if (view) {
82 view->setCursorPosition(Cursor(_word.start().line(), _word.start().column() + includeItem.name.size() + 1));
83 }
84 }
85 }
86
87 }
88