File: context_base.cpp

package info (click to toggle)
codelite 12.0+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 95,112 kB
  • sloc: cpp: 424,040; ansic: 18,284; php: 9,569; lex: 4,186; yacc: 2,820; python: 2,294; sh: 312; makefile: 51; xml: 13
file content (370 lines) | stat: -rw-r--r-- 13,434 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : context_base.cpp
//
// -------------------------------------------------------------------------
// A
//              _____           _      _     _ _
//             /  __ \         | |    | |   (_) |
//             | /  \/ ___   __| | ___| |    _| |_ ___
//             | |    / _ \ / _  |/ _ \ |   | | __/ _ )
//             | \__/\ (_) | (_| |  __/ |___| | ||  __/
//              \____/\___/ \__,_|\___\_____/_|\__\___|
//
//                                                  F i l e
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#include <wx/xrc/xmlres.h>
#include "context_base.h"
#include "drawingutils.h"
#include <vector>
#include "editor_config.h"
#include "cl_editor.h"
#include "frame.h"
#include "ctags_manager.h"
#include "cl_command_event.h"
#include "event_notifier.h"
#include "plugin.h"
#include "macros.h"
#include "commentconfigdata.h"
#include "editor_config.h"
#include <wx/tokenzr.h>
#include <wx/regex.h>

// static wxColor GetInactiveColor(const wxColor& col)
//{
//    wxUnusedVar(col);
//#ifdef __WXGTK__
//    return wxColor(wxT("GREY"));
//#else
//    return wxColor(wxT("LIGHT GREY"));
//#endif
//}

ContextBase::ContextBase(LEditor* container)
    : m_container(container)
    , m_name(wxEmptyString)
{
}

ContextBase::ContextBase(const wxString& name)
    : m_name(name)
{
}

ContextBase::~ContextBase() {}

// provide basic indentation
void ContextBase::AutoIndent(const wxChar& ch)
{
    LEditor& rCtrl = GetCtrl();
    int prevpos(wxNOT_FOUND);
    int curpos = rCtrl.GetCurrentPos();
    int line = rCtrl.LineFromPosition(curpos);

    if(ch == wxT('\n')) {
        wxChar prevCh = rCtrl.PreviousChar(curpos, prevpos);
        if(prevCh == '{') {
            // an enter was hit just after an open brace
            int prevLine = rCtrl.LineFromPosition(prevpos);
            rCtrl.SetLineIndentation(line, rCtrl.GetIndent() + rCtrl.GetLineIndentation(prevLine));
            rCtrl.SetCaretAt(rCtrl.GetLineIndentPosition(line));

        } else {
            // just copy the previous line indentation
            int line = rCtrl.LineFromPosition(rCtrl.GetCurrentPos());
            rCtrl.SetLineIndentation(line, rCtrl.GetLineIndentation(line - 1));
            // place the caret at the end of the line
            rCtrl.SetCaretAt(rCtrl.GetLineIndentPosition(line));
            rCtrl.ChooseCaretX();
        }
    } else if(ch == '}' && !IsCommentOrString(curpos)) {
        long matchPos = wxNOT_FOUND;
        if(!rCtrl.MatchBraceBack(wxT('}'), rCtrl.PositionBefore(curpos), matchPos)) return;
        int secondLine = rCtrl.LineFromPosition(matchPos);
        if(secondLine == line) return;
        rCtrl.SetLineIndentation(line, rCtrl.GetLineIndentation(secondLine));
    }
}

void ContextBase::DoApplySettings(LexerConf::Ptr_t lexPtr) { lexPtr->Apply(&GetCtrl()); }

int ContextBase::GetHyperlinkRange(int pos, int& start, int& end)
{
    LEditor& rCtrl = GetCtrl();
    if(!IsCommentOrString(rCtrl.GetCurrentPos())) {
        // get tag as hyperlink
        start = rCtrl.WordStartPos(pos, true);
        end = rCtrl.WordEndPos(pos, true);
        if(start < end) return XRCID("find_tag");
    }
    return wxID_NONE;
}

void ContextBase::GoHyperlink(int start, int end, int type, bool alt)
{
    wxUnusedVar(start);
    wxUnusedVar(end);
    wxUnusedVar(type);
    wxUnusedVar(alt);
}

wxMenu* ContextBase::GetMenu() { return wxXmlResource::Get()->LoadMenu(wxT("editor_right_click_default")); }

void ContextBase::PrependMenuItem(wxMenu* menu, const wxString& text, wxObjectEventFunction func, int eventId)
{
    wxMenuItem* item;
    wxString menuItemText;
    if(eventId == -1) eventId = wxNewId();

    item = new wxMenuItem(menu, eventId, text);
    menu->Prepend(item);
    menu->Connect(eventId, wxEVT_COMMAND_MENU_SELECTED, func, NULL, this);
    m_dynItems.push_back(item);
}

void ContextBase::PrependMenuItem(wxMenu* menu, const wxString& text, int id)
{
    wxMenuItem* item;
    wxString menuItemText;
    item = new wxMenuItem(menu, id, text);
    menu->Prepend(item);
    m_dynItems.push_back(item);
}

void ContextBase::PrependMenuItemSeparator(wxMenu* menu)
{
    wxMenuItem* item;
    item = new wxMenuItem(menu, wxID_SEPARATOR);
    menu->Prepend(item);
    m_dynItems.push_back(item);
}

int ContextBase::DoGetCalltipParamterIndex()
{
    int index(0);
    LEditor& ctrl = GetCtrl();
    int pos = ctrl.DoGetOpenBracePos();
    if(pos != wxNOT_FOUND) {

        // loop over the text from pos -> current position and count the number of commas found
        int depth(0);
        while(pos < ctrl.GetCurrentPos()) {
            wxChar ch = ctrl.SafeGetChar(pos);
            // wxChar ch_before = ctrl.SafeGetChar(ctrl.PositionBefore(pos));

            if(IsCommentOrString(pos)) {
                pos = ctrl.PositionAfter(pos);
                continue;
            }

            switch(ch) {
            case wxT(','):
                if(depth == 0) index++;
                break;
            case wxT('('):
                depth++;
                break;
            case wxT(')'):
                depth--;
                break;
            default:
                break;
            }
            pos = ctrl.PositionAfter(pos);
        }
    } else {
        return wxNOT_FOUND;
    }
    return index;
}

void ContextBase::OnUserTypedXChars(const wxString& word)
{
    // user typed more than X chars
    // trigger code complete event (as if the user typed ctrl-space)
    // if no one handles this event, fire a word completion event
    if(IsCommentOrString(GetCtrl().GetCurrentPos())) {
        return;
    }

    const TagsOptionsData& options = TagsManagerST::Get()->GetCtagsOptions();
    if(options.GetFlags() & CC_WORD_ASSIST) {
        // Try to call code completion
        clCodeCompletionEvent ccEvt(wxEVT_CC_CODE_COMPLETE);
        ccEvt.SetEditor(&GetCtrl());
        ccEvt.SetPosition(GetCtrl().GetCurrentPos());
        ccEvt.SetWord(word);

        if(!EventNotifier::Get()->ProcessEvent(ccEvt)) {
            // This is ugly, since CodeLite should not be calling
            // the plugins... we take comfort in the fact that it
            // merely fires an event and not calling it directly
            wxCommandEvent wordCompleteEvent(wxEVT_MENU, XRCID("simple_word_completion"));
            EventNotifier::Get()->TopFrame()->GetEventHandler()->ProcessEvent(wordCompleteEvent);
        }
    }
}

void ContextBase::AutoAddComment()
{
    LEditor& rCtrl = GetCtrl();

    CommentConfigData data;
    EditorConfigST::Get()->ReadObject(wxT("CommentConfigData"), &data);

    int curpos = rCtrl.GetCurrentPos();
    int line = rCtrl.LineFromPosition(curpos);
    int cur_style = rCtrl.GetStyleAt(curpos);
    wxString text = rCtrl.GetLine(line - 1).Trim(false);

    bool dontadd = false;
    if(IsAtLineComment()) {
        dontadd = !text.StartsWith(wxT("//")) || !data.GetContinueCppComment();
    } else if(IsAtBlockComment()) {
        dontadd = !data.GetAddStarOnCComment();

    } else {
        dontadd = true;
    }

    if(dontadd) {
        ContextBase::AutoIndent(wxT('\n'));
        return;
    }

    wxString toInsert;
    if(IsAtLineComment()) {
        if(text.StartsWith(wxT("//"))) {
            toInsert = wxT("// ");
        }
    } else if(IsAtBlockComment()) {
        // Check the text typed before this char
        int startPos = rCtrl.PositionBefore(curpos);
        startPos -= 3; // for "/**"
        if(startPos >= 0) {
            wxString textTyped = rCtrl.GetTextRange(startPos, rCtrl.PositionBefore(curpos));
            if(((textTyped == "/**") || (textTyped == "/*!")) && data.IsAutoInsertAfterSlash2Stars()) {
                // Let the plugins/codelite check if they can provide a doxy comment
                // for the current entry
                clCodeCompletionEvent event(wxEVT_CC_GENERATE_DOXY_BLOCK);
                event.SetEditor(&rCtrl);
                if(EventNotifier::Get()->ProcessEvent(event) && !event.GetTooltip().IsEmpty()) {
                    rCtrl.BeginUndoAction();

                    // To make the doxy block fit in, we need to prepend each line
                    // with the exact whitespace of the line that starts with "/**"
                    int lineStartPos = rCtrl.PositionFromLine(rCtrl.LineFromPos(startPos));
                    wxString whitespace = rCtrl.GetTextRange(lineStartPos, startPos);
                    // Break the comment, for each line, prepend the 'whitespace' buffer
                    wxArrayString lines = ::wxStringTokenize(event.GetTooltip(), "\n", wxTOKEN_STRTOK);
                    for(size_t i = 0; i < lines.GetCount(); ++i) {
                        if(i) { // don't add it to the first line (it already exists in the editor)
                            lines.Item(i).Prepend(whitespace);
                        }
                    }

                    // Join the lines back
                    wxString doxyBlock = ::wxJoin(lines, '\n');

                    rCtrl.SetSelection(startPos, curpos);
                    rCtrl.ReplaceSelection(doxyBlock);

                    // Try to place the caret after the @brief
                    wxRegEx reBrief("[@\\]brief[ \t]*");
                    if(reBrief.IsValid() && reBrief.Matches(doxyBlock)) {
                        wxString match = reBrief.GetMatch(doxyBlock);
                        // Get the index
                        int where = doxyBlock.Find(match);
                        if(where != wxNOT_FOUND) {
                            where += match.length();
                            int caretPos = startPos + where;
                            rCtrl.SetCaretAt(caretPos);

                            // Remove the @brief as its non standard in the PHP world
                            rCtrl.DeleteRange(caretPos - match.length(), match.length());
                        }
                    }
                    rCtrl.EndUndoAction();
                    return;
                }
            }
        }

        if(rCtrl.GetStyleAt(rCtrl.PositionBefore(rCtrl.PositionBefore(curpos))) == cur_style) {
            toInsert = rCtrl.GetCharAt(rCtrl.GetLineIndentPosition(line - 1)) == wxT('*') ? wxT("* ") : wxT(" * ");
        }
    }

    if(!toInsert.IsEmpty()) {
        rCtrl.SetLineIndentation(line, rCtrl.GetLineIndentation(line - 1));
        int insertPos = rCtrl.GetLineIndentPosition(line);
        rCtrl.InsertText(insertPos, toInsert);
        rCtrl.SetCaretAt(insertPos + toInsert.Length());
        rCtrl.ChooseCaretX(); // set new column as "current" column
    }
}

bool ContextBase::IsStringTriggerCodeComplete(const wxString& str) const
{
    // default behavior is to check if 'str' exists in the m_completionTriggerStrings container
    if(GetCtrl().GetLexer() == wxSTC_LEX_XML) {
        return str == "<" || str == "</";
    } else if(GetCtrl().GetLexer() == wxSTC_LEX_CSS) {
        return str == ":";
    } else {
        return (m_completionTriggerStrings.count(str) > 0);
    }
}

int ContextBase::FindNext(const wxString& what, int& pos, bool wholePage)
{
    wxStyledTextCtrl* ctrl = GetCtrl().GetCtrl();
    int startpos(wxNOT_FOUND);
    int lastLine(wxNOT_FOUND);
    int endpos(wxNOT_FOUND);
    if(wholePage) {
        startpos = ctrl->GetCurrentPos();
        endpos = ctrl->GetLastPosition();
    } else {
        startpos = ctrl->PositionFromLine(ctrl->GetFirstVisibleLine());
        lastLine = ctrl->GetFirstVisibleLine() + ctrl->LinesOnScreen();
        endpos = ctrl->GetLineEndPosition(lastLine);
    }
    if((pos < startpos) || (pos > endpos)) return wxNOT_FOUND;
    int where = ctrl->FindText(pos, endpos, what);
    if(where != wxNOT_FOUND) {
        pos = where + what.length();
    }
    return where;
}

int ContextBase::FindPrev(const wxString& what, int& pos, bool wholePage)
{
    wxStyledTextCtrl* ctrl = GetCtrl().GetCtrl();
    int startpos(wxNOT_FOUND);
    int lastLine(wxNOT_FOUND);
    int endpos(wxNOT_FOUND);
    if(wholePage) {
        startpos = 0;
        endpos = ctrl->GetCurrentPos();
    } else {
        startpos = ctrl->PositionFromLine(ctrl->GetFirstVisibleLine());
        lastLine = ctrl->GetFirstVisibleLine() + ctrl->LinesOnScreen();
        endpos = ctrl->GetLineEndPosition(lastLine);
    }
    if((pos < startpos) || (pos > endpos)) return wxNOT_FOUND;
    int where = ctrl->FindText(pos, startpos, what);
    if(where != wxNOT_FOUND) {
        pos = where;
    }
    return where;
}