// Expands all regions in the current document
        public static void ExpandAllRegions(DTE dte, Language language)
        {
            if (IsSupportedLanguage(language))
            {
                bool suppressedUI = false;
                if (!dte.SuppressUI)
                {
                    dte.SuppressUI = true;                     // Disable UI while we do this
                    suppressedUI   = true;
                }

                try
                {
                    if (language == Language.Python)
                    {
                        // The Python Tools language provider outlines a #region as "#region Test[...]".
                        // Using FindText(...) to force a region expansion won't work for Python because
                        // the "#region" part is still in the visible, non-hidden, non-collapsed text.
                        // So we'll use the ExpandAllOutlining command instead.  It will also expand
                        // non-region collapses (e.g., if someone has collapsed a function definition),
                        // so it's not really just an "ExpandAllRegions" command like we want.  :-(
                        // Note: This command is only available if outlining is enabled and something
                        // in the document is collapsed.
                        const string   ExpandAllCommand = "Edit.ExpandAllOutlining";
                        EnvDTE.Command command          = dte.Commands.Item(ExpandAllCommand, 0);
                        if (command.IsAvailable)
                        {
                            dte.ExecuteCommand(ExpandAllCommand);
                        }
                    }
                    else
                    {
                        TextSelection selection = (TextSelection)dte.ActiveDocument.Selection; // Hook up to the ActiveDocument's selection
                        selection.StartOfDocument();                                           // Shoot to the start of the document

                        string regionBeginRegex = GetRegionBeginRegex(language);

                        // Loop through the document finding all instances of #region. This action has the side benefit
                        // of actually zooming us to the text in question when it is found and ALSO expanding it since it
                        // is an outline.
                        const int FindOptions = (int)vsFindOptions.vsFindOptionsMatchInHiddenText +
                                                (int)vsFindOptions.vsFindOptionsMatchCase +
                                                (int)vsFindOptions.vsFindOptionsRegularExpression;
                        while (selection.FindText(regionBeginRegex, FindOptions))
                        {
                            // The FindText command will expand the #region block if "#region" is hidden.
                        }

                        selection.StartOfDocument();                         // Shoot us back to the start of the document
                    }
                }
                finally
                {
                    if (suppressedUI)
                    {
                        dte.SuppressUI = false;                         // Reenable the UI
                    }
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Insert header in document
        /// </summary>
        /// <param name="template">Template to be added</param>
        /// <param name="textSelection">Text selection of document</param>
        private void InsertHeader(string template, TextSelection textSelection)
        {
            // Add header
            textSelection.StartOfDocument();
            textSelection.NewLine();
            textSelection.StartOfDocument();

            textSelection.Text = template;
            textSelection.NewLine();
            textSelection.NewLine();
            RemoveSpecialCharacters(textSelection, template);
        }
        /// <summary>
        /// Saves the file menu item click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="MenuItemEventArgs" /> instance containing the event data.</param>
        protected virtual void SaveFileMenuItemClick(object sender, MenuItemEventArgs e)
        {
            IExplorerNode parentNode   = e.Owner as IExplorerNode;
            var           fileNodeInfo = parentNode.Annotations.GetValue <FileNodeInfo>();

            DTEManager.SetStatus(CKSProperties.FileUtilities_SavingFile);

            Document      file      = DTEManager.DTE.ActiveDocument;
            TextSelection selection = file.Selection as TextSelection;

            selection.SelectAll();
            fileNodeInfo.Contents = selection.Text;
            selection.StartOfDocument();

            bool result = parentNode.Context.SharePointConnection.ExecuteCommand <FileNodeInfo, bool>(FileSharePointCommandIds.SaveFileCommand, fileNodeInfo);

            if (result)
            {
                DTEManager.SetStatus(CKSProperties.FileUtilities_FileSuccessfullySaved);
            }
            else
            {
                MessageBox.Show(CKSProperties.FileUtilities_FileSaveError, CKSProperties.FileUtilities_FileSaveErrorMessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 4
0
        public static string GetOutputText()
        {
            var dte = GetDTE();

            if (dte == null)
            {
                return("");
            }


            OutputWindowPane buildOutputPane = null;

            foreach (OutputWindowPane pane in dte.ToolWindows.OutputWindow.OutputWindowPanes)
            {
                if (pane.Guid == VSConstants.OutputWindowPaneGuid.BuildOutputPane_string)
                {
                    buildOutputPane = pane;
                    break;
                }
            }
            if (buildOutputPane == null)
            {
                Output.Instance.ErrorMsg("Failed to query for build output pane!");
                return(null);
            }
            TextSelection sel = buildOutputPane.TextDocument.Selection;

            sel.StartOfDocument(false);
            sel.EndOfDocument(true);

            return(sel.Text);
        }
Esempio n. 5
0
        /// <summary>
        /// This returns the text contained in the given output window pane.
        /// </summary>
        /// <param name="pane">Pane to get text from.</param>
        /// <returns>Text in the window.</returns>
        public static string GetPaneText(OutputWindowPane pane)
        {
            TextSelection selection = pane.TextDocument.Selection;

            selection.StartOfDocument(false);
            selection.EndOfDocument(true);
            return(selection.Text);
        }
Esempio n. 6
0
        public static void CreateNewFile(string fileType, string title, string fileContents)
        {
            Document      document      = DteService.DTE.ItemOperations.NewFile(fileType, title, "{00000000-0000-0000-0000-000000000000}").Document;
            TextSelection textSelection = document.Selection as TextSelection;

            textSelection.SelectAll();
            textSelection.Text = "";
            textSelection.Insert(fileContents, 1);
            textSelection.StartOfDocument(false);
        }
Esempio n. 7
0
        /// <summary>
        /// Runs custom wizard logic when the wizard has completed all tasks.
        /// </summary>
        public void RunFinished()
        {
            try
            {
                // The interface implmentation inserted in the ProjectFinishedGenerating event has its Region twistie open
                // This code is to close the interface implmentation twistie so that the region appears like the common methods and support code twisties

                TL.Enabled = true;
                TL.LogMessage("RunFinished", "Start");

                Diagnostics.Enter();
                if (myProjectItem != null) // We do have a project item to work on
                {
                    myProjectItem.Open();  // Open the item for editing
                    TL.LogMessage("RunFinished", "Done Open");

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

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

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

                    documentSelection.StartOfDocument(); // GO to the top of the document
                    TL.LogMessage("RunFinished", "Done StartOfDocument Region");

                    string pattern = "[Rr]egion \"*I" + DeviceClass;                                            // Cerate a regular expression string that works for region in both VB and C#
                    TL.LogMessage("", "RegEx search pattern: " + pattern);
                    if (documentSelection.FindText(pattern, (int)vsFindOptions.vsFindOptionsRegularExpression)) // Search for the interface implemnetation start of region
                    {
                        // Found the interface implementation region so toggle its twistie closed
                        documentSelection.SelectLine();
                        TL.LogMessage("RunFinished", "Found region I" + DeviceClass + " - " + documentSelection.Text); // Log the line actuall found
                        myDTE.ExecuteCommand("Edit.ToggleOutliningExpansion");                                         // Toggle the twistie closed
                        TL.LogMessage("RunFinished", "Done ToggleOutliningExpansion Region");
                    }

                    itemDocument.Close(vsSaveChanges.vsSaveChangesYes); // SAve changes and close the file
                    TL.LogMessage("RunFinished", "Done Save");
                }
                else // No project item so just report this (happens when a test project is being created)
                {
                    TL.LogMessage("RunFinished", "Project item is null, no action taken");
                }
                TL.LogMessage("RunFinished", "End");
                Diagnostics.Exit();
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf(" RunFinished Exception", ex.ToString());                                             // Log any error message
                MessageBox.Show(ex.ToString(), "RunFinished Wizard Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // Show an error message
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Adds the header comment.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="headerComment">The header comment.</param>
        public static void AddHeaderComment(
            this ProjectItem instance,
            string headerComment)
        {
            TextSelection selection = (TextSelection)instance.Document.Selection;

            selection.StartOfDocument();
            selection.NewLine();
            selection.LineUp();
            selection.Text = headerComment;
        }
Esempio n. 9
0
        /// <summary>
        /// Creates the new file.
        /// </summary>
        /// <param name="fileType">Type of the file.</param>
        /// <param name="title">The title.</param>
        /// <param name="fileContents">The file contents.</param>
        public static void CreateNewFile(
            string fileType, string title, string fileContents)
        {
            Document      file      = DTE.ItemOperations.NewFile(fileType, title).Document;
            TextSelection selection = file.Selection as TextSelection;

            selection.SelectAll();
            selection.Text = "";
            selection.Insert(fileContents);
            selection.StartOfDocument();
        }
Esempio n. 10
0
 /// <summary>
 /// Removes special characters after inserting header
 /// </summary>
 /// <param name="textSelection">Text selection</param>
 /// <param name="template">Template</param>
 private void RemoveSpecialCharacters(TextSelection textSelection, string template)
 {
     // Remove special characters from beginning of each line in template
     textSelection.StartOfDocument();
     for (int i = 0; i < template.Split('\n').Length; i++)
     {
         textSelection.StartOfLine();
         textSelection.CharRight(true, SpecialCharacters.Length);
         textSelection.Delete();
         textSelection.LineDown();
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Extract document information. Such as namespace, class or interface.
        /// </summary>
        /// <param name="textSelection">TextSelection object of a document</param>
        /// <returns>Basic Information object</returns>
        private DocumentInformation ExtractDocumentInformation(TextSelection textSelection)
        {
            textSelection.StartOfDocument();

            string @namespace = string.Empty;
            string @class     = string.Empty;
            string @interface = string.Empty;

            int previousLine = -1;

            while (previousLine != textSelection.CurrentLine)
            {
                if (textSelection.Text.Contains("//"))
                {
                    previousLine = textSelection.CurrentLine;
                    textSelection.SelectLine();
                    continue;
                }

                string[] split = textSelection.Text.Split(' ');

                if (@namespace == string.Empty)
                {
                    @namespace = FindName(split, "namespace");
                }

                if (@class == string.Empty)
                {
                    @class = FindName(split, "class");
                }

                if (@interface == string.Empty)
                {
                    @interface = FindName(split, "interface");
                }

                if (@namespace != string.Empty && (@class != string.Empty || @interface != string.Empty))
                {
                    break;
                }

                previousLine = textSelection.CurrentLine;
                textSelection.SelectLine();
            }

            return(new DocumentInformation
            {
                Namespace = @namespace,
                Class = @class,
                Interface = @interface
            });
        }
        /// <summary>
        /// Adds the header comment.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="headerComment">The header comment.</param>
        public static void AddHeaderComment(
            this ProjectItem instance,
            string headerComment)
        {
            TraceService.WriteLine("ProjectItemExtensions::AddHeaderComment");

            TextSelection selection = (TextSelection)instance.Document.Selection;

            selection.StartOfDocument();
            selection.NewLine();
            selection.LineUp();
            selection.Text = headerComment;
        }
Esempio n. 13
0
    public Bookmark GotoBookmark(int number) {
      var bookmark = _Bookmarks[number];
      if(bookmark == null)
        return null;

      var row = _Bookmarks[number].GetRow(_Buffer);
      TextSelection selection = _DTE2.ActiveDocument.Selection;
      int column = selection.ActivePoint.DisplayColumn;
      selection.StartOfDocument();
      selection.MoveToLineAndOffset(row, column);
                                            
      return _Bookmarks[number];
    }
Esempio n. 14
0
        public static string GetAllTextFromPane(EnvDTE.OutputWindowPane Pane)
        {
            if (Pane == null)
            {
                return(null);
            }

            TextDocument  doc = Pane.TextDocument;
            TextSelection sel = doc.Selection;

            sel.StartOfDocument(false);
            sel.EndOfDocument(true);

            string content = sel.Text;

            return(content);
        }
        public static void Execute(ProjectItem projectItem)
        {
            TextSelection txtSel = (TextSelection)projectItem.Document.Selection;

            usingSystemFound = false;
            txtSel.StartOfDocument();
            if (txtSel.FindText("using System;"))
            {
                usingSystemFound = true;
            }

            foreach (var codeElement in projectItem.FileCodeModel.CodeElements)
            {
                if ((codeElement as CodeElement) != null)
                {
                    AddCommentsTo(codeElement as CodeElement);
                }
            }
        }
Esempio n. 16
0
        protected void SelectObjectMethod(CodeFunction cf)
        {
            ProjectItem p = cf.ProjectItem;

            //  Open the file as a source code file
            EnvDTE.Window theWindow = p.Open(Constants.vsViewKindCode);

            //Get a handle to the new document in the open window
            TextDocument objTextDoc   = (TextDocument)theWindow.Document.Object("TextDocument");
            EditPoint    objEditPoint = (EditPoint)objTextDoc.StartPoint.CreateEditPoint();

            theWindow.Visible = true;

            TextSelection ts = (TextSelection)theWindow.Selection;

            ts.StartOfDocument(false);
            objEditPoint.MoveToLineAndOffset(cf.StartPoint.Line, 1);
            ts.MoveToPoint(objEditPoint, false);
        }
Esempio n. 17
0
        public static void navigate(KnowledgeController controller, Object tag, String sourceFile)
        {
            try
            {
                log.Debug(" navigation ... ");

                string regExpression = getRegExpr(tag);
                if (regExpression == null)
                {
                    return;
                }
                string actualString = getActualString(sourceFile, regExpression);
                if (actualString == null)
                {
                    return;
                }

                Window        textEditor    = controller.environment.ApplicationObject.OpenFile(Constants.vsViewKindCode, sourceFile);
                TextSelection textSelection = (TextSelection)textEditor.Document.Selection;
                textSelection.StartOfDocument(false);
                textSelection.EndOfDocument(false);

                // TODO: textSelection.findPattern doesn't work for some reason
                if (textSelection.FindText(actualString, (int)vsFindOptions.vsFindOptionsFromStart))
                {
                    textSelection.SelectLine();
                }
                else
                {
                    log.Debug("log. actualString is not found in text file, actualString=" + actualString);
                }

                textEditor.Visible = true;
                textEditor.Activate();
                // TODO: save of the document
            }
            catch (Exception e0)
            {
                MessageBox.Show(e0.Message);
            }
        }
Esempio n. 18
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] };
        }
        /// <summary>
        /// takes a project item file contents and re-saves through IDE editor window, hopefully this triggers
        /// other extensions like bundlers, minifiers, linters etc to update themselves
        /// </summary>
        /// <param name="outputFile"></param>
        public static void SaveOutputFileThroughEditorWindow(string outputFile)
        {
            string jsSource = System.IO.File.ReadAllText(outputFile);
            var    dte      = TsWspPackage.DTE;
            var    item     = dte.Solution.FindProjectItem(outputFile);

            if (item != null)
            {
                // open it
                var w = item.Open(EnvDTE.Constants.vsViewKindCode);
                if (w != null)
                {
                    TextSelection ts = w.Document.Selection as TextSelection;
                    if (ts != null)
                    {
                        // replace all text with new source
                        ts.SelectAll();
                        ts.Insert(jsSource);
                        item.Save();
                        // move to top
                        ts.StartOfDocument();
                    }
                    else
                    {
                        Logger.Log("Could not update text in " + outputFile);
                    }
                }
                else
                {
                    Logger.Log("Could not open code window for " + outputFile);
                }
            }
            else
            {
                Logger.Log("Could not locate project item = " + outputFile);
            }
        }
Esempio n. 20
0
        private void postCompileCpp(string generatedFile, int mode, string functionOfInterest, string curCodeLine)
        {
            if (!File.Exists(generatedFile))
            {
                package.showMsgBox("Could not find expected output file\n" + generatedFile);
                return;
            }

            // clean the preprocessed output
            // TODO: do this in a better way
            if (mode == 2)
            {
                var input = new StreamReader(generatedFile);
                generatedFile = Path.GetTempFileName() + ".cpp";
                var output = new StreamWriter(generatedFile);

                while (input.Peek() >= 0)
                {
                    string curReadLine = input.ReadLine();
                    if (curReadLine != "")
                    {
                        output.WriteLine(curReadLine);
                    }
                }
                input.Close();
                output.Close();
            }

            // TODO: there are a thousand ways to open a file
            //			dte.Documents.Open(asmFile, EnvDTE.Constants.vsViewKindCode);
            //			dte.ExecuteCommand("File.OpenFile", asmFile);
            Window       tmp           = dte.ItemOperations.OpenFile(generatedFile, Constants.vsViewKindCode);
            TextDocument genFileWindow = (TextDocument)tmp.Document.Object("TextDocument");

            // crashes VS
            //			bool ddd = genFileWindow.ReplacePattern("^$\n", "", (int)vsFindOptions.vsFindOptionsRegularExpression);
            // http://stackoverflow.com/questions/12453160/remove-empty-lines-in-text-using-visual-studio
            // ^:b*$\n -> ^(?([^\r\n])\s)*\r?$\r?\n

            // now try to find the function the user was looking at

            // if it's a template the fullName will be like ns::bar<T>
            // try to find an instantiation instead then
            int bracketPos = functionOfInterest.IndexOf("<", StringComparison.Ordinal);

            if (bracketPos > 0)
            {
                functionOfInterest = functionOfInterest.Substring(0, bracketPos + 1);
            }

            TextSelection textSelObj = genFileWindow.Selection;

            // first try to find the function
            // TODO: for some reason vsFindOptions.vsFindOptionsFromStart option doesn't work
            textSelObj.StartOfDocument();
            bool res = textSelObj.FindText("PROC ; " + functionOfInterest, (int)vsFindOptions.vsFindOptionsMatchCase);

            if (!res && mode == 1)
            {
                dte.StatusBar.Text = "Couldn't find function '" + functionOfInterest + "'";
                dte.StatusBar.Highlight(true);
            }

            // then search for the code line
            // it might not be there if it's optimized away
            if (!string.IsNullOrWhiteSpace(curCodeLine))
            {
                textSelObj.FindText(curCodeLine.Trim(), (int)vsFindOptions.vsFindOptionsMatchCase);
            }

            textSelObj.StartOfLine();
        }
Esempio n. 21
0
        private void CreateFlowerPot(UserData userData)
        {
            DTE2 applicationObject = (DTE2)ServiceProvider.GlobalProvider.GetService(typeof(DTE));

            try
            {
                TextDocument textDoc   = (TextDocument)applicationObject.ActiveDocument.Object("TextDocument");
                EditPoint    editPoint = (EditPoint)textDoc.StartPoint.CreateEditPoint();

                string fileName = applicationObject.ItemOperations.DTE.ActiveDocument.Name;
                string version  = "1.0";

                TextSelection selection = textDoc.Selection;
                selection.SelectAll();
                string text = selection.Text;
                selection.StartOfDocument(false);

                string entity     = "Code file";
                string entityName = "";

                string[] lines = text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string line in lines)
                {
                    if (line.Contains("class "))
                    {
                        entity = "Class";
                        Regex rxClass = new Regex("^.*class (?'Class'\\w*)");
                        entityName = rxClass.Match(line).Groups["Class"].Value;
                        break;
                    }
                    else if (line.Contains("interface "))
                    {
                        entity = "Interface";
                        Regex rxInterface = new Regex("^.*interface (?'Interface'\\w*)");
                        entityName = rxInterface.Match(line).Groups["Interface"].Value;
                        break;
                    }
                    else if (line.Contains("enum "))
                    {
                        entity = "Enum";
                        Regex rxEnum = new Regex("^.*enum (?'Enum'\\w*)");
                        entityName = rxEnum.Match(line).Groups["Enum"].Value;
                        break;
                    }
                    else if (line.Contains("delegate "))
                    {
                        entity = "Delegate";
                        Regex rxDelegate = new Regex("^.*delegate (?'Delegate'\\w*)");
                        entityName = rxDelegate.Match(line).Groups["Delegate"].Value;
                        break;
                    }
                }

                string[] fileHeader = new string[8];
                fileHeader[0] = $"/{new string('*', userData.HeaderWidth - 1)}";
                fileHeader[1] = $"* File:         {fileName}";
                fileHeader[2] = $"* Contents:     {entity} {entityName}";
                fileHeader[3] = $"* Author:       {userData.AuthorName} ({userData.AuthorEmail})";
                fileHeader[4] = $"* Date:         {DateTime.Now.ToString("yyyy-MM-dd HH:mm")}";
                fileHeader[5] = $"* Version:      {version}";
                fileHeader[6] = $"* Copyright:    {userData.CompanyName} ({userData.CompanyWebsite})";
                fileHeader[7] = $"{new string('*', userData.HeaderWidth - 1)}/";

                for (int i = 1; i <= 6; i++)
                {
                    fileHeader[i] += new string(' ', userData.HeaderWidth - 1 - fileHeader[i].Length) + "*";
                }

                string strResult = string.Join("\n", fileHeader) + "\n";

                editPoint.Insert(strResult);
            }
            catch   {}
        }
Esempio n. 22
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);
        }
        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);
        }
Esempio n. 24
0
        private void EnterTextToActiveDocument(string text)
        {
            if (Statics.DTE.ActiveDocument == null)
            {
                MessageBox.Show("No active document is visible to write the generated code in, copying to clipboard instead (press ctrl-v on the document you want to place the code into)", "No Active Document", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Clipboard.Clear();
                if (!string.IsNullOrEmpty(text))
                {
                    Clipboard.SetText(text);
                }
                return;
            }
            TextSelection sel   = (TextSelection)Statics.DTE.ActiveDocument.Selection;
            TextRanges    dummy = null;

            if (Statics.Language == ProjectLanguage.CSharp)
            {
                bool isRegionExists = false;

                sel.StartOfDocument(true);
                if (sel.FindPattern("#region Temporary Recording", (int)vsFindOptions.vsFindOptionsMatchInHiddenText, ref dummy))
                {
                    isRegionExists = true;
                }

                sel.EndOfDocument(true);

                sel.FindPattern("}", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsMatchInHiddenText), ref dummy);
                sel.FindPattern("}", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsMatchInHiddenText), ref dummy);
                if (isRegionExists)
                {
                    sel.FindPattern("#endregion", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsMatchInHiddenText), ref dummy);
                }
                sel.LineUp(true, 1);
                if (!isRegionExists)
                {
                    sel.Insert("\t\t#region Temporary Recording Code\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                }
                sel.Insert("\t\tprivate void " + GetAvailableMethodName() + "()\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert("\t\t{\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert(text, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert("\r\n\t\t}\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                if (!isRegionExists)
                {
                    sel.Insert("\t\t#endregion\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                    sel.Insert("\t}\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                }
            }
            else if (Statics.Language == ProjectLanguage.VB)
            {
                sel.EndOfDocument(true);

                sel.FindPattern("End Class", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsMatchInHiddenText), ref dummy);
                //sel.LineUp(true, 1);
                sel.Insert("\tPrivate Sub " + GetAvailableMethodName() + "()\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert(text, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert("\tEnd Sub\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert("End Class\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
            }


            //sel.SelectAll();
            Statics.DTE.ActiveDocument.Activate();
            System.Threading.Thread.Sleep(200);
            Statics.DTE.ExecuteCommand("Edit.FormatDocument", string.Empty);
        }
Esempio n. 25
0
        public static void ApplyPrefeence(DTE2 dte, string region, string controller, string field, string property, string preferredValue)
        {
            //string preferredValue = GetMostPreferredValue(region, controller, field, property);
            List <PreviousPropertyValue> listDefault = new List <PreviousPropertyValue>();

            foreach (ProjectItem pi in dte.Solution.Projects.Item(1).ProjectItems)
            {
                if (pi.ProjectItems != null)
                {
                    foreach (ProjectItem p in pi.ProjectItems)
                    {
                        if (p.Name.EndsWith(".Designer.cs"))
                        {
                            p.Open(EnvDTE.Constants.vsViewKindCode);
                            p.Document.Activate();
                            TextSelection     ts           = (TextSelection)dte.ActiveDocument.Selection;
                            TextSelection     ts2          = (TextSelection)dte.ActiveDocument.Selection;
                            string            srchPattern1 = "new System.Windows.Forms.Button();";
                            EnvDTE.TextRanges textRanges   = null;

                            ts.StartOfDocument(false);

                            int count = 0;

                            string   nameLine = "";
                            string   name     = "";
                            string[] np       = new string[50];

                            while (ts.FindPattern(srchPattern1, 0, ref textRanges))
                            {
                                ts.SelectLine();
                                nameLine = ts.Text;
                                count++;
                                string[] sp  = nameLine.Split('.');
                                string   spi = sp[1];
                                string[] sp2 = spi.Split('=');
                                name      = sp2[0];
                                np[count] = name;
                            }

                            int i = 1;
                            while (ts2.FindPattern(".BackColor = System.Drawing.Color", 0, ref textRanges))
                            {
                                PreviousPropertyValue def = new PreviousPropertyValue();

                                ts2.SelectLine();
                                string codeLine = ts2.Text;
                                codeLine = codeLine.Trim();
                                foreach (string s in np)
                                {
                                    string ss = s;
                                    if (ss != null)
                                    {
                                        ss = ss.Trim();
                                        if (codeLine.Contains(ss) == true)
                                        {
                                            ts2.ReplacePattern(codeLine, "this." + s + ".BackColor = System.Drawing.Color." + preferredValue + ";", 0, ref textRanges);
                                            np                 = np.Where(w => w != s).ToArray();
                                            def.FileName       = p.Name;
                                            def.ControllerType = controller;
                                            def.Property       = property;
                                            def.ControllerName = ss;
                                            def.DefaultValue   = codeLine;
                                            listDefault.Add(def);
                                        }
                                        //else
                                        //{
                                        //    ts2.LineDown();
                                        //    ts2.NewLine();
                                        //    ts2.Insert("this." + np[i] + ".BackColor = System.Drawing.Color." + preferredValue + ";");
                                        //}
                                        //def.FileName = p.Name;
                                        //def.ControllerType = controller;
                                        //def.Property = property;
                                        //def.ControllerName = ss;
                                        //def.DefaultValue = codeLine;
                                        //listDefault.Add(def);
                                    }
                                }

                                //i++;
                            }
                            if (np != null)
                            {
                                foreach (string s in np)
                                {
                                    if (s != null)
                                    {
                                        ts2.EndOfLine();

                                        ts2.NewLine();
                                        ts2.Insert("this." + np[i] + ".BackColor = System.Drawing.Color." + preferredValue + ";");
                                        np = np.Where(w => w != s).ToArray();
                                    }
                                }
                            }
                            SaveDefaultValues(listDefault);
                            dte.ActiveDocument.Save(p.Document.FullName);
                            dte.ActiveDocument.Close(vsSaveChanges.vsSaveChangesNo);
                        }
                    }
                }
            }
        }
Esempio n. 26
0
        public void ListWindows()
        {
            OutputWindow outWindow = _dte.ToolWindows.OutputWindow;

            outWindow.Parent.AutoHides = false;
            outWindow.Parent.Activate();

            //string test = window.ActivePane.Name;

            OutputWindowPane buildPane = null;

            try
            {
                buildPane = outWindow.OutputWindowPanes.Item("Build");
            }
            catch
            {
                buildPane = outWindow.OutputWindowPanes.Add("Build");
            }
            finally
            {
                //buildPane.Clear();
            }



            for (int i = count; i < count + 20; ++i)
            {
                buildPane.OutputString("Line " + i + "\n");
            }


            buildPane.Activate();

            try
            {
                if (buildPane.TextDocument != null)
                {
                    TextDocument  doc = buildPane.TextDocument;
                    TextSelection sel = doc.Selection;

                    sel.StartOfDocument(false);
                    sel.EndOfDocument(true);

                    count += 20;


                    sel.GotoLine(count - 5);


                    try
                    {
                        sel.ActivePoint.TryToShow(vsPaneShowHow.vsPaneShowCentered, null);
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine("Exception! " + ex.ToString());
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Exception! " + ex.ToString());
            }
        }
Esempio n. 27
0
        public void ThenTheProjectShouldBuildAndItsTestsRunSuccessfully()
        {
            Trace.WriteLine("Building solution");

            AutoResetEvent autoResetEvent = new AutoResetEvent(false);

            bool buildSucceeded = false;

            this.dte.Events.BuildEvents.OnBuildProjConfigDone += (project, projectConfig, platform, solutionConfig, success) =>
            {
                Trace.WriteLine(
                    string.Format(
                        "Project {0} Project Configuration {1} Platform {2} Solution Configuration {3} Success {4}",
                        project,
                        projectConfig,
                        platform,
                        solutionConfig,
                        success));

                buildSucceeded = success;

                autoResetEvent.Set();
            };

            this.dte.ExecuteCommand("Build.RebuildSolution");

            autoResetEvent.WaitOne();

            Trace.WriteLine("Done building solution");

            if (!buildSucceeded)
            {
                const string buildOutputPaneGuid = "{1BD8A850-02D1-11D1-BEE7-00A0C913D1F8}";

                Window vsWindow = this.dte.Windows.Item(Constants.vsWindowKindOutput);

                OutputWindowPane objBuildOutputWindowPane = null;

                OutputWindow vsOutputWindow = (OutputWindow)vsWindow.Object;

                foreach (OutputWindowPane objOutputWindowPane in vsOutputWindow.OutputWindowPanes)
                {
                    if (objOutputWindowPane.Guid.ToUpper() == buildOutputPaneGuid)
                    {
                        objBuildOutputWindowPane = objOutputWindowPane;
                    }
                }

                Assert.IsNotNull(objBuildOutputWindowPane);

                TextDocument  txtOutput    = objBuildOutputWindowPane.TextDocument;
                TextSelection txtSelection = txtOutput.Selection;

                txtSelection.StartOfDocument();
                txtSelection.EndOfDocument(true);

                txtSelection = txtOutput.Selection;

                Assert.IsTrue(buildSucceeded, txtSelection.Text);
            }

            this.RunAllTests();
        }
        // 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
                }
            }
        }
Esempio n. 29
0
        public static bool ChangeToPreveiousValue(DTE2 dte, string controller, string property)
        {
            List <PreviousPropertyValue> listDefault = new List <PreviousPropertyValue>();
            List <PreviousPropertyValue> list        = LoadDefaultValues();

            if (list == null)
            {
                return(false);
            }
            else
            {
                foreach (ProjectItem pi in
                         dte.Solution.Projects.Item(1).ProjectItems)
                {
                    if (pi.ProjectItems != null)
                    {
                        foreach (ProjectItem p in pi.ProjectItems)
                        {
                            if (p.Name.EndsWith(".Designer.cs"))
                            {
                                p.Open(EnvDTE.Constants.vsViewKindCode);
                                p.Document.Activate();
                                TextSelection ts2 = (TextSelection)dte.ActiveDocument.Selection;

                                EnvDTE.TextRanges textRanges = null;

                                ts2.StartOfDocument(false);
                                //Find2 findWin = (Find2)dte.Find;
                                int count = 0;
                                //c = findWin.FindReplace(vsFindAction.vsFindActionFindAll, "button1", 0);
                                string   s    = "";
                                string   name = "";
                                string[] np   = new string[50];
                                // Advance to the next Visual Basic function beginning or end by
                                // searching for  "Sub" with white space before and after it.
                                //while
                                //while (ts.FindPattern(srchPattern1, 0, ref textRanges))
                                //{

                                //    //    //  Select the entire line.

                                //    count++;
                                //    ts.SelectLine();
                                //    s = ts.Text;

                                //    string[] sp = s.Split('.');
                                //    string spi = sp[1];


                                //    string[] sp2 = spi.Split('=');
                                //    name = sp2[0];

                                //    np[count] = name;
                                //    //ts.FindPattern("this." + name + ".BackColor = System.Drawing.Color", 0, ref textRanges);
                                //    //ts.SelectLine();
                                //    //s = ts.Text;
                                //    //ts2.StartOfDocument(false);
                                //    //while (ts.FindText("this." + name + ".BackColor = System.Drawing.Color", 0))
                                //    //{

                                //    //    ts.SelectLine();
                                //    //    string sd = ts.Text;
                                //    //    bool t = ts.ReplacePattern(sd, "this.button1.BackColor = System.Drawing.Color.Red;", 0, ref textRanges);
                                //    //}

                                //}

                                int i = 1;
                                //for(int i=1; i<=5;i++)
                                //{
                                //ts2 = null;


                                while (ts2.FindPattern(".BackColor = System.Drawing.Color", 0, ref textRanges))
                                {
                                    ts2.SelectLine();
                                    string sd = ts2.Text;
                                    sd = sd.Trim();
                                    foreach (PreviousPropertyValue dfcon in list)
                                    {
                                        if (dfcon.FileName == p.Name && sd.Contains(dfcon.ControllerName) && dfcon.Property == property && dfcon.ControllerType == controller)
                                        {
                                            ts2.ReplacePattern(sd, dfcon.DefaultValue, 0, ref textRanges);
                                        }
                                        i++;
                                        //}
                                    }
                                }
                                //ts.NewLine(1);


                                dte.ActiveDocument.Save(p.Document.FullName);
                                dte.ActiveDocument.Close(vsSaveChanges.vsSaveChangesNo);
                            }
                        }
                    }
                }
                return(true);
            }
        }