File: abbreviation.cpp

package info (click to toggle)
codelite 17.0.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 136,204 kB
  • sloc: cpp: 491,547; ansic: 280,393; php: 10,259; sh: 8,930; lisp: 7,664; vhdl: 6,518; python: 6,020; lex: 4,920; yacc: 3,123; perl: 2,385; javascript: 1,715; cs: 1,193; xml: 1,110; makefile: 804; cobol: 741; sql: 709; ruby: 620; f90: 566; ada: 534; asm: 464; fortran: 350; objc: 289; tcl: 258; java: 157; erlang: 61; pascal: 51; ml: 49; awk: 44; haskell: 36
file content (361 lines) | stat: -rw-r--r-- 12,798 bytes parent folder | download | duplicates (3)
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
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : abbreviation.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 "abbreviation.h"

#include "abbreviationentry.h"
#include "abbreviationssettingsdlg.h"
#include "clKeyboardManager.h"
#include "cl_config.h"
#include "event_notifier.h"
#include "globals.h"
#include "macromanager.h"
#include "wxCodeCompletionBoxEntry.hpp"
#include "wxCodeCompletionBoxManager.h"

#include <algorithm>
#include <wx/app.h>
#include <wx/bitmap.h>
#include <wx/clntdata.h>
#include <wx/log.h>
#include <wx/menu.h>
#include <wx/regex.h>
#include <wx/textdlg.h>
#include <wx/xrc/xmlres.h>

static AbbreviationPlugin* thePlugin = NULL;

// Define the plugin entry point
CL_PLUGIN_API IPlugin* CreatePlugin(IManager* manager)
{
    if(thePlugin == 0) {
        thePlugin = new AbbreviationPlugin(manager);
    }
    return thePlugin;
}

CL_PLUGIN_API PluginInfo* GetPluginInfo()
{
    static PluginInfo info;
    info.SetAuthor("Eran Ifrah");
    info.SetName("Abbreviation");
    info.SetDescription(_("Abbreviation plugin"));
    info.SetVersion("v1.1");
    return &info;
}

CL_PLUGIN_API int GetPluginInterfaceVersion() { return PLUGIN_INTERFACE_VERSION; }

class AbbreviationClientData : public wxClientData
{
public:
    AbbreviationClientData() {}
    virtual ~AbbreviationClientData() {}
};

AbbreviationPlugin::AbbreviationPlugin(IManager* manager)
    : IPlugin(manager)
    , m_topWindow(NULL)
    , m_config("abbreviations.conf")
{
    m_longName = _("Abbreviation plugin");
    m_shortName = "Abbreviation";
    m_topWindow = m_mgr->GetTheApp();
    EventNotifier::Get()->Bind(wxEVT_CCBOX_SELECTION_MADE, &AbbreviationPlugin::OnAbbrevSelected, this);

    EventNotifier::Get()->Bind(wxEVT_CCBOX_SHOWING, &AbbreviationPlugin::OnCompletionBoxShowing, this);
    // m_helper = new AbbreviationServiceProvider(this);
    InitDefaults();
}

AbbreviationPlugin::~AbbreviationPlugin() {}

void AbbreviationPlugin::CreateToolBar(clToolBarGeneric* toolbar) { wxUnusedVar(toolbar); }

void AbbreviationPlugin::CreatePluginMenu(wxMenu* pluginsMenu)
{
    wxMenu* menu = new wxMenu();
    wxMenuItem* item(NULL);

    item = new wxMenuItem(menu, XRCID("abbrev_insert"), _("Show abbreviations completion box"),
                          _("Show abbreviations completion box"), wxITEM_NORMAL);
    menu->Append(item);
    menu->AppendSeparator();
    item = new wxMenuItem(menu, XRCID("abbrev_settings"), _("Settings..."), _("Settings..."), wxITEM_NORMAL);
    menu->Append(item);

    pluginsMenu->Append(XRCID("abbreviations_plugin_menu"), _("Abbreviation"), menu);
    m_topWindow->Bind(wxEVT_MENU, &AbbreviationPlugin::OnSettings, this, XRCID("abbrev_settings"));
    m_topWindow->Bind(wxEVT_MENU, &AbbreviationPlugin::OnShowAbbvreviations, this, XRCID("abbrev_insert"));
}

void AbbreviationPlugin::HookPopupMenu(wxMenu* menu, MenuType type)
{
    wxUnusedVar(menu);
    wxUnusedVar(type);
}

void AbbreviationPlugin::UnPlug()
{
    DeletePluginMenu(XRCID("abbreviations_plugin_menu"));
    m_topWindow->Unbind(wxEVT_MENU, &AbbreviationPlugin::OnSettings, this, XRCID("abbrev_settings"));
    m_topWindow->Unbind(wxEVT_MENU, &AbbreviationPlugin::OnShowAbbvreviations, this, XRCID("abbrev_insert"));
    EventNotifier::Get()->Unbind(wxEVT_CCBOX_SELECTION_MADE, &AbbreviationPlugin::OnAbbrevSelected, this);
    EventNotifier::Get()->Unbind(wxEVT_CCBOX_SHOWING, &AbbreviationPlugin::OnCompletionBoxShowing, this);
}

void AbbreviationPlugin::OnSettings(wxCommandEvent& e)
{
    AbbreviationsSettingsDlg dlg(m_mgr->GetTheApp()->GetTopWindow(), m_mgr);
    dlg.ShowModal();
    m_config.Reload();
}

void AbbreviationPlugin::GetAbbreviations(wxCodeCompletionBoxEntry::Vec_t& V, const wxString& filter)
{
    wxString lcFilter = filter.Lower();

    AbbreviationJSONEntry jsonData;
    if(!m_config.ReadItem(&jsonData)) {
        // merge the data from the old configuration
        AbbreviationEntry data;
        m_mgr->GetConfigTool()->ReadObject("AbbreviationsData", &data);

        jsonData.SetAutoInsert(data.GetAutoInsert());
        jsonData.SetEntries(data.GetEntries());
        m_config.WriteItem(&jsonData);
    }

    wxBitmap bmp = clGetManager()->GetStdIcons()->LoadBitmap("replace-blue");
    if(bmp.IsOk()) {
        // search for the old item
        const wxStringMap_t& entries = jsonData.GetEntries();
        std::for_each(entries.begin(), entries.end(), [&](const wxStringMap_t::value_type& vt) {
            // Only add matching entries (entries that "starts_with")
            wxString lcAbbv = vt.first.Lower();
            if(lcAbbv.StartsWith(lcFilter)) {
                // Append our entries
                wxString textHelp;
                textHelp << "**Abbreviation entry**\n===```" << vt.second << "```";
                V.push_back(wxCodeCompletionBoxEntry::New(vt.first, textHelp, bmp, new AbbreviationClientData()));
            }
        });
    }
}

void AbbreviationPlugin::OnAbbrevSelected(clCodeCompletionEvent& e)
{
    if(!e.GetEntry()) {
        e.Skip();
        return;
    }

    AbbreviationClientData* cd = dynamic_cast<AbbreviationClientData*>(e.GetEntry()->GetClientData());
    if(!cd) {
        e.Skip();
        return;
    }
    InsertExpansion(e.GetWord());
}

void AbbreviationPlugin::InitDefaults()
{
    // check to see if there are any abbreviations configured
    AbbreviationJSONEntry jsonData;
    if(!m_config.ReadItem(&jsonData)) {
        // merge the data from the old configuration
        AbbreviationEntry data;
        m_mgr->GetConfigTool()->ReadObject("AbbreviationsData", &data);

        jsonData.SetAutoInsert(data.GetAutoInsert());
        jsonData.SetEntries(data.GetEntries());
        m_config.WriteItem(&jsonData);
    }

    // search for the old item
    if(jsonData.GetEntries().empty()) {
        // fill some default abbreviations
        wxStringMap_t entries;
        entries["main"] = "int main(int argc, char **argv) {\n    |\n}\n";
        entries["while"] = "while(|) {\n    \n}\n";
        entries["dowhile"] = "do {\n    \n} while( | );\n";
        entries["for_size"] = "for(size_t |=0; |<; ++|) {\n}\n";
        entries["for_int"] = "for(int |=0; |<; ++|) {\n}\n";
        entries["for_php"] = "for($|=0; $|<; ++$|) {\n}\n";
        jsonData.SetEntries(entries);
        m_config.WriteItem(&jsonData);
    }
    clKeyboardManager::Get()->AddAccelerator("abbrev_insert", _("Abbreviations"),
                                             _("Show abbreviations completion box"), "Ctrl-Alt-SPACE");
}

bool AbbreviationPlugin::InsertExpansion(const wxString& abbreviation)
{
    // get the active editor
    IEditor* editor = m_mgr->GetActiveEditor();
    if(!editor || abbreviation.IsEmpty()) {
        return false;
    }

    // search for abbreviation that matches str
    // prepate list of abbreviations
    AbbreviationJSONEntry jsonData;
    if(!m_config.ReadItem(&jsonData)) {
        // merge the data from the old configuration
        AbbreviationEntry data;
        m_mgr->GetConfigTool()->ReadObject("AbbreviationsData", &data);

        jsonData.SetAutoInsert(data.GetAutoInsert());
        jsonData.SetEntries(data.GetEntries());
        m_config.WriteItem(&jsonData);
    }

    // search for the old item
    const wxStringMap_t& entries = jsonData.GetEntries();
    wxStringMap_t::const_iterator iter = entries.find(abbreviation);

    if(iter != entries.end()) {

        wxString text = iter->second;
        int selStart = editor->WordStartPos(editor->GetCurrentPosition(), true);
        int selEnd = editor->WordEndPos(editor->GetCurrentPosition(), true);
        int curPos = editor->GetCurrentPosition();
        int typedWordLen = curPos - selStart;
        wxString textOrig;
        wxString textLeadingSpaces;

        if(typedWordLen < 0) {
            typedWordLen = 0;
        }

        // format the text to insert
        bool appendEol(false);
        if(text.EndsWith("\r") || text.EndsWith("\n")) {
            appendEol = true;
        }

        textOrig = text;
        text.Trim(false);
        textLeadingSpaces = textOrig.Left(textOrig.length() - text.length());

        text = editor->FormatTextKeepIndent(text, selStart, Format_Text_Save_Empty_Lines);

        // remove the first line indenation that might have been placed by CL
        text.Trim(false).Trim();
        text = textLeadingSpaces + text;

        if(appendEol) {
            wxString eol;
            switch(editor->GetEOL()) {
            case 1:
                eol = "\r";
                break;
            case 0:
                eol = "\r\n";
                break;
            case 2:
                eol = "\n";
                break;
            }
            text << eol;
        }

        //--------------------------------------------
        // replace any place holders
        //--------------------------------------------
        wxString project;
        text = MacroManager::Instance()->Expand(text, m_mgr, editor->GetProjectName());

        // locate the caret(s)
        std::vector<int> carets;
        int where = text.Find("|");
        while(where != wxNOT_FOUND) {
            carets.push_back(where);
            where = text.find('|', where + 1);
        }

        // remove the pipe (|) character
        text.Replace("|", " ");

        if(selEnd - selStart >= 0) {
            editor->SelectText(selStart, selEnd - selStart);
            editor->ReplaceSelection(text);
            editor->GetCtrl()->ClearSelections();

            bool first = true;
            std::for_each(carets.begin(), carets.end(), [&](int where) {
                int caretPos = curPos + where - typedWordLen;
                if(first) {
                    editor->GetCtrl()->SetSelection(caretPos, caretPos + 1);
                    first = false;
                } else {
                    editor->GetCtrl()->AddSelection(caretPos, caretPos + 1);
                }
            });
        }
        return true;
    } else
        return false;
}

void AbbreviationPlugin::OnCompletionBoxShowing(clCodeCompletionEvent& event) { event.Skip(); }

void AbbreviationPlugin::OnShowAbbvreviations(wxCommandEvent& e)
{
    e.Skip();
    IEditor* editor = clGetManager()->GetActiveEditor();
    CHECK_PTR_RET(editor);

    wxStyledTextCtrl* ctrl = editor->GetCtrl();
    wxCodeCompletionBoxEntry::Vec_t V;
    GetAbbreviations(V, editor->GetWordAtPosition(editor->GetCurrentPosition()));
    if(!V.empty()) {
        wxCodeCompletionBoxManager::Get().ShowCompletionBox(ctrl, V, wxCodeCompletionBox::kRefreshOnKeyType,
                                                            wxNOT_FOUND);
    }
}

// Helper
// AbbreviationServiceProvider::AbbreviationServiceProvider(AbbreviationPlugin* plugin)
//    : ServiceProvider("Abbreviations", eServiceType::kCodeCompletion)
//    , m_plugin(plugin)
//{
//    SetPriority(10);
//    Bind(wxEVT_CC_WORD_COMPLETE, &AbbreviationServiceProvider::OnWordComplete, this);
//}
//
// AbbreviationServiceProvider::~AbbreviationServiceProvider()
//{
//    Unbind(wxEVT_CC_WORD_COMPLETE, &AbbreviationServiceProvider::OnWordComplete, this);
//}
//
// void AbbreviationServiceProvider::OnWordComplete(clCodeCompletionEvent& event)
//{
//    event.Skip();
//    if(event.GetTriggerKind() == LSP::CompletionItem::kTriggerUser) {
//        // user used Ctr-SPACE
//        m_plugin->AddAbbreviations(event);
//    }
//}