Beispiel #1
0
        private void Inspect(MyTreeViewItem item)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (CheckNotInBreakMode())
            {
                return;
            }

            inspectorWindow.control.ParentPanel.Children.Clear();
            VsUnityInspectorCommand.Instance.curInspectedObjects.Clear();

            int[]  index   = item.GetIndexOfItem();
            string tfQuery = GetTransformQuery(index);

            if (!isInitInspectObj)
            {
                dte.Debugger.ExecuteStatement(Statement: "UnityEngine.GameObject inspectObj;");
                isInitInspectObj = true;
            }

            EnvDTE.TextSelection selection = commandWindow?.Selection as EnvDTE.TextSelection;
            string gameObjectInfo          = GetDebuggerExecutionOutput(Statement: $"inspectObj = objs{tfQuery}.gameObject;", TreatAsExpression: true, selection);

            VsGameObject obj = new VsGameObject(gameObjectInfo);

            obj.Inspect(inspectorWindow);

            VsUnityInspectorCommand.Instance.curInspectedObjects.Add(obj);
        }
        private void IssueTrackingWebCallback(object sender, EventArgs e)
        {
            EnvDTE.TextSelection ts = _dte.ActiveWindow.Selection as EnvDTE.TextSelection;

            if (String.IsNullOrEmpty(TechnologicatorDefines.IssueTrackingWebURL) ||
                String.IsNullOrEmpty(TechnologicatorDefines.ConfigFile) ||
                String.IsNullOrEmpty(TechnologicatorDefines.TaskRegex))
            {
                return;
            }

            SelectWord(ts);

            if (ts.Text.StartsWith("[") && ts.Text.EndsWith("]"))
            {
                OpenTaskInBrowser(ProcessBracketedTaskName(ts.Text));
            }
            else
            {
                string task = GetTaskNameFromTechnology(ts.Text);
                if (task != "")
                {
                    OpenTaskInBrowser(ProcessBracketedTaskName(task));
                }
            }
        }
        private string GetTaskNameFromTechnology(string techName)
        {
            string configFile = System.IO.Path.GetDirectoryName(_dte.Solution.FullName) + TechnologicatorDefines.ConfigFile;

            _dte.ExecuteCommand("File.OpenFile", configFile);
            _dte.Find.MatchWholeWord    = false;
            _dte.Find.Action            = vsFindAction.vsFindActionFind;
            _dte.Find.Target            = vsFindTarget.vsFindTargetCurrentDocument;
            _dte.Find.MatchCase         = false;
            _dte.Find.Backwards         = false;
            _dte.Find.MatchInHiddenText = true;
            _dte.Find.PatternSyntax     = vsFindPatternSyntax.vsFindPatternSyntaxLiteral;
            _dte.Find.FindWhat          = "#define " + techName;
            if (_dte.Find.Execute() != vsFindResult.vsFindResultFound)
            {
                return("");
            }
            EnvDTE.TextSelection ts = _dte.ActiveWindow.Selection as EnvDTE.TextSelection;
            ts.SelectLine();
            string defLine          = ts.Text;
            string taskRegexPattern = TechnologicatorDefines.TaskRegex;

            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(defLine, taskRegexPattern);

            if (m.Success)
            {
                return(m.Value);
            }
            else
            {
                return("");
            }
        }
        private bool SelectLines()
        {
            EnvDTE.TextSelection ts = _dte.ActiveWindow.Selection as EnvDTE.TextSelection;

            if (ts.IsEmpty)
            {
                ts.SelectLine();
                return(true);
            }
            else
            {
                int startLine = ts.AnchorPoint.Line;
                int endLine   = ts.ActivePoint.Line;

                if (endLine < startLine)
                {
                    int temp = startLine;
                    startLine = endLine;
                    endLine   = temp;
                    ts.SwapAnchor();
                }

                ts.EndOfLine(true);
                int endChar = ts.ActivePoint.LineCharOffset;


                ts.GotoLine(startLine, true);
                ts.MoveToLineAndOffset(endLine, endChar, true);

                return(false);
            }
        }
 public void BeforeKeyPress(string Keypress, EnvDTE.TextSelection Selection, bool InStatementCompletion, ref bool CancelKeypress)
 {
     _outputWindowPane.OutputString("TextDocumentKeyPressEvents, BeforeKeyPress\n");
     _outputWindowPane.OutputString("\tKey: " + Keypress + "\n");
     _outputWindowPane.OutputString("\tSelection: " + Selection.Text + "\n");
     _outputWindowPane.OutputString("\tInStatementCompletion: " + InStatementCompletion.ToString() + "\n");
 }
Beispiel #6
0
        static public void GetCursorPosition(out string path,out int line,out int column)
        {
            path = "";
            line = column = -1;
            var      dte = Package.GetGlobalService(typeof(DTE)) as DTE2;
            Document doc = null;

            if (dte != null)
            {
                try
                {
                    doc = dte.ActiveDocument;
                }
                catch (Exception)
                {
                    return;
                }
            }
            if (doc == null)
            {
                return;
            }
            path = doc.FullName;
            EnvDTE.TextSelection ts = doc.Selection as EnvDTE.TextSelection;
            if (ts != null)
            {
                line   = ts.ActivePoint.Line;
                column = ts.ActivePoint.DisplayColumn;
            }
        }
 private void OnBeforeKeyPress(string Keypress, EnvDTE.TextSelection Selection, bool InStatementCompletion, ref bool CancelKeypress)
 {
     if (mPlugin.App.ActiveDocument.ReadOnly)
     {
         P4Operations.EditFile(mPlugin.OutputPane, mPlugin.App.ActiveDocument.FullName);
     }
 }
Beispiel #8
0
        static public void GetCursorElement(out Document document,out CodeElement element,out int line)
        {
            document = null;
            element  = null;
            line     = -1;
            var dte = Package.GetGlobalService(typeof(DTE)) as DTE2;

            if (dte != null)
            {
                document = dte.ActiveDocument;
                //var docItem = document.ProjectItem;
                //if (docItem == null)
                //{
                //    return;
                //}
                var docModel = GetFileCodeModel(document);
                if (docModel == null)
                {
                    return;
                }
                EnvDTE.TextSelection ts = document.Selection as EnvDTE.TextSelection;
                line = ts.CurrentLine;
                try
                {
                    element = docModel.CodeElementFromPoint(ts.ActivePoint,vsCMElement.vsCMElementFunction);
                }
                catch (Exception e)
                {
                    element = null;
                }
                return;
            }
            return;
        }
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        EnvDTE.TextSelection ts = DTE.ActiveWindow.Selection as EnvDTE.TextSelection;
        if (ts == null)
        {
            throw new Exception("No Selection");
        }

        EnvDTE.CodeParameter codeParam = ts.ActivePoint.CodeElement[vsCMElement.vsCMElementParameter] as EnvDTE.CodeParameter;
        if (codeParam == null)
        {
            throw new Exception("Not Parameter");
        }

        System.Type tClass     = GetTypeByName(DTE, package, codeParam.Type.AsFullName);
        string      properties = System.Environment.NewLine;

        foreach (var p in tClass.GetProperties())
        {
            properties += codeParam.Name + "." + p.Name + System.Environment.NewLine;
        }

        // Move into the method and dump the properties there
        ts.FindText("{");
        ts.Insert("{" + properties);
    }
Beispiel #10
0
        private void timer_Jump(object sender, System.Timers.ElapsedEventArgs e)
        {
            m_timer.Stop();

            if (m_activeDocumentFileName != null)
            {
                s_dte.ExecuteCommand("Window.ActivateDocumentWindow");
                // s_dte.ExecuteCommand("File.OpenFile", m_activeDocumentFileName);
                s_dte.ItemOperations.OpenFile(m_activeDocumentFileName, EnvDTE.Constants.vsViewKindTextView);

                Document document = GetActiveDocument();
                if (document != null)
                {
                    EnvDTE.TextSelection textSelection = (EnvDTE.TextSelection)(document.Selection);
                    textSelection.GotoLine(m_activeDocumentLineNo, false);
                    document.Activate();
                    if (document.Windows.Count > 0)
                    {
                        document.Windows.Item(1).Activate();
                    }
                    textSelection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn);
                }

                m_activeDocumentFileName = null;
            }
        }
        private void OnBeforeKeyPress(string Keypress, EnvDTE.TextSelection Selection, bool InStatementCompletion, ref bool CancelKeypress)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            if (mPlugin.App.ActiveDocument != null && mPlugin.App.ActiveDocument.ReadOnly)
            {
                P4Operations.EditFile(mPlugin.App.ActiveDocument.FullName, false);
            }
        }
        private void SelectWord(EnvDTE.TextSelection ts)
        {
            if (!ts.IsEmpty)
            {
                return;
            }

            ts.WordLeft(true);
            ts.SwapAnchor();
            ts.WordRight(true);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="d"></param>
 /// <param name="text"></param>
 public static void InsertTextIntoActiveDocument(EnvDTE.Document d, string text)
 {
     if ((!String.IsNullOrEmpty(text)) && (!String.IsNullOrEmpty(text.Trim())))
     {
         EnvDTE.TextSelection SelectedText = d.Selection as EnvDTE.TextSelection;
         EnvDTE.EditPoint     TopPoint     = SelectedText.TopPoint.CreateEditPoint();
         TopPoint.LineUp(1);
         TopPoint.EndOfLine();
         TopPoint.Insert(text);
     }
 }
Beispiel #14
0
 private void OnBeforeKeyPress(string Keypress, EnvDTE.TextSelection Selection, bool InStatementCompletion, ref bool CancelKeypress)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     if (_application.ActiveDocument == null)
     {
         return;
     }
     if (_application.ActiveDocument.ReadOnly)
     {
         AutoCheckout(_application.ActiveDocument.FullName, true);
     }
 }
Beispiel #15
0
        public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
        {
            EnvDTE.TextSelection ts = DTE.ActiveWindow.Selection as EnvDTE.TextSelection;
            if (ts == null)
            {
                return;
            }
            var codeClass = ts.ActivePoint.CodeElement[vsCMElement.vsCMElementClass]
                            as EnvDTE.CodeClass;

            if (codeClass == null)
            {
                return;
            }
            EnvDTE.Project project   = DTE.ActiveWindow.Project;
            var            resolutor = GetResolutionService(project, Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider);
            var            a         = project.
                                       var type = resolutor.GetType(codeClass.FullName, true);
            var bases    = new List <Type>();
            var baseType = type.BaseType;

            while (baseType != typeof(object) && baseType != null)
            {
                bases.Add(baseType);
                baseType = baseType.BaseType;
            }
            bases.Insert(0, type);

            var fields_list = new List <PropertyInfo>();

            foreach (var type_base in bases)
            {
                var tmp = type_base.GetProperties(
                    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Default | BindingFlags.Instance);
                foreach (var fieldInfo in tmp)
                {
                    fields_list.Add(fieldInfo);
                }
            }
            var text = "//numero di fields = ' " + fields_list.Count + " '" + System.Environment.NewLine;

            foreach (var fieldInfo in fields_list)
            {
                if (text.Contains("public " + fieldInfo.PropertyType + " " + fieldInfo.Name + ";"))
                {
                    continue;
                }
                text += "public " + fieldInfo.PropertyType + " " + fieldInfo.Name + ";" + System.Environment.NewLine + System.Environment.NewLine;
            }
            text = text.Replace("+", ".");
            System.Windows.Clipboard.SetText(text);
        }
Beispiel #16
0
        static public void GetCursorWord(EnvDTE.TextSelection ts,out string name,out string longName,out int lineNum)
        {
            name     = null;
            longName = null;
            lineNum  = ts.AnchorPoint.Line;
            int lineOffset = ts.AnchorPoint.LineCharOffset;

            // If a line of text is selected, used as search word.
            var cursorStr = ts.Text.Trim();

            if (cursorStr.Length != 0 && cursorStr.IndexOf('\n') == -1)
            {
                name     = cursorStr;
                longName = cursorStr;
                return;
            }

            // Otherwise, use the word under the cursor.
            ts.SelectLine();
            string lineText = ts.Text;

            ts.MoveToLineAndOffset(lineNum,lineOffset);

            Regex           rx      = new Regex(@"\b(?<word>\w+)\b",RegexOptions.Compiled | RegexOptions.IgnoreCase);
            MatchCollection matches = rx.Matches(lineText);

            // Report on each match
            int lastStartIndex = 0;
            int lastEndIndex   = 0;

            for (int ithMatch = 0; ithMatch < matches.Count; ++ithMatch)
            {
                var    match      = matches[ithMatch];
                string word       = match.Groups["word"].Value;
                int    startIndex = match.Groups["word"].Index;
                int    endIndex   = startIndex + word.Length;
                int    lineIndex  = lineOffset - 1;
                if (startIndex <= lineIndex && endIndex >= lineIndex)
                {
                    name     = word;
                    longName = word;
                    var midStr = lineText.Substring(lastEndIndex,(startIndex - lastEndIndex));
                    if (ithMatch > 0 && midStr == "::")
                    {
                        longName = lineText.Substring(lastStartIndex,(endIndex - lastStartIndex));
                        break;
                    }
                }
                lastStartIndex = startIndex;
                lastEndIndex   = endIndex;
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public string GetCurrentMethodName()
 {
     try{
         EnvDTE.TextSelection   SelectedText    = this.Application.ActiveDocument.Selection as EnvDTE.TextSelection;
         EnvDTE.TextPoint       tp              = SelectedText.TopPoint as EnvDTE.TextPoint;
         EnvDTE.CodeElement     c               = this.Application.ActiveDocument.ProjectItem.FileCodeModel.CodeElementFromPoint(tp, EnvDTE.vsCMElement.vsCMElementFunction);
         EnvDTE80.CodeFunction2 CurrentFunction = c as EnvDTE80.CodeFunction2;
         return(c.Name);
     }
     catch {
         return("");
     }
 }
Beispiel #18
0
        /// <summary>
        /// Sorts the text within the specified text selection.
        /// </summary>
        /// <param name="textSelection">The text selection.</param>
        private void SortText(TextSelection textSelection)
        {
            // If the selection has no length, try to pick up the next line.
            if (textSelection.IsEmpty)
            {
                textSelection.LineDown(true);
                textSelection.EndOfLine(true);
            }

            // Start of selection should always be at the beginning of the line.
            var start = textSelection.TopPoint.CreateEditPoint();

            start.StartOfLine();

            // End of selection should always be at the start of the following line (i.e. extend past the last line's newline character).
            var end = textSelection.BottomPoint.CreateEditPoint();

            if (!end.AtStartOfLine)
            {
                end.EndOfLine();
                end.CharRight();
            }

            // Capture the selected text.
            var selectedText = start.GetText(end);

            // Create the sorted text lines.
            var splitText   = selectedText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var orderedText = splitText.OrderBy(x => x);

            var sb = new StringBuilder();

            foreach (var line in orderedText)
            {
                sb.AppendLine(line);
            }

            var sortedText = sb.ToString();

            // If the selected and sorted text do not match, delete and insert the replacement.
            if (!selectedText.Equals(sortedText, StringComparison.CurrentCulture))
            {
                start.Delete(end);

                var insertCursor = start.CreateEditPoint();
                insertCursor.Insert(sortedText);

                textSelection.MoveToPoint(start, false);
                textSelection.MoveToPoint(insertCursor, true);
            }
        }
Beispiel #19
0
 /*Shortcut actions*/
 internal void DoFocus()
 {
     EnvDTE.Window window = ((VSFindTool.VSFindToolPackage)(this.parentToolWindow.Package)).LastDocWindow;
     if (window != null)
     {
         EnvDTE.TextSelection selection = GetSelection(window);
         if (selection != null && selection.Text != "")
         {
             tbPhrase.Text = selection.Text;
         }
     }
     tbiSearch.IsSelected = true;                                              //use instead of "tbcMain.SelectedIndex = 0;"
     System.Windows.Input.FocusManager.SetFocusedElement(tbiSearch, tbPhrase); //use instead of "tbPhrase.Focus();"
 }
Beispiel #20
0
        private void PerformBugTracker(bool dotNet)
        {
            //! https://blogs.msdn.microsoft.com/vsx/2016/04/21/how-to-add-a-custom-paste-special-command-to-the-vs-editor-menu/

            Application.DoEvents();

            EnvDTE.TextSelection selection = (EnvDTE.TextSelection) this.CommandManager.ApplicationObject.ActiveDocument.Selection;
            string text           = selection.Text;
            string text_trim      = text.Trim();
            bool   is_numeric     = int.TryParse(text_trim, out int n);
            string bug_tracker_id = is_numeric ? text_trim : "00000";

            string        date   = DateTime.Now.ToString("yyyy-MM-dd");
            List <string> result = new List <string>();

            string comment_line = dotNet ?
                                  "/// @date " + date + "  @author " + this.CommandManager.UserName + "  @bugtracker{" + bug_tracker_id + "}" :
                                  "//! @date " + date + "  @author " + this.CommandManager.UserName + "  @bugtracker{" + bug_tracker_id + "}";

            /* TODO $$$ `selection.CurrentColumn` does not give a proper result
             *      try
             *      {
             *              int column = selection.CurrentColumn;
             *              if (column > 0)
             *              {
             *                      string indent_str = "";
             *                      for (int i = 0; i < column; ++i)
             *                              indent_str += " ";
             *                      comment_line = indent_str + comment_line;
             *              }
             *      }
             *      catch {}
             */

            result.Add(comment_line);

            string str = "";

            for (int i = 0; i < result.Count; i++)
            {
                str += result[i] + "\n";
            }

            selection.Insert(str, 2);
            if (!is_numeric)
            {
                selection.FindText("00000");
            }
        }
Beispiel #21
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 async void ExecuteAsync(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (!(this.package is ExecomExtensionsPackage execomPackage))
            {
                VsShellUtilities.ShowMessageBox(
                    this.package,
                    "Couldn't load ExecomExtensionsPackage",
                    "Error",
                    OLEMSGICON.OLEMSGICON_CRITICAL,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                return;
            }

            var template = execomPackage.AddHeaderOptions.TemplateHeader;

            if (string.IsNullOrWhiteSpace(template))
            {
                VsShellUtilities.ShowMessageBox(
                    this.package,
                    "Template for AddHeader command is empty!",
                    "Error",
                    OLEMSGICON.OLEMSGICON_CRITICAL,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                return;
            }

            EnvDTE80.DTE2 applicationObject = await ServiceProvider.GetServiceAsync(typeof(DTE)) as EnvDTE80.DTE2;

            EnvDTE.TextSelection textSelection = applicationObject?.ActiveDocument.Selection as TextSelection;

            if (textSelection == null)
            {
                return;
            }

            var information = ExtractDocumentInformation(textSelection);

            var userInformation = ExtractUserInformation(execomPackage.DefaultOptions.RegistrySubKey);

            template = ReplacePlaceholders(template, information, userInformation);

            InsertHeader(template, textSelection);

            applicationObject.ActiveDocument.Save();
        }
Beispiel #22
0
        public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
        {
            EnvDTE.TextSelection ts = DTE.ActiveWindow.Selection as EnvDTE.TextSelection;
            if (ts == null)
            {
                return;
            }
            var codeClass = ts.ActivePoint.CodeElement[vsCMElement.vsCMElementClass]
                            as EnvDTE.CodeClass;

            if (codeClass == null)
            {
                return;
            }
            EnvDTE.Project project   = DTE.ActiveWindow.Project;
            var            resolutor = GetResolutionService(project, Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider);
            var            type      = resolutor.GetType(codeClass.FullName, true);
            var            bases     = new List <Type>();

            //var baseType = type.BaseType;
            //while (baseType != typeof(object) && baseType != null)
            //{
            //    bases.Add(baseType);
            //    baseType = baseType.BaseType;
            //}
            bases.Insert(0, type);

            var fields_list = new List <FieldInfo>();

            foreach (var type_base in bases)
            {
                var tmp = type_base.GetFields(
                    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Default | BindingFlags.Instance);
                foreach (var fieldInfo in tmp)
                {
                    fields_list.Add(fieldInfo);
                }
            }
            var text = " //numero di fields = ' " + fields_list.Count + " '" + System.Environment.NewLine;

            foreach (var fieldInfo in fields_list)
            {
                var propName = fieldInfo.Name.Replace("_", "").Substring(0, 1).ToUpper() +
                               fieldInfo.Name.Replace("_", "").Substring(1);
                text += "public " + fieldInfo.FieldType + " " + propName + "{get{ return " + fieldInfo.Name + ";} set{  " + fieldInfo.Name + " = value ; RaisePropertyChanged( () => (" + fieldInfo.Name + ")); }}" + System.Environment.NewLine + System.Environment.NewLine;;
            }
            text = text.Replace("+", ".");
            System.Windows.Clipboard.SetText(text);
        }
Beispiel #23
0
        /// <summary>
        /// Sorts the text within the specified text selection.
        /// </summary>
        /// <param name="textSelection">The text selection.</param>
        private void SortText(TextSelection textSelection)
        {
            // If the selection has no length, try to pick up the next line.
            if (textSelection.IsEmpty)
            {
                textSelection.LineDown(true);
                textSelection.EndOfLine(true);
            }

            // Start of selection should always be at the beginning of the line.
            var start = textSelection.TopPoint.CreateEditPoint();
            start.StartOfLine();

            // End of selection should always be at the start of the following line (i.e. extend past the last line's newline character).
            var end = textSelection.BottomPoint.CreateEditPoint();
            if (!end.AtStartOfLine)
            {
                end.EndOfLine();
                end.CharRight();
            }

            // Capture the selected text.
            var selectedText = start.GetText(end);

            // Create the sorted text lines.
            var splitText = selectedText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var orderedText = splitText.OrderBy(x => x);

            var sb = new StringBuilder();
            foreach (var line in orderedText)
            {
                sb.AppendLine(line);
            }

            var sortedText = sb.ToString();

            // If the selected and sorted text do not match, delete and insert the replacement.
            if (!selectedText.Equals(sortedText, StringComparison.CurrentCulture))
            {
                start.Delete(end);

                var insertCursor = start.CreateEditPoint();
                insertCursor.Insert(sortedText);

                textSelection.MoveToPoint(start, false);
                textSelection.MoveToPoint(insertCursor, true);
            }
        }
Beispiel #24
0
        static public void MoveToLindEnd()
        {
            var dte = Package.GetGlobalService(typeof(DTE)) as DTE2;

            if (dte != null)
            {
                var document = dte.ActiveDocument;
                if (document == null)
                {
                    return;
                }

                EnvDTE.TextSelection ts = document.Selection as EnvDTE.TextSelection;
                ts.EndOfLine();
            }
        }
Beispiel #25
0
        //! \brief Gets either the selected text or the current line
        //! EnvDTE.TextSelection: [https://msdn.microsoft.com/en-us/library/envdte.textselection.aspx]
        protected string GetCurrentSelectionOrLine()
        {
            EnvDTE.TextSelection selection = (EnvDTE.TextSelection) this.CommandManager.ApplicationObject.ActiveDocument.Selection;
            string selectionText           = selection.Text.Trim();

            if (selectionText != "")
            {
                return(selectionText);
            }
            int currentLine = selection.CurrentLine;

            selection.SelectLine();
            string lineText = selection.Text.Trim();

            selection.GotoLine(currentLine, false);
            selection.Text = selectionText;
            return(lineText);
        }
Beispiel #26
0
        internal bool markType(Lookup lookup, Projects projects)
        {
            foreach (Project p in projects)
            {
                try
                {
                    if (p.CodeModel != null)
                    {
                        CodeClass2 codeClass = (CodeClass2)p.CodeModel.CodeTypeFromFullName(lookup.typeName);
                        if (codeClass == null)
                        {
                            CodeType codeType = FindCodeType(p.ProjectItems, lookup.typeName);
                            if (codeType != null)
                            {
                                codeClass = (CodeClass2)codeType;
                            }
                        }
                        if (codeClass != null)
                        {
                            try
                            {
                                object test = codeClass.ProjectItem;
                                dte.Documents.Open(codeClass.ProjectItem.get_FileNames(0), "Auto", false);
                                TextSelection textSelection = (TextSelection)dte.ActiveDocument.Selection;
                                textSelection.MoveToLineAndOffset(codeClass.StartPoint.Line, codeClass.StartPoint.LineCharOffset, false);
                                dte.MainWindow.Activate();
                                log(String.Format(Context.LOG_INFO + "Method {0} not found but type {1} -> marking type", lookup.methodName, lookup.typeName));
                                return(true);
                            }
                            catch (System.Runtime.InteropServices.COMException) { }
                        }
                    }
                }
                catch (NotImplementedException) { }
                catch (Exception e)
                {
                    log(Context.LOG_ERROR + e.ToString());
                }
            }

            log(Context.LOG_WARN + "Could not find the Type \"" + lookup.typeName + "\"!");
            return(false);
        }
Beispiel #27
0
        /// <summary>mark the method and bring the Visual Studio on front</summary>
        /// <param term='codeFunction'>is the right codeFunction element to the searched method</param>
        /// <param name="methodString">name of the method</param>

        internal void markMethod(CodeFunction codeFunction)
        {
            dte.Documents.Open(codeFunction.ProjectItem.get_FileNames(0), "Auto", false);

            TextSelection textSelection = (TextSelection)dte.ActiveDocument.Selection;

            textSelection.MoveToLineAndOffset(codeFunction.StartPoint.Line, codeFunction.StartPoint.LineCharOffset, false);

            TextRanges textRanges = null;
            string     pattern    = @"[:b]<{" + codeFunction.Name + @"}>[:b(\n]";

            if (textSelection.FindPattern(pattern, (int)vsFindOptions.vsFindOptionsRegularExpression, ref textRanges))
            {
                TextRange r = textRanges.Item(2);
                textSelection.MoveToLineAndOffset(r.StartPoint.Line, r.StartPoint.LineCharOffset, false);
                textSelection.MoveToLineAndOffset(r.EndPoint.Line, r.EndPoint.LineCharOffset, true);
            }
            dte.MainWindow.Activate();
        }
Beispiel #28
0
        /// <summary>
        /// Sorts the text within the specified text selection.
        /// </summary>
        /// <param name="textSelection">The text selection.</param>
        private void SortText(TextSelection textSelection)
        {
            // If the selection has no length, try to pick up the next line.
            if (textSelection.IsEmpty)
            {
                textSelection.LineDown(true);
                textSelection.EndOfLine(true);
            }

            // Capture the selected text lines.
            var start = textSelection.TopPoint.CreateEditPoint();

            start.StartOfLine();

            var end = textSelection.BottomPoint.CreateEditPoint();

            end.EndOfLine();
            end.CharRight();

            var selectedText = start.GetText(end);

            // Create the sorted text lines.
            var splitText   = selectedText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var orderedText = splitText.OrderBy(x => x);

            var sb = new StringBuilder();

            foreach (var line in orderedText)
            {
                sb.AppendLine(line);
            }

            var sortedText = sb.ToString();

            // If the selected and sorted text do not match, delete and insert the replacement.
            if (!selectedText.Equals(sortedText, StringComparison.CurrentCulture))
            {
                start.Delete(end);
                start.Insert(sortedText);
            }
        }
Beispiel #29
0
        //preview on MouseUp
        public void PreviewResultDoc(object src, EventArgs args)
        {
            ResultItem   resultLine = dictResultItems[(TreeViewItem)src];
            FindSettings settings   = dictSearchSettings[(TreeViewItem)src];
            RichTextBox  tbPreview  = dictTBPreview[settings];

            tbPreview.Document.Blocks.Clear();

            EnvDTE.Document document = GetDocumentByPath(resultLine.linePath);
            //It document exists in VS memory
            if (document != null)
            {
                EnvDTE.TextSelection selection = GetSelection(document);
                FillPreviewFromDocument(tbPreview.Document.Blocks, selection, resultLine);
                SelectOffsetLength(selection, resultLine);
            }
            else
            {
                FillPreviewFromFile(tbPreview.Document.Blocks, resultLine);
            }
        }
        private TextSelection GetTextSelection()
        {
            try
            {
                EnvDTE.Document objDocument = this.dteProvider.Dte.ActiveDocument;
                if (objDocument == null)
                {
                    ShowMessageBox("GetTextSelection()", "ActiveDocument not found. Are you in a code editor window ?");
                    return(null);
                }

                EnvDTE.TextDocument  objTextDocument  = (EnvDTE.TextDocument)objDocument.Object("TextDocument");
                EnvDTE.TextSelection objTextSelection = objTextDocument.Selection;
                return(objTextSelection);
            }
            catch (Exception ex)
            {
                ShowMessageBox("GetTextSelection()", ex.Message);
            }
            return(null);
        }
Beispiel #31
0
        internal void FillPreviewFromDocument(BlockCollection blocks, EnvDTE.TextSelection selection, ResultItem resultLine)
        {
            if (selection != null)
            {
                selection.EndOfDocument();
                int docLength  = selection.CurrentLine;
                int countEmpty = 0;

                Paragraph paragraph = new Paragraph();
                blocks.Add(paragraph);

                //Pre
                for (int i = resultLine.lineNumber.Value - 2; i < 1; i++)
                {
                    paragraph.Inlines.Add(new Run("\n"));
                    countEmpty++;
                }
                for (int i = Math.Max(1, resultLine.lineNumber.Value - 2); i < resultLine.lineNumber.Value; i++)
                {
                    selection.GotoLine(i, true);
                    paragraph.Inlines.Add(new Run(selection.Text + "\n"));
                }
                //Res
                selection.GotoLine(resultLine.lineNumber.Value, true);
                (string pre, string res, string post) = resultLine.GetSplitLine(selection.Text, false);
                paragraph.Inlines.Add(new Run(pre));
                paragraph.Inlines.Add(new Run(res)
                {
                    Foreground = Brushes.Red
                });
                paragraph.Inlines.Add(new Run(post + "\n"));
                //Post
                for (int i = 1; i <= Math.Min(2, docLength - resultLine.lineNumber.Value); i++)
                {
                    selection.GotoLine(resultLine.lineNumber.Value + i, true);
                    paragraph.Inlines.Add(new Run(selection.Text + "\n"));
                }
            }
            return;
        }
Beispiel #32
0
        /// <summary>
        /// Sorts the text within the specified text selection.
        /// </summary>
        /// <param name="textSelection">The text selection.</param>
        private void SortText(TextSelection textSelection)
        {
            // If the selection has no length, try to pick up the next line.
            if (textSelection.IsEmpty)
            {
                textSelection.LineDown(true);
                textSelection.EndOfLine(true);
            }

            // Capture the selected text lines.
            var start = textSelection.TopPoint.CreateEditPoint();
            start.StartOfLine();

            var end = textSelection.BottomPoint.CreateEditPoint();
            end.EndOfLine();
            end.CharRight();

            var selectedText = start.GetText(end);

            // Create the sorted text lines.
            var splitText = selectedText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var orderedText = splitText.OrderBy(x => x);

            var sb = new StringBuilder();
            foreach (var line in orderedText)
            {
                sb.AppendLine(line);
            }

            var sortedText = sb.ToString();

            // If the selected and sorted text do not match, delete and insert the replacement.
            if (!selectedText.Equals(sortedText, StringComparison.CurrentCulture))
            {
                start.Delete(end);
                start.Insert(sortedText);
            }
        }