private void AfterTextDocumentKeyPress(string keypress, TextSelection selection, bool inStatementCompletion)
        {
            if (!_isRenameCandidate && !_isExpandingCandidate)
            {
                return;
            }

            try
            {
                if (_isRenameCandidate)
                {
                    DoRename(selection);
                }
                if (_isExpandingCandidate)
                {
                    DoExpand(selection);
                }
                if (_openedUndoContext)
                {
                    _application.UndoContext.Close();
                }

            }
            finally
            {
                _isRenameCandidate = false;
                _isExpandingCandidate = false;
                _openedUndoContext = false;
            }
        }
예제 #2
0
        /// <summary>
        /// Joins the text within the specified text selection.
        /// </summary>
        /// <param name="textSelection">The text selection.</param>
        private void JoinText(TextSelection textSelection)
        {
            // If the selection has no length, try to pick up the next line.
            if (textSelection.IsEmpty)
            {
                textSelection.LineDown(true);
                textSelection.EndOfLine(true);
            }

            const string pattern = @"[ \t]*\r?\n[ \t]*";
            const string replacement = @" ";

            // Substitute all new lines (and optional surrounding whitespace) with a single space.
            TextDocumentHelper.SubstituteAllStringMatches(textSelection, pattern, replacement);

            // Move the cursor forward, clearing the selection.
            textSelection.CharRight();
        }
예제 #3
0
        /// <summary>
        /// Finds all matches of the specified pattern within the specified text selection.
        /// </summary>
        /// <param name="textSelection">The text selection.</param>
        /// <param name="patternString">The pattern string.</param>
        /// <returns>The set of matches.</returns>
        internal static IEnumerable<EditPoint> FindMatches(TextSelection textSelection, string patternString)
        {
            var matches = new List<EditPoint>();
            var cursor = textSelection.TopPoint.CreateEditPoint();
            EditPoint end = null;
            TextRanges dummy = null;

            while (cursor != null && cursor.FindPattern(patternString, StandardFindOptions, ref end, ref dummy))
            {
                if (end.AbsoluteCharOffset > textSelection.BottomPoint.AbsoluteCharOffset)
                {
                    break;
                }

                matches.Add(cursor.CreateEditPoint());
                cursor = end;
            }

            return matches;
        }
        private void BeforeKeyPress(string keypress, TextSelection selection,
		                            bool inStatementCompletion, ref bool cancelKeypress)
        {
            if (!ConvertTabsToSpaces || !selection.IsEmpty || inStatementCompletion) return;

            switch (keypress)
            {
                case BACKSPACE_KEY:
                    do
                    {
                        selection.CharLeft(true);
                        if (selection.Text == " ")
                        {
                            cancelKeypress = true;
                            selection.Delete();
                            continue;
                        }
                        selection.CharRight(true);
                        return;
                    } while (selection.CurrentColumn%IndentSize != 1);
                    return;

                case DELETE_KEY:
                    for (var i = 0; i < IndentSize; i++)
                    {
                        selection.CharRight(true);
                        if (selection.Text == " ")
                        {
                            cancelKeypress = true;
                            selection.Delete();
                            continue;
                        }
                        selection.CharLeft(true);
                        return;
                    }
                    return;
            }
        }
예제 #5
0
        public RequestKeys GetKeys(TextSelection selection)
        {
            //Example key
            //@ApiKey:f568d28a-8280-459d-a21d-80fd82b6cab2,Bot:24@

            selection.StartOfDocument(false);
            selection.SelectLine();
            var selectedText = selection.Text;
            var firstIndex = selectedText.IndexOf('@');
            var lastIndex = selectedText.IndexOf('@', firstIndex + 1);
            var keysPart = selectedText.Substring(firstIndex + 1, lastIndex - (firstIndex + 1));

            var keysArray = keysPart.Split(',');

            var keysList = new List<string>();
            for (int i = 0; i < keysArray.Length; i++)
            {
                var kvp = keysArray[i].Split(':');
                keysList.Add(kvp[1]);
            }

            return new RequestKeys { Key = keysList[0], Bot = keysList[1] };
        }
예제 #6
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            DTE          dte    = Package.GetGlobalService(typeof(DTE)) as DTE;
            Document     doc    = dte.ActiveDocument;
            TextDocument txtDoc = doc.Object() as TextDocument;
            var          text   = txtDoc.CreateEditPoint(txtDoc.StartPoint).GetText(txtDoc.EndPoint);

            text = text.Replace("\r", "");

            uint cookie = 0;

            StatusBar.Progress(ref cookie, 1, string.Empty, 0, 0);

            if (txtDoc.Language == "HTMLX" || txtDoc.Language == "HTML")
            {
                var html           = text;
                var elementList    = new List <HtmlElement>();
                var parsed         = _parser.ParseHtml(html, elementList, txtDoc, StatusBar, ref cookie);
                var cssFileContent = string.Empty;

                if (elementList.Any())
                {
                    foreach (var item in elementList)
                    {
                        var cssClass = string.Empty;
                        if (string.IsNullOrEmpty(item.Class))
                        {
                            cssClass = string.Format(".{0}", string.IsNullOrEmpty(item.Id) ? CreateUniqueElementKey(item.Name, item.LineNumber) : item.Id);
                        }
                        else
                        {
                            cssClass = string.Format(".{0} .{1}", item.Class, CreateUniqueElementKey(item.Name, item.LineNumber));
                        }

                        var idAttr      = string.IsNullOrEmpty(item.Id) ? string.Empty : string.Format("id=\"{0}\"", item.Id);
                        var replaceText = string.Format("{0} {1} class=\"{2}\"", item.Name, idAttr, cssClass.Replace(".", string.Empty));

                        parsed          = parsed.Replace(item.Guid, replaceText);
                        cssFileContent += string.Format("{0}{{{1}}}\n\n", cssClass, "\n" + item.Style);
                    }

                    //css file beautification
                    cssFileContent = cssFileContent.Replace(";", ";\n");

                    //update html file
                    TextSelection txtSelHtml = (TextSelection)doc.Selection;
                    txtSelHtml.SelectAll();
                    txtSelHtml.Delete();
                    txtSelHtml.Insert(parsed);

                    //create css file
                    var docName = doc.Name.Substring(0, doc.Name.IndexOf('.'));
                    docName = string.Format("{0}.css", docName);
                    string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);
                    dte.ItemOperations.NewFile(@"General\Text File", docName, EnvDTE.Constants.vsViewKindTextView);
                    TextSelection txtSelCss = (TextSelection)dte.ActiveDocument.Selection;
                    txtSelCss.SelectAll();
                    txtSelCss.Delete();
                    txtSelCss.Insert(cssFileContent);
                }
                else
                {
                    VsShellUtilities.ShowMessageBox(this.ServiceProvider, "Not found inline css.", "That's Cool!",
                                                    OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                }
            }
            else
            {
                VsShellUtilities.ShowMessageBox(this.ServiceProvider, "This is not a html file!", "Oops!",
                                                OLEMSGICON.OLEMSGICON_WARNING, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }

            // Clear the progress bar.
            StatusBar.Progress(ref cookie, 0, string.Empty, 0, 0);
            StatusBar.FreezeOutput(0);
            StatusBar.Clear();
        }
예제 #7
0
        /// <summary>
        /// Runs custom wizard logic when a project has finished generating.
        /// </summary>
        /// <param name="project"></param>
        public void ProjectFinishedGenerating(Project project)
        {
            Diagnostics.Enter();
            // Iterate through the project items and
            // remove any files that begin with the word "Placeholder".
            // and the Rates class unless it's the Telescope class
            // done this way to avoid removing items from inside a foreach loop
            List <string> rems = new List <string>();

            foreach (ProjectItem item in project.ProjectItems)
            {
                if (item.Name.StartsWith("Placeholder", StringComparison.OrdinalIgnoreCase) ||
                    item.Name.StartsWith("Rate", StringComparison.OrdinalIgnoreCase) &&
                    !this.DeviceClass.Equals("Telescope", StringComparison.OrdinalIgnoreCase))
                {
                    //MessageBox.Show("adding " + item.Name);
                    rems.Add(item.Name);
                }
            }
            foreach (string item in rems)
            {
                //MessageBox.Show("Deleting " + item);
                project.ProjectItems.Item(item).Delete();
            }

            // Special handling for VB and C# driver template projects to add the interface implementation to the core driver code
            try
            {
                TL.Enabled = true;
                // Check the name of each item in the project and execute if this is a driver template project (contains Driver.vb or Driver.cs)
                foreach (ProjectItem projectItem in project.ProjectItems)
                {
                    TL.LogMessage("ProjectFinishedGenerating", "Item name: " + projectItem.Name);
                    if ((projectItem.Name.ToUpperInvariant() == "DRIVER.CS") | (projectItem.Name.ToUpperInvariant() == "DRIVER.VB"))
                    {
                        myProjectItem = projectItem; // Save the driver item
                        // This is a driver template
                        // Get the filename and directory of the Driver.xx file
                        string directory = Path.GetDirectoryName(projectItem.FileNames[1].ToString());
                        TL.LogMessage("ProjectFinishedGenerating", "File name: " + projectItem.FileNames[1].ToString() + ", Directory: " + directory);
                        TL.LogMessage("ProjectFinishedGenerating", "Found " + projectItem.Name);

                        projectItem.Open(); // Open the item for editing
                        TL.LogMessage("ProjectFinishedGenerating", "Done Open");

                        Document itemDocument = projectItem.Document; // Get the open file's document object
                        TL.LogMessage("ProjectFinishedGenerating", "Created Document");

                        itemDocument.Activate(); // Make this the current document
                        TL.LogMessage("ProjectFinishedGenerating", "Activated Document");

                        TextSelection documentSelection = (TextSelection)itemDocument.Selection; // Create a document selection
                        TL.LogMessage("ProjectFinishedGenerating", "Created Selection object");

                        const string insertionPoint = "//INTERFACECODEINSERTIONPOINT"; // Find the insertion point in the Driver.xx item
                        documentSelection.FindText(insertionPoint, (int)vsFindOptions.vsFindOptionsMatchWholeWord);
                        TL.LogMessage("ProjectFinishedGenerating", "Done INTERFACECODEINSERTIONPOINT FindText:" + documentSelection.Text);

                        // Create the name of the device interface file to be inserted
                        string insertFile = directory + "\\Device" + this.DeviceClass + Path.GetExtension(projectItem.Name);
                        TL.LogMessage("ProjectFinishedGenerating", "Opening file: " + insertFile);

                        documentSelection.InsertFromFile(insertFile); // Insert the required file at the current selection point
                        TL.LogMessage("ProjectFinishedGenerating", "Done InsertFromFile");

                        // Remove the top lines of the inserted file until we get to #Region
                        // These lines are only there to make the file error free in the template develpment project and are not required here
                        documentSelection.SelectLine(); // Select the current line
                        TL.LogMessage("ProjectFinishedGenerating", "Selected initial line: " + documentSelection.Text);
                        while (!documentSelection.Text.ToUpperInvariant().Contains("#REGION"))
                        {
                            TL.LogMessage("ProjectFinishedGenerating", "Deleting start line: " + documentSelection.Text);
                            documentSelection.Delete();     // Delete the current line
                            documentSelection.SelectLine(); // Select the new current line ready to test on the next loop
                        }

                        // Find the end of file marker that came from the inserted file
                        const string endOfInsertFile = "//ENDOFINSERTEDFILE";
                        documentSelection.FindText(endOfInsertFile, (int)vsFindOptions.vsFindOptionsMatchWholeWord);
                        TL.LogMessage("ProjectFinishedGenerating", "Done ENDOFINSERTEDFILE FindText:" + documentSelection.Text);

                        // Delete the marker line and the last 2 lines from the inserted file
                        documentSelection.SelectLine();
                        TL.LogMessage("ProjectFinishedGenerating", "Found end line: " + documentSelection.Text);
                        while (!documentSelection.Text.ToUpperInvariant().Contains("#REGION"))
                        {
                            TL.LogMessage("ProjectFinishedGenerating", "Deleting end line: " + documentSelection.Text);
                            documentSelection.Delete();     // Delete the current line
                            documentSelection.SelectLine(); // Select the new current line ready to test on the next loop
                            TL.LogMessage("ProjectFinishedGenerating", "Found end line: " + documentSelection.Text);
                        }

                        // Reformat the document to make it look pretty
                        documentSelection.SelectAll();
                        TL.LogMessage("ProjectFinishedGenerating", "Done SelectAll");
                        documentSelection.SmartFormat();
                        TL.LogMessage("ProjectFinishedGenerating", "Done SmartFormat");

                        itemDocument.Save(); // Save the edited file readyfor use!
                        TL.LogMessage("ProjectFinishedGenerating", "Done Save");
                        itemDocument.Close(vsSaveChanges.vsSaveChangesYes);
                        TL.LogMessage("ProjectFinishedGenerating", "Done Close");
                    }
                }

                // Iterate through the project items and remove any files that begin with the word "Device".
                // These are the partial device implementations that are merged in to create a complete device driver template by the code above
                // They are not required in the final project

                // Done this way to avoid removing items from inside a foreach loop
                rems = new List <string>();
                foreach (ProjectItem item in project.ProjectItems)
                {
                    if (item.Name.StartsWith("Device", StringComparison.OrdinalIgnoreCase))
                    {
                        //MessageBox.Show("adding " + item.Name);
                        rems.Add(item.Name);
                    }
                }
                foreach (string item in rems)
                {
                    TL.LogMessage("ProjectFinishedGenerating", "Deleting file: " + item);
                    project.ProjectItems.Item(item).Delete();
                }
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("ProjectFinishedGenerating Exception", ex.ToString());                                              // Log any error message
                MessageBox.Show(ex.ToString(), "ProjectFinishedGenerating Wizard Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // Show an error message
            }

            TL.LogMessage("ProjectFinishedGenerating", "End");
            TL.Enabled = false;

            Diagnostics.Exit();
        }
예제 #8
0
 public string GetDocument(TextSelection selection)
 {
     selection.SelectAll();
     return selection.Text;
 }
예제 #9
0
        /// <summary>
        /// Removes all region tags from the specified text selection.
        /// </summary>
        /// <param name="textSelection">The text selection to update.</param>
        internal void RemoveRegions(TextSelection textSelection)
        {
            // Retrieve the regions and put them in reverse order (reduces line number updates during removal).
            var regions = _codeModelHelper.RetrieveCodeRegions(textSelection).OrderByDescending(x => x.StartLine);

            new UndoTransactionHelper(_package, "CodeMaid Remove Selected Regions").Run(() =>
            {
                foreach (var region in regions)
                {
                    RemoveRegion(region);
                }
            });
        }
        void BeforeTextDocumentKeyPress(string keypress, TextSelection selection, bool inStatementCompletion, ref bool cancelKeypress)
        {
            if (keypress != "\t" || _application.ActiveDocument.Language != "CSharp")
            {
                return;
            }
            if (HandleCreateDelegateTemplate(selection))
            {
                return;
            }

            HandleExpandDelegateTemplate(selection);
        }
        private void DoRename(TextSelection selection)
        {
            if (selection.Text.Length == 0 || !selection.Text.Contains("_" + _eventName))
            {
                return;
            }
            //Now look in more detail and figure out if this actually is what we're looking for
            string original = selection.Text;
            int lastPost = original.LastIndexOf('_');
            string siteName = original.Substring(0, lastPost);
            string eventName = original.Substring(lastPost + 1);
            var classElement = selection.ActivePoint.CodeElement[vsCMElement.vsCMElementClass];
            string name = _nameProvider.CreateEventHandlerName(siteName, eventName, classElement.Name, selection.Text);

            selection.TopPoint.CreateEditPoint().ReplaceText(selection.BottomPoint, name, 0);
        }
예제 #12
0
		protected override void OnMouseDown(MouseEventArgs e)
		{
			base.OnMouseDown(e);

			if(e.Button == MouseButtons.Left)
			{
				bIsSelecting = true;

				TextLocation Location = PointToTextLocation(e.Location);
				Selection = new TextSelection(Location, Location);

				SelectionScrollTimer.Start();
				AutoScrollRate = 0;

				Capture = true;
				Invalidate();
			}
		}
예제 #13
0
        /// <summary>
        /// 使用spire设置文本格式
        /// </summary>
        /// <param name="myts"></param>
        /// <param name="f"></param>
        public void FormatSet(TextSelection myts, Format f)
        {
            //如果该格式未启用,不执行任何方法
            if (!f.enable || myts == null || myts.Count == 0)
            {
                return;
            }

            //得到文本区域
            TextRange mytr = myts.GetAsOneRange();

            //设置字体名称
            mytr.CharacterFormat.FontName = f.fontname;
            //设置字体大小
            mytr.CharacterFormat.FontSize = f.fontsize;
            //设置粗体
            mytr.CharacterFormat.Bold = f.bold == 1 ? true : false;
            //设置行距
            switch (f.lstype)
            {
            case "单倍行距":
                mytr.OwnerParagraph.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.AtLeast;
                break;

            case "1.5倍行距":
                mytr.OwnerParagraph.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Exactly;
                break;

            case "2倍行距":
                mytr.OwnerParagraph.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Multiple;
                break;

            default:
                mytr.OwnerParagraph.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Exactly;
                mytr.OwnerParagraph.Format.LineSpacing     = f.lsvalue;
                break;
            }
            //设置居中
            switch (f.juzhong)
            {
            case "左对齐":
                mytr.OwnerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left;
                break;

            case "居中":
                mytr.OwnerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                break;

            case "右对齐":
                mytr.OwnerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right;
                break;
            }
            //先删除空格

            //增加空行
            int spacenum = f.space;

            for (int spaceindex = 0; spaceindex < spacenum; spaceindex++)
            {
                mytr.OwnerParagraph.AppendText("\n");
            }
            //设置缩进
            Spire.Doc.Formatting.ParagraphFormat mypformat = new Spire.Doc.Formatting.ParagraphFormat();
            mytr.OwnerParagraph.Format.FirstLineIndent = f.suojin;
        }
        public override bool Indent()
        {
            bool singleLineSelection = (GetStartPoint().LineNumber == GetEndPoint().LineNumber);
            bool entireLastLineSelected
                = (GetStartPoint().CurrentPosition != GetEndPoint().CurrentPosition&&
                   GetStartPoint().CurrentPosition == TextBuffer.GetEndPoint().StartOfLine&&
                   GetEndPoint().CurrentPosition == TextBuffer.GetEndPoint().EndOfLine);

            if (singleLineSelection && !entireLastLineSelected)
            {
                TextPoint endPoint = GetEndPoint();
                if (!Delete())
                {
                    return(false);
                }
                if (!endPoint.InsertIndent())
                {
                    return(false);
                }
                TextView.AdvancedTextView.Caret.MoveTo(endPoint.AdvancedTextPoint);
            }
            else // indent the selected lines
            {
                VirtualSnapshotPoint oldStartPoint = TextSelection.Start;
                VirtualSnapshotPoint oldEndPoint   = TextSelection.End;
                bool isReversed = TextSelection.IsReversed;

                ITextSnapshotLine startLine = AdvancedTextRange.Snapshot.GetLineFromPosition(oldStartPoint.Position);
                ITextSnapshotLine endLine   = AdvancedTextRange.Snapshot.GetLineFromPosition(oldEndPoint.Position);

                // If the selection span initially starts at the whitespace at the beginning of the line in the startLine or
                // ends at the whitespace at the beginning of the line in the endLine, restore selection and caret position,
                // *unless* the selection was in box mode.
                bool startAtStartLineWhitespace = oldStartPoint.Position <= _textView.GetTextPoint(startLine.Start).GetFirstNonWhiteSpaceCharacterOnLine().CurrentPosition;
                bool endAtEndLineWhitespace     = oldEndPoint.Position < _textView.GetTextPoint(endLine.Start).GetFirstNonWhiteSpaceCharacterOnLine().CurrentPosition;
                bool isBoxSelection             = AdvancedSelection.Mode == TextSelectionMode.Box;

                if (isBoxSelection)
                {
                    if (!this.BoxIndent())
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!TextRange.Indent())
                    {
                        return(false);
                    }
                }

                // Computing the new selection and caret position
                VirtualSnapshotPoint newStartPoint = TextSelection.Start;
                VirtualSnapshotPoint newEndPoint   = TextSelection.End;

                if (!isBoxSelection && (startAtStartLineWhitespace || endAtEndLineWhitespace))
                {
                    // After indent selection span should start at the start of startLine and end at the start of endLine
                    if (startAtStartLineWhitespace)
                    {
                        newStartPoint = new VirtualSnapshotPoint(AdvancedTextRange.Snapshot, oldStartPoint.Position.Position);
                    }

                    if (endAtEndLineWhitespace && oldEndPoint.Position.Position != endLine.Start && endLine.Length != 0)
                    {
                        int insertedTextSize = _editorOptions.IsConvertTabsToSpacesEnabled() ? _editorOptions.GetTabSize() : 1;
                        newEndPoint = new VirtualSnapshotPoint(AdvancedTextRange.Snapshot, newEndPoint.Position.Position - insertedTextSize);
                    }

                    if (!isReversed)
                    {
                        TextSelection.Select(newStartPoint, newEndPoint);
                    }
                    else
                    {
                        TextSelection.Select(newEndPoint, newStartPoint);
                    }

                    TextView.AdvancedTextView.Caret.MoveTo(TextSelection.ActivePoint, PositionAffinity.Successor);
                }
            }
            TextView.AdvancedTextView.Caret.EnsureVisible();
            return(true);
        }
 public override void Clear()
 {
     TextSelection.Clear();
 }
예제 #16
0
 protected override void Execute(OleMenuCommand Button) =>
 TextSelection.GetSelection(Package, out int[] poses, out NewlineType newlineType, out bool newLine)
예제 #17
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var dte = Package.GetGlobalService(typeof(DTE)) as DTE;

            if (dte == null || dte.ActiveDocument == null)
            {
                return;
            }

            TextSelection ts = dte.ActiveDocument.Selection as TextSelection;

            // Check if we're at the beginning of the document and should generate a file comment.
            if (ts.ActivePoint.Line == 1)
            {
                string fileComment = m_generator.GenerateFileComment(dte, out int selectedLine);
                ts.DeleteLeft(2); // Removing the // part here.
                ts.Insert(fileComment);

                // Move the caret.
                ts.MoveToLineAndOffset(selectedLine + 1, 1);
                ts.EndOfLine();
                return;
            }

            ts.EndOfLine();

            // Scroll down until we find a non-comment line.
            if (!ScrollToCodeStart(ts))
            {
                return;
            }

            // Save the position so that we know where to place the comment.
            ts.StartOfLine();
            var funcPoint = ts.ActivePoint.CreateEditPoint();
            int oldLine   = ts.ActivePoint.Line;
            int oldOffset = ts.ActivePoint.LineCharOffset;

            ts.EndOfLine();

            // Determine indentation level.
            string currentLine = ts.ActivePoint.CreateEditPoint().GetLines(ts.ActivePoint.Line, ts.ActivePoint.Line + 1);
            string spaces      = currentLine.Replace(currentLine.TrimStart(), "");

            // Search for the associated code element.
            CodeElement   codeElement = null;
            FileCodeModel fcm         = dte.ActiveDocument.ProjectItem.FileCodeModel;

            if (fcm != null)
            {
                while (codeElement == null)
                {
                    codeElement = fcm.CodeElementFromPoint(ts.ActivePoint, vsCMElement.vsCMElementFunction);

                    if (ts.ActivePoint.AtEndOfDocument)
                    {
                        break;
                    }

                    if (codeElement == null || !(codeElement is CodeFunction))
                    {
                        codeElement = null;
                        ts.LineDown();
                        ts.EndOfLine();
                    }
                }
            }

            // Extract existing comment if found.
            ts.MoveToLineAndOffset(oldLine, oldOffset);
            int startLine = ExtractComment(ts, out string existingDoxyComment);

            // Delete old comment from the text.
            if (startLine >= 0)
            {
                ts.ActivePoint.CreateEditPoint().Delete(funcPoint);
                oldLine   = ts.ActivePoint.Line;
                oldOffset = ts.ActivePoint.LineCharOffset;
            }

            // Generate new comment.
            string doxyComment = m_generator.GenerateComment(spaces, codeElement, existingDoxyComment);

            // Write the doxygen comment to the correct position.
            ts.MoveToLineAndOffset(oldLine, oldOffset);
            ts.LineUp();

            // If the upper line is empty, we should go to the start of the line. Otherwise go to the end of the line.
            currentLine = ts.ActivePoint.CreateEditPoint().GetLines(ts.ActivePoint.Line, ts.ActivePoint.Line + 1);

            if (currentLine.Trim().Length == 0)
            {
                ts.StartOfLine();
            }
            else
            {
                ts.EndOfLine();
            }

            ts.Insert("\r\n" + spaces + doxyComment);

            // If this is a new comment, move to the main comment position immediately.
            if (startLine < 0)
            {
                ts.MoveToLineAndOffset(oldLine, oldOffset);
                ts.LineDown();
                ts.EndOfLine();
            }
        }
예제 #18
0
        private void button_ok_Click(object sender, EventArgs e)
        {
            try
            {
                assertiveToolDS dafnyCreate = new assertiveToolDS();
                TextDocument    activeDoc   = null;
                DTE             dte         = null;

                try
                {
                    dte       = Package.GetGlobalService(typeof(DTE)) as DTE;
                    activeDoc = dte.ActiveDocument.Object() as TextDocument;
                }
                catch
                {
                    MessageBox.Show("Please open a Dafny file befor using the aplication.", "File not open", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.Close();
                    return;
                }

                //get position
                var cursPoint = activeDoc.Selection.ActivePoint;

                // to insert
                TextSelection toInsert = (EnvDTE.TextSelection)(activeDoc.Selection);

                //get all text
                var text = activeDoc.CreateEditPoint(activeDoc.StartPoint).GetText(activeDoc.EndPoint);

                // get input
                string name = get_method_name(text, cursPoint);
                if (name == String.Empty)
                {
                    MessageBox.Show("Method not found.", "Method not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.Close();
                    return;
                }
                dafnyCreate.Name = name;

                //validation:
                if (this.methodName.Text == string.Empty)
                {
                    MessageBox.Show("Please enter Method Name.", "Empty input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                if (preCondName.Text == string.Empty)
                {
                    MessageBox.Show("Please enter Lema name.", "Empty input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }


                bool isFound = false;
                foreach (Control x in this.Controls)
                {
                    if (x is TextBox && x.Name.StartsWith("pre_cond") && x.Text != String.Empty)
                    {
                        isFound = true;
                        dafnyCreate.weakenPreCond(x.Text);
                    }
                }

                if (!isFound)
                {
                    MessageBox.Show("Please enter at least one preCondition.", "Empty input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                // add the new pre_condition and method

                dafnyCreate.WeakLemma.Name = this.preCondName.Text;
                dafnyCreate.NewMethod.Name = this.methodName.Text;

                // input from parser
                try
                {
                    DafnyCodeParser p = new DafnyCodeParser();
                    p.parse_file(dte.ActiveDocument.FullName, dafnyCreate.Name);

                    //vars:
                    List <String> varNames = p.get_var_names();
                    List <String> varTypes = p.get_var_types();
                    for (int i = 0; i < varNames.Count; i++)
                    {
                        Variable arg1 = new Variable(varNames[i], varTypes[i]);
                        dafnyCreate.AddArgument(arg1);
                    }
                    // returns
                    List <String> retNames = p.get_ret_names();
                    List <String> retTypes = p.get_ret_types();
                    for (int i = 0; i < retNames.Count; i++)
                    {
                        Variable arg1 = new Variable(retNames[i], retTypes[i]);
                        dafnyCreate.AddRetValue(arg1);
                    }

                    // preconditions
                    List <String> precond = p.get_req();
                    for (int i = 0; i < precond.Count; i++)
                    {
                        dafnyCreate.AddPreCond(precond[i]);
                    }

                    //post conditions
                    List <String> postcond = p.get_ens();
                    for (int i = 0; i < postcond.Count; i++)
                    {
                        dafnyCreate.AddPostCond(postcond[i]);
                    }
                }
                catch
                {
                    MessageBox.Show("Error in parsing the file.", "Parser Exeption", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.Close();
                    return;
                }

                // insert text
                toInsert.Insert("{\n" + dafnyCreate.generateBody() + "}\n\n" + dafnyCreate.generateMethod() + "\n\n" + dafnyCreate.generateWeakLemma() + "\n\n");
                this.Close();
            }
            catch
            {
                MessageBox.Show("Unexpected Exeption occurred during the execution.", "Unexpected Exeption", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
                return;
            }
        }
예제 #19
0
        public static IOsbideEvent FromCommand(string commandName, DTE2 dte)
        {
            IOsbideEvent oEvent = null;

            //debugging events
            if (debugCommands.Contains(commandName))
            {
                DebugActions action = (DebugActions)debugCommands.IndexOf(commandName);
                DebugEvent   debug  = new DebugEvent();
                debug.SolutionName = dte.Solution.FullName;
                debug.EventDate    = DateTime.UtcNow;

                //sometimes document name can be null
                try
                {
                    debug.DocumentName = dte.ActiveDocument.Name;
                }
                catch (Exception)
                {
                    debug.DocumentName = dte.Solution.FullName;
                }

                //add line number if applicable
                if (action == DebugActions.StepInto ||
                    action == DebugActions.StepOut ||
                    action == DebugActions.StepOver
                    )
                {
                    //line number can be null if there is no document open
                    try
                    {
                        TextSelection debugSelection = dte.ActiveDocument.Selection;
                        debugSelection.SelectLine();
                        int lineNumber = debugSelection.CurrentLine;
                        debug.LineNumber  = lineNumber;
                        debug.DebugOutput = debugSelection.Text;
                    }
                    catch (Exception)
                    {
                        debug.LineNumber = 0;
                    }
                }

                //kind of reappropriating this for our current use.  Consider refactoring.
                debug.ExecutionAction = (int)action;

                //throw the content of the output window into the event if we just stopped debugging
                if (action == DebugActions.StopDebugging)
                {
                    OutputWindowPane debugWindow = dte.ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug");
                    if (debugWindow != null)
                    {
                        TextDocument  text      = debugWindow.TextDocument;
                        TextSelection selection = text.Selection;
                        selection.StartOfDocument();
                        selection.EndOfDocument(true);
                        debug.DebugOutput = selection.Text;
                        selection.EndOfDocument();
                    }
                }

                oEvent = debug;
            }
            else if (cutCopyPasteCommands.Contains(commandName))
            {
                CutCopyPasteEvent ccp = new CutCopyPasteEvent();
                ccp.SolutionName = dte.Solution.FullName;
                ccp.EventDate    = DateTime.UtcNow;
                ccp.EventAction  = cutCopyPasteCommands.IndexOf(commandName);
                ccp.Content      = Clipboard.GetText();
                //sometimes document name can be null
                try
                {
                    ccp.DocumentName = dte.ActiveDocument.Name;
                }
                catch (Exception)
                {
                    ccp.DocumentName = dte.Solution.FullName;
                }
                oEvent = ccp;
            }

            return(oEvent);
        }
예제 #20
0
 void BeforeKeyPress(string Keypress, TextSelection Selection, bool InStatementCompletion, ref bool CancelKeypress)
 {
     if (isOn) {
         bool isAlpha = (Keypress[0] >= 'A' && Keypress[0] <= 'Z') || (Keypress[0] >= 'a' && Keypress[0] <= 'z');
         bool swap = Selection.IsActiveEndGreater;
         if (isAlpha) {
             if (!nextShouldBeCaps) {
                 if (swap)
                     Selection.SwapAnchor();
                 Selection.CharLeft(true);
                 if (Selection.Text[0] == '_')
                     nextShouldBeCaps = true;
                 Selection.CharRight(true);
                 if (swap)
                     Selection.SwapAnchor();
             }
             if (nextShouldBeCaps) {
                 CancelKeypress = true;
                 if (!Selection.IsEmpty) {
                     Selection.Delete();
                 }
                 Selection.Insert(Keypress.ToUpper());
             }
         } else if (Keypress == " ") {
             CancelKeypress = true;
             if (!Selection.IsEmpty) {
                 Selection.Delete();
             }
             Selection.Insert("_");
         } else if (Keypress == "(") {
             CancelKeypress = false;
             ToggleIsOn();
         }
         nextShouldBeCaps = false;
     }
 }
예제 #21
0
		public void Clear()
		{
			Lines.Clear();
			MaxLineLength = 0;

			ScrollLine = 0;
			ScrollColumn = 0;
			bIsSelecting = false;
			Selection = null;

			SCROLLINFO ScrollInfo = new SCROLLINFO();
			ScrollInfo.cbSize = Marshal.SizeOf(ScrollInfo);
			ScrollInfo.fMask = ScrollInfoMask.SIF_RANGE | ScrollInfoMask.SIF_PAGE | ScrollInfoMask.SIF_POS;
			SetScrollInfo(Handle, ScrollBarType.SB_HORZ, ScrollInfo, true);
			SetScrollInfo(Handle, ScrollBarType.SB_VERT, ScrollInfo, true);

			QueuedLines = new ConcurrentQueue<string>();
			if(LogFileStream != null)
			{
				LogFileStream.SetLength(0);
			}
		}
예제 #22
0
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            try
            {
                if (VsShellUtilities.IsInAutomationFunction(m_provider.ServiceProvider))
                {
                    return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
                }

                // make a copy of this so we can look at it after forwarding some commands
                uint commandID = nCmdID;
                char typedChar = char.MinValue;

                // make sure the input is a char before getting it
                if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR)
                {
                    typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);
                }

                // check for the triple slash
                if (typedChar == '/' && m_dte != null)
                {
                    string currentLine = m_textView.TextSnapshot.GetLineFromPosition(
                        m_textView.Caret.Position.BufferPosition.Position).GetText();
                    if ((currentLine + "/").Trim() == "///")
                    {
                        // Calculate how many spaces
                        string        spaces    = currentLine.Replace(currentLine.TrimStart(), "");
                        TextSelection ts        = m_dte.ActiveDocument.Selection as TextSelection;
                        int           oldLine   = ts.ActivePoint.Line;
                        int           oldOffset = ts.ActivePoint.LineCharOffset;
                        ts.LineDown();
                        ts.EndOfLine();

                        CodeElement   codeElement = null;
                        FileCodeModel fcm         = m_dte.ActiveDocument.ProjectItem.FileCodeModel;
                        if (fcm != null)
                        {
                            codeElement = fcm.CodeElementFromPoint(ts.ActivePoint, vsCMElement.vsCMElementFunction);
                        }

                        if (codeElement != null && codeElement is CodeFunction)
                        {
                            CodeFunction  function = codeElement as CodeFunction;
                            StringBuilder sb       = new StringBuilder("/ <summary>\r\n" + spaces + "/// \r\n" + spaces + "/// </summary>");
                            foreach (CodeElement child in codeElement.Children)
                            {
                                CodeParameter parameter = child as CodeParameter;
                                if (parameter != null)
                                {
                                    sb.AppendFormat("\r\n" + spaces + "/// <param name=\"{0}\"></param>", parameter.Name);
                                }
                            }

                            if (function.Type.AsString != "void")
                            {
                                sb.AppendFormat("\r\n" + spaces + "/// <returns></returns>");
                            }

                            ts.MoveToLineAndOffset(oldLine, oldOffset);
                            ts.Insert(sb.ToString());
                            ts.MoveToLineAndOffset(oldLine, oldOffset);
                            ts.LineDown();
                            ts.EndOfLine();
                            return(VSConstants.S_OK);
                        }
                        else
                        {
                            ts.MoveToLineAndOffset(oldLine, oldOffset);
                            ts.Insert("/ <summary>\r\n" + spaces + "/// \r\n" + spaces + "/// </summary>");
                            ts.MoveToLineAndOffset(oldLine, oldOffset);
                            ts.LineDown();
                            ts.EndOfLine();
                            return(VSConstants.S_OK);
                        }
                    }
                }

                if (m_session != null && !m_session.IsDismissed)
                {
                    // check for a commit character
                    if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN ||
                        nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB ||
                        typedChar == '>')
                    {
                        // check for a selection
                        // if the selection is fully selected, commit the current session
                        if (m_session.SelectedCompletionSet.SelectionStatus.IsSelected)
                        {
                            string selectedCompletion = m_session.SelectedCompletionSet.SelectionStatus.Completion.DisplayText;
                            m_session.Commit();
                            TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection;
                            switch (selectedCompletion)
                            {
                            case "<!-->":
                                ts.CharLeft(false, 3);
                                break;

                            case "<![CDATA[>":
                                ts.CharLeft(false, 3);
                                break;

                            case "<c>":
                                ts.CharLeft(false, 4);
                                break;

                            case "<code>":
                                ts.CharLeft(false, 7);
                                break;

                            case "<example>":
                                ts.CharLeft(false, 10);
                                break;

                            case "<exception>":
                                ts.CharLeft(false, 14);
                                break;

                            case "<include>":
                                ts.CharLeft(false, 21);
                                break;

                            case "<list>":
                                ts.CharLeft(false, 7);
                                break;

                            case "<para>":
                                ts.CharLeft(false, 7);
                                break;

                            case "<param>":
                                ts.CharLeft(false, 10);
                                break;

                            case "<paramref>":
                                ts.CharLeft(false, 3);
                                break;

                            case "<permission>":
                                ts.CharLeft(false, 15);
                                break;

                            case "<remarks>":
                                ts.CharLeft(false, 10);
                                break;

                            case "<returns>":
                                ts.CharLeft(false, 10);
                                break;

                            case "<see>":
                                ts.CharLeft(false, 3);
                                break;

                            case "<seealso>":
                                ts.CharLeft(false, 3);
                                break;

                            case "<typeparam>":
                                ts.CharLeft(false, 14);
                                break;

                            case "<typeparamref>":
                                ts.CharLeft(false, 3);
                                break;

                            case "<value>":
                                ts.CharLeft(false, 8);
                                break;

                            default:
                                break;
                            }

                            // also, don't add the character to the buffer
                            return(VSConstants.S_OK);
                        }
                        else
                        {
                            // if there is no selection, dismiss the session
                            m_session.Dismiss();
                        }
                    }
                }
                else
                {
                    if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN)
                    {
                        string currentLine = m_textView.TextSnapshot.GetLineFromPosition(
                            m_textView.Caret.Position.BufferPosition.Position).GetText();
                        if (currentLine.TrimStart().StartsWith("///"))
                        {
                            TextSelection ts     = m_dte.ActiveDocument.Selection as TextSelection;
                            string        spaces = currentLine.Replace(currentLine.TrimStart(), "");
                            ts.Insert("\r\n" + spaces + "/// ");
                            return(VSConstants.S_OK);
                        }
                    }
                }

                // pass along the command so the char is added to the buffer
                int retVal = m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                if (typedChar == '<')
                {
                    string currentLine = m_textView.TextSnapshot.GetLineFromPosition(
                        m_textView.Caret.Position.BufferPosition.Position).GetText();
                    if (currentLine.TrimStart().StartsWith("///"))
                    {
                        if (m_session == null || m_session.IsDismissed) // If there is no active session, bring up completion
                        {
                            if (this.TriggerCompletion())
                            {
                                m_session.SelectedCompletionSet.SelectBestMatch();
                                m_session.SelectedCompletionSet.Recalculate();
                                return(VSConstants.S_OK);
                            }
                        }
                    }
                }
                else if (
                    commandID == (uint)VSConstants.VSStd2KCmdID.BACKSPACE ||
                    commandID == (uint)VSConstants.VSStd2KCmdID.DELETE ||
                    char.IsLetter(typedChar))
                {
                    if (m_session != null && !m_session.IsDismissed) // the completion session is already active, so just filter
                    {
                        m_session.SelectedCompletionSet.SelectBestMatch();
                        m_session.SelectedCompletionSet.Recalculate();
                        return(VSConstants.S_OK);
                    }
                }

                return(retVal);
            }
            catch
            {
            }

            return(VSConstants.E_FAIL);
        }
예제 #23
0
 private static void ReplaceSelection(TextSelection selection, string text)
 {
     var anchor = selection.AnchorPoint.CreateEditPoint();
     anchor.ReplaceText(selection.Text.Length, text, (int) vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
 }
예제 #24
0
 private void LostFocusMethod(object obj)
 {
     prevSelection = (obj as RichTextBox).Selection;
 }
        private void HandleExpandDelegateTemplate(TextSelection selection)
        {
            if (!_options.UseDelegateInference)
            {
                return;
            }
            var editPoint = selection.TopPoint.CreateEditPoint();
            editPoint.StartOfLine();
            string previousLine = editPoint.GetText(selection.TopPoint);

            Match matchExpandingEventHandler = Regex.Match(previousLine, @"\.\w+\s*\+=\s*new\s+[a-zA-Z0-9_\.]+\s*\((\w*)$");
            _isExpandingCandidate = matchExpandingEventHandler.Success;
            if (_isExpandingCandidate)
            {
                StartUndoOperation();
                _delegateStart = selection.TopPoint.CreateEditPoint();
                _delegateStart.CharLeft(matchExpandingEventHandler.Groups[1].Value.Length); //We are now right after the (
            }
        }
예제 #26
0
 void _handleSelectionChanged(TextSelection selection,
                              SelectionChangedCause cause)
 {
     this.selection = selection;
     this.onSelectionChanged?.Invoke();
 }
예제 #27
0
        /// <summary>
        /// Replaces the selected text with the given text.
        /// </summary>
        /// <param name="point">The start point of the specified range of text.</param>
        /// <param name="oldText">The text to replace.</param>
        /// <param name="newText">The replacement text for pattern.</param>
        public bool Replace(TextSelection point, string oldText, string newText)
        {
            if (point == null)
                throw new ArgumentNullException("point");

            return luaCodeFile.Replace(point.AnchorPoint.Line, point.AnchorPoint.DisplayColumn,
                                       point.ActivePoint.Line,
                                       point.ActivePoint.DisplayColumn,
                                       point.Text, newText);
        }
예제 #28
0
 public abstract int Replace(Regex pattern, TextSelection textSelection);
예제 #29
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Moves the down after comment.
        /// </summary>
        /// <param name="sel">The sel.</param>
        /// ------------------------------------------------------------------------------------
        private void MoveDownAfterComment(TextSelection sel)
        {
            // Go to the beginning of the line and move down until we find a line that doesn't
            // start with ///.
            while (true)
            {
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                sel.EndOfLine(true);
                if (!sel.Text.StartsWith("///"))
                    break;

                // GhostDoc messes up dashed lines from inherited comments from base class,
                // so delete those
                if (sel.Text.StartsWith("/// -----"))
                {
                    sel.WordRight(true, 1);
                    sel.Delete(1);
                    sel.LineUp(false, 1);
                }
                sel.MoveToLineAndOffset(sel.ActivePoint.Line + 1, 1, false);
            }
        }
예제 #30
0
 public abstract int Replace(Regex pattern, TextSelection textSelection, bool saveFormatting);
예제 #31
0
 /// <summary>
 /// Substitutes all occurrences in the specified text selection of the specified pattern
 /// string with the specified replacement string.
 /// </summary>
 /// <param name="textSelection">The text selection.</param>
 /// <param name="patternString">The pattern string.</param>
 /// <param name="replacementString">The replacement string.</param>
 internal static void SubstituteAllStringMatches(TextSelection textSelection, string patternString, string replacementString)
 {
     TextRanges dummy = null;
     int lastCount = -1;
     while (textSelection.ReplacePattern(patternString, replacementString, StandardFindOptions, ref dummy))
     {
         // it is possible that the replacements aren't actually being done. In such a case,
         // we can detect the situation by seeing if the count always remains the same, and
         // if so exiting early.
         if (lastCount == dummy.Count)
         {
             OutputWindowHelper.WarningWriteLine("Forced a break out of TextDocumentHelper's SubstituteAllStringMatches for a selection.");
             break;
         }
         lastCount = dummy.Count;
     }
 }
예제 #32
0
        public ActionResult FindandHighlight(string Group1, string Button, string Group2)
        {
            if (Group1 == null)
            {
                return(View());
            }
            string     basePath     = _hostingEnvironment.WebRootPath;
            string     dataPath     = basePath + @"/DocIO/Adventure.docx";
            string     contenttype1 = "application/vnd.ms-word.document.12";
            FileStream fileStream   = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (Button == "View Template")
            {
                return(File(fileStream, contenttype1, "Adventure.docx"));
            }
            try
            {
                //Load template document
                WordDocument doc = new WordDocument(fileStream, FormatType.Docx);
                fileStream.Dispose();
                fileStream = null;
                //Get the pattern for regular expression
                Regex regex = new Regex(Group2);
                //Find the first occurrence of the text in the Word document.
                TextSelection text = doc.Find(regex);
                //Set the highlight color for the text.
                text.GetAsOneRange().CharacterFormat.HighlightColor = Syncfusion.Drawing.Color.Green;
                try
                {
                    FormatType type        = FormatType.Docx;
                    string     filename    = "Sample.docx";
                    string     contenttype = "application/vnd.ms-word.document.12";
                    #region Document SaveOption
                    //Save as .doc format
                    if (Group1 == "WordDoc")
                    {
                        type        = FormatType.Doc;
                        filename    = "Sample.doc";
                        contenttype = "application/msword";
                    }
                    //Save as .xml format
                    else if (Group1 == "WordML")
                    {
                        type        = FormatType.WordML;
                        filename    = "Sample.xml";
                        contenttype = "application/msword";
                    }
                    #endregion Document SaveOption
                    MemoryStream ms = new MemoryStream();
                    doc.Save(ms, type);
                    doc.Close();
                    ms.Position = 0;
                    return(File(ms, contenttype, filename));
                }
                catch (Exception)
                { }
            }
            catch (Exception)
            { }
            return(View());
        }
예제 #33
0
 internal static void SubstituteAllStringMatches(TextSelection textSelection, string patternString, string replacementString)
 {
     TextRanges dummy = null;
     int lastCount = -1;
     while (textSelection.ReplacePattern(patternString, replacementString, StandardFindOptions, ref dummy))
     {
         if (lastCount == dummy.Count)
         {
             break;
         }
         lastCount = dummy.Count;
     }
 }
예제 #34
0
        private void _Do_2(Func <string, bool> doneToConfirmContinue = null)
        {
            if (string.IsNullOrEmpty(_Namespace))
            {
                MessageBox.Show("Please provide a namespace");
                return;
            }

            if (!_Namespace.Contains(":"))
            {
                MessageBox.Show("Please provide a namespace:objectPrefix");
                return;
            }

            var parts    = _Namespace.SplitEx(':');
            var template = GetTemplatePath("ABP.Context");
            var now      = DateTime.Now;
            var projects = (Array)_App.ActiveSolutionProjects;

            var boPrefix  = parts[1];
            var nameSpace = parts[0];


            // 准备插入代码
            ProjectItem   file = null;
            Window        win  = null;
            TextSelection ts   = null;
            StringBuilder sb   = null;

            var batchIndex = -1;
            var batchSize  = 10000;
            var saved      = true;

            Action <ProjectItem> _newFile = f =>
            {
                batchIndex++;
                file = f.ProjectItems.AddFromTemplate(template, $"{boPrefix}.ALL.cs");
                win  = file.Open(Constants.vsViewKindCode);
                sb   = new StringBuilder();

                ts = win.Document.Selection as TextSelection;
                // ts.EndOfDocument();

                // 插入生成日期
                sb.AppendLine(@"/// <summary>");
                sb.AppendLine($"/// {now}");
                sb.AppendLine(@"/// </summary>");

                // 插入 namespace 行
                sb.AppendLine("namespace " + nameSpace);
                sb.AppendLine("{");

                saved = false;
            };

            Action _saveAndClose = () =>
            {
                ts.EndOfDocument();
                ts.Insert(sb.ToString());
                ts.Insert("}");
                ts.NewLine();
                ts.SelectAll();

                win.Activate();
                win.Document.Activate();

                _App.ExecuteCommand("Edit.FormatDocument");

                win.Close(vsSaveChanges.vsSaveChangesYes);
                saved = true;
            };

            if (projects.Length > 0)
            {
                foreach (Project p in projects)
                {
                    ProjectItem folder = p.ProjectItems
                                         .AddFolder("_Entities", Constants.vsProjectItemKindPhysicalFolder);
                    List <MBTable> tables =
                        _Context.Tables.Where(_Filter).OrderBy(t => t.Name).ToList();

                    for (int i = 0; i < tables.Count; i++)
                    {
                        if (i % batchSize == 0)
                        {
                            _newFile(folder);
                        }

                        var t = tables[i];

                        List <string> keys = new List <string>();
                        if (!
                            string.IsNullOrEmpty(t.KeyInfo))
                        {
                            foreach (string part in t.KeyInfo.Split(','))
                            {
                                if (part.Trim().Length > 0)
                                {
                                    keys.Add(part.Trim());
                                }
                            }
                        }

                        var columns = _Context.Columns
                                      .Where(c => c.TableId == t.TableId).OrderBy(c => c.Name).ToList();
                        var properties = _Context.Properties
                                         .Where(d => d.TableId == t.TableId).ToList();

                        // 说明
                        if (_Context.IsMySql)
                        {
                        }
                        else
                        {
                            properties.SingleOrDefault(d => d.TableId == t.TableId &&
                                                       d.Field == string.Empty && d.Name == FIELD_SUMMARY &&
                                                       !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                            {
                                sb.AppendLine(@"/// <summary>");
                                sb.AppendLine($"/// {d.Value}");
                                sb.AppendLine(@"/// </summary>");
                            });
                        }

                        if (keys.Count == 0)
                        {
                            doneToConfirmContinue($"Error: no primary key found for {t.Name}");
                            continue;
                        }

                        // Decide base class
                        var isCompoundKey = keys.Count > 1;
                        var singleKeyType = string.Empty;
                        var baseType      = "Entity";
                        var ignoreKeys    = new List <string>();

                        if (!
                            isCompoundKey)
                        {
                            singleKeyType = _getType(columns.First(c => c.Name == keys[0]));
                            ignoreKeys.Add(keys[0]);
                        }

                        if (columns.Exists(c => c.Name == "CreationTime" && c.Type.StartsWith("datetime")) &&
                            columns.Exists(c => c.Name == "CreatorId" && c.Type.StartsWith("uniqueidentifier")))
                        {
                            baseType = "CreationAuditedEntity";
                            ignoreKeys.AddRange(new string[] { "CreationTime", "CreatorId" });

                            if (columns.Exists(c => c.Name == "LastModificationTime" && c.Type.StartsWith("datetime")) &&
                                columns.Exists(c => c.Name == "LastModifierId" && c.Type.StartsWith("uniqueidentifier")))
                            {
                                ignoreKeys.AddRange(new string[] { "LastModificationTime", "LastModifierId" });
                                baseType = "AuditedEntity";

                                if (columns.Exists(c => c.Name == "DeletionTime" && c.Type.StartsWith("datetime")) &&
                                    columns.Exists(c => c.Name == "DeleterId" && c.Type.StartsWith("uniqueidentifier")) &&
                                    columns.Exists(c => c.Name == "IsDeleted" && c.Type.StartsWith("bit")))
                                {
                                    ignoreKeys.AddRange(new string[] { "DeletionTime", "DeleterId", "IsDeleted" });
                                    baseType = "FullAuditedEntity";
                                }
                            }
                        }

                        if (!isCompoundKey)
                        {
                            baseType += $"<{singleKeyType}>";
                        }

                        // 表格名字
                        sb.AppendLine($"public partial class {boPrefix}_{t.Name}:{baseType}{{");

                        // public constructor
                        sb.AppendLine($"public {boPrefix}_{t.Name}(){{}}");

                        if (isCompoundKey)
                        {
                            sb.AppendLine($"public override object[] GetKeys() => new object[] {{ {t.KeyInfo} }};");
                        }

                        columns.ForEach(c =>
                        {
                            if (ignoreKeys.Contains(c.Name))
                            {
                                return;
                            }

                            // Summary
                            if (_Context.IsMySql)
                            {
                            }
                            else
                            {
                                // 说明
                                properties.SingleOrDefault(d =>
                                                           d.TableId == t.TableId &&
                                                           d.Field == c.Name && d.Name == FIELD_SUMMARY &&
                                                           !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                                {
                                    sb.AppendLine(@"/// <summary>");
                                    sb.AppendLine($"/// {d.Value}");
                                    sb.AppendLine(@"/// </summary>");
                                });
                            }

                            var s = "public ";
                            s    += _getType(c) + " ";
                            s    += c.Name;
                            s    += " { get; set; }";

                            sb.AppendLine(s);
                        });

                        sb.AppendLine("}");

                        if (doneToConfirmContinue != null)
                        {
                            if (!doneToConfirmContinue(t.Name))
                            {
                                break;
                            }
                        }

                        if (i > 0 && ((i + 1) % batchSize) == 0)
                        {
                            _saveAndClose();
                        }
                    }

                    if (!saved)
                    {
                        _saveAndClose();
                    }
                }
            }
        }
 private static TextSelection GetTextSelectionFromWindow(Window window, TextSelection sel)
 {
     try
     {
         sel = window.Selection as TextSelection;
     }
     catch (Exception eSelection)
     {
         DiagnosticService.TraceError("An error occured accessing Active window selection unavailable. Exception:'{0}'", eSelection.ToString());
     }
     return sel;
 }
        public ActionResult FindandHighlight(string Group1, string Button, string Group2)
        {
            if (Group1 == null)
            {
                return(View());
            }
            if (Button == "View Template")
            {
                return(new TemplateResult("Adventure.docx", ResolveApplicationDataPath("App_Data\\DocIO"), HttpContext.ApplicationInstance.Response));
            }

            try
            {
                //Load template document
                WordDocument doc = new WordDocument(ResolveApplicationDataPath("Adventure.docx", "App_Data\\DocIO"));
                //Get the pattern for regular expression
                Regex regex = new Regex(Group2);
                //Find the first occurrence of the text in the Word document.
                TextSelection text = doc.Find(regex);
                //Set the highlight color for the text.
                text.GetAsOneRange().CharacterFormat.HighlightColor = Color.Green;
                try
                {
                    #region Document SaveOption

                    //Save as .doc format
                    if (Group1 == "WordDoc")
                    {
                        return(doc.ExportAsActionResult("Sample.doc", FormatType.Doc,
                                                        HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
                    }
                    //Save as .docx format
                    else if (Group1 == "WordDocx")
                    {
                        return(doc.ExportAsActionResult("Sample.docx", FormatType.Docx,
                                                        HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
                    }
                    // Save as WordML(.xml) format
                    else if (Group1 == "WordML")
                    {
                        return(doc.ExportAsActionResult("Sample.xml", FormatType.WordML,
                                                        HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
                    }
                    //Save as .pdf format
                    else if (Group1 == "Pdf")
                    {
                        DocToPDFConverter converter = new DocToPDFConverter();
                        PdfDocument       pdfDoc    = converter.ConvertToPDF(doc);

                        return(pdfDoc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response,
                                                           HttpReadType.Save));
                    }

                    #endregion Document SaveOption
                }
                catch (Exception)
                { }
            }
            catch (Exception Ex)
            {
                System.Diagnostics.Trace.WriteLine(Ex.Message + "\n\n\n" + Ex.StackTrace);
            }
            return(View());
        }
예제 #37
0
 public TextSelectionManager(TextSelection selection)
 {
     _selection = selection;
 }
예제 #38
0
 public static bool IsFullLine(this TextSelection selection)
 {
     return(!selection.IsEmpty && selection.TopPoint.AtStartOfLine && selection.BottomPoint.AtStartOfLine);
 }
예제 #39
0
		protected void ContextMenu_SelectAll(object sender, EventArgs e)
		{
			if(Lines.Count > 0)
			{
				Selection = new TextSelection(new TextLocation(0, 0), new TextLocation(Lines.Count - 1, Lines[Lines.Count - 1].Length));
				Invalidate();
			}
		}
예제 #40
0
 public static void BeginUpdate(this TextSelection selection, string name)
 {
     selection.DTE.UndoContext.Open(name);
 }
예제 #41
0
		void EndSelection()
		{
			if(bIsSelecting)
			{
				if(Selection != null && Selection.IsEmpty())
				{
					Selection = null;
				}
				SelectionScrollTimer.Stop();
				bIsSelecting = false;
			}
		}
예제 #42
0
 public static void EndUpdate(this TextSelection selection)
 {
     selection.DTE.UndoContext.Close();
 }
        private void DoExpand(TextSelection selection)
        {
            if (_delegateStart == null)
            {
                return;
            }
            var point = selection.BottomPoint.CreateEditPoint();
            point.EndOfLine();
            var point2 = selection.BottomPoint.CreateEditPoint();
            string line = point2.GetText(point);
            if (line.Trim() == "throw new NotImplementedException();")
            {
                var delPoint = _delegateStart.CreateEditPoint();
                delPoint.GetText(-1);
                delPoint.WordLeft(3);

                delPoint.Delete(_delegateStart);
                _delegateStart.WordRight();
                _delegateStart.Delete(1);
            }
            _delegateStart = null;
        }
예제 #44
0
 public void AddFormula(TextSelection selection)
 {
     AddBlock(new FormulaBlock {
         Formula = "f(x)"
     }, selection);
 }
        private bool HandleCreateDelegateTemplate(TextSelection selection)
        {
            var editPoint = selection.TopPoint.CreateEditPoint();
            editPoint.StartOfLine();
            string previousLine = editPoint.GetText(selection.TopPoint);

            Match matchCreatingEventHandler = Regex.Match(previousLine, @"\.(\w+)\s*\+=\s*$");
            _isRenameCandidate = matchCreatingEventHandler.Success;
            if (_isRenameCandidate)
            {
                _eventName = matchCreatingEventHandler.Groups[1].Value;
                StartUndoOperation();
                return true;
            }
            return false;
        }
예제 #46
0
 public void AddUnorderedList(TextSelection selection)
 {
     AddBlock(new List {
         ListItems = { new ListItem() }
     }, selection);
 }
예제 #47
0
        public void Navigate(object item)
        {
            if (m_dte == null)
            {
                return;
            }

            var    codeItem    = item as CodeUIItem;
            var    edgeItem    = item as CodeUIEdgeItem;
            var    fileName    = "";
            int    line        = 0;
            int    column      = 0;
            bool   res         = false;
            string searchToken = "";

            try
            {
                if (codeItem != null)
                {
                    codeItem.GetDefinitionPosition(out fileName,out line,out column);
                    if (codeItem.GetKind() == DoxygenDB.EntKind.PAGE)
                    {
                        MoveTo(fileName,line,column);
                        return;
                    }
                    if (codeItem.GetKind() == DoxygenDB.EntKind.FILE)
                    {
                        OpenFile(fileName);
                        return;
                    }
                    res         = ShowItemDefinition(codeItem,fileName);
                    searchToken = codeItem.GetName();
                }
                else if (edgeItem != null)
                {
                    line     = edgeItem.m_line;
                    column   = edgeItem.m_column;
                    fileName = edgeItem.m_file;

                    var scene    = UIManager.Instance().GetScene();
                    var itemDict = scene.GetItemDict();
                    var srcItem  = itemDict[edgeItem.m_srcUniqueName];
                    var tarItem  = itemDict[edgeItem.m_tarUniqueName];
                    searchToken = tarItem.GetName();

                    if (srcItem.IsFunction())
                    {
                        if (File.Exists(fileName))
                        {
                            OpenFile(fileName);
                            var document = m_dte.ActiveDocument;

                            var codeElement = GetCodeElement(srcItem,document);

                            if (codeElement != null)
                            {
                                var funcStart = codeElement.GetStartPoint(vsCMPart.vsCMPartBody);
                                var funcText  = UpdateBodyCode(srcItem,codeElement);

                                int offset = -1;
                                if (tarItem.IsFunction())
                                {
                                    offset = FindOffset(funcText,string.Format(@"\b{0}\(",tarItem.GetName()));
                                }
                                if (offset == -1)
                                {
                                    offset = FindOffset(funcText,string.Format(@"\b{0}\b",tarItem.GetName()));
                                }
                                if (offset != -1)
                                {
                                    var           absOffset = funcStart.AbsoluteCharOffset + offset;
                                    TextSelection ts        = document.Selection as TextSelection;
                                    ts.MoveToAbsoluteOffset(absOffset);
                                    res = true;
                                }
                            }
                        }
                    }
                    else if (srcItem.GetKind() == DoxygenDB.EntKind.PAGE)
                    {
                        srcItem.GetDefinitionPosition(out fileName,out line,out column);
                        MoveTo(fileName,line,column);
                        return;
                    }
                    else
                    {
                        res = ShowItemDefinition(tarItem,fileName);
                    }
                }
            }
            catch (Exception)
            {
                res = false;
            }

            if (res == false)
            {
                if (File.Exists(fileName))
                {
                    try
                    {
                        OpenFile(fileName);
                        TextSelection ts      = m_dte.ActiveDocument.Selection as TextSelection;
                        TextDocument  textDoc = ts.Parent;
                        if (ts != null && line > 0 && textDoc != null)
                        {
                            var formatStr = string.Format(@"\b{0}\b",searchToken);
                            int beginLine = Math.Max(1,line - 30);
                            int endLine   = line + 31;
                            int endOffset = 1;
                            if (endLine > textDoc.EndPoint.Line)
                            {
                                endLine   = textDoc.EndPoint.Line;
                                endOffset = textDoc.EndPoint.LineLength + 1;
                            }
                            ts.MoveToLineAndOffset(beginLine,1,false);
                            ts.MoveToLineAndOffset(endLine,endOffset,true);
                            string searchText = ts.Text.Replace("\r\n","\n");
                            int    lineBeginIdx = 0;
                            int    bestLine = int.MaxValue,bestColumn = -1;
                            for (int currentLine = beginLine; ; currentLine++)
                            {
                                int lineEndIdx = searchText.IndexOf("\n",lineBeginIdx);
                                if (lineEndIdx == -1)
                                {
                                    lineEndIdx = searchText.Length;
                                }
                                string lineStr = searchText.Substring(lineBeginIdx,lineEndIdx - lineBeginIdx);
                                var    matches = Regex.Matches(lineStr,formatStr,RegexOptions.ExplicitCapture);
                                foreach (Match nextMatch in matches)
                                {
                                    if (Math.Abs(currentLine - line) < Math.Abs(bestLine - line))
                                    {
                                        bestLine   = currentLine;
                                        bestColumn = nextMatch.Index + 1;
                                    }
                                }
                                if (lineEndIdx == -1 || lineEndIdx >= searchText.Length - 1)
                                {
                                    break;
                                }
                                lineBeginIdx = lineEndIdx + 1;
                            }
                            if (bestColumn != -1)
                            {
                                ts.MoveTo(bestLine,bestColumn);
                                res = true;
                            }

                            if (res == false)
                            {
                                ts.MoveTo(line,column);
                                //ts.GotoLine(line);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        Logger.Debug("Go to page fail.");
                    }
                }
            }
        }
예제 #48
0
 public void AddOrderedList(TextSelection selection)
 {
     AddBlock(new List {
         ListItems = { new ListItem() }, MarkerStyle = TextMarkerStyle.Decimal
     }, selection);
 }
예제 #49
0
        /// <summary></summary>
        bool ChangeSelectedTextCase(TextSelection selection, TextTransformationOption option)
        {
            string before = selection.Text;
            string after = CodeManager.TransformText(before, option);
            bool changed = (before != after);

            if (changed)
            {
                selection.Delete();
                selection.Insert(after);
            }
            return changed;
        }
예제 #50
0
 public void AddDrawing(TextSelection currentSelection)
 {
     AddBlock(new DrawerBlock(), currentSelection);
 }
예제 #51
0
        private void _OnTextDocumentBeforeKeyPress(string keypress, TextSelection selection, bool inStatementCompletion, ref bool cancelKeypress)
        {
            const char BACKSPACE_CHAR_ASCII = (char)8;
            if (keypress != BACKSPACE_CHAR_ASCII.ToString(CultureInfo.InvariantCulture))
                return;

            var textDocument = (TextDocument)_applicationObject.ActiveDocument.Object("TextDocument");
            if (textDocument == null)
                return;

            IndentOptions indentOptions;
            if (_languageIndentOptions.ContainsKey(textDocument.Language) == false)
            {
                Properties properties = _applicationObject.get_Properties("TextEditor", textDocument.Language);
                indentOptions = new IndentOptions
                                    {
                                        InsertTabs = bool.Parse(properties.Item("InsertTabs").Value.ToString()),
                                        IndentSize = int.Parse(properties.Item("IndentSize").Value.ToString())
                                    };

                _languageIndentOptions.Add(textDocument.Language, indentOptions);
            }
            else
                indentOptions = _languageIndentOptions[textDocument.Language];

            // if tabs are used for indentation lets not do anything
            if (indentOptions.InsertTabs)
                return;

            var lineStartPoint = selection.ActivePoint.CreateEditPoint();
            lineStartPoint.StartOfLine();

            var activeEditPoint = selection.ActivePoint.CreateEditPoint();
            string currentLine = activeEditPoint.GetText(lineStartPoint);

            if (currentLine.Length == 0)
                return;

            // if the current line full of white space chars and multiple of indent size then left indent by deleting
            // indent amount of white space character
            const char WHITESPACE_CHAR = ' ';
            if (IsLineFullOf(currentLine, WHITESPACE_CHAR) && (currentLine.Length % indentOptions.IndentSize) == 0)
            {
                activeEditPoint.CharLeft(indentOptions.IndentSize);
                activeEditPoint.Delete(indentOptions.IndentSize);
                cancelKeypress = true;
            }
        }
예제 #52
0
 public void AddImage(TextSelection currentSelection, ImageSource source)
 {
     AddBlock(new ImageBlock {
         Source = source
     }, currentSelection);
 }
예제 #53
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Gets the method or property.
 /// </summary>
 /// <param name="sel">The sel.</param>
 /// <returns></returns>
 /// ------------------------------------------------------------------------------------
 private static CodeElement GetMethodOrProperty(TextSelection sel)
 {
     CodeElement codeElement;
     codeElement = sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementFunction);
     if (codeElement == null)
         codeElement = sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementProperty);
     return codeElement;
 }
예제 #54
0
 public void AddPlot(TextSelection currentSelection)
 {
     AddBlock(new PlotBlock(), currentSelection);
 }
예제 #55
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Moves the up before comment.
        /// </summary>
        /// <param name="sel">The sel.</param>
        /// ------------------------------------------------------------------------------------
        private void MoveUpBeforeComment(TextSelection sel)
        {
            TextRanges textRanges = null;
            for (; true; )
            {
                if (sel.FindPattern("\\<summary\\>|/// ---", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsRegularExpression),
                    ref textRanges))
                {
                    // GhostDoc messes up dashed lines from inherited comments from base class,
                    // so delete those
                    if (sel.Text.StartsWith("/// ---"))
                    {
                        sel.EndOfLine(true);
                        sel.WordRight(true, 1);
                        sel.Delete(1);
                    }
                    else if (sel.Text.StartsWith("<summary>"))
                    {
                        while (true)
                        {
                            sel.MoveToLineAndOffset(sel.ActivePoint.Line - 1, 1, false);
                            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                            sel.EndOfLine(true);
                            if (!sel.Text.StartsWith("///"))
                            {
                                if (sel.Text.Length > 0)
                                {
                                    // there is a non-empty comment line. We want to start at the end
                                    // of it
                                    sel.EndOfLine(false);
                                }
                                else
                                    sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                                break;
                            }

                            // GhostDoc messes up dashed lines from inherited comments from base class,
                            // so delete those
                            if (sel.Text.StartsWith("/// -----"))
                            {
                                sel.WordRight(true, 1);
                                sel.Delete(1);
                            }
                        }
                        return;
                    }
                }
                else
                    return;
            }
        }
예제 #56
0
        public TextEditingValue getValueForAction(TextInputAction operation)
        {
            TextPosition     newPosition  = null;
            TextPosition     newExtend    = null;
            TextEditingValue newValue     = null;
            TextSelection    newSelection = null;
            TextPosition     startPos     = new TextPosition(this._value.selection.start, this._value.selection.affinity);

            switch (operation)
            {
            case TextInputAction.moveLeft:
                newValue = this._value.moveLeft();
                break;

            case TextInputAction.moveRight:
                newValue = this._value.moveRight();
                break;

            case TextInputAction.moveUp:
                newPosition = this.renderEditable.getPositionUp(startPos);
                break;

            case TextInputAction.moveDown:
                newPosition = this.renderEditable.getPositionDown(startPos);
                break;

            case TextInputAction.moveLineStart:
                newPosition = this.renderEditable.getParagraphStart(startPos, TextAffinity.downstream);
                break;

            case TextInputAction.moveLineEnd:
                newPosition = this.renderEditable.getParagraphEnd(startPos, TextAffinity.upstream);
                break;

            case TextInputAction.moveWordRight:
                newPosition = this.renderEditable.getWordRight(startPos);
                break;

            case TextInputAction.moveWordLeft:
                newPosition = this.renderEditable.getWordLeft(startPos);
                break;

//                case TextInputAction.MoveToStartOfNextWord:      MoveToStartOfNextWord(); break;
//                case TextInputAction.MoveToEndOfPreviousWord:        MoveToEndOfPreviousWord(); break;
            case TextInputAction.moveTextStart:
                newPosition = new TextPosition(0);
                break;

            case TextInputAction.moveTextEnd:
                newPosition = new TextPosition(this._value.text.Length);
                break;

            case TextInputAction.moveParagraphForward:
                newPosition = this.renderEditable.getParagraphForward(startPos);
                break;

            case TextInputAction.moveParagraphBackward:
                newPosition = this.renderEditable.getParagraphBackward(startPos);
                break;

            case TextInputAction.moveGraphicalLineStart:
                newPosition = this.renderEditable.getLineStartPosition(startPos, TextAffinity.downstream);
                break;

            case TextInputAction.moveGraphicalLineEnd:
                newPosition = this.renderEditable.getLineEndPosition(startPos, TextAffinity.upstream);
                break;

            case TextInputAction.selectLeft:
                newValue = this._value.extendLeft();
                break;

            case TextInputAction.selectRight:
                newValue = this._value.extendRight();
                break;

            case TextInputAction.selectUp:
                newExtend = this.renderEditable.getPositionUp(this._value.selection.extendPos);
                break;

            case TextInputAction.selectDown:
                newExtend = this.renderEditable.getPositionDown(this._value.selection.extendPos);
                break;

            case TextInputAction.selectWordRight:
                newExtend = this.renderEditable.getWordRight(this._value.selection.extendPos);
                break;

            case TextInputAction.selectWordLeft:
                newExtend = this.renderEditable.getWordLeft(this._value.selection.extendPos);
                break;

//                case TextInputAction.SelectToEndOfPreviousWord:  SelectToEndOfPreviousWord(); break;
//                case TextInputAction.SelectToStartOfNextWord:    SelectToStartOfNextWord(); break;
//
            case TextInputAction.selectTextStart:
                newExtend = new TextPosition(0);
                break;

            case TextInputAction.selectTextEnd:
                newExtend = new TextPosition(this._value.text.Length);
                break;

            case TextInputAction.expandSelectGraphicalLineStart:
                if (this._value.selection.isCollapsed ||
                    !this.renderEditable.isLineEndOrStart(this._value.selection.start))
                {
                    newSelection = new TextSelection(this.renderEditable.getLineStartPosition(startPos).offset,
                                                     this._value.selection.end, this._value.selection.affinity);
                }

                break;

            case TextInputAction.expandSelectGraphicalLineEnd:
                if (this._value.selection.isCollapsed ||
                    !this.renderEditable.isLineEndOrStart(this._value.selection.end))
                {
                    newSelection = new TextSelection(this._value.selection.start,
                                                     this.renderEditable.getLineEndPosition(this._value.selection.endPos).offset,
                                                     this._value.selection.affinity);
                }

                break;

            case TextInputAction.selectParagraphForward:
                newExtend = this.renderEditable.getParagraphForward(this._value.selection.extendPos);
                break;

            case TextInputAction.selectParagraphBackward:
                newExtend = this.renderEditable.getParagraphBackward(this._value.selection.extendPos);
                break;

            case TextInputAction.selectGraphicalLineStart:
                newExtend = this.renderEditable.getLineStartPosition(this._value.selection.extendPos);
                break;

            case TextInputAction.selectGraphicalLineEnd:
                newExtend = this.renderEditable.getLineEndPosition(startPos);
                break;

            case TextInputAction.delete:
                newValue = this._value.deleteSelection(false);
                break;

            case TextInputAction.backspace:
                newValue = this._value.deleteSelection();
                break;

            case TextInputAction.selectAll:
                newSelection = this._value.selection.copyWith(baseOffset: 0, extentOffset: this._value.text.Length);
                break;
            }

            if (newPosition != null)
            {
                return(this._value.copyWith(selection: TextSelection.fromPosition(newPosition)));
            }
            else if (newExtend != null)
            {
                return(this._value.copyWith(selection: this._value.selection.copyWith(extentOffset: newExtend.offset)));
            }
            else if (newSelection != null)
            {
                return(this._value.copyWith(selection: newSelection));
            }
            else if (newValue != null)
            {
                return(newValue);
            }

            return(this._value);
        }
예제 #57
0
        void eventTextEditor2_BeforeKeyPress(string Keypress, TextSelection Selection, bool InStatementCompletion, ref bool CancelKeypress)
        {
            Document activeDoc = _applicationObject.DTE.ActiveDocument;
            if (activeDoc == null)
            {
                return;
            }
            else if (activeDoc.Language == "JScript" || activeDoc.Language.ToUpper().IndexOf("SQL") >= 0)
            {
                if (option.AutoCompleteBracket)
                {
                    if (Keypress == "}")
                    {
                        EditPoint ep = Selection.ActivePoint.CreateEditPoint();
                        EditPoint sp = ep.CreateEditPoint();
                        sp.CharLeft(1);

                        sp.StartOfDocument();
                        string txt = sp.GetText(ep);
                        if (txt != "")
                        {
                            txt += "}";
                            VSBlockInfo block = beautifier.GetBLOCK(txt);
                            if (block.text != "")
                            {
                                sp.LineDown(block.line - 1);
                                beautifier.Indent = block.indent;
                                beautifier.js_beautify(block.text);
                                StringBuilder sb = new StringBuilder();
                                string formatedCode = beautifier.output.Remove(beautifier.output.Length - 1, 1);
                                sb.Append('\t', block.indent);
                                sb.Append(formatedCode);

                                //sp.Delete(txt.Length-1);
                                //sp.Insert(sb.ToString());

                                ep.ReplaceText(sp, sb.ToString(), (int)vsEPReplaceTextOptions.vsEPReplaceTextKeepMarkers);
                                return;
                            }

                        }
                    }
                    else if (Keypress == " " || Keypress == "\t")
                    {
                        try
                        {
                            bool outLined = outliner.doLineEvent(Selection.ActivePoint, Selection.ActivePoint, 0, true);
                            if (outLined)
                            {
                                CancelKeypress = true;
                            }
                        }
                        catch (System.Exception e)
                        {
                            MessageBox.Show(e.Message);
                        }

                    }
                }
            }
        }
		private static void MoveUsingsInsideNameSpace(ProjectItem projectItem, TextSelection txtSel, CodeNamespace nameSpace)
		{
			var usingsOutsideNameSpace = SearchService.FindUsings(projectItem.FileCodeModel.CodeElements);
			if (usingsOutsideNameSpace.Any())
			{
				List<string> linesToMove = new List<string>();
				for (int i = 0; i < usingsOutsideNameSpace.Count(); i++)
				{
					linesToMove.Add(usingsOutsideNameSpace[i].InnerText());
					usingsOutsideNameSpace[i].Delete();
				}

				var editPoint = nameSpace.GetStartPoint().CreateEditPoint();
				editPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsNone, ref editPoint);
				txtSel.MoveToPoint(editPoint);
				txtSel.NewLine();
				foreach (var line in linesToMove)
				{
					txtSel.Insert(line);
					txtSel.NewLine();
				}
			}
		}
        /// <summary>
        /// Replace a specific content in the Word document with another document
        /// </summary>
        /// <returns>Return the created Word document as stream</returns>
        public MemoryStream AdvancedReplace(string documentType, string button)
        {
            string basePath         = _hostingEnvironment.WebRootPath;
            string dataPathTemp     = basePath + @"/DocIO/SourceTemplate1.doc";
            string dataPathTemplate = basePath + @"/DocIO/SourceTemplate2.doc";
            string dataPathMaster   = basePath + @"/DocIO/MasterTemplate.doc";
            //Load Template document stream.
            FileStream fileStream = new FileStream(dataPathMaster, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (button == "View Template")
            {
                MemoryStream ms = new MemoryStream();
                fileStream.Position = 0;
                fileStream.CopyTo(ms);
                fileStream.Dispose();
                return(ms);
            }
            fileStream = null;
            //Creating new documents.
            WordDocument docSource1 = new WordDocument();
            WordDocument docSource2 = new WordDocument();
            WordDocument docMaster  = new WordDocument();

            //Load Templates.
            fileStream = new FileStream(dataPathTemp, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            docSource1.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            fileStream = new FileStream(dataPathTemplate, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            docSource2.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            fileStream = new FileStream(dataPathMaster, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            docMaster.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            //Search for a string and store in TextSelection
            //The TextSelection copies a text segment with formatting.
            TextSelection selection1 = docSource1.Find("PlaceHolder text is replaced with this formatted animated text", false, false);
            //Get the text segment to replace the tex across multiple paragraphs
            TextBodyPart replacePart = new TextBodyPart(docSource2);

            foreach (TextBodyItem bodyItem in docSource2.LastSection.Body.ChildEntities)
            {
                replacePart.BodyItems.Add(bodyItem.Clone());
            }
            //Replacing the placeholder inside Master Template with matches found while
            //search the two template documents.
            docMaster.Replace("PlaceHolder1", selection1, true, true, true);
            docMaster.ReplaceSingleLine((new System.Text.RegularExpressions.Regex("PlaceHolder2Start:Suppliers/Vendors of Northwind." +
                                                                                  "Customers of Northwind.Employee details of Northwind traders.The product information.The inventory details.The shippers." +
                                                                                  "PO transactions i.e Purchase Order transactions.Sales Order transaction.Inventory transactions.Invoices.PlaceHolder2End")), replacePart);

            FormatType formatType = FormatType.Docx;

            //Save as .doc format
            if (documentType == "WordDoc")
            {
                formatType = FormatType.Doc;
            }
            //Save as .xml format
            else if (documentType == "WordML")
            {
                formatType = FormatType.WordML;
            }
            //Save the document as a stream and retrun the stream
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the created Word document to MemoryStream
                docMaster.Save(stream, formatType);
                docMaster.Close();
                stream.Position = 0;
                return(stream);
            }
        }
예제 #60
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (radioButton1.Checked)
                {
                    // Get Template files path.
                    string dataPath = Application.StartupPath + @"..\..\..\..\..\..\..\..\Common\Data\DocIO\";

                    // Creating new documents.
                    WordDocument docSource1 = new WordDocument();
                    WordDocument docSource2 = new WordDocument();
                    WordDocument docMaster  = new WordDocument();

                    // Load Templates.
                    docSource1.Open(Path.Combine(dataPath, "TemplateSource1.doc"), FormatType.Doc);
                    docSource2.Open(Path.Combine(dataPath, "TemplateSource2.doc"), FormatType.Doc);
                    docMaster.Open(Path.Combine(dataPath, "TemplateMaster.doc"), FormatType.Doc);

                    // Search for a string and store in TextSelection
                    //The TextSelection copies a text segment with formatting.
                    TextSelection selection1 = docSource1.Find("PlaceHolder text is replaced with this formatted animated text", false, false);

                    // Search for a string and store in TextSelection
                    TextSelection selection2 = docSource2.Find(new Regex("This is the second Sentence"));

                    // Replacing the placeholder inside Master Template with matches found while
                    //search the two template documents.
                    docMaster.Replace(new Regex("PlaceHolder1"), selection1);
                    docMaster.Replace(new Regex("PlaceHolder2"), selection2);

                    //Save as doc format
                    if (wordDocRadioBtn.Checked)
                    {
                        //Saving the document to disk.
                        docMaster.Save("Sample.doc");

                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                            System.Diagnostics.Process.Start("Sample.doc");
                            //Exit
                            this.Close();
                        }
                    }
                    //Save as docx format
                    else if (wordDocxRadioBtn.Checked)
                    {
                        //Saving the document as .docx
                        docMaster.Save("Sample.docx", FormatType.Docx);
                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            try
                            {
                                //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                                System.Diagnostics.Process.Start("Sample.docx");
                                //Exit
                                this.Close();
                            }
                            catch (Win32Exception ex)
                            {
                                MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                                Console.WriteLine(ex.ToString());
                            }
                        }
                    }
                    //Save as pdf format
                    else if (pdfRadioBtn.Checked)
                    {
                        DocToPDFConverter converter = new DocToPDFConverter();
                        //Convert word document into PDF document
                        PdfDocument pdfDoc = converter.ConvertToPDF(docMaster);
                        //Save the pdf file
                        pdfDoc.Save("Sample.pdf");
                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            try
                            {
                                System.Diagnostics.Process.Start("Sample.pdf");
                                //Exit
                                this.Close();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }
                        }
                    }
                    else
                    {
                        // Exit
                        this.Close();
                    }
                }
                else
                {
                    //Load template document
                    WordDocument doc = new WordDocument(@"..\..\..\..\..\..\..\Common\Data\DocIO\original.doc");

                    //Load the document to be replaced
                    WordDocument replaceDoc = new WordDocument(@"..\..\..\..\..\..\..\Common\Data\DocIO\Replace.doc");

                    //Set Margin of the section
                    doc.LastSection.PageSetup.Margins.All = 72;
                    //Select a table and add it to TextBodyPart
                    TextBodyPart replacePart = new TextBodyPart(replaceDoc);
                    replacePart.BodyItems.Add(replaceDoc.Sections[0].Body.Tables[0] as WTable);

                    //Replace Text with table
                    doc.Replace("INSERT TABLE", replacePart, true, true);

                    //Select text and image
                    replacePart = new TextBodyPart(replaceDoc);
                    TextBodySelection textSel = new TextBodySelection(replaceDoc.LastSection.Body, 0, replaceDoc.LastSection.Paragraphs.Count, 0, 1);
                    replacePart.Copy(textSel);

                    //Replace Text with image and text.
                    doc.Replace("INSERT PARAGRAPH ITEMS", replacePart, false, true);

                    //Save as doc format
                    if (wordDocRadioBtn.Checked)
                    {
                        //Saving the document to disk.
                        doc.Save("Sample.doc");

                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                            System.Diagnostics.Process.Start("Sample.doc");
                            //Exit
                            this.Close();
                        }
                    }
                    //Save as docx format
                    else if (wordDocxRadioBtn.Checked)
                    {
                        //Saving the document as .docx
                        doc.Save("Sample.docx", FormatType.Docx);
                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            try
                            {
                                //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                                System.Diagnostics.Process.Start("Sample.docx");
                                //Exit
                                this.Close();
                            }
                            catch (Win32Exception ex)
                            {
                                MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                                Console.WriteLine(ex.ToString());
                            }
                        }
                    }
                    //Save as pdf format
                    else if (pdfRadioBtn.Checked)
                    {
                        DocToPDFConverter converter = new DocToPDFConverter();
                        //Convert word document into PDF document
                        PdfDocument pdfDoc = converter.ConvertToPDF(doc);
                        //Save the pdf file
                        pdfDoc.Save("Sample.pdf");
                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            try
                            {
                                System.Diagnostics.Process.Start("Sample.pdf");
                                //Exit
                                this.Close();
                            }
                            catch (Exception ex)
                            {
                                MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                                Console.WriteLine(ex.ToString());
                            }
                        }
                    }
                    else
                    {
                        // Exit
                        this.Close();
                    }
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }