Example #1
0
 public void Close()
 {
     _selection.MoveToAbsoluteOffset(_currentEditPoint, false);
 }
Example #2
0
 /// <summary>
 ///     A TextSelection extension method that sets a selection.
 /// </summary>
 /// <param name="target">
 ///     The target to act on.
 /// </param>
 /// <param name="AnchorPoint">
 ///     The anchor point.
 /// </param>
 /// <param name="ActivePoint">
 ///     The active point.
 /// </param>
 public static void SetSelection(this TextSelection target, int AnchorPoint, int ActivePoint)
 {
     target.MoveToAbsoluteOffset(AnchorPoint);
     target.MoveToAbsoluteOffset(ActivePoint, true);
 }
        public bool FormatFile(EnvDTE.DTE dte)
        {
            m_CfSuccessful = false;
            DateTime localDate = DateTime.Now;
            string   localDateString;
            string   localTimeString;

            localDateString = String.Format("Date: {0:dddd, d. MMMM yyyy}", localDate);
            localTimeString = String.Format("Time: {0:HH:mm:ss}", localDate);
            //DateTime utcDate = DateTime.UtcNow;

            m_sClangExecutable = (string)mProps.Item("ClangExecutable").Value;
            m_sCfStyle         = (string)mProps.Item("CfStyle").Value;
            m_sFallbackStyle   = (string)mProps.Item("FallbackStyle").Value;
            m_sAssumeFilename  = (string)mProps.Item("AssumeFilename").Value;
            m_sCursorPosition  = (string)mProps.Item("CursorPosition").Value;;
            m_sSortIncludes    = (bool)mProps.Item("SortIncludes").Value;
            m_sSaveOnFormat    = (bool)mProps.Item("SaveOnFormat").Value;
            m_sOutputEnabled   = (bool)mProps.Item("OutputEnabled").Value;
            m_formatLinesOnly  = false;
            m_argument         = "";

            LogToOutputWindow(Environment.NewLine);
            LogToOutputWindow("[ Log " + localDateString + " ]");
            LogToOutputWindow(Environment.NewLine);
            LogToOutputWindow("[ Log " + localTimeString + " ]");
            LogToOutputWindow(Environment.NewLine);

            if (dte.ActiveDocument == null)
            {
                LogToOutputWindow("Make sure you have a document opened. Done nothing.");
                LogToOutputWindow(Environment.NewLine);
                return(false);
            }

            if (dte.ActiveDocument.Type != "Text")
            {
                LogToOutputWindow("Document type is not a text document. Done nothing.");
                LogToOutputWindow(Environment.NewLine);
                return(false);
            }

            Document tdToSave = dte.ActiveDocument;

            m_fullFileName = dte.ActiveDocument.FullName;  // full file name
            m_td           = (TextDocument)dte.ActiveDocument.Object("");
            TextSelection sel = m_td.Selection;

            VirtualPoint topPt = sel.TopPoint;

            m_dTopLine = topPt.Line;
            VirtualPoint bottomPt = sel.BottomPoint;

            m_dBottomLine = bottomPt.Line;
            VirtualPoint activePt = sel.ActivePoint; // restore this point;

            m_dCursorLine = activePt.Line;
            int restoredCursorLine = m_dTopLine;

            m_dRestoreCaret = sel.ActivePoint.AbsoluteCharOffset;

            m_dCurrentFileBuffer      = "";
            tmpOut.Length             = 0;
            cfErrOutputBuilder.Length = 0;

            if (!(sel.IsEmpty))
            {
                m_formatLinesOnly = true;
            }
            // no selection
            sel.EndOfDocument(false);
            sel.StartOfDocument(true);
            //sel.SelectAll();
            m_dCurrentFileBuffer = sel.Text; // load complete buffer

            createArgumentString();
            m_procStart.Arguments = m_argument;

            LogToOutputWindow("Buffer of file: " + m_fullFileName);
            LogToOutputWindow(Environment.NewLine);

            startProcessAndGetOutput();

            try
            {
                //// write stdout from clang-format to editor buffer
                writeOutputToEditorBuffer(sel, tdToSave);
            }
            catch
            {
                LogToOutputWindow("Caught exception, while trying to change buffer.");
                LogToOutputWindow(Environment.NewLine);
            }

            // restore cursor
            if (m_sCursorPosition == "Top")
            {
                restoredCursorLine = 1;
                sel.MoveToLineAndOffset(restoredCursorLine, 1, false);
            }
            else if (m_sCursorPosition == "Bottom")
            {
                restoredCursorLine = m_td.EndPoint.Line;
                sel.MoveToLineAndOffset(restoredCursorLine, 1, false);
            }
            else if (m_sCursorPosition == "SameLine")
            {
                restoredCursorLine = m_dCursorLine;
                if (m_td.EndPoint.Line < restoredCursorLine)
                {
                    restoredCursorLine = m_td.EndPoint.Line;
                }
                sel.MoveToLineAndOffset(restoredCursorLine, 1, false);
            }
            else if (m_sCursorPosition == "Restore")
            {
                try
                {
                    sel.MoveToAbsoluteOffset(m_dRestoreCaret, false);
                }
                catch
                {}
            }

            return(true);
        }
        // Collapses all regions in the current document
        public static void CollapseAllRegions(DTE dte, Language language, MainPackage package, bool showErrors = true)
        {
            if (IsSupportedLanguage(language))
            {
                dte.SuppressUI = true;                 // Disable UI while we do this
                try
                {
                    // Outling must be enabled.  If Outlining is turned off then the rest of this method will get stuck in an infinite loop.
                    // It can be turned off by default from the C# advanced text editor properties, or it can be turned off by running
                    // the Edit.StopOutlining command (e.g., in the Command window or via Edit -> Outlining -> Stop Outlining).
                    // If the Edit.StartAutomaticOutlining command is available, then that means outlining needs to be turned back on.
                    const string   StartOutliningCommand = "Edit.StartAutomaticOutlining";
                    EnvDTE.Command command = dte.Commands.Item(StartOutliningCommand);
                    if (command.IsAvailable)
                    {
                        dte.ExecuteCommand(StartOutliningCommand);
                    }

                    const string ToggleOutliningExpansion = "Edit.ToggleOutliningExpansion";
                    command = dte.Commands.Item(ToggleOutliningExpansion);
                    const int MaxAttempts = 3;
                    int       maxAttempts = command.IsAvailable ? MaxAttempts : 0;

                    string regionBeginRegex = GetRegionBeginRegex(language);

                    // Sometimes VS can't collapse some regions, so we'll try the whole operation a few times if necessary.
                    bool failedToCollapse = true;
                    for (int attempt = 1; attempt <= maxAttempts && failedToCollapse; attempt++)
                    {
                        failedToCollapse = false;
                        ExpandAllRegions(dte, language);                                       // Force the expansion of all regions

                        TextSelection selection = (TextSelection)dte.ActiveDocument.Selection; // Hook up to the ActiveDocument's selection
                        selection.EndOfDocument();                                             // Shoot to the end of the document

                        // Find the first occurence of #region from the end of the document to the start of the document.
                        int       currentFindOffset  = 0;
                        int       previousFindOffset = int.MaxValue;
                        const int FindOptions        = (int)vsFindOptions.vsFindOptionsBackwards +
                                                       (int)vsFindOptions.vsFindOptionsMatchCase +
                                                       (int)vsFindOptions.vsFindOptionsRegularExpression;
                        while (selection.FindText(regionBeginRegex, FindOptions))
                        {
                            currentFindOffset = selection.TopPoint.AbsoluteCharOffset;
                            if (currentFindOffset >= previousFindOffset)
                            {
                                // I don't want to get stuck in an infinite loop.  I'd rather throw if something unexpected happens.
                                throw new InvalidOperationException(string.Format(
                                                                        "FindText did not go backward!  Previous offset: {0}; Current offset: {1}.",
                                                                        previousFindOffset,
                                                                        currentFindOffset));
                            }

                            // We can ignore matches where #region is used inside a string or single line comment.
                            // However, this still won't detect if it's used inside a multiline comment with the opening
                            // delimiter on another line.
                            selection.SelectLine();
                            string lineText = selection.Text ?? string.Empty;

                            // Make sure the region begin token is the first non-whitespace on the line.
                            Match match = Regex.Match(lineText.TrimStart(), regionBeginRegex);
                            if (match.Success && match.Index == 0)
                            {
                                // The SelectLine call above will leave the end anchor on the next line.  If there's no blank line between
                                // a #region line and an XML doc comment after it, then having the end anchor on the line with the
                                // XML doc comment will cause the comment to collapse instead of the #region.  So we'll avoid that
                                // by moving back to the find offset.
                                selection.MoveToAbsoluteOffset(currentFindOffset);

                                // Try to increase the chances that the ToggleOutliningExpansion command will be available.
                                selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText);

                                // Collapse this #region.  Sometimes VS reports that the Edit.ToggleOutliningExpansion command
                                // isn't available even though it should be.  Poke it and give it a little bit of time to sync up.
                                if (!command.IsAvailable)
                                {
                                    const int WaitMilliseconds = 20;
                                    System.Threading.Thread.Sleep(WaitMilliseconds);
                                    int tempOffset = selection.TopPoint.AbsoluteCharOffset;
                                    selection.CharRight();
                                    selection.MoveToAbsoluteOffset(tempOffset);
                                    System.Threading.Thread.Sleep(WaitMilliseconds);
                                }

                                if (command.IsAvailable)
                                {
                                    // If #region is found in a multiline comment, then this will collapse the enclosing block.
                                    dte.ExecuteCommand(ToggleOutliningExpansion);
                                }
                                else
                                {
                                    // We couldn't collapse a #region.
                                    failedToCollapse = true;
                                }
                            }

                            // Move to the start of the last FindText match, so we can continue searching backward from there.
                            selection.MoveToAbsoluteOffset(currentFindOffset);
                            previousFindOffset = currentFindOffset;
                        }

                        selection.StartOfDocument();                         // All done, head back to the start of the doc
                    }

                    if (failedToCollapse && package != null && showErrors)
                    {
                        package.ShowMessageBox(
                            "Some regions couldn't be collapsed because Visual Studio's Edit.ToggleOutliningExpansion command wasn't available.",
                            true);
                    }
                }
                finally
                {
                    dte.SuppressUI = false;                     // Reenable the UI
                }
            }
        }