Exemplo n.º 1
0
        private void UpdateSNList()
        {
            Editor = new ScintillaGateway(PluginBase.GetCurrentScintilla());
            List <SourceNavigationItem> SNList = new List <SourceNavigationItem>();

            SNList.Clear();
            SNList.Add(new SourceNavigationItem
            {
                Name       = "<TOP>",
                LineNumber = 0
            });
            if (Editor.GetTextLength() <= 999999)
            {
                string          text    = Editor.GetText(Editor.GetTextLength());
                string          search  = @"^[\s]*([\w|-]+)[\s]+(SECTION|DIVISION)[\s]*\.[\s]*$";
                MatchCollection matches = Regex.Matches(text, search, RegexOptions.Multiline | RegexOptions.IgnoreCase);
                if (matches.Count > 0)
                {
                    foreach (Match match in matches)
                    {
                        SNList.Add(new SourceNavigationItem
                        {
                            Name       = ((match.Groups[2].Value.StartsWith("SECTION", StringComparison.OrdinalIgnoreCase) ? " " : "") + match.Groups[1].Value + " " + match.Groups[2].Value).ToUpper(),
                            LineNumber = Editor.LineFromPosition(new Position(match.Index))
                        });
                    }
                }
            }
            PostDataToSNListBox(SNList);
        }
Exemplo n.º 2
0
        private static void EnsureFirstWordIsSelected(ScNotification notification)
        {
            if (isPluginActive)
            {
                nppResource.ClearIndicator();

                if (notification.Header.Code == (ulong)SciMsg.SCN_UPDATEUI)
                {
                    var scintillaGateway = new ScintillaGateway(PluginBase.GetCurrentScintilla());
                    var currentPosition  = scintillaGateway.GetCurrentPos();
                    if (currentPosition != lastPositionWhenUiUpdate)
                    {
                        if (scintillaGateway.GetSelectionEmpty())
                        {
                            lastPositionWhenUiUpdate = firstWordSelector.SelectFirstWordOfLine(scintillaGateway);
                        }
                    }
                    return;
                }

                if (notification.Header.Code == (ulong)SciMsg.SCN_MODIFIED)
                {
                    var isTextInsertedOrDeleted = (notification.ModificationType &
                                                   ((int)SciMsg.SC_MOD_INSERTTEXT | (int)SciMsg.SC_MOD_DELETETEXT)) > 0;
                    if (isTextInsertedOrDeleted)
                    {
                        lastPositionWhenUiUpdate = null;
                    }
                }
            }
        }
Exemplo n.º 3
0
        private static void ScrollToLine(int sectionImplementationLine)
        {
            var editor        = new ScintillaGateway(PluginBase.GetCurrentScintilla());
            int linesOnScreen = editor.LinesOnScreen();

            editor.SetFirstVisibleLine(sectionImplementationLine - linesOnScreen / 2 + 1 < 0 ? 0 : sectionImplementationLine - linesOnScreen / 2 + 1);
        }
Exemplo n.º 4
0
        public static void OnNotification(ScNotification notification)
        {
            if (notification.Header.Code == (ulong)NppMsg.NPPN_BUFFERACTIVATED)
            {
                isPluginActive = IsGitRebaseFile();
                return;
            }

            if (notification.Header.Code == (ulong)NppMsg.NPPN_FILEOPENED)
            {
                if (IsGitRebaseFile())
                {
                    var scintillaGateway = new ScintillaGateway(PluginBase.GetCurrentScintilla());

                    AddTextToRebaseFile(scintillaGateway);

                    DisableAutoCompletePopup(scintillaGateway);

                    SetSyntaxHighlighting();
                }

                return;
            }

            EnsureFirstWordIsSelected(notification);
        }
Exemplo n.º 5
0
        private static void MoveLineDown()
        {
            var scintillaGateway = new ScintillaGateway(PluginBase.GetCurrentScintilla());

            scintillaGateway.SelectCurrentLine();
            scintillaGateway.MoveSelectedLinesDown();
            scintillaGateway.ClearSelectionToCursor();
        }
Exemplo n.º 6
0
        public static void CheckAndSwitchOnCobolWords()
        {
            var editor = new ScintillaGateway(PluginBase.GetCurrentScintilla());

            if (!editor.GetWordChars().Contains("-"))
            {
                SetCobolLikeWords(true);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Find and capitalize the first letter of the beginning of all
        /// sentences in a document.
        /// </summary>
        internal static void CapSentence()
        {
            // Get current scintilla instance.
            IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
            ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);

            try
            {
                // Get the length of the document.
                int length = scintillaGateway.GetLength();
                // Get the text in the document.
                string allText = scintillaGateway.GetText(length + 1);

                // Convert the text to char array for easy manipulation.
                char[] charArrayAllText = allText.ToCharArray();

                char firstLetter   = new char();
                bool capAfterPunct = true;

                // For the length of the selected text...
                for (int i = 0; i < allText.Length; i++)
                {
                    // If there is punctuation that ends a sentence
                    // the next word should be capitalized.
                    if (allText[i] == '.' || allText[i] == '?' || allText[i] == '!' || allText[i] == '\r')
                    {
                        capAfterPunct = true;
                    }
                    // Don't capitalize Markdown titles in this method.
                    else if (allText[i] == '#')
                    {
                        capAfterPunct = false;
                    }

                    if (capAfterPunct && !ignoreChars.Contains(allText[i]))
                    {
                        // If the current character is not a whitespace character
                        // convert the first letter of the word to uppercase.
                        firstLetter = Convert.ToChar(allText[i].ToString().ToUpperInvariant());
                        // Replace the correct char in the selected text with its uppercase letter.
                        charArrayAllText.SetValue(firstLetter, i);
                        // Revert to false until beginning of next sentence.
                        capAfterPunct = false;
                    }
                }
                // Convert char array back to string.
                allText = new string(charArrayAllText);
                // Replace the document text with the new text.
                scintillaGateway.SelectAll();
                scintillaGateway.ReplaceSel(allText);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Exemplo n.º 8
0
        private static void CopySelectionOrLine()
        {
            var scintilla = new ScintillaGateway(PluginBase.GetCurrentScintilla());

            if (scintilla.GetSelectionLength() != 0)
            {
                scintilla.Copy();
            }
            else
            {
                scintilla.CopyAllowLine();
            }
        }
Exemplo n.º 9
0
        private void GotoSelectedSection()
        {
            Editor = new ScintillaGateway(PluginBase.GetCurrentScintilla());
            SourceNavigationItem selectedItem = (SourceNavigationItem)SNListBox.SelectedItem;
            int    line          = selectedItem.LineNumber;
            int    linesOnScreen = Editor.LinesOnScreen();
            string sectionName   = selectedItem.Name.Trim().Split(' ')[0];
            string lineText      = Editor.GetLine(line).ToUpper();

            Editor.GotoLine(line);
            Editor.SetFirstVisibleLine(line - linesOnScreen / 2 + 1 < 0 ? 0 : line - linesOnScreen / 2 + 1);
            Editor.SetSelection(Editor.PositionFromLine(line).Value + lineText.IndexOf(sectionName) + sectionName.Length, Editor.PositionFromLine(line).Value + lineText.IndexOf(sectionName));
            Editor.GrabFocus();
        }
Exemplo n.º 10
0
        private static void GotoSectionOrPerform()
        {
            if (SNDialogStruct.Form == null)
            {
                SourceNavigationDialog();
            }
            var editor = new ScintillaGateway(PluginBase.GetCurrentScintilla());

            CheckAndSwitchOnCobolWords();
            editor.SetSelection(editor.WordEndPosition(editor.GetCurrentPos(), true), editor.WordStartPosition(editor.GetCurrentPos(), true));

            if (editor.GetSelectionLength() == 0)
            {
                return;
            }
            // If new search
            if (sectionName != editor.GetSelText().ToUpper())
            {
                sectionName = editor.GetSelText().ToUpper();
                int sectionImplementationLine = GetSectionImplementationLine(sectionName);
                if (sectionImplementationLine >= 0)
                {
                    if (editor.GetCurrentLineNumber() == sectionImplementationLine)
                    {
                        if (!SearchNextSectionOrPerform(sectionName, editor.GetCurrentPos().Value))
                        {
                            SearchNextSectionOrPerform(sectionName, 0);
                        }
                    }
                    else
                    {
                        ScrollToLine(sectionImplementationLine);
                        CurrentSearchOffset = sectionImplementationLine;
                    }
                }
                else
                {
                    sectionName = "";
                }
            }
            //If continuing search
            else
            {
                if (!SearchNextSectionOrPerform(sectionName, CurrentSearchOffset))
                {
                    SearchNextSectionOrPerform(sectionName, 0);
                }
            }
        }
Exemplo n.º 11
0
        internal static void myMenuFunction()
        {
            IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
            ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);
            // Get selected text.
            string selectedText = scintillaGateway.GetSelText();


            var lines = selectedText.Split('\n');
            //var html = "<table style='box-sizing: inherit; font-family: arial, sans-serif; border-collapse: collapse; color: rgb(0, 0, 0); font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;'>";

            var myHtml = generator.GenerateMarkdown(lines);

            ClipboardHelper.CopyToClipboard(selectedText, myHtml);
        }
Exemplo n.º 12
0
        private void FrmSNDlg_SNListBox_Context_Click(object sender, EventArgs e)
        {
            Editor = new ScintillaGateway(PluginBase.GetCurrentScintilla());
            int    line          = int.Parse(((ToolStripItem)sender).Text.Split(':')[0]) - 1;
            int    linesOnScreen = Editor.LinesOnScreen();
            string lineText      = Editor.GetLine(line);

            Editor.GotoLine(line);
            Editor.SetFirstVisibleLine(line - linesOnScreen / 2 + 1 < 0 ? 0 : line - linesOnScreen / 2 + 1);
            string sectionName = lineText.Trim().Split(' ')[1];

            Editor.SetSelection(Editor.WordEndPosition(new Position(Editor.PositionFromLine(line).Value + lineText.IndexOf(sectionName)), true), Editor.PositionFromLine(line).Value + lineText.IndexOf(sectionName));
            Editor.GrabFocus();
            ((ToolStripItem)sender).Owner.Dispose();
        }
Exemplo n.º 13
0
        internal static void printDebugLine()
        {
            IntPtr           hCurrScintilla = PluginBase.GetCurrentScintilla();
            ScintillaGateway sci            = new ScintillaGateway(hCurrScintilla);
            var lineNumber       = sci.GetCurrentLineNumber() + 1;
            NotepadPPGateway npp = new NotepadPPGateway();
            var fileName         = Path.GetFileNameWithoutExtension(npp.GetCurrentFilePath());
            var stream           = new FileStream(@"plugins/Config/GoToDefinition/debug_table.txt", FileMode.Open, FileAccess.Read);

            using (var streamReader = new StreamReader(stream, Encoding.UTF8))
            {
                var text = streamReader.ReadToEnd();
                text = text + $"'{fileName}', {lineNumber}, )";
                sci.AddText(text.Length, text);
            }
        }
Exemplo n.º 14
0
        private void SNListBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Editor = new ScintillaGateway(PluginBase.GetCurrentScintilla());
                ContextMenuStrip menuStrip = new ContextMenuStrip();
                int index = SNListBox.IndexFromPoint(e.X, e.Y);
                SNListBox.SetSelected(index, true);
                string          text    = Editor.GetText(Editor.GetTextLength());
                string          search  = @"^[ ]*PERFORM[\s]*" + ((SourceNavigationItem)SNListBox.Items[index]).Name.Trim().Split(' ')[0] + @"[\s]*[\.]{0,1}[\s]*$";
                MatchCollection matches = Regex.Matches(text, search, RegexOptions.Multiline | RegexOptions.IgnoreCase);
                if (matches.Count > 0)
                {
                    foreach (Match match in matches)
                    {
                        string itemName = "";
                        foreach (SourceNavigationItem item in GetStoredSectionsList())
                        {
                            int    line        = Editor.LineFromPosition(new Position(match.Index));
                            string currentText = "";
                            if (item.LineNumber > line)
                            {
                                break;
                            }
                            else
                            {
                                currentText = item.Name.Trim().Split(' ')[0];
                            }
                            if (currentText != "")
                            {
                                itemName = (line + 1) + ": " + currentText;
                            }
                            Editor.LineFromPosition(new Position(match.Index));
                        }

                        menuStrip.Items.Add(itemName).Click += FrmSNDlg_SNListBox_Context_Click;
                    }
                }
                if (menuStrip.Items.Count > 0)
                {
                    menuStrip.Show(SNListBox, e.X, e.Y);
                }
            }
        }
Exemplo n.º 15
0
        private static void FormatRtf()
        {
            IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
            ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);

            string allText = scintillaGateway.GetAllText();

            if (!IsTextRtf(allText))
            {
                return;
            }

            string newText = rtfFormatter.GetFormattedText(allText);

            if (allText != newText)
            {
                scintillaGateway.SetText(newText);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Find and capitalize all Markdown Titles in the document.
        /// </summary>
        internal static void CapitalizeMDTitles()
        {
            // Get scintilla gateway.
            IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
            ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);

            string line;

            // Get the number of lines in the document.
            int numLines = scintillaGateway.GetLineCount();

            // Traverse through each line.
            for (int i = 0; i < numLines; i++)
            {
                // Set line to the current line.
                line = scintillaGateway.GetLine(i);

                // Check each character in the line to see if it begins
                // with a '#'.
                for (int j = 0; j < line.Length; j++)
                {
                    if (line[j] == '#')
                    {
                        // If it begins with '#', select the line and call
                        // the CapitalizeTitle method with these parameters.
                        scintillaGateway.GotoLine(i);
                        scintillaGateway.SetSel(scintillaGateway.PositionFromLine(i), scintillaGateway.GetLineEndPosition(i));
                        CapitalizeTitle();
                        break;
                    }
                    // Support for Setext headers.
                    else if ((line[j] == '-' || line[j] == '=') && !IsAlphaNumeric(line))
                    {
                        // If it begins with '-' or '=', select the previous line and call
                        // the CapitalizeTitle method with these parameters.
                        scintillaGateway.GotoLine(i - 1);
                        scintillaGateway.SetSel(scintillaGateway.PositionFromLine(i - 1), scintillaGateway.GetLineEndPosition(i - 1));
                        CapitalizeTitle();
                        break;
                    }
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Returns a string containing the last word typed.
        /// </summary>
        /// <returns>string</returns>
        internal static string getLastWord()
        {
            IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
            ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);

            var selectionStart = scintillaGateway.GetCurrentPos();
            var selectionEnd   = scintillaGateway.GetCurrentPos();
            var endOfVariable  = scintillaGateway.GetCurrentPos();

            scintillaGateway.WordLeft();
            selectionStart = scintillaGateway.GetCurrentPos();
            scintillaGateway.WordRight();
            selectionEnd  = scintillaGateway.GetCurrentPos();
            endOfVariable = selectionEnd;

            scintillaGateway.SetSel(selectionStart, selectionEnd);

            return(scintillaGateway.GetSelText());
        }
Exemplo n.º 18
0
        internal static void myDockableDialog()
        {
            if (frmMyDlg == null)
            {
                frmMyDlg = new frmMyDlg();

                using (Bitmap newBmp = new Bitmap(16, 16))
                {
                    Graphics   g        = Graphics.FromImage(newBmp);
                    ColorMap[] colorMap = new ColorMap[1];
                    colorMap[0]          = new ColorMap();
                    colorMap[0].OldColor = Color.Fuchsia;
                    colorMap[0].NewColor = Color.FromKnownColor(KnownColor.ButtonFace);
                    ImageAttributes attr = new ImageAttributes();
                    attr.SetRemapTable(colorMap);
                    g.DrawImage(tbBmp_tbTab, new Rectangle(0, 0, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel, attr);
                    tbIcon = Icon.FromHandle(newBmp.GetHicon());
                }

                NppTbData _nppTbData = new NppTbData();
                _nppTbData.hClient       = frmMyDlg.Handle;
                _nppTbData.pszName       = "My dockable dialog";
                _nppTbData.dlgID         = idMyDlg;
                _nppTbData.uMask         = NppTbMsg.DWS_DF_CONT_RIGHT | NppTbMsg.DWS_ICONTAB | NppTbMsg.DWS_ICONBAR;
                _nppTbData.hIconTab      = (uint)tbIcon.Handle;
                _nppTbData.pszModuleName = PluginName;
                IntPtr _ptrNppTbData = Marshal.AllocHGlobal(Marshal.SizeOf(_nppTbData));
                Marshal.StructureToPtr(_nppTbData, _ptrNppTbData, false);

                Win32.SendMessage(PluginBase.nppData._nppHandle, (uint)NppMsg.NPPM_DMMREGASDCKDLG, 0, _ptrNppTbData);
            }
            else
            {
                Win32.SendMessage(PluginBase.nppData._nppHandle, (uint)NppMsg.NPPM_DMMSHOW, 0, frmMyDlg.Handle);
                Win32.SendMessage(PluginBase.GetCurrentScintilla(),
                                  SciMsg.SCI_SETSELFORE, 1, 0xFFFFFF);
                Win32.SendMessage(PluginBase.GetCurrentScintilla(),
                                  SciMsg.SCI_SETSELBACK, 1, 0xFFFFFF);
                Win32.SendMessage(PluginBase.GetCurrentScintilla(),
                                  SciMsg.SCI_SETVIEWWS, 1, SCWS_VISIBLEALWAYS);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Replace the tag at the caret with an expansion defined in the [Tags]
        /// ini-file section.
        /// </summary>
        internal static void ReplaceTag()
        {
            IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
            ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);
            int position = scintillaGateway.GetSelectionEnd();

            string selectedText = scintillaGateway.GetSelText();

            if (string.IsNullOrEmpty(selectedText))
            {
                // TODO: remove this hardcoded 10 crap. Remove selection manipulation:
                // user will not be happy to see any such side-effects.
                scintillaGateway.SetSelection(position > 10 ? (position - 10) : (position - position), position);
                selectedText = scintillaGateway.GetSelText();
                var reges = Regex.Matches(scintillaGateway.GetSelText(), @"(\w+)");
                if (reges.Count > 0)
                {
                    selectedText = reges.Cast <Match>().Select(m => m.Value).LastOrDefault();
                    scintillaGateway.SetSelection(position - selectedText.Length, position);
                    selectedText = scintillaGateway.GetSelText();
                }
            }
            try {
                if (string.IsNullOrEmpty(selectedText))
                {
                    throw new Exception("No tag here.");
                }
                byte[] buffer = new byte[1048];
                var    ini    = new IniFile(iniFilePath);
                string value  = ini.Get("Tags", selectedText, 1048);
                if (string.IsNullOrEmpty(value.Trim('\0')))
                {
                    throw new Exception("No tag here.");
                }
                value = TransformTags(value);
                scintillaGateway.ReplaceSel(value.Replace("|", null));
                scintillaGateway.SetSelectionEnd(position + value.Substring(0, value.IndexOf('|')).Length - selectedText.Length);
            } catch (Exception ex) {
                scintillaGateway.CallTipShow(position, ex.Message);
            }
        }
Exemplo n.º 20
0
        internal static void goToDefinition()
        {
            IntPtr           hCurrScintilla = PluginBase.GetCurrentScintilla();
            NotepadPPGateway npp            = new NotepadPPGateway();
            ScintillaGateway sci            = new ScintillaGateway(hCurrScintilla);
            var selectedText = sci.GetSelText();

            if (string.IsNullOrEmpty(selectedText))
            {
                return;
            }
            Dictionary <string, string> filePaths = new Dictionary <string, string>();
            var stream = new FileStream(@"plugins/Config/GoToDefinition/sql_repos.txt", FileMode.Open, FileAccess.Read);

            using (var streamReader = new StreamReader(stream, Encoding.UTF8))
            {
                var text         = streamReader.ReadToEnd();
                var allFilePaths = text.Split(';');
                foreach (var filePath in allFilePaths)
                {
                    var kvp = filePath.Split('=');
                    if (kvp.Length > 1)
                    {
                        filePaths.Add(kvp[0], kvp[1]);
                    }
                }
            }
            StringBuilder sb = new StringBuilder();

            var matchingFileNames = new List <string>();

            foreach (var kvp in filePaths)
            {
                var matchingFiles = Directory.GetFiles(kvp.Value, $"{selectedText}*", SearchOption.TopDirectoryOnly);
                matchingFileNames.AddRange(matchingFiles);
            }

            FilesDialog fd = new FilesDialog(matchingFileNames.ToArray());

            fd.Show();
        }
Exemplo n.º 21
0
        internal static void myMenuFunction()
        {
            try
            {
                IntPtr hCurrScintilla = PluginBase.GetCurrentScintilla();
                int    textLen        = (int)Win32.SendMessage(hCurrScintilla, SciMsg.SCI_GETLENGTH, 0, 0);
                IntPtr ptrText        = Marshal.AllocHGlobal(textLen + 5);
                Win32.SendMessage(hCurrScintilla, SciMsg.SCI_GETTEXT, textLen + 1, ptrText);
                string s = Marshal.PtrToStringAnsi(ptrText);
                s = s.Trim();
                List <Error> errors = new List <Error>();
                string[]     lines  = s.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                Error        error  = null;
                //Marshal.FreeHGlobal(ptrText);


                for (int i = 0; i < lines.Length; i++)
                {
                    try
                    {
                        error = Helper.CheckLine(lines[i], i);
                    }
                    catch (Exception)
                    {
                    }
                    if (error != null)
                    {
                        errors.Add(error);
                    }
                }

                myDockableDialog(errors);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Exemplo n.º 22
0
 private static void generateDiagram()
 {
     try
     {
         IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
         ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);
         // Get selected text.
         string        selectedText = scintillaGateway.GetSelText();
         var           lines        = selectedText.Split('\n');
         DrawIOBuilder builder      = new DrawIOBuilder();
         for (var i = 0; i < lines.Length; i++)
         {
             var line = lines[i];
             lines[i] = line.Trim(new char[] { ' ', '\r' });
         }
         DrawIOComponent[] drawIOComponent = builder.FlowchartBuilder(lines);
         builder.CopyToClipBoard(drawIOComponent);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Exemplo n.º 23
0
        private static bool SearchNextSectionOrPerform(string sectionName, int offset)
        {
            var editor = new ScintillaGateway(PluginBase.GetCurrentScintilla());

            using (TextToFind textToFind = new TextToFind(offset, editor.GetTextLength() - 1, sectionName))
            {
                Position sectionPosition = editor.FindText(0, textToFind);
                if (sectionPosition.Value >= 0)
                {
                    if (editor.GetLine(editor.LineFromPosition(sectionPosition)).StartsWith("*"))
                    {
                        CurrentSearchOffset = sectionPosition.Value + sectionName.Length;
                        return(SearchNextSectionOrPerform(sectionName, CurrentSearchOffset));
                    }
                    ScrollToLine(editor.LineFromPosition(sectionPosition));
                    CurrentSearchOffset = sectionPosition.Value + sectionName.Length;
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Exemplo n.º 24
0
        internal static void saveAsDrawIO()
        {
            try
            {
                frmMyDlg frmMyDlg = new frmMyDlg();
                var      filename = frmMyDlg.filename;

                IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
                ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);
                // Get selected text.
                string selectedText = scintillaGateway.GetSelText();
                var    lines        = selectedText.Split('\n'); for (var i = 0; i < lines.Length; i++)
                {
                    var line = lines[i];
                    lines[i] = line.Trim(new char[] { ' ', '\r' });
                }
                DrawIOBuilder     builder         = new DrawIOBuilder();
                DrawIOComponent[] drawIOComponent = builder.FlowchartBuilder(lines);
                builder.SaveToFile(filename, drawIOComponent);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Capitalize user selected text based on Chicago Manual of Style.
        /// </summary>
        internal static void CapitalizeTitle()
        {
            // Only call this once per notepad-plus-plus session.
            if (forbidden.Count == 0)
            {
                // Get the list of forbidden words.
                forbidden = GetForbiddenWords(@"plugins\doc\FirstUpper\FirstUpperForbiddenWords.txt");
            }

            IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
            ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);

            try
            {
                // Get selected text.
                string selectedText = scintillaGateway.GetSelText();
                // Convert to lower case in case some words are already
                // capitalized that should not be capitalized.
                selectedText = selectedText.ToLowerInvariant();
                // Change to char array for easy editing of single chars.
                char[] charArraySelText = selectedText.ToCharArray();

                StringBuilder word             = new StringBuilder();
                char          firstLetter      = new char();
                int           firstLetterIndex = -1;
                bool          firstWord        = true;

                // For the length of the selected text...
                for (int i = 0; i < selectedText.Length; i++)
                {
                    // If the current character is not a whitespace character...
                    if (!ignoreChars.Contains(selectedText[i]))
                    {
                        // If first letter index is negative that means this
                        // is the first letter of the word. Set the index accordingly.
                        if (i >= 0 && firstLetterIndex < 0)
                        {
                            // Set the first letter index to the index of the first letter of this word.
                            firstLetterIndex = i;
                        }

                        // Build the string one char at a time.
                        word.Append(selectedText[i]);
                    }

                    // Out of bounds check.
                    if ((i + 1) < selectedText.Length - 1)
                    {
                        // If the next char is whitespace char that means the current
                        // char is the last char of the current word.
                        if (ignoreChars.Contains(selectedText[i + 1]))
                        {
                            // Make sure it is not a forbidden word.
                            if ((firstWord || !forbidden.Contains(word.ToString())) && word.Length != 0)
                            {
                                // Convert the first letter of the word to uppercase.
                                firstLetter = Convert.ToChar(word[0].ToString().ToUpperInvariant());
                                // Replace the correct char in the selected text with its uppercase letter.
                                charArraySelText.SetValue(firstLetter, firstLetterIndex);
                                // Clear the word to make ready for the next one.
                                Clear(word);
                                // Reset first letter and first word indicators.
                                firstLetterIndex = -1;
                                firstWord        = false;
                            }
                            // Otherwise we do not want the word to be capitalized...
                            else
                            {
                                // Clear the word to make ready for the next one.
                                Clear(word);
                                // Reset first letter indicator.
                                firstLetterIndex = -1;
                            }
                        }
                    }
                    // Otherwise this is the last word of the selected text.
                    else if (i == selectedText.Length - 1)
                    {
                        // Convert the first letter of the word to uppercase.
                        firstLetter = Convert.ToChar(word[0].ToString().ToUpperInvariant());
                        // Replace the correct char in the selected text with its uppercase letter.
                        charArraySelText.SetValue(firstLetter, firstLetterIndex);
                        // Reset first letter indicator.
                        firstLetterIndex = -1;
                        break;
                    }
                }
                // Convert the char array back to string.
                selectedText = new string(charArraySelText);
                // Replace the selected text with the new string
                scintillaGateway.ReplaceSel(selectedText);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Turn the last word typed into camel case.
        /// Uses "Directed Acyclic Word Graph" or "DAWG" for short.
        /// </summary>
        internal static void CamelCaseLastWord()
        {
            //MessageBox.Show("Camel Case Last Word");
            Dawg <bool> dawg;

            try
            {
                Stream fs = File.Open("./plugins/doc/FirstUpper/FirstUpperDAWG.bin", FileMode.Open, FileAccess.Read);

                dawg = Dawg <bool> .Load(fs);

                IntPtr           currentScint     = PluginBase.GetCurrentScintilla();
                ScintillaGateway scintillaGateway = new ScintillaGateway(currentScint);

                string word          = getLastWord().ToLower();
                var    wordCharArray = word.ToCharArray();

                var    index     = 0;
                var    wordCount = 0;
                string wordSubstr;

                #region "Repeat steps until no more words."
                // See if the text is a word.
                // If it is not a word, we remove the last letter
                // until we find a word. Then we capitalize this word.
                // We repeat this process for the entire variable.
                while (true)
                {
                    //MessageBox.Show("Index: " + index + "\nWord End: " + (word.Length - 1));
                    if (index >= word.Length - 1)
                    {
                        break;
                    }

                    // Get the substring word based on the start position.
                    wordSubstr = word.Substring(index);

                    while (true)
                    {
                        // Is the substring word an actual word?
                        if (dawg[wordSubstr])
                        {
                            // Increment the word count.
                            ++wordCount;
                            // Do not capitalize the first word of the variable.
                            if (wordCount > 1)
                            {
                                // Capitalize word.
                                wordCharArray[index] = Convert.ToChar(wordCharArray[index].ToString().ToUpper());
                            }

                            //MessageBox.Show("Word Length: “" + word.Length + "”\nSubstr Length: “" + wordSubstr.Length + "”");
                            index += wordSubstr.Length;
                            //MessageBox.Show("Substr After Caps: " + word.Substring(index));
                            break;
                        }
                        else
                        {
                            //MessageBox.Show("Substr before removal: “" + wordSubstr + "”\nLength: " + wordSubstr.Length);
                            if (wordSubstr.Length > 0)
                            {
                                wordSubstr = wordSubstr.Remove(wordSubstr.Length - 1);
                                //MessageBox.Show("Substr after removal: “" + wordSubstr + "”\nLength: " + wordSubstr.Length);
                            }
                            else
                            {
                                index = word.Length;
                                break;
                            }
                        }
                    }
                }
                #endregion "Repeat steps until no more words."

                // Replace selected word with new word.
                word = new string(wordCharArray);
                scintillaGateway.ReplaceSel(word);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Exemplo n.º 27
0
        internal static void C7GSPFunction()
        {
            //Preparing some variables
            var scintilla = new ScintillaGateway(PluginBase.GetCurrentScintilla());

            //Starting Undo "recording". Next steps can be undo with one undo command
            scintilla.BeginUndoAction();

            //Is there any text selected
            if (scintilla.GetSelText() != "")
            {
                //Calculating selections first line begin
                Position selStartPos  = scintilla.GetSelectionStart();
                int      startLineNum = scintilla.LineFromPosition(selStartPos);
                Position startLinePos = scintilla.PositionFromLine(startLineNum);

                //Calculating selections last line end
                Position selEndPos  = scintilla.GetSelectionEnd();
                int      endLineNum = scintilla.LineFromPosition(selEndPos);
                Position endLinePos = scintilla.GetLineEndPosition(endLineNum);

                //Setting the selection as needed
                scintilla.SetSel(startLinePos, endLinePos);

                //Preparing needed variables
                int ignoreMe = 0;

                //Gathered information
                string line = "";
                int    lineFeedLen = 0;
                int    tt = 0, np = 0, na = 0, gtrc = 0;
                string ns        = "";
                string modifiers = "";

                //Loopping through the selected lines
                int i = startLineNum;
                while (i <= endLineNum)
                {
                    //Line to the memory
                    line = scintilla.GetLine(i);

                    if (line.Length > 2)
                    {
                        //Checking did we get a fresh GT line (three first chars are int (TT))
                        if (int.TryParse(line.Substring(0, 3), out ignoreMe))
                        {
                            //Gathering the basic GT information
                            tt   = int.Parse(line.Substring(0, 3));
                            np   = int.Parse(line.Substring(5, 2));
                            na   = int.Parse(line.Substring(9, 3));
                            ns   = line.Substring(14, 16).Replace(" ", string.Empty);
                            gtrc = na = int.Parse(line.Substring(56, 3));

                            //Move carret to the begin of the line
                            scintilla.SetCurrentPos(scintilla.PositionFromLine(i));
                            //Delete all from the line
                            scintilla.DelLineRight();
                            //Add text
                            scintilla.InsertText(scintilla.PositionFromLine(i), "C7GSI:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",GTRC=" + gtrc + ";");

                            //Checking next line if it it's not empty
                            if (scintilla.GetLine(i + 1).Length >= 9)
                            {
                                //And the line will contain header which begins with MTT
                                if (scintilla.GetLine(i + 1).Substring(9, 3) == "MTT")
                                {
                                    //If yes then take the line under it to the variable
                                    modifiers = scintilla.GetLine(i + 2);

                                    //If linefeed is CRLF, then two extra characters in the end of line
                                    if (scintilla.GetEOLMode() == 0)
                                    {
                                        lineFeedLen = 2;
                                    }
                                    else
                                    {
                                        lineFeedLen = 1;
                                    }

                                    //Removing lines which not needed anymore
                                    scintilla.SetCurrentPos(scintilla.PositionFromLine(i + 1));
                                    scintilla.LineDelete();
                                    scintilla.LineDelete();

                                    endLineNum = endLineNum - 2;

                                    //Determining which variables the modifiers line will contain
                                    if (modifiers.Length == (12 + lineFeedLen))
                                    {
                                        //Insert command to the line
                                        scintilla.InsertText(scintilla.PositionFromLine(i + 1), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MTT=" + modifiers.Substring(9, 3).Replace(" ", string.Empty) + ";");
                                    }
                                    else if (modifiers.Length == (17 + lineFeedLen))
                                    {
                                        if (!string.IsNullOrWhiteSpace(modifiers.Substring(9, 3)))
                                        {
                                            //Insert command to the line
                                            scintilla.InsertText(scintilla.GetCurrentPos(), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MTT=" + modifiers.Substring(9, 3).Replace(" ", string.Empty) + ";");
                                            //Go to end of the current line
                                            scintilla.GotoPos(scintilla.GetLineEndPosition(scintilla.LineFromPosition(scintilla.GetCurrentPos())));
                                            //Adding new line
                                            scintilla.NewLine();
                                            endLineNum++;
                                        }
                                        scintilla.InsertText(scintilla.GetCurrentPos(), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MNP=" + modifiers.Substring(14, 3).Replace(" ", string.Empty) + ";");
                                    }
                                    else if (modifiers.Length == (22 + lineFeedLen))
                                    {
                                        if (!string.IsNullOrWhiteSpace(modifiers.Substring(9, 3)))
                                        {
                                            scintilla.InsertText(scintilla.GetCurrentPos(), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MTT=" + modifiers.Substring(9, 3).Replace(" ", string.Empty) + ";");
                                            scintilla.GotoPos(scintilla.GetLineEndPosition(scintilla.LineFromPosition(scintilla.GetCurrentPos())));
                                            scintilla.NewLine();
                                            endLineNum++;
                                        }
                                        if (!string.IsNullOrWhiteSpace(modifiers.Substring(14, 3)))
                                        {
                                            scintilla.InsertText(scintilla.GetCurrentPos(), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MNP=" + modifiers.Substring(14, 3).Replace(" ", string.Empty) + ";");
                                            scintilla.GotoPos(scintilla.GetLineEndPosition(scintilla.LineFromPosition(scintilla.GetCurrentPos())));
                                            scintilla.NewLine();
                                            endLineNum++;
                                        }
                                        scintilla.InsertText(scintilla.GetCurrentPos(), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MNA=" + modifiers.Substring(19, 3).Replace(" ", string.Empty) + ";");
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrWhiteSpace(modifiers.Substring(9, 3)))
                                        {
                                            scintilla.InsertText(scintilla.GetCurrentPos(), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MTT=" + modifiers.Substring(9, 3).Replace(" ", string.Empty) + ";");
                                            scintilla.GotoPos(scintilla.GetLineEndPosition(scintilla.LineFromPosition(scintilla.GetCurrentPos())));
                                            scintilla.NewLine();
                                            endLineNum++;
                                        }
                                        if (!string.IsNullOrWhiteSpace(modifiers.Substring(14, 3)))
                                        {
                                            scintilla.InsertText(scintilla.GetCurrentPos(), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MNP=" + modifiers.Substring(14, 3).Replace(" ", string.Empty) + ";");
                                            scintilla.GotoPos(scintilla.GetLineEndPosition(scintilla.LineFromPosition(scintilla.GetCurrentPos())));
                                            scintilla.NewLine();
                                            endLineNum++;
                                        }
                                        if (!string.IsNullOrWhiteSpace(modifiers.Substring(19, 3)))
                                        {
                                            scintilla.InsertText(scintilla.GetCurrentPos(), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MNA=" + modifiers.Substring(19, 3).Replace(" ", string.Empty) + ";");
                                            scintilla.GotoPos(scintilla.GetLineEndPosition(scintilla.LineFromPosition(scintilla.GetCurrentPos())));
                                            scintilla.NewLine();
                                            endLineNum++;
                                        }
                                        scintilla.InsertText(scintilla.GetCurrentPos(), "C7GSC:TT=" + tt + ",NP=" + np + ",NA=" + ",NS=" + ns + ",MNS=" + modifiers.Substring(24, (modifiers.Length - 24 - lineFeedLen)).Replace(" ", string.Empty) + ";");
                                    }
                                }
                            }
                        }
                    }

                    i++;
                }
            }
            scintilla.EndUndoAction();
        }
Exemplo n.º 28
0
 internal static void InsertGuid()
 {
     new InsertGuid(new ScintillaGateway(PluginBase.GetCurrentScintilla())).Execute(false);
 }
Exemplo n.º 29
0
        /// <summary>
        /// Perform an XPath search.
        /// </summary>
        /// <param name="xpathStrings">List of strings to search against.</param>
        public void DoSearch(string[] xpathStrings)
        {
            try
            {
                worker.ReportProgress(0, new ProgressReporter("Processing..."));
                XmlDocument XMLdoc = new XmlDocument();
                try
                {
                    IntPtr        curScintilla = PluginBase.GetCurrentScintilla();
                    int           length       = (int)Win32.SendMessage(curScintilla, SciMsg.SCI_GETLENGTH, 0, 0) + 1;
                    StringBuilder sb           = new StringBuilder(length);

                    //Construct Scintilla Gateway, pull text and append document text into sb object.
                    //This prevents the need for massive reconstruction
                    ScintillaGateway Scintilla = new ScintillaGateway(curScintilla);
                    sb.Append(Scintilla.GetText(length));

                    string doc = sb.ToString();

                    if (Main.settings.IgnoreDocType)
                    {
                        XMLdoc.XmlResolver = null;
                    }
                    XMLdoc.LoadXml(doc.Replace("&", "&amp;"));
                }
                catch (XmlException xex)
                {
                    worker.ReportProgress(0, new ProgressReporter("Document ERROR"));
                    worker.ReportProgress(0, new ProgressReporter(xex.Message, "Document ERROR"));
                    try
                    {
                        IntPtr curScintilla = PluginBase.GetCurrentScintilla();
                        int    startPos     = (int)Win32.SendMessage(curScintilla, SciMsg.SCI_POSITIONFROMLINE, xex.LineNumber - 1, 0) + xex.LinePosition - 1;
                        Win32.SendMessage(curScintilla, SciMsg.SCI_GOTOPOS, startPos, 0);
                    }
                    catch { }
                    return;
                }

                bool bitDefaultRemoved = false;

                if (Main.settings.defaultNamespace == "")
                {
                    int Before = XMLdoc.OuterXml.Length;
                    XMLdoc = Main.RemoveDefaultNamespaces(XMLdoc);
                    if (XMLdoc.OuterXml.Length != Before)
                    {
                        bitDefaultRemoved = true;
                    }
                }

                XPathNavigator      navigator = XMLdoc.CreateNavigator();
                XmlNamespaceManager xnm       = new XmlNamespaceManager(XMLdoc.NameTable);
                Main.DNSCount = 1;
                xnm           = Main.GetNameSpaces(XMLdoc.SelectSingleNode("/*"), xnm);
                XPathExpression xpe;
                object          result;
                string          strres = "";
                System.Xml.XPath.XPathResultType xprt = System.Xml.XPath.XPathResultType.Any;

                int i = 1;

                foreach (string s in xpathStrings)
                {
                    if (worker.CancellationPending)
                    {
                        return;
                    }
                    string xPath = s;
                    //xPath Comments support.
                    //I know xPath 1.0 does not support these, but it is nice to be able to store comments at least in NPP.
                    while (xPath.Contains("(:") && xPath.Contains(":)"))
                    {
                        int intStart = xPath.IndexOf("(:");
                        int intEnd   = xPath.IndexOf(":)", i);

                        if (intEnd <= intStart)
                        {
                            intEnd = xPath.Length - 2;
                        }

                        xPath = xPath.Remove(intStart, intEnd - intStart + 2);
                    }
                    if (xPath != "")
                    {
                        try
                        {
                            xpe    = XPathExpression.Compile(xPath, xnm);
                            result = navigator.Evaluate(xpe);
                            xprt   = xpe.ReturnType;
                            strres = result.ToString();
                        }
                        catch (System.Xml.XPath.XPathException xpx)
                        {
                            worker.ReportProgress(0, new ProgressReporter(i + ": ERROR"));
                            worker.ReportProgress(0, new ProgressReporter(xpx.Message.Replace("'" + xPath + "'", "The xPath statement"), i + ": ERROR"));
                            i++;
                            continue;
                        }
                        if (xprt == System.Xml.XPath.XPathResultType.NodeSet)
                        {
                            XPathNodeIterator xpni = navigator.Select(xPath, xnm);
                            string            ss   = "s";
                            try
                            {
                                if (xpni.Count == 1)
                                {
                                    ss = "";
                                }
                            }
                            catch (Exception ex)
                            {
                                worker.ReportProgress(0, new ProgressReporter(i + ": ERROR"));
                                worker.ReportProgress(0, new ProgressReporter(ex.Message, i + ": ERROR"));
                                i++;
                                continue;
                            }
                            TreeNode tNode = new TreeNode(i + ": " + xpni.Count + " Hit" + ss);
                            tNode.Tag = "X:" + xPath;
                            worker.ReportProgress(0, new ProgressReporter(tNode));
                            while (xpni.MoveNext())
                            {
                                if (worker.CancellationPending)
                                {
                                    return;
                                }
                                if (xpni.Current is IHasXmlNode)
                                {
                                    XmlNode Node     = ((IHasXmlNode)xpni.Current).GetNode();
                                    string  pos      = Main.FindXPath(Node, bitDefaultRemoved);
                                    string  NodeText = Main.NodetoText(xpni.Current.OuterXml);
                                    if (NodeText.StartsWith("Text") || NodeText.StartsWith("CDATA"))
                                    {
                                        tNode = new TreeNode(NodeText);
                                    }
                                    else
                                    {
                                        TreeNode[] childNodes = GetChildren(Node, bitDefaultRemoved);
                                        if (childNodes != null)
                                        {
                                            tNode = new TreeNode(NodeText, childNodes);
                                        }
                                    }
                                    tNode.Tag = pos;
                                    worker.ReportProgress(0, new ProgressReporter(tNode, i + ": " + xpni.Count + " Hit" + ss));
                                }
                            }
                        }
                        else
                        {
                            worker.ReportProgress(0, new ProgressReporter(i + ": " + xprt + ": " + strres));
                        }
                    }
                    i++;
                }
            }
            catch (Exception ex)
            {
                worker.ReportProgress(0, new ProgressReporter("An unexpected error has occured: " + ex.Message));
            }
        }
Exemplo n.º 30
0
 static Main()
 {
     editor  = new ScintillaGateway(PluginBase.GetCurrentScintilla());
     notepad = new NotepadPPGateway();
 }