File: snipwiz.cpp

package info (click to toggle)
codelite 14.0+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 112,816 kB
  • sloc: cpp: 483,662; ansic: 150,144; php: 9,569; lex: 4,186; python: 3,417; yacc: 2,820; sh: 1,147; makefile: 52; xml: 13
file content (464 lines) | stat: -rw-r--r-- 17,396 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : snipwiz.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.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////
// Name:        snipwiz.cpp
// Purpose:
// Author:      Frank Lichtner
// Modified by:
// Created:     09/02/08
// RCS-ID:
// Copyright:   2008 Frank Lichtner
// Licence:		GNU General Public Licence
/////////////////////////////////////////////////////////////////////////////
#include "event_notifier.h"
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "editsnippetsdlg.h"
#include "snipwiz.h"
#include "swGlobals.h"
#include "templateclassdlg.h"
#include "workspace.h"
#include "wxSerialize.h"
#include <wx/clipbrd.h>
#include <wx/filename.h>
#include <wx/numdlg.h>
#include <wx/textdlg.h>
#include <wx/wfstream.h>
//------------------------------------------------------------

#define FRLSNIPWIZ_VERSION 1000
#define FRLSNIPWIZ_HEADER _T("Code snippet wizard file")

#define CARET wxT("@")
#define USER_ESC_CARET wxT("\\@")
#define SELECTION wxT("$")
#define USER_ESC_SELECTION wxT("\\$")
#define REAL_CARET_STR wxT("%CARET%")
#define REAL_SELECTION_STR wxT("%SELECTION%")
#define TMP_ESC_CARET_STR wxT("%ESC_CARET%")
#define TMP_ESC_SELECTION_STR wxT("%ESC_SELECTION%")

////------------------------------------------------------------
static SnipWiz* thePlugin = NULL;

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

CL_PLUGIN_API PluginInfo* GetPluginInfo()
{
    static PluginInfo info;
    info.SetAuthor(wxT("Frank Lichtner"));
    info.SetName(plugName);
    info.SetDescription(_("A small tool to add expandable code snippets and template classes"));
    info.SetVersion(wxT("v1.0"));
    return &info;
}
//------------------------------------------------------------
CL_PLUGIN_API int GetPluginInterfaceVersion() { return PLUGIN_INTERFACE_VERSION; }

//------------------------------------------------------------
// When creating new file, we default the EOL mode to
// the OS conventions
static int GetEOLByOS()
{
#if defined(__WXMAC__)
    return 1 /*wxSCI_EOL_CR*/;
#elif defined(__WXGTK__)
    return 2 /*wxSCI_EOL_LF*/;
#else
    return 0 /*wxSCI_EOL_CRLF*/;
#endif
}

//------------------------------------------------------------
SnipWiz::SnipWiz(IManager* manager)
    : IPlugin(manager)
{
    m_topWin = NULL;
    m_longName = _("Snippet wizard");
    m_shortName = plugName;
    m_topWin = m_mgr->GetTheApp();

    // get plugin path
    m_pluginPath = m_mgr->GetStartupDirectory();
    m_pluginPath += wxFILE_SEP_PATH;
    m_pluginPath += wxT("templates");
    m_pluginPath += wxFILE_SEP_PATH;
    if(!wxFileName::DirExists(m_pluginPath)) { wxFileName::Mkdir(m_pluginPath); }

    m_StringDb.SetCompress(true);

    m_StringDb.Load(m_pluginPath + defaultTmplFile);

    m_StringDb.GetAllSnippetKeys(m_snippets);
    if(!m_snippets.GetCount()) {
        IntSnippets();
        m_StringDb.GetAllSnippetKeys(m_snippets);
    }
    m_snippets.Sort();
    m_modified = false;
    m_clipboard.Empty();
    EventNotifier::Get()->Bind(wxEVT_CONTEXT_MENU_EDITOR, &SnipWiz::OnEditorContextMenu, this);
}

//------------------------------------------------------------
SnipWiz::~SnipWiz()
{
    if(m_modified) m_StringDb.Save(m_pluginPath + defaultTmplFile);
}
//------------------------------------------------------------

void SnipWiz::CreateToolBar(clToolBar* toolbar) { wxUnusedVar(toolbar); }
//------------------------------------------------------------

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

    item = new wxMenuItem(menu, IDM_SETTINGS, _("Settings..."), _("Settings..."), wxITEM_NORMAL);
    menu->Append(item);
    item = new wxMenuItem(menu, IDM_CLASS_WIZ, _("Template class..."), _("Template class..."), wxITEM_NORMAL);
    menu->Append(item);

    pluginsMenu->Append(wxID_ANY, plugName, menu);

    m_topWin->Connect(IDM_SETTINGS, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(SnipWiz::OnSettings), NULL,
                      this);
    m_topWin->Connect(IDM_CLASS_WIZ, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(SnipWiz::OnClassWizard), NULL,
                      this);

    m_topWin->Connect(IDM_EXP_SWITCH, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(SnipWiz::OnMenuExpandSwitch),
                      NULL, this);
    m_topWin->Connect(IDM_PASTE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(SnipWiz::OnMenuPaste), NULL, this);
    AttachDynMenus();
}

//------------------------------------------------------------
void SnipWiz::HookPopupMenu(wxMenu* menu, MenuType type)
{
    if(type == MenuTypeFileView_Folder) {
        // Create the popup menu for the virtual folders
        wxMenuItem* item(NULL);

        item = new wxMenuItem(menu, wxID_SEPARATOR);
        menu->Prepend(item);
        m_vdDynItems.push_back(item);

        item = new wxMenuItem(menu, IDM_CLASS_WIZ, _("New Class from Template..."), wxEmptyString, wxITEM_NORMAL);
        menu->Prepend(item);
        m_vdDynItems.push_back(item);
    }
}

//------------------------------------------------------------

void SnipWiz::UnPlug()
{
    m_topWin->Disconnect(IDM_SETTINGS, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(SnipWiz::OnSettings), NULL,
                         this);
    m_topWin->Disconnect(IDM_CLASS_WIZ, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(SnipWiz::OnClassWizard),
                         NULL, this);

    m_topWin->Disconnect(IDM_EXP_SWITCH, wxEVT_COMMAND_MENU_SELECTED,
                         wxCommandEventHandler(SnipWiz::OnMenuExpandSwitch), NULL, this);
    m_topWin->Disconnect(IDM_PASTE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(SnipWiz::OnMenuPaste), NULL,
                         this);

    EventNotifier::Get()->Unbind(wxEVT_CONTEXT_MENU_EDITOR, &SnipWiz::OnEditorContextMenu, this);
    DetachDynMenus();
}

//------------------------------------------------------------
void SnipWiz::OnMenuExpandSwitch(wxCommandEvent& e)
{
    IEditor* editor = GetEditor();
    if(!editor) return;

    bool isSelection = false;
    wxString var = editor->GetSelection();
    if(!var.IsEmpty()) isSelection = true;
    var = ::wxGetTextFromUser(_("Enter identifier name"), _("switch(...)"), var);
    if(var.IsEmpty()) return;
    long count = ::wxGetNumberFromUser(_("Enter number of cases"), _("Cases:"), _("switch(...)"), 1, 1, 20);
    if(count < 1) return;

    int curEol = editor->GetEOL();
    int curPos = editor->GetCurrentPosition();
    wxString tabs = GetTabs(editor, curPos);

    wxString output = wxString::Format(wxT("switch( %s )%s%s{%s"), var.c_str(), eol[curEol].c_str(), tabs.c_str(),
                                       eol[curEol].c_str());
    for(long i = 0; i < count; i++)
        output += wxString::Format(wxT("%scase :%s%sbreak;%s"), tabs.c_str(), eol[curEol].c_str(), tabs.c_str(),
                                   eol[curEol].c_str());

    output += tabs.c_str();
    output += wxT("}");
    if(isSelection)
        editor->ReplaceSelection(output);
    else
        editor->InsertText(curPos, output);
}

//------------------------------------------------------------
void SnipWiz::OnMenuSnippets(wxCommandEvent& e)
{
    IEditor* editor = GetEditor();
    if(!editor) return;

    bool crtl = ::wxGetKeyState(WXK_CONTROL);
    bool sourceIsMenu(false);

    wxMenu* m = dynamic_cast<wxMenu*>(e.GetEventObject());
    if(m) { sourceIsMenu = true; }

    if(e.GetId() >= IDM_ADDSTART && e.GetId() < (IDM_ADDSTART + (int)m_snippets.GetCount())) {
        wxString key = m_snippets.Item(e.GetId() - IDM_ADDSTART);
        wxString srText = m_StringDb.GetSnippetString(key);
        wxString selection = editor->GetSelection();

        // replace template eols with current
        int curEol = editor->GetEOL();
        if(srText.Find(eol[2]) != wxNOT_FOUND) srText.Replace(eol[2], eol[curEol].c_str());

        // Replace any escaped carets/selection strings
        srText.Replace(USER_ESC_CARET, TMP_ESC_CARET_STR);
        srText.Replace(USER_ESC_SELECTION, TMP_ESC_SELECTION_STR);
        srText.Replace(CARET, REAL_CARET_STR);
        srText.Replace(SELECTION, REAL_SELECTION_STR);

        // selection ?
        if(srText.Find(REAL_SELECTION_STR) != wxNOT_FOUND) srText.Replace(REAL_SELECTION_STR, selection.c_str());

        // restore the escaped selection, this time without the escaping backslash
        srText.Replace(TMP_ESC_SELECTION_STR, SELECTION);

        // restore the escaped caret, this time without the escaping backslash
        srText.Replace(TMP_ESC_CARET_STR, CARET);

        // if the user pressed control while clicking
        if(crtl && sourceIsMenu) {
            m_clipboard = srText;
            // remove caret mark if there
            srText.Replace(REAL_CARET_STR, wxT(""));

            // copy text to clipboard
            if(wxTheClipboard->Open()) {
                wxTheClipboard->SetData(new wxTextDataObject(srText));
                wxTheClipboard->Close();
            }
        } else {
            // otherwise insert text

            // format the text for insertion
            wxString output = FormatOutput(editor, srText);

            int curPos = editor->GetCurrentPosition();
            if(selection.Len() != 0) { curPos = editor->GetSelectionStart(); }

            // get caret position
            long cursorPos = output.Find(REAL_CARET_STR);
            if(cursorPos != wxNOT_FOUND) output.Remove(cursorPos, wxStrlen(REAL_CARET_STR));
            editor->ReplaceSelection(output);
            // set caret
            if(cursorPos != wxNOT_FOUND)
                editor->SetCaretAt(curPos + cursorPos);
            else
                editor->SetCaretAt(curPos + output.Len());
        }
    }
}
//------------------------------------------------------------
void SnipWiz::OnMenuPaste(wxCommandEvent& e)
{
    wxUnusedVar(e);
    IEditor* editor = GetEditor();
    if(!editor) return;

    if(m_clipboard.IsEmpty()) return;
    // otherwise insert text
    wxString output = FormatOutput(editor, m_clipboard);
    wxString selection = editor->GetSelection();
    int curPos = editor->GetCurrentPosition() - selection.Len();
    // get caret position
    long cursorPos = output.Find(REAL_CARET_STR);
    if(cursorPos != wxNOT_FOUND) output.Remove(cursorPos, wxStrlen(REAL_CARET_STR));
    editor->ReplaceSelection(output);
    // set caret
    if(cursorPos != wxNOT_FOUND)
        editor->SetCaretAt(curPos + cursorPos);
    else
        editor->SetCaretAt(curPos + output.Len());
}
//------------------------------------------------------------
wxString SnipWiz::FormatOutput(IEditor* pEditor, const wxString& text)
{
    wxString output = text;
    int curPos = pEditor->GetCurrentPosition();
    int curEol = pEditor->GetEOL();
    wxString tabs = GetTabs(pEditor, curPos);
    output.Replace(eol[curEol], eol[curEol] + tabs);
    return output;
}

//------------------------------------------------------------
wxMenu* SnipWiz::CreateSubMenu()
{
    wxMenu* parentMenu = new wxMenu();

    wxMenuItem* item(NULL);
    if(!m_clipboard.IsEmpty()) {
        item = new wxMenuItem(parentMenu, IDM_PASTE, _("Paste buffer"), _("Paste buffer"), wxITEM_NORMAL);
        parentMenu->Append(item);
        parentMenu->AppendSeparator();
    }
    item = new wxMenuItem(parentMenu, IDM_EXP_SWITCH, _("switch{...}"), _("switch{...}"), wxITEM_NORMAL);
    parentMenu->Append(item);
    parentMenu->AppendSeparator();

    for(wxUint32 i = 0; i < m_snippets.GetCount(); i++) {
        item = new wxMenuItem(parentMenu, IDM_ADDSTART + i, m_snippets.Item(i), m_snippets.Item(i), wxITEM_NORMAL);
        parentMenu->Append(item);
    }

    return parentMenu;
}
//------------------------------------------------------------
// opens settings
void SnipWiz::OnSettings(wxCommandEvent& e)
{
    EditSnippetsDlg dlg(m_mgr->GetTheApp()->GetTopWindow(), this, m_mgr);
    dlg.ShowModal();

    if(dlg.GetModified()) {
        m_snippets.Clear();
        m_StringDb.GetAllSnippetKeys(m_snippets);
        m_snippets.Sort();
        DetachDynMenus();
        AttachDynMenus();
        m_modified = true;
    }
}

//------------------------------------------------------------
// generate some default entries
void SnipWiz::IntSnippets()
{
    m_StringDb.SetSnippetString(wxT("//-"), wxT("//------------------------------------------------------------@"));
    m_StringDb.SetSnippetString(wxT("wxT(\""), wxT("wxT(\"@\")"));
    m_StringDb.SetSnippetString(wxT("wxT($"), wxT("wxT( $ )"));
    m_StringDb.SetSnippetString(wxT("if($"), wxT("if ( $ )\n{\n\t@\n}"));
    m_StringDb.SetSnippetString(wxT("whi($"), wxT("while ( $ )\n{\n\t@\n}"));
    m_StringDb.SetSnippetString(wxT("($)"), wxT("( $ )@"));
    m_StringDb.SetSnippetString(wxT("{$}"), wxT("{ $ }@"));
    m_StringDb.SetSnippetString(wxT("[$]"), wxT("[ $ ]@"));
    m_StringDb.SetSnippetString(wxT("wxU($"), wxT("wxUnusedVar( $ );@"));
    m_StringDb.SetSnippetString(wxT("for($"), wxT("for( $ = 0; $  < @; $++ )"));
    m_StringDb.SetSnippetString(wxT("for(Ii"), wxT("for( int i = 0; i  < $; i++ )@"));
    m_StringDb.SetSnippetString(wxT("for(Ui"), wxT("for( unsigned int i = 0; i  < $; i++ )@"));
}

//------------------------------------------------------------
// detach dynamic menus
void SnipWiz::DetachDynMenus()
{
    m_topWin->Disconnect(IDM_ADDSTART, IDM_ADDSTART + m_snippets.GetCount() - 1, wxEVT_COMMAND_MENU_SELECTED,
                         wxCommandEventHandler(SnipWiz::OnMenuSnippets), NULL, this);
}
//------------------------------------------------------------
// attach dynamic menus
void SnipWiz::AttachDynMenus()
{
    m_topWin->Connect(IDM_ADDSTART, IDM_ADDSTART + m_snippets.GetCount() - 1, wxEVT_COMMAND_MENU_SELECTED,
                      wxCommandEventHandler(SnipWiz::OnMenuSnippets), NULL, this);
}
//------------------------------------------------------------
// find current indentation
long SnipWiz::GetCurrentIndentation(IEditor* pEditor, long pos)
{
    wxString buffer = pEditor->GetEditorText().Left(pos);
    long tabCount = 0;
    wxChar ch = (pEditor->GetEOL() == 1) ? wxT('\r') : wxT('\n');
    buffer = buffer.AfterLast(ch);
    for(long i = 0; i < (long)buffer.Len(); i++)
        if(buffer.GetChar(i) == wxT('\t')) tabCount++;

    return tabCount;
}
//------------------------------------------------------------
// generates a string with tabs for current indentation
wxString SnipWiz::GetTabs(IEditor* pEditor, long pos)
{
    long indent = GetCurrentIndentation(pEditor, pos);
    wxString tabs = wxT("");
    for(long i = 0; i < indent; i++)
        tabs += wxT("\t");
    return tabs;
}
//------------------------------------------------------------
// returns pointer to editor
IEditor* SnipWiz::GetEditor()
{
    IEditor* editor = m_mgr->GetActiveEditor();
    if(!editor) {
        ::wxMessageBox(noEditor, codeLite, wxICON_WARNING | wxOK);
        return NULL;
    }
    return editor;
}
//------------------------------------------------------------
void SnipWiz::OnClassWizard(wxCommandEvent& e)
{
    TemplateClassDlg dlg(m_mgr->GetTheApp()->GetTopWindow(), this, m_mgr);

    dlg.SetCurEol(GetEOLByOS());
    dlg.SetPluginPath(m_pluginPath);
    dlg.ShowModal();
    if(dlg.GetModified()) { m_modified = true; }
}

void SnipWiz::OnEditorContextMenu(clContextMenuEvent& event)
{
    event.Skip();
    IEditor* editor = m_mgr->GetActiveEditor();
    CHECK_PTR_RET(editor);

    if(FileExtManager::IsCxxFile(editor->GetFileName())) {
        wxMenu* newMenu = CreateSubMenu();
        event.GetMenu()->Append(wxID_ANY, _("Snippets"), newMenu);
    }
}
//------------------------------------------------------------