void TestStyleExporter::testHashChar() {
    FormatOptions opts;
    opts.useFontSize(false);
    StyleExporter e(CEDPagePtr(), opts);
    CEDChar c1, c2;

    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));
    c1.setColor(Color(100, 0, 0));
    CPPUNIT_ASSERT(e.hash(c1) != e.hash(c2));
    c2.setColor(c1.color());
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));
    c1.setBackgroundColor(Color(0, 100, 0));
    CPPUNIT_ASSERT(e.hash(c1) != e.hash(c2));
    c2.setBackgroundColor(c1.backgroundColor());
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));

    e.formatOptions().useFontSize(false);
    c1.setFontHeight(10);
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));
    e.formatOptions().useFontSize(true);
    CPPUNIT_ASSERT(e.hash(c1) != e.hash(c2));
    c2.setFontHeight(c1.fontHeight());
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));

    e.formatOptions().useItalic(false);
    c1.setFontStyle(FONT_ITALIC);
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));
    e.formatOptions().useItalic(true);
    CPPUNIT_ASSERT(e.hash(c1) != e.hash(c2));
    c2.setFontStyle(FONT_ITALIC);
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));

    e.formatOptions().useBold(false);
    c1.setFontStyle(FONT_BOLD);
    c2.setFontStyle(0);
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));
    e.formatOptions().useBold(true);
    CPPUNIT_ASSERT(e.hash(c1) != e.hash(c2));
    c2.setFontStyle(FONT_BOLD);
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));

    c1.setFontStyle(FONT_UNDERLINE);
    c2.setFontStyle(0);
    CPPUNIT_ASSERT(e.hash(c1) != e.hash(c2));
    c2.setFontStyle(FONT_UNDERLINE);
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));

    c1.setFontStyle(FONT_SUPER);
    c2.setFontStyle(0);
    CPPUNIT_ASSERT(e.hash(c1) != e.hash(c2));
    c2.setFontStyle(FONT_SUPER);
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));

    c1.setFontStyle(FONT_SUB);
    c2.setFontStyle(0);
    CPPUNIT_ASSERT(e.hash(c1) != e.hash(c2));
    c2.setFontStyle(FONT_SUB);
    CPPUNIT_ASSERT_EQUAL(e.hash(c1), e.hash(c2));
}
Exemple #2
0
bool CodeFormatter::BatchFormat(const std::vector<wxFileName>& files)
{
    FormatOptions options;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &options);

    if(options.GetEngine() == kFormatEngineAStyle) {
        return AStyleBatchFOrmat(files, options);

    } else if(options.GetEngine() == kFormatEngineClangFormat) {
        return ClangBatchFormat(files, options);
    }
}
Exemple #3
0
void CodeFormatter::OnFormatString(clSourceFormatEvent& e)
{
    wxString str = e.GetInputString();
    if(str.IsEmpty()) {
        e.SetFormattedString(str);
        return;
    }

    // execute the formatter
    FormatOptions fmtroptions;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &fmtroptions);

    wxString output;
    if(FileExtManager::IsPHPFile(e.GetFileName())) {
        // use the built-in PHP formatter
        // Construct the formatting options
        PHPFormatterOptions phpOptions;
        phpOptions.flags = fmtroptions.GetPHPFormatterOptions();
        if(m_mgr->GetEditorSettings()->GetIndentUsesTabs()) {
            phpOptions.flags |= kPFF_UseTabs;
        }
        phpOptions.indentSize = m_mgr->GetEditorSettings()->GetTabWidth();
        phpOptions.eol = m_mgr->GetEditorSettings()->GetEOLAsString();
        // Create the formatter buffer
        PHPFormatterBuffer buffer(e.GetInputString(), phpOptions);

        // Format the source
        buffer.format();

        // set the output
        output = buffer.GetBuffer();

    } else if(fmtroptions.GetEngine() == kFormatEngineAStyle) {
        wxString options = fmtroptions.AstyleOptionsAsString();

        // determine indentation method and amount
        bool useTabs = m_mgr->GetEditorSettings()->GetIndentUsesTabs();
        int tabWidth = m_mgr->GetEditorSettings()->GetTabWidth();
        int indentWidth = m_mgr->GetEditorSettings()->GetIndentWidth();
        options << (useTabs && tabWidth == indentWidth ? wxT(" -t") : wxT(" -s")) << indentWidth;

        AstyleFormat(str, options, output);
        output << DoGetGlobalEOLString();

    } else if(fmtroptions.GetEngine() == kFormatEngineClangFormat) {
        ClangPreviewFormat(str, output, fmtroptions);

    } else {
        // ??
    }
    e.SetFormattedString(output);
}
Exemple #4
0
bool CodeFormatter::BatchFormat(const std::vector<wxFileName>& files)
{
    FormatOptions options;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &options);

    switch(options.GetEngine()) {
    case kFormatEngineAStyle:
        return AStyleBatchFOrmat(files, options);
    case kFormatEngineClangFormat:
        return ClangBatchFormat(files, options);
    }
    return false;
}
Exemple #5
0
void CodeFormatter::OnBeforeFileSave(clCommandEvent& e)
{
    e.Skip();
    FormatOptions fmtroptions;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &fmtroptions);
    if(fmtroptions.HasFlag(kCF_AutoFormatOnFileSave)) {
        // format the file before we save it
        IEditor* editor = m_mgr->FindEditor(e.GetFileName());
        if(editor && m_mgr->GetActiveEditor() == editor) {
            // we have our editor, format it
            DoFormatFile(editor);
        }
    }
}
Exemple #6
0
bool CodeFormatter::AStyleBatchFOrmat(const std::vector<wxFileName>& files, const FormatOptions& options)
{
    wxString fmtOptions = options.AstyleOptionsAsString();

    wxProgressDialog dlg(
        _("Source Code Formatter"), _("Formatting files..."), (int)files.size(), m_mgr->GetTheApp()->GetTopWindow());
    for(size_t i = 0; i < files.size(); ++i) {

        wxString content;
        if(!FileUtils::ReadFileContent(files.at(i), content)) {
            CL_WARNING("Failed to read file content. File: %s", files.at(i).GetFullPath());
            continue;
        }

        wxString msg;
        msg << "[ " << i << " / " << files.size() << " ] " << files.at(i).GetFullName();
        dlg.Update(i, msg);

        // determine indentation method and amount
        bool useTabs = m_mgr->GetEditorSettings()->GetIndentUsesTabs();
        int tabWidth = m_mgr->GetEditorSettings()->GetTabWidth();
        int indentWidth = m_mgr->GetEditorSettings()->GetIndentWidth();
        fmtOptions << (useTabs && tabWidth == indentWidth ? wxT(" -t") : wxT(" -s")) << indentWidth;

        wxString output;
        AstyleFormat(content, fmtOptions, output);
        output << DoGetGlobalEOLString();

        // Replace the content of the file
        if(!FileUtils::WriteFileContent(files.at(i), output)) {
            CL_WARNING("Failed to write file content. File: %s", files.at(i).GetFullPath());
        }
    }
    return true;
}
void TestLocalRecognitionServer::testRecognizeImage()
{
    TRACE();

    LocalRecognitionServer server;
    ImagePtr img;
    BinarizeOptions bopts;
    RecognizeOptions ropts;
    FormatOptions fopts;
    fopts.writeBom(false);

    // null image
    CPPUNIT_ASSERT_THROW(server.recognizeImage(img, bopts, ropts, fopts),
                         AbstractRecognitionServer::RecognitionException);

    img.reset(new Image());

    // invalid image
    CPPUNIT_ASSERT_THROW(server.recognizeImage(img, bopts, ropts, fopts),
                         AbstractRecognitionServer::RecognitionException);

    // normal image
    img = ImageLoaderFactory::instance().load(URL("/english.png"));

    CEDPagePtr p = server.recognizeImage(img, bopts, ropts, fopts);
    CPPUNIT_ASSERT(p.get());
    CPPUNIT_ASSERT(!p->empty());

    TextExporter exp(p, fopts);
    std::ostringstream buf;
    exp.exportTo(buf);
    CPPUNIT_ASSERT_EQUAL(boost::algorithm::trim_copy(buf.str()), std::string("ENGLISH"));
    buf.str("");

    // debug off
    DebugExporter dexp(fopts);
    dexp.exportTo(buf);
    CPPUNIT_ASSERT(boost::algorithm::trim_copy(buf.str()).empty());
    buf.str("");

    // debug on
    server.setTextDebug(true);
    server.recognizeImage(img, bopts, ropts, fopts);
    dexp.exportTo(buf);
    CPPUNIT_ASSERT(!boost::algorithm::trim_copy(buf.str()).empty());
    CPPUNIT_ASSERT_EQUAL(boost::algorithm::trim_copy(buf.str()), std::string("ENGLISH"));
}
Exemple #8
0
bool CodeFormatter::ClangBatchFormat(const std::vector<wxFileName>& files, const FormatOptions& options)
{
    if(options.GetClangFormatExe().IsEmpty()) {
        return false;
    }

    wxProgressDialog dlg(
        _("Source Code Formatter"), _("Formatting files..."), (int)files.size(), m_mgr->GetTheApp()->GetTopWindow());

    clClangFormatLocator locator;
    double version = locator.GetVersion(options.GetClangFormatExe());

    for(size_t i = 0; i < files.size(); ++i) {
        wxString command, file;
        command << options.GetClangFormatExe();
        ::WrapWithQuotes(command);

        command << " -i "; // inline editing
        command << options.ClangFormatOptionsAsString(files.at(i), version);
        file = files.at(i).GetFullPath();
        ::WrapWithQuotes(file);
        command << " " << file;

        // Wrap the command in the local shell
        ::WrapInShell(command);

        // Log the command
        CL_DEBUG("CodeForamtter: running:\n%s\n", command);

        wxString msg;
        msg << "[ " << i << " / " << files.size() << " ] " << files.at(i).GetFullName();
        dlg.Update(i, msg);

        // Execute clang-format and read the output
        IProcess::Ptr_t clangFormatProc(
            ::CreateSyncProcess(command, IProcessCreateDefault | IProcessCreateWithHiddenConsole));
        CHECK_PTR_RET_FALSE(clangFormatProc);

        wxString output;
        clangFormatProc->WaitForTerminate(output);
        CL_DEBUG("clang-format returned with:\n%s\n", output);
    }

    EventNotifier::Get()->PostReloadExternallyModifiedEvent(false);
    return true;
}
Exemple #9
0
bool CodeFormatter::PhpFormat(const wxString& content, wxString& formattedOutput, const FormatOptions& options)
{
    // Construct the formatting options
    PHPFormatterOptions phpOptions;
    phpOptions.flags = options.GetPHPFormatterOptions();
    if(m_mgr->GetEditorSettings()->GetIndentUsesTabs()) {
        phpOptions.flags |= kPFF_UseTabs;
    }
    phpOptions.indentSize = m_mgr->GetEditorSettings()->GetTabWidth();
    phpOptions.eol = m_mgr->GetEditorSettings()->GetEOLAsString();
    // Create the formatter buffer
    PHPFormatterBuffer buffer(content, phpOptions);

    // Format the source
    buffer.format();
    formattedOutput << buffer.GetBuffer();
    return true;
}
Exemple #10
0
CodeFormatter::CodeFormatter(IManager* manager)
    : IPlugin(manager)
{
    m_longName = _("Source Code Formatter");
    m_shortName = wxT("Source Code Formatter");

    EventNotifier::Get()->Connect(
        wxEVT_FORMAT_STRING, clSourceFormatEventHandler(CodeFormatter::OnFormatString), NULL, this);
    EventNotifier::Get()->Connect(
        wxEVT_FORMAT_FILE, clSourceFormatEventHandler(CodeFormatter::OnFormatFile), NULL, this);
    m_mgr->GetTheApp()->Connect(ID_TOOL_SOURCE_CODE_FORMATTER,
                                wxEVT_COMMAND_MENU_SELECTED,
                                wxCommandEventHandler(CodeFormatter::OnFormatProject),
                                NULL,
                                this);
    EventNotifier::Get()->Bind(wxEVT_BEFORE_EDITOR_SAVE, clCommandEventHandler(CodeFormatter::OnBeforeFileSave), this);
    
    // Migrate settings if needed
    FormatOptions fmtroptions;
    m_mgr->GetConfigTool()->ReadObject("FormatterOptions", &fmtroptions);
    if(fmtroptions.GetEngine() == kFormatEngineClangFormat) {
        // check to see that the selected clang executable exists
        wxFileName clangFomatExe(fmtroptions.GetClangFormatExe());
        if(fmtroptions.GetClangFormatExe().IsEmpty() || !clangFomatExe.Exists()) {
            // No valid clang executable found, try to locate one
            clClangFormatLocator locator;
            wxString clangFormatPath;
            if(locator.Locate(clangFormatPath)) {
                fmtroptions.SetClangFormatExe(clangFormatPath);
            } else {
                // Change the active engine to AStyle
                fmtroptions.SetEngine(kFormatEngineAStyle);
                fmtroptions.SetClangFormatExe(""); // Clear the non existed executable
            }
            
            
        }
    }
    // Save the options
    EditorConfigST::Get()->WriteObject("FormatterOptions", &fmtroptions);
}
Exemple #11
0
bool CodeFormatter::DoClangFormat(const wxFileName& filename,
                                  wxString& formattedOutput,
                                  int& cursorPosition,
                                  int startOffset,
                                  int length,
                                  const FormatOptions& options)
{
    // clang-format
    // Build the command line to run

    if(options.GetClangFormatExe().IsEmpty()) {
        return false;
    }

    wxString command, file;

    clClangFormatLocator locator;
    double version = locator.GetVersion(options.GetClangFormatExe());

    command << options.GetClangFormatExe();
    file = filename.GetFullPath();
    ::WrapWithQuotes(command);
    ::WrapWithQuotes(file);

    command << options.ClangFormatOptionsAsString(filename, version);
    if(cursorPosition != wxNOT_FOUND) {
        command << " -cursor=" << cursorPosition;
    }

    if(startOffset != wxNOT_FOUND && length != wxNOT_FOUND) {
        command << " -offset=" << startOffset << " -length=" << length;
    }
    command << " " << file;

    // Wrap the command in the local shell
    ::WrapInShell(command);

    // Log the command
    CL_DEBUG("CodeForamtter: running:\n%s\n", command);

    // Execute clang-format and reand the output
    formattedOutput.Clear();
    IProcess::Ptr_t clangFormatProc(
        ::CreateSyncProcess(command, IProcessCreateDefault | IProcessCreateWithHiddenConsole));
    CHECK_PTR_RET_FALSE(clangFormatProc);
    clangFormatProc->WaitForTerminate(formattedOutput);
    CL_DEBUG("clang-format returned with:\n%s\n", formattedOutput);

    if(formattedOutput.IsEmpty()) {
        // crash?
        return false;
    }

    // The first line contains the cursor position
    if(cursorPosition != wxNOT_FOUND) {
        wxString metadata = formattedOutput.BeforeFirst('\n');
        JSONRoot root(metadata);
        cursorPosition = root.toElement().namedObject("cursor").toInt(wxNOT_FOUND);
        formattedOutput = formattedOutput.AfterFirst('\n');
    }
    return true;
}
Exemple #12
0
void CodeFormatter::OnFormatString(clSourceFormatEvent& e)
{
    wxString str = e.GetInputString();
    if(str.IsEmpty()) {
        e.SetFormattedString(str);
        return;
    }

    // execute the formatter
    FormatOptions fmtroptions;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &fmtroptions);

    wxString output;
    if(FileExtManager::IsPHPFile(e.GetFileName())) {

        if(fmtroptions.GetPhpEngine() == kPhpFormatEngineBuiltin) {
            // use the built-in PHP formatter
            // Construct the formatting options
            PHPFormatterOptions phpOptions;
            phpOptions.flags = fmtroptions.GetPHPFormatterOptions();
            if(m_mgr->GetEditorSettings()->GetIndentUsesTabs()) {
                phpOptions.flags |= kPFF_UseTabs;
            }
            phpOptions.indentSize = m_mgr->GetEditorSettings()->GetTabWidth();
            phpOptions.eol = m_mgr->GetEditorSettings()->GetEOLAsString();
            // Create the formatter buffer
            PHPFormatterBuffer buffer(e.GetInputString(), phpOptions);

            // Format the source
            buffer.format();

            // set the output
            output = buffer.GetBuffer();
        } else {
            wxFileName php(fmtroptions.GetPhpExecutable());
            if(!php.Exists()) {
                ::wxMessageBox(_("Can not format file using PHP-CS-Fixer: Missing PHP executable path"),
                               "Code Formatter",
                               wxICON_ERROR | wxOK | wxCENTER);
                return;
            }
            wxFileName phar(fmtroptions.GetPHPCSFixerPhar());
            if(!phar.Exists()) {
                ::wxMessageBox(_("Can not format file using PHP-CS-Fixer: Missing PHAR file"),
                               "Code Formatter",
                               wxICON_ERROR | wxOK | wxCENTER);
                return;
            }

            // Run the command, PHP-CS-Fixer works directly on the file
            //
            output.Clear();
            IProcess::Ptr_t phpFixer(::CreateSyncProcess(fmtroptions.GetPhpFixerCommand(),
                                                         IProcessCreateDefault | IProcessCreateWithHiddenConsole));
            CHECK_PTR_RET(phpFixer);
            phpFixer->WaitForTerminate(output);
        }
    } else if(fmtroptions.GetEngine() == kFormatEngineAStyle) {
        wxString options = fmtroptions.AstyleOptionsAsString();

        // determine indentation method and amount
        bool useTabs = m_mgr->GetEditorSettings()->GetIndentUsesTabs();
        int tabWidth = m_mgr->GetEditorSettings()->GetTabWidth();
        int indentWidth = m_mgr->GetEditorSettings()->GetIndentWidth();
        options << (useTabs && tabWidth == indentWidth ? wxT(" -t") : wxT(" -s")) << indentWidth;

        AstyleFormat(str, options, output);
        output << DoGetGlobalEOLString();

    } else if(fmtroptions.GetEngine() == kFormatEngineClangFormat) {
        ClangPreviewFormat(str, output, fmtroptions);

    } else {
        // ??
    }
    e.SetFormattedString(output);
}
Exemple #13
0
void CodeFormatter::DoFormatFile(IEditor* editor)
{
    int curpos = editor->GetCurrentPosition();

    // execute the formatter
    FormatOptions fmtroptions;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &fmtroptions);
    if(FileExtManager::IsPHPFile(editor->GetFileName())) {

        if(fmtroptions.GetPhpEngine() == kPhpFormatEngineBuiltin) {

            // use the built-in PHP formatter

            // Construct the formatting options
            PHPFormatterOptions phpOptions;
            phpOptions.flags = fmtroptions.GetPHPFormatterOptions();
            if(m_mgr->GetEditorSettings()->GetIndentUsesTabs()) {
                phpOptions.flags |= kPFF_UseTabs;
            }
            phpOptions.indentSize = m_mgr->GetEditorSettings()->GetTabWidth();
            phpOptions.eol = m_mgr->GetEditorSettings()->GetEOLAsString();
            // Create the formatter buffer
            PHPFormatterBuffer buffer(editor->GetCtrl()->GetText(), phpOptions);

            // Format the source
            buffer.format();

            // Restore line
            if(!buffer.GetBuffer().IsEmpty()) {
                clSTCLineKeeper lk(editor);
                editor->GetCtrl()->BeginUndoAction();
                // Replace the text with the new formatted buffer
                editor->SetEditorText(buffer.GetBuffer());
                editor->GetCtrl()->EndUndoAction();
            }
        } else {
            wxFileName php(fmtroptions.GetPhpExecutable());
            if(!php.Exists()) {
                ::wxMessageBox(_("Can not format file using PHP-CS-Fixer: Missing PHP executable path"),
                               "Code Formatter",
                               wxICON_ERROR | wxOK | wxCENTER);
                return;
            }
            wxFileName phar(fmtroptions.GetPHPCSFixerPhar());
            if(!phar.Exists()) {
                ::wxMessageBox(_("Can not format file using PHP-CS-Fixer: Missing PHAR file"),
                               "Code Formatter",
                               wxICON_ERROR | wxOK | wxCENTER);
                return;
            }

            // Run the command, PHP-CS-Fixer works directly on the file
            // so create a copy of the file and format it, then replace the buffers
            // we do this like this so we won't lose our ability to undo the action
            wxString output;
            wxString command, filename, tmpfile;
            filename = editor->GetFileName().GetFullPath();
            tmpfile << filename << ".php-cs-fixer";
            if(!FileUtils::WriteFileContent(tmpfile, editor->GetEditorText())) {
                ::wxMessageBox(_("Can not format file using PHP-CS-Fixer:\nFailed to write temporary file"),
                               "Code Formatter",
                               wxICON_ERROR | wxOK | wxCENTER);
                return;
            }

            // Ensure that the temporary file is deleted once we are done with it
            FileUtils::Deleter fd(tmpfile);

            ::WrapWithQuotes(tmpfile);
            command << fmtroptions.GetPhpFixerCommand() << " " << tmpfile;
            ::WrapInShell(command);
            IProcess::Ptr_t phpFixer(
                ::CreateSyncProcess(command, IProcessCreateDefault | IProcessCreateWithHiddenConsole));
            CHECK_PTR_RET(phpFixer);
            phpFixer->WaitForTerminate(output);

            output.clear();
            if(!FileUtils::ReadFileContent(tmpfile, output)) {
                ::wxMessageBox(_("Can not format file using PHP-CS-Fixer:\nfailed to read temporary file content"),
                               "Code Formatter",
                               wxICON_ERROR | wxOK | wxCENTER);
                return;
            }

            // Update the editor
            clEditorStateLocker lk(editor->GetCtrl());
            editor->GetCtrl()->BeginUndoAction();
            editor->SetEditorText(output);
            editor->GetCtrl()->EndUndoAction();
        }

    } else {
        // We allow ClangFormat to work only when the source file is known to be
        // a C/C++ source file or JavaScript (these are the types of files that clang-format can handle properly)
        if(fmtroptions.GetEngine() == kFormatEngineClangFormat &&
           (FileExtManager::IsCxxFile(editor->GetFileName()) ||
            FileExtManager::IsJavascriptFile(editor->GetFileName()))) {

            int from = wxNOT_FOUND, length = wxNOT_FOUND;
            wxString formattedOutput;
            if(editor->GetSelectionStart() != wxNOT_FOUND) {
                // we got a selection, only format it
                from = editor->GetSelectionStart();
                length = editor->GetSelectionEnd() - from;
                if(length <= 0) {
                    from = wxNOT_FOUND;
                    length = wxNOT_FOUND;
                }
            }

            // Make sure we format the editor string and _not_ the file (there might be some newly added lines
            // that could be missing ...)
            if(!ClangFormatBuffer(
                   editor->GetCtrl()->GetText(), editor->GetFileName(), formattedOutput, curpos, from, length)) {
                ::wxMessageBox(_("Source code formatting error!"), "CodeLite", wxICON_ERROR | wxOK | wxCENTER);
                return;
            }

            clEditorStateLocker lk(editor->GetCtrl());
            editor->GetCtrl()->BeginUndoAction();
            editor->SetEditorText(formattedOutput);
            editor->SetCaretAt(curpos);
            editor->GetCtrl()->EndUndoAction();

        } else {
            // AStyle
            wxString options = fmtroptions.AstyleOptionsAsString();

            // determine indentation method and amount
            bool useTabs = m_mgr->GetEditorSettings()->GetIndentUsesTabs();
            int tabWidth = m_mgr->GetEditorSettings()->GetTabWidth();
            int indentWidth = m_mgr->GetEditorSettings()->GetIndentWidth();
            options << (useTabs && tabWidth == indentWidth ? wxT(" -t") : wxT(" -s")) << indentWidth;

            wxString output;
            wxString inputString;
            bool formatSelectionOnly(editor->GetSelection().IsEmpty() == false);

            if(formatSelectionOnly) {
                // get the lines contained in the selection
                int selStart = editor->GetSelectionStart();
                int selEnd = editor->GetSelectionEnd();
                int lineNumber = editor->LineFromPos(selStart);

                selStart = editor->PosFromLine(lineNumber);
                selEnd = editor->LineEnd(editor->LineFromPos(selEnd));

                editor->SelectText(selStart, selEnd - selStart);
                inputString = editor->GetSelection();

            } else {
                inputString = editor->GetEditorText();
            }

            AstyleFormat(inputString, options, output);
            if(!output.IsEmpty()) {

                // append new-line
                wxString eol;
                if(editor->GetEOL() == 0) { // CRLF
                    eol = wxT("\r\n");
                } else if(editor->GetEOL() == 1) { // CR
                    eol = wxT("\r");
                } else {
                    eol = wxT("\n");
                }

                if(!formatSelectionOnly) output << eol;

                if(formatSelectionOnly) {
                    clEditorStateLocker lk(editor->GetCtrl());
                    // format the text (add the indentation)
                    output = editor->FormatTextKeepIndent(output,
                                                          editor->GetSelectionStart(),
                                                          Format_Text_Indent_Prev_Line | Format_Text_Save_Empty_Lines);
                    editor->ReplaceSelection(output);

                } else {
                    clEditorStateLocker lk(editor->GetCtrl());
                    editor->SetEditorText(output);
                }
            }
        }
    }
    // Notify that a file was indented
    wxCommandEvent evt(wxEVT_CODEFORMATTER_INDENT_COMPLETED);
    evt.SetString(editor->GetFileName().GetFullPath());
    EventNotifier::Get()->AddPendingEvent(evt);
}
Exemple #14
0
void CodeFormatter::DoFormatFile(IEditor* editor)
{
    int curpos = editor->GetCurrentPosition();

    // execute the formatter
    FormatOptions fmtroptions;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &fmtroptions);
    if(FileExtManager::IsPHPFile(editor->GetFileName())) {
        // use the built-in PHP formatter

        // Construct the formatting options
        PHPFormatterOptions phpOptions;
        phpOptions.flags = fmtroptions.GetPHPFormatterOptions();
        if(m_mgr->GetEditorSettings()->GetIndentUsesTabs()) {
            phpOptions.flags |= kPFF_UseTabs;
        }
        phpOptions.indentSize = m_mgr->GetEditorSettings()->GetTabWidth();
        phpOptions.eol = m_mgr->GetEditorSettings()->GetEOLAsString();
        // Create the formatter buffer
        PHPFormatterBuffer buffer(editor->GetCtrl()->GetText(), phpOptions);

        // Format the source
        buffer.format();

        // Restore line
        clSTCLineKeeper lk(editor);
        editor->GetCtrl()->BeginUndoAction();
        // Replace the text with the new formatted buffer
        editor->SetEditorText(buffer.GetBuffer());

        // Restore caret position
        editor->SetCaretAt(curpos);
        
        editor->GetCtrl()->EndUndoAction();
        
    } else {
        // We allow ClangFormat to work only when the source file is known to be
        // a C/C++ source file or JavaScript (these are the types of files that clang-format can handle properly)
        if(fmtroptions.GetEngine() == kFormatEngineClangFormat &&
           (FileExtManager::IsCxxFile(editor->GetFileName()) ||
            FileExtManager::IsJavascriptFile(editor->GetFileName()))) {

            int from = wxNOT_FOUND, length = wxNOT_FOUND;
            wxString formattedOutput;
            if(editor->GetSelectionStart() != wxNOT_FOUND) {
                // we got a selection, only format it
                from = editor->GetSelectionStart();
                length = editor->GetSelectionEnd() - from;
                if(length <= 0) {
                    from = wxNOT_FOUND;
                    length = wxNOT_FOUND;
                }
            }

            // Make sure we format the editor string and _not_ the file (there might be some newly added lines
            // that could be missing ...)
            if(!ClangFormatBuffer(
                   editor->GetCtrl()->GetText(), editor->GetFileName(), formattedOutput, curpos, from, length)) {
                ::wxMessageBox(_("Source code formatting error!"), "CodeLite", wxICON_ERROR | wxOK | wxCENTER);
                return;
            }

            clEditorStateLocker lk(editor->GetCtrl());
            editor->GetCtrl()->BeginUndoAction();
            editor->SetEditorText(formattedOutput);
            editor->SetCaretAt(curpos);
            editor->GetCtrl()->EndUndoAction();

        } else {
            // AStyle
            wxString options = fmtroptions.AstyleOptionsAsString();

            // determine indentation method and amount
            bool useTabs = m_mgr->GetEditorSettings()->GetIndentUsesTabs();
            int tabWidth = m_mgr->GetEditorSettings()->GetTabWidth();
            int indentWidth = m_mgr->GetEditorSettings()->GetIndentWidth();
            options << (useTabs && tabWidth == indentWidth ? wxT(" -t") : wxT(" -s")) << indentWidth;

            wxString output;
            wxString inputString;
            bool formatSelectionOnly(editor->GetSelection().IsEmpty() == false);

            if(formatSelectionOnly) {
                // get the lines contained in the selection
                int selStart = editor->GetSelectionStart();
                int selEnd = editor->GetSelectionEnd();
                int lineNumber = editor->LineFromPos(selStart);

                selStart = editor->PosFromLine(lineNumber);
                selEnd = editor->LineEnd(editor->LineFromPos(selEnd));

                editor->SelectText(selStart, selEnd - selStart);
                inputString = editor->GetSelection();

            } else {
                inputString = editor->GetEditorText();
            }

            AstyleFormat(inputString, options, output);
            if(!output.IsEmpty()) {

                // append new-line
                wxString eol;
                if(editor->GetEOL() == 0) { // CRLF
                    eol = wxT("\r\n");
                } else if(editor->GetEOL() == 1) { // CR
                    eol = wxT("\r");
                } else {
                    eol = wxT("\n");
                }

                if(!formatSelectionOnly) output << eol;

                if(formatSelectionOnly) {
                    clEditorStateLocker lk(editor->GetCtrl());
                    // format the text (add the indentation)
                    output = editor->FormatTextKeepIndent(output,
                                                          editor->GetSelectionStart(),
                                                          Format_Text_Indent_Prev_Line | Format_Text_Save_Empty_Lines);
                    editor->ReplaceSelection(output);

                } else {
                    clEditorStateLocker lk(editor->GetCtrl());
                    editor->SetEditorText(output);
                }
            }
        }
    }
    // Notify that a file was indented
    wxCommandEvent evt(wxEVT_CODEFORMATTER_INDENT_COMPLETED);
    evt.SetString(editor->GetFileName().GetFullPath());
    EventNotifier::Get()->AddPendingEvent(evt);
}