Esempio n. 1
0
        public virtual void OnItemChosen(int combo, int entry)
        {
            SourceContext c = new SourceContext(null, 1, 1);

            if (combo == TypeAndMemberDropdownBars.DropClasses)
            {
                if (this.sortedDropDownTypes != null && entry >= 0 && entry < this.sortedDropDownTypes.Length)
                {
                    c = this.sortedDropDownTypes[entry].SourceContext;
                }
            }
            else
            {
                if (this.sortedDropDownMembers != null && entry >= 0 && entry < this.sortedDropDownMembers.Length)
                {
                    c = this.sortedDropDownMembers[entry].SourceContext;
                }
            }
            if (c.Document != null && this.textView != null)
            {
                int line = c.StartLine - 1;
                int col  = c.StartColumn - 1;
                try{
                    textView.CenterLines(line, 16);
                }catch {}
                this.textView.SetCaretPos(line, col);
                NativeWindowHelper.SetFocus(this.textView.GetWindowHandle());
                this.SynchronizeDropdowns(this.textView, line, col);
            }
        }
Esempio n. 2
0
 private static void MoveCaretToPosition(IVsTextView textView, Position position, bool sendFocus = true)
 {
     textView.SetCaretPos(position.Line, position.Character);
     textView.EnsureSpanVisible(new TextSpan()
     {
         iStartIndex = position.Character, iStartLine = position.Line, iEndIndex = position.Character, iEndLine = position.Line
     });
     textView.CenterLines(position.Line, 1);
     if (sendFocus)
     {
         textView.SendExplicitFocus();
     }
 }
Esempio n. 3
0
        static void SetSelection(IVsTextView textView, GitHubContext context)
        {
            var line    = context.Line;
            var lineEnd = context.LineEnd ?? line;

            if (line != null)
            {
                ErrorHandler.ThrowOnFailure(textView.GetBuffer(out IVsTextLines buffer));
                buffer.GetLengthOfLine(lineEnd.Value - 1, out int lineEndLength);
                ErrorHandler.ThrowOnFailure(textView.SetSelection(line.Value - 1, 0, lineEnd.Value - 1, lineEndLength));
                ErrorHandler.ThrowOnFailure(textView.CenterLines(line.Value - 1, lineEnd.Value - line.Value + 1));
            }
        }
Esempio n. 4
0
        internal static void FocusLine(IVsTextView viewAdapter, int line, int col)
        {
            ErrorHandler.ThrowOnFailure(viewAdapter.SetCaretPos(line, col));
            // Make sure that the text is visible.
            int topline = line - 10;

            if (topline < 0)
            {
                topline = 0;
            }

            viewAdapter.SetTopLine(topline);
            viewAdapter.CenterLines(line, 1);
        }
Esempio n. 5
0
        /// <include file='doc\CodeWindowManager.uex' path='docs/doc[@for="TypeAndMemberDropdownBars.OnItemChosen"]/*' />
        public virtual int OnItemChosen(int combo, int entry)
        {
            DropDownMember member = GetMember(combo, entry);

            if (member != null && this.textView != null)
            {
                int line = member.Span.iStartLine;
                int col  = member.Span.iStartIndex;
                try {
                    // Here we don't want to throw or to check the return value.
                    textView.CenterLines(line, 16);
                } catch (COMException) { }
                NativeMethods.ThrowOnFailure(this.textView.SetCaretPos(line, col));
                NativeMethods.SetFocus(this.textView.GetWindowHandle());
                this.SynchronizeDropdowns(this.textView, line, col);
            }
            return(NativeMethods.S_OK);
        }
Esempio n. 6
0
        /// <include file='doc\CodeWindowManager.uex' path='docs/doc[@for="TypeAndMemberDropdownBars.OnItemChosen"]/*' />
        public override int OnItemChosen(int combo, int entryIndex)
        {
            var entry = GetEntry(combo, entryIndex);

            if (entry != null && _textView != null)
            {
                int line = entry.Location.Line.ToVsLineCoord();
                int col  = entry.Location.Column.ToVsColCoord();
                try
                {
                    // Here we don't want to throw or to check the return value.
                    _textView.CenterLines(line, 16);
                }
                catch (System.Runtime.InteropServices.COMException) { }
                ErrorHandler.ThrowOnFailure(_textView.SetCaretPos(line, col));
                SetFocus(_textView.GetWindowHandle());
                SynchronizeDropdownsRsdn(_textView, line, col);
            }
            return(NativeMethods.S_OK);
        }
Esempio n. 7
0
        public virtual int OnItemChosen(int combo, int entry)
        {
            int line = 0;
            int col  = 0;

            if (combo == 0)
            {
                if (this.dropDownTypeNames != null && entry >= 0 && entry < this.dropDownTypeNames.Length)
                {
                    line = this.dropDownTypeStartLines[entry];
                    col  = this.dropDownTypeStartColumns[entry];
                }
            }
            else
            {
                if (this.dropDownMemberSignatures != null && entry >= 0 && entry < this.dropDownMemberSignatures.Length)
                {
                    line = this.dropDownMemberStartLines[entry];
                    col  = this.dropDownMemberStartColumns[entry];
                }
            }
            if (this.textView != null)
            {
                try{
                    textView.CenterLines(line, 16);
                }catch {}
                this.textView.SetCaretPos(line, col);
                NativeWindowHelper.SetFocus(this.textView.GetWindowHandle());
                this.SynchronizeDropdowns(this.textView, line, col);
                if (combo == 0)
                {
                    this.dropDownBar.RefreshCombo(1, this.selectedMember);
                }
                else
                {
                    this.dropDownBar.RefreshCombo(0, this.selectedType);
                }
                this.dropDownBar.RefreshCombo(combo, entry);
            }
            return(0);
        }
Esempio n. 8
0
        public void NavigateToEquivalentPosition(IVsTextView sourceView, IVsTextView targetView)
        {
            int line;
            int column;

            ErrorHandler.ThrowOnFailure(sourceView.GetCaretPos(out line, out column));
            var text1 = GetText(sourceView);
            var text2 = GetText(targetView);

            var fromLines    = ReadLines(text1);
            var toLines      = ReadLines(text2);
            var matchingLine = FindMatchingLine(fromLines, toLines, line, matchLinesAbove: MatchLinesAboveTarget);

            if (matchingLine == -1)
            {
                // If we can't match line use orignal as best guess.
                matchingLine = line < toLines.Count ? line : toLines.Count - 1;
                column       = 0;
            }

            ErrorHandler.ThrowOnFailure(targetView.SetCaretPos(matchingLine, column));
            ErrorHandler.ThrowOnFailure(targetView.CenterLines(matchingLine, 1));
        }
Esempio n. 9
0
        public int NavigateTo(string file, int line, int column)
        {
            int hr      = VSConstants.S_OK;
            var openDoc = _provider.globalServiceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;

            if (openDoc == null)
            {
                return(VSConstants.E_UNEXPECTED);
            }

            Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = null;
            IVsUIHierarchy hierarchy = null;
            uint           itemID    = 0;
            IVsWindowFrame frame     = null;
            Guid           viewGuid  = VSConstants.LOGVIEWID_TextView;

            hr = openDoc.OpenDocumentViaProject(file, ref viewGuid, out sp, out hierarchy, out itemID, out frame);
            if (hr != VSConstants.S_OK)
            {
                return(hr);
            }
            hr = frame.Show();
            if (hr != VSConstants.S_OK)
            {
                return(hr);
            }

            IntPtr viewPtr       = IntPtr.Zero;
            Guid   textLinesGuid = typeof(IVsTextLines).GUID;

            hr = frame.QueryViewInterface(ref textLinesGuid, out viewPtr);
            if (hr != VSConstants.S_OK)
            {
                return(hr);
            }

            IVsTextLines textLines = Marshal.GetUniqueObjectForIUnknown(viewPtr) as IVsTextLines;

            var textMgr = _provider.globalServiceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager;

            if (textMgr == null)
            {
                return(VSConstants.E_UNEXPECTED);
            }

            IVsTextView textView = null;

            hr = textMgr.GetActiveView(0, textLines, out textView);
            if (hr != VSConstants.S_OK)
            {
                return(hr);
            }

            if (textView != null && line > 0)
            {
                int col = Math.Max(column - 1, 0);
                textView.SetCaretPos(line - 1, col);
                var span = new TextSpan {
                    iStartLine = line - 1, iStartIndex = col, iEndLine = line - 1, iEndIndex = col + 1
                };
                textView.EnsureSpanVisible(span);
                textView.CenterLines(line - 1, 1);
            }

            return(VSConstants.S_OK);
        }
Esempio n. 10
0
        private void MenuItemCallback(object sender, EventArgs e, bool forward)
        {
            try
            {
                ////////////////////////
                /// Next rule.
                ////////////////////////

                IVsTextManager manager = ((IServiceProvider)ServiceProvider).GetService(typeof(VsTextManagerClass)) as IVsTextManager;
                if (manager == null)
                {
                    return;
                }

                manager.GetActiveView(1, null, out IVsTextView view);
                if (view == null)
                {
                    return;
                }

                view.GetCaretPos(out int l, out int c);
                view.GetBuffer(out IVsTextLines buf);
                if (buf == null)
                {
                    return;
                }

                IWpfTextView xxx    = AntlrLanguageClient.AdaptersFactory.GetWpfTextView(view);
                ITextBuffer  buffer = xxx.TextBuffer;
                string       ffn    = buffer.GetFFN().Result;
                if (ffn == null)
                {
                    return;
                }

                Workspaces.Document document = Workspaces.Workspace.Instance.FindDocument(ffn);
                if (document == null)
                {
                    return;
                }

                int pos = LanguageServer.Module.GetIndex(l, c, document);
                AntlrLanguageClient alc = AntlrLanguageClient.Instance;
                if (alc == null)
                {
                    return;
                }

                int new_pos = alc.CMNextSymbolSendServer(ffn, pos, forward);
                if (new_pos < 0)
                {
                    return;
                }

                List <IToken> where = new List <IToken>();
                List <ParserDetails> where_details = new List <ParserDetails>();
                IVsTextView          vstv          = IVsTextViewExtensions.FindTextViewFor(ffn);
                if (vstv == null)
                {
                    return;
                }

                IWpfTextView wpftv = AntlrLanguageClient.AdaptersFactory.GetWpfTextView(vstv);
                if (wpftv == null)
                {
                    return;
                }

                vstv.GetLineAndColumn(new_pos, out int line_number, out int colum_number);
                ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot;
                SnapshotSpan  ss = new SnapshotSpan(cc, new_pos, 1);
                SnapshotPoint sp = ss.Start;
                // Put cursor on symbol.
                wpftv.Caret.MoveTo(sp);
                if (line_number > 0)
                {
                    vstv.CenterLines(line_number - 1, 2);
                }
                else
                {
                    vstv.CenterLines(line_number, 1);
                }
            }
            catch (Exception exception)
            {
                Logger.Log.Notify(exception.StackTrace);
            }
        }
        private void MenuItemCallback(object sender, EventArgs e)
        {
            ////////////////////////
            // Go to definition....
            ////////////////////////

            // First, open up every .g4 file in project.
            // Get VS solution, if any, and parse all grammars
            DTE application = DteExtensions.GetApplication();

            if (application != null)
            {
                IEnumerable <ProjectItem> iterator = DteExtensions.SolutionFiles(application);
                ProjectItem[]             list     = iterator.ToArray();
                foreach (var item in list)
                {
                    //var doc = item.Document; CRASHES!!!! DO NOT USE!
                    //var props = item.Properties;
                    string file_name = item.Name;
                    if (file_name != null)
                    {
                        string prefix = file_name.TrimSuffix(".g4");
                        if (prefix == file_name)
                        {
                            continue;
                        }

                        try
                        {
                            object prop = item.Properties.Item("FullPath").Value;
                            string ffn  = (string)prop;
                            if (!ParserDetails._per_file_parser_details.ContainsKey(ffn))
                            {
                                StreamReader  sr  = new StreamReader(ffn);
                                ParserDetails foo = new ParserDetails();
                                ParserDetails._per_file_parser_details[ffn] = foo;
                                foo.Parse(sr.ReadToEnd(), ffn);
                            }
                        } catch (Exception eeks)
                        { }
                    }
                }
            }

            string       classification = this.Classification;
            SnapshotSpan span           = this.Symbol;
            ITextView    view           = this.View;

            // First, find out what this view is, and what the file is.
            ITextBuffer   buffer = view.TextBuffer;
            ITextDocument doc    = buffer.GetTextDocument();
            string        path   = doc.FilePath;

            //ParserDetails details = null;
            //bool found = ParserDetails._per_file_parser_details.TryGetValue(path, out details);
            //if (!found) return;

            List <IToken> where = new List <IToken>();
            List <ParserDetails> where_details = new List <ParserDetails>();
            IToken token = null;

            foreach (var kvp in ParserDetails._per_file_parser_details)
            {
                string        file_name = kvp.Key;
                ParserDetails details   = kvp.Value;
                if (classification == AntlrVSIX.Constants.ClassificationNameNonterminal)
                {
                    var it = details._ant_nonterminals_defining.Where(
                        (t) => t.Text == span.GetText());
                    where.AddRange(it);
                    foreach (var i in it)
                    {
                        where_details.Add(details);
                    }
                }
                else if (classification == AntlrVSIX.Constants.ClassificationNameTerminal)
                {
                    var it = details._ant_terminals_defining.Where(
                        (t) => t.Text == span.GetText());
                    where.AddRange(it);
                    foreach (var i in it)
                    {
                        where_details.Add(details);
                    }
                }
            }
            if (where.Any())
            {
                token = where.First();
            }
            else
            {
                return;
            }
            ParserDetails where_token = where_details.First();

            string      full_file_name = where_token.full_file_name;
            IVsTextView vstv           = IVsTextViewExtensions.GetIVsTextView(full_file_name);

            IVsTextViewExtensions.ShowFrame(full_file_name);
            vstv = IVsTextViewExtensions.GetIVsTextView(where_token.full_file_name);

            IWpfTextView wpftv = vstv.GetIWpfTextView();

            if (wpftv == null)
            {
                return;
            }

            int line_number;
            int colum_number;

            vstv.GetLineAndColumn(token.StartIndex, out line_number, out colum_number);

            // Create new span in the appropriate view.
            ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot;
            SnapshotSpan  ss = new SnapshotSpan(cc, token.StartIndex, 1);
            SnapshotPoint sp = ss.Start;

            // Put cursor on symbol.
            wpftv.Caret.MoveTo(sp);     // This sets cursor, bot does not center.
            // Center on cursor.
            //wpftv.Caret.EnsureVisible(); // This works, sort of. It moves the scroll bar, but it does not CENTER! Does not really work!
            if (line_number > 0)
            {
                vstv.CenterLines(line_number - 1, 2);
            }
            else
            {
                vstv.CenterLines(line_number, 1);
            }
        }
Esempio n. 12
0
        // --------------------------------------------------------------
        // Editor control
        // --------------------------------------------------------------

        private void ShowSource(string emitter, string path, int line_no)
        {
            IVsUIShellOpenDocument od = (IVsUIShellOpenDocument)MsVsShell.Package.GetGlobalService(typeof(SVsUIShellOpenDocument));

            // not clear why lookup needs a string array; documentation does not mention returning
            // more than one path
            uint search_strategy = (uint)__VSRELPATHSEARCHFLAGS.RPS_UseAllSearchStrategies;

            String[] found_abs_paths = new String[1];
            int      res             = od.SearchProjectsForRelativePath(search_strategy, path, found_abs_paths);

            // if the whole path wasn't found, retry with just the filename
            String chosen_abs_path;

            if (res != VsConstants.S_OK)
            {
                int last_elem_pos = path.LastIndexOf('\\');
                if (last_elem_pos >= 0)
                {
                    string last_elem = path.Substring(last_elem_pos + 1);
                    res = od.SearchProjectsForRelativePath(search_strategy, last_elem, found_abs_paths);
                }
            }

            if (res == VsConstants.S_OK)
            {
                chosen_abs_path = found_abs_paths[0];
            }
            else
            {
                OutputString(System.String.Format("Unable to find source code in any project: path:'{0}' line:{1}", path, line_no));
                return;
            }

            // fetch a hierarchy for the absolute path
            IVsUIHierarchy hierarchy;
            UInt32         item_id;

            Microsoft.VisualStudio.OLE.Interop.IServiceProvider provider;
            Int32 in_proj;

            res = od.IsDocumentInAProject(chosen_abs_path, out hierarchy, out item_id, out provider, out in_proj);

            if (res != VsConstants.S_OK)
            {
                OutputString(System.String.Format("Unable to find project for source code: emitter: '{0}'", emitter));
                return;
            }

            if (in_proj == 0)
            {
                OutputString(System.String.Format("Unable to find source code in project: emitter: '{0}'", emitter));
                return;
            }

            // convert the hierarchy to a project, and open & show the source code document
            IVsProject     project = (IVsProject)hierarchy;
            IntPtr         DOCDATAEXISTING_UNKNOWN = (IntPtr)(int)-1;
            Guid           logical_view            = new Guid(LogicalViewID.Code);
            IVsWindowFrame frame;

            res = project.OpenItem(item_id, logical_view, DOCDATAEXISTING_UNKNOWN, out frame);

            if (res != VsConstants.S_OK)
            {
                OutputString(System.String.Format("Unable to open editor for source code: emitter: '{0}'", emitter));
                return;
            }

            frame.Show();

            // move the cursor to the correct line in the editor
            IVsTextView text_view = Microsoft.VisualStudio.Shell.VsShellUtilities.GetTextView(frame);

            if (text_view == null)
            {
                OutputString(System.String.Format("Unable to access editor for source code: emitter: '{0}'", emitter));
                return;
            }

            line_no = line_no - 1;
            res     = text_view.SetCaretPos(line_no, 0);
            if (res != VsConstants.S_OK)
            {
                OutputString(System.String.Format("Unable to set cursor to source code: emitter: '{0}'", emitter));
                return;
            }

            // and finally, centre the view on the source code line - ignore errors, it doesn't
            // matter that much
            text_view.CenterLines(line_no, 1);
        }
Esempio n. 13
0
        private void MenuItemCallback(object sender, EventArgs e, bool visitor)
        {
            try
            {
                ////////////////////////
                /// Go to visitor.
                ////////////////////////

                IVsTextManager manager = ((IServiceProvider)ServiceProvider).GetService(typeof(VsTextManagerClass)) as IVsTextManager;
                if (manager == null)
                {
                    return;
                }

                manager.GetActiveView(1, null, out IVsTextView view);
                if (view == null)
                {
                    return;
                }

                view.GetCaretPos(out int l, out int c);
                view.GetBuffer(out IVsTextLines buf);
                if (buf == null)
                {
                    return;
                }

                IWpfTextView xxx      = AntlrLanguageClient.AdaptersFactory.GetWpfTextView(view);
                ITextBuffer  buffer   = xxx.TextBuffer;
                string       orig_ffn = buffer.GetFFN().Result;
                if (orig_ffn == null)
                {
                    return;
                }

                Workspaces.Document document = Workspaces.Workspace.Instance.FindDocument(orig_ffn);
                if (document == null)
                {
                    return;
                }

                int pos = LanguageServer.Module.GetIndex(l, c, document);
                AntlrLanguageClient alc = AntlrLanguageClient.Instance;
                if (alc == null)
                {
                    return;
                }

                CMGotoResult symbol = null;
                if (visitor)
                {
                    symbol = alc.CMGotoVisitorSendServer(orig_ffn, pos);
                }
                else
                {
                    var is_enter = CtrlKeyState.GetStateForView(xxx).Enabled;
                    symbol = alc.CMGotoListenerSendServer(orig_ffn, is_enter, pos);
                }
                if (symbol == null)
                {
                    return;
                }

                {
                    string class_file_path = symbol.TextDocument.LocalPath;
                    int    index           = symbol.Start;
                    // Open to this line in editor.
                    IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path);
                    {
                        IVsTextViewExtensions.ShowFrame(ServiceProvider, class_file_path);
                        vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path);
                    }

                    IWpfTextView wpftv = AntlrLanguageClient.AdaptersFactory.GetWpfTextView(vstv);
                    if (wpftv == null)
                    {
                        return;
                    }

                    // Create new span in the appropriate view.
                    ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot;
                    vstv.GetLineAndColumn(index, out int line_number, out int colum_number);

                    // Put cursor on symbol.
                    wpftv.Caret.MoveTo(new SnapshotPoint(cc, index)); // This sets cursor, bot does not center.
                                                                      // Center on cursor.
                                                                      //wpftv.Caret.EnsureVisible(); // This works, sort of. It moves the scroll bar, but it does not CENTER! Does not really work!
                    if (line_number > 0)
                    {
                        vstv.CenterLines(line_number - 1, 2);
                    }
                    else
                    {
                        vstv.CenterLines(line_number, 1);
                    }

                    return;
                }
            }
            catch (Exception exception)
            {
                Logger.Log.Notify(exception.StackTrace);
            }
        }
Esempio n. 14
0
        private void MenuItemCallback(object sender, EventArgs e, bool visitor)
        {
            try
            {
                // Return if I can't determine what application this is.
                DTE application = Workspaces.Help.GetApplication();
                if (application == null)
                {
                    return;
                }

                // Get active view and determine if it's a grammar file.
                var grammar_view = AntlrLanguagePackage.Instance.GetActiveView();
                if (grammar_view == null)
                {
                    return;
                }
                ITextCaret    car          = grammar_view.Caret;
                CaretPosition cp           = car.Position;
                SnapshotPoint bp           = cp.BufferPosition;
                int           pos          = bp.Position;
                ITextBuffer   buffer       = grammar_view.TextBuffer;
                var           g4_file_path = buffer.GetFFN().Result;
                if (g4_file_path == null)
                {
                    return;
                }
                IGrammarDescription grammar_description = LanguageServer.GrammarDescriptionFactory.Create(g4_file_path);
                if (!grammar_description.IsFileType(g4_file_path))
                {
                    return;
                }

                // Get name of base class for listener and visitor. These are generated by Antlr,
                // constructed from the name of the file.
                var grammar_name = Path.GetFileName(g4_file_path);
                grammar_name = Path.GetFileNameWithoutExtension(grammar_name);
                var listener_baseclass_name = visitor ? (grammar_name + "BaseVisitor") : (grammar_name + "BaseListener");
                var listener_class_name     = visitor ? ("My" + grammar_name + "Visitor") : ("My" + grammar_name + "Listener");

                // In the current view, find the details of the Antlr symbol at the cursor.
                TextExtent extent = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Navigator[grammar_view]
                                    .GetExtentOfWord(bp);
                SnapshotSpan span = extent.Span;
                AntlrLanguagePackage.Instance.Span = span;

                //  Now, check for valid classification type.
                var  cla             = -1;
                bool can_gotovisitor = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Aggregator[grammar_view].GetClassificationSpans(span).Where(
                    classification =>
                {
                    var name = classification.ClassificationType.Classification;
                    if (!grammar_description.InverseMap.TryGetValue(name, out int c))
                    {
                        return(false);
                    }
                    cla = c;
                    return(grammar_description.CanGotovisitor[cla]);
                }).Any();
                if (!can_gotovisitor)
                {
                    return;
                }

                // Find defining occurrence.
                List <Antlr4.Runtime.Tree.TerminalNodeImpl> where = new List <Antlr4.Runtime.Tree.TerminalNodeImpl>();
                List <ParserDetails> where_details         = new List <ParserDetails>();
                Antlr4.Runtime.Tree.TerminalNodeImpl token = null;
                foreach (var kvp in ParserDetailsFactory.AllParserDetails)
                {
                    string        file_name = kvp.Key;
                    ParserDetails details   = kvp.Value;
                    {
                        var it = details.Defs.Where(
                            (t) => t.Value == cla && t.Key.Symbol.Text == span.GetText()).Select(t => t.Key);
                        where.AddRange(it);
                        foreach (var i in it)
                        {
                            where_details.Add(details);
                        }
                    }
                }

                if (where.Any())
                {
                    token = where.First();
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show(
                        "Symbol '" + span.GetText() + "' definer not found.");
                    return;
                }

                // Get the symbol name as a string.
                var symbol_name             = token.Symbol.Text;
                var capitalized_symbol_name = Capitalized(symbol_name);

                // Parse all the C# files in the solution.
                Dictionary <string, SyntaxTree> trees = new Dictionary <string, SyntaxTree>();
                foreach (var item in DteExtensions.SolutionFiles(application))
                {
                    string file_name = item.Name;
                    if (file_name != null)
                    {
                        string prefix = file_name.TrimSuffix(".cs");
                        if (prefix == file_name)
                        {
                            continue;
                        }
                        try
                        {
                            object       prop = item.Properties.Item("FullPath").Value;
                            string       ffn  = (string)prop;
                            StreamReader sr   = new StreamReader(ffn);
                            string       code = sr.ReadToEnd();
                            SyntaxTree   tree = CSharpSyntaxTree.ParseText(code);
                            trees[ffn] = tree;
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

                // Find all occurrences of visitor class.
                List <ClassDeclarationSyntax> found_class = new List <ClassDeclarationSyntax>();
                string class_file_path = null;
                try
                {
                    foreach (var kvp in trees)
                    {
                        var file_name = kvp.Key;
                        var tree      = kvp.Value;

                        // Look for IParseTreeListener or IParseTreeVisitor classes.
                        var root = (CompilationUnitSyntax)tree.GetRoot();
                        if (root == null)
                        {
                            continue;
                        }
                        foreach (var nm in root.Members)
                        {
                            var namespace_member = nm as NamespaceDeclarationSyntax;
                            if (namespace_member == null)
                            {
                                continue;
                            }
                            foreach (var cm in namespace_member.Members)
                            {
                                var class_member = cm as ClassDeclarationSyntax;
                                if (class_member == null)
                                {
                                    continue;
                                }
                                var bls = class_member.BaseList;
                                if (bls == null)
                                {
                                    continue;
                                }
                                var   types = bls.Types;
                                Regex reg   = new Regex("[<].+[>]");
                                foreach (var type in types)
                                {
                                    var s = type.ToString();
                                    s = reg.Replace(s, "");
                                    if (s.ToString() == listener_baseclass_name)
                                    {
                                        // Found the right class.
                                        found_class.Add(class_member);
                                        throw new Exception();
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                }

                if (found_class.Count == 0)
                {
                    if (!global::Options.POptions.GetBoolean("GenerateVisitorListener"))
                    {
                        return;
                    }

                    // Look in grammar directory for any C# files.
                    string name_space = null;
                    string ffn        = Path.GetFullPath(g4_file_path);
                    ffn = Path.GetDirectoryName(ffn);
                    foreach (var i in DteExtensions.SolutionFiles(application))
                    {
                        string file_name = i.Name;
                        if (file_name != null)
                        {
                            string prefix = file_name.TrimSuffix(".cs");
                            if (prefix == file_name)
                            {
                                continue;
                            }
                            try
                            {
                                object prop  = i.Properties.Item("FullPath").Value;
                                string ffncs = (string)prop;
                                // Look for namespace.
                                var t = trees[ffncs];
                                if (t == null)
                                {
                                    continue;
                                }
                                var root = t.GetCompilationUnitRoot();
                                foreach (var nm in root.Members)
                                {
                                    var namespace_member = nm as NamespaceDeclarationSyntax;
                                    if (namespace_member == null)
                                    {
                                        continue;
                                    }
                                    name_space = namespace_member.Name.ToString();
                                    break;
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    if (name_space == null)
                    {
                        name_space = "Generated";
                    }

                    // Create class.
                    string clazz = visitor ? $@"
using System;
using System.Collections.Generic;
using System.Text;

namespace {name_space}
{{
    class {listener_class_name}<Result> : {listener_baseclass_name}<Result>
    {{
        //public override Result VisitA([NotNull] A3Parser.AContext context)
        //{{
        //  return VisitChildren(context);
        //}}
    }}
}}
"
                    : $@"
using System;
using System.Collections.Generic;
using System.Text;

namespace {name_space}
{{
    class {listener_class_name} : {listener_baseclass_name}
    {{
        //public override void EnterA(A3Parser.AContext context)
        //{{
        //    base.EnterA(context);
        //}}
        //public override void ExitA(A3Parser.AContext context)
        //{{
        //    base.ExitA(context);
        //}}
    }}
}}
";

                    class_file_path = ffn + Path.DirectorySeparatorChar + listener_class_name + ".cs";
                    System.IO.File.WriteAllText(class_file_path, clazz);
                    var    item   = ProjectHelpers.GetSelectedItem();
                    string folder = FindFolder(item);
                    if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                    {
                        return;
                    }
                    var file         = new FileInfo(class_file_path);
                    var selectedItem = Workspaces.Workspace.Instance.FindDocument(class_file_path);
                    if (selectedItem == null)
                    {
                        //var selectedProject = item as Project;
                        //Project project = selectedItem?.ContainingProject ?? selectedProject ?? null;
                        //var projectItem = project.AddFileToProject(file);
                    }
                    // Redo parse.
                    try
                    {
                        StreamReader sr   = new StreamReader(class_file_path);
                        string       code = sr.ReadToEnd();
                        SyntaxTree   tree = CSharpSyntaxTree.ParseText(code);
                        trees[class_file_path] = tree;
                    }
                    catch (Exception)
                    {
                    }
                    // Redo find class.
                    try
                    {
                        var tree = trees[class_file_path];
                        var save = class_file_path;
                        class_file_path = null;
                        // Look for IParseTreeListener or IParseTreeVisitor classes.
                        var root = (CompilationUnitSyntax)tree.GetRoot();
                        foreach (var nm in root.Members)
                        {
                            var namespace_member = nm as NamespaceDeclarationSyntax;
                            if (namespace_member == null)
                            {
                                continue;
                            }
                            foreach (var cm in namespace_member.Members)
                            {
                                var class_member = cm as ClassDeclarationSyntax;
                                if (class_member == null)
                                {
                                    continue;
                                }
                                var bls = class_member.BaseList;
                                if (bls == null)
                                {
                                    continue;
                                }
                                var   types = bls.Types;
                                Regex reg   = new Regex("[<].+[>]");
                                foreach (var type in types)
                                {
                                    var s = type.ToString();
                                    s = reg.Replace(s, "");
                                    if (s.ToString() == listener_baseclass_name)
                                    {
                                        // Found the right class.
                                        found_class.Add(class_member);
                                        throw new Exception();
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }

                // Look for enter or exit method for symbol.
                MethodDeclarationSyntax found_member = null;
                var ctl = CtrlKeyState.GetStateForView(grammar_view).Enabled;
                var capitalized_member_name = "";
                if (visitor)
                {
                    capitalized_member_name = "Visit" + capitalized_symbol_name;
                }
                else if (ctl)
                {
                    capitalized_member_name = "Exit" + capitalized_symbol_name;
                }
                else
                {
                    capitalized_member_name = "Enter" + capitalized_symbol_name;
                }
                var capitalized_grammar_name = Capitalized(grammar_name);
                try
                {
                    foreach (var fc in found_class)
                    {
                        foreach (var me in fc.Members)
                        {
                            var method_member = me as MethodDeclarationSyntax;
                            if (method_member == null)
                            {
                                continue;
                            }
                            if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower())
                            {
                                found_member = method_member;
                                throw new Exception();
                            }
                        }
                    }
                }
                catch
                {
                }
                if (found_member == null)
                {
                    if (!global::Options.POptions.GetBoolean("GenerateVisitorListener"))
                    {
                        return;
                    }

                    // Find point for edit.
                    var fc   = found_class.First();
                    var here = fc.OpenBraceToken;
                    var spn  = here.FullSpan;
                    var end  = spn.End;

                    IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path);
                    if (vstv == null)
                    {
                        IVsTextViewExtensions.ShowFrame(class_file_path);
                        vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path);
                    }
                    IWpfTextView wpftv = vstv.GetIWpfTextView();
                    if (wpftv == null)
                    {
                        return;
                    }
                    ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot;

                    var res = vstv.GetBuffer(out IVsTextLines ppBuffer);

                    var nss      = new SnapshotSpan(cc, spn.End + 1, 0);
                    var txt_span = nss.Span;

                    int line_number;
                    int colum_number;
                    vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number);
                    res = ppBuffer.CreateEditPoint(line_number, colum_number, out object ppEditPoint);
                    EditPoint editPoint = ppEditPoint as EditPoint;
                    // Create class.
                    string member = visitor ? $@"
public override Result {capitalized_member_name}([NotNull] {capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context)
{{
    return VisitChildren(context);
}}
"
                        : $@"
public override void {capitalized_member_name}({capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context)
{{
    base.{capitalized_member_name}(context);
}}
";
                    editPoint.Insert(member);
                    // Redo parse.
                    try
                    {
                        vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path);
                        if (vstv == null)
                        {
                            IVsTextViewExtensions.ShowFrame(class_file_path);
                            vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path);
                        }
                        var        text_buffer = vstv.GetITextBuffer();
                        var        code        = text_buffer.GetBufferText();
                        SyntaxTree tree        = CSharpSyntaxTree.ParseText(code);
                        trees[class_file_path] = tree;
                    }
                    catch (Exception)
                    {
                    }
                    // Redo find class.
                    try
                    {
                        var tree = trees[class_file_path];
                        var save = class_file_path;
                        class_file_path = null;
                        // Look for IParseTreeListener or IParseTreeVisitor classes.
                        var root = (CompilationUnitSyntax)tree.GetRoot();
                        foreach (var nm in root.Members)
                        {
                            var namespace_member = nm as NamespaceDeclarationSyntax;
                            if (namespace_member == null)
                            {
                                continue;
                            }
                            foreach (var cm in namespace_member.Members)
                            {
                                var class_member = cm as ClassDeclarationSyntax;
                                if (class_member == null)
                                {
                                    continue;
                                }
                                var bls = class_member.BaseList;
                                if (bls == null)
                                {
                                    continue;
                                }
                                var   types = bls.Types;
                                Regex reg   = new Regex("[<].+[>]");
                                foreach (var type in types)
                                {
                                    var s = type.ToString();
                                    s = reg.Replace(s, "");
                                    if (s.ToString() == listener_baseclass_name)
                                    {
                                        // Found the right class.
                                        found_class.Add(class_member);
                                        class_file_path = save;
                                        throw new Exception();
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                    try
                    {
                        foreach (var fcc in found_class)
                        {
                            foreach (var me in fcc.Members)
                            {
                                var method_member = me as MethodDeclarationSyntax;
                                if (method_member == null)
                                {
                                    continue;
                                }
                                if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower())
                                {
                                    found_member = method_member;
                                    throw new Exception();
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }

                {
                    // Open to this line in editor.
                    IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path);
                    {
                        IVsTextViewExtensions.ShowFrame(class_file_path);
                        vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path);
                    }

                    IWpfTextView wpftv = vstv.GetIWpfTextView();
                    if (wpftv == null)
                    {
                        return;
                    }

                    int line_number;
                    int colum_number;
                    var txt_span = found_member.Identifier.Span;
                    vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number);

                    // Create new span in the appropriate view.
                    ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot;
                    SnapshotSpan  ss = new SnapshotSpan(cc, txt_span.Start, txt_span.Length);
                    SnapshotPoint sp = ss.Start;
                    // Put cursor on symbol.
                    wpftv.Caret.MoveTo(sp); // This sets cursor, bot does not center.
                                            // Center on cursor.
                                            //wpftv.Caret.EnsureVisible(); // This works, sort of. It moves the scroll bar, but it does not CENTER! Does not really work!
                    if (line_number > 0)
                    {
                        vstv.CenterLines(line_number - 1, 2);
                    }
                    else
                    {
                        vstv.CenterLines(line_number, 1);
                    }
                    return;
                }
            }
            catch (Exception exception)
            {
                Logger.Log.Notify(exception.StackTrace);
            }
        }
Esempio n. 15
0
        private void MenuItemCallback(object sender, EventArgs e)
        {
            try
            {
                ////////////////////////
                // Go to definition....
                ////////////////////////

                SnapshotSpan span      = AntlrLanguagePackage.Instance.Span;
                ITextView    view      = AntlrLanguagePackage.Instance.View;
                ITextBuffer  buffer    = view.TextBuffer;
                var          file_name = buffer.GetFFN().Result;
                if (file_name == null)
                {
                    return;
                }
                var document      = Workspaces.Workspace.Instance.FindDocument(file_name);
                var ref_pd        = ParserDetailsFactory.Create(document);
                var list_location = LanguageServer.Module.FindDef(span.Start.Position, document);
                if (list_location == null || !list_location.Any())
                {
                    return;
                }
                var location = list_location.First();
                var sym      = LanguageServer.Module.GetDocumentSymbol(location.Range.Start.Value, location.Uri);
                if (sym == null)
                {
                    return;
                }
                string      full_file_name = location.Uri.FullPath;
                IVsTextView vstv           = IVsTextViewExtensions.FindTextViewFor(full_file_name);
                {
                    IVsTextViewExtensions.ShowFrame(full_file_name);
                    vstv = IVsTextViewExtensions.FindTextViewFor(full_file_name);
                }
                if (vstv == null)
                {
                    return;
                }
                IWpfTextView wpftv = vstv.GetIWpfTextView();
                if (wpftv == null)
                {
                    return;
                }
                vstv.GetLineAndColumn(sym.range.Start.Value, out int line_number, out int column_number);
                ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot;
                SnapshotSpan  ss = new SnapshotSpan(cc, sym.range.Start.Value, 1);
                SnapshotPoint sp = ss.Start;
                wpftv.Caret.MoveTo(sp);
                if (line_number > 0)
                {
                    vstv.CenterLines(line_number - 1, 2);
                }
                else
                {
                    vstv.CenterLines(line_number, 1);
                }
                AntlrVSIX.Package.Menus.ResetMenus();
            }
            catch (Exception exception)
            {
                Logger.Log.Notify(exception.StackTrace);
            }
        }
Esempio n. 16
0
        private void MenuItemCallback(object sender, EventArgs e, bool forward)
        {
            try
            {
                ////////////////////////
                /// Next rule.
                ////////////////////////

                string       classification = AntlrLanguagePackage.Instance.Classification;
                SnapshotSpan span           = AntlrLanguagePackage.Instance.Span;
                ITextView    view           = AntlrLanguagePackage.Instance.View;

                view = AntlrLanguagePackage.Instance.GetActiveView();
                if (view == null)
                {
                    return;
                }

                ITextCaret    car = view.Caret;
                CaretPosition cp  = car.Position;
                SnapshotPoint bp  = cp.BufferPosition;
                int           pos = bp.Position;

                // First, find out what this view is, and what the file is.
                ITextBuffer buffer = view.TextBuffer;
                string      path   = buffer.GetFFN().Result;
                if (path == null)
                {
                    return;
                }

                List <IToken> where = new List <IToken>();
                List <ParserDetails> where_details = new List <ParserDetails>();
                int next_sym = forward ? Int32.MaxValue : -1;
                foreach (var kvp in ParserDetailsFactory.AllParserDetails)
                {
                    string file_name = kvp.Key;
                    if (file_name != path)
                    {
                        continue;
                    }
                    ParserDetails details = kvp.Value;
                    foreach (var p in details.Defs)
                    {
                        if (p.Value != 0)
                        {
                            continue;
                        }
                        var t = p.Key;
                        if (forward)
                        {
                            if (t.Symbol.StartIndex > pos && t.Symbol.StartIndex < next_sym)
                            {
                                next_sym = t.Symbol.StartIndex;
                            }
                        }
                        else
                        {
                            if (t.Symbol.StartIndex < pos && t.Symbol.StartIndex > next_sym)
                            {
                                next_sym = t.Symbol.StartIndex;
                            }
                        }
                    }

                    foreach (var p in details.Defs)
                    {
                        if (p.Value != 1)
                        {
                            continue;
                        }
                        var t = p.Key;
                        if (forward)
                        {
                            if (t.Symbol.StartIndex > pos && t.Symbol.StartIndex < next_sym)
                            {
                                next_sym = t.Symbol.StartIndex;
                            }
                        }
                        else
                        {
                            if (t.Symbol.StartIndex < pos && t.Symbol.StartIndex > next_sym)
                            {
                                next_sym = t.Symbol.StartIndex;
                            }
                        }
                    }

                    break;
                }

                if (next_sym == Int32.MaxValue || next_sym < 0)
                {
                    return;
                }

                string      full_file_name = path;
                IVsTextView vstv           = IVsTextViewExtensions.FindTextViewFor(full_file_name);
                if (vstv == null)
                {
                    IVsTextViewExtensions.ShowFrame(full_file_name);
                    vstv = IVsTextViewExtensions.FindTextViewFor(full_file_name);
                }

                IWpfTextView wpftv = vstv.GetIWpfTextView();
                if (wpftv == null)
                {
                    return;
                }

                int line_number;
                int colum_number;
                vstv.GetLineAndColumn(next_sym, out line_number, out colum_number);

                // Create new span in the appropriate view.
                ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot;
                SnapshotSpan  ss = new SnapshotSpan(cc, next_sym, 1);
                SnapshotPoint sp = ss.Start;
                // Put cursor on symbol.
                wpftv.Caret.MoveTo(sp); // This sets cursor, bot does not center.
                                        // Center on cursor.
                if (line_number > 0)
                {
                    vstv.CenterLines(line_number - 1, 2);
                }
                else
                {
                    vstv.CenterLines(line_number, 1);
                }
                AntlrVSIX.Package.Menus.ResetMenus();
            }
            catch (Exception exception)
            {
                Logger.Log.Notify(exception.StackTrace);
            }
        }
Esempio n. 17
0
        internal static void FocusLine(IVsTextView viewAdapter, int line, int col) {
            ErrorHandler.ThrowOnFailure(viewAdapter.SetCaretPos(line, col));
            // Make sure that the text is visible.
            int topline = line - 10;
            if(topline < 0)
                topline = 0;

            viewAdapter.SetTopLine(topline);
            viewAdapter.CenterLines(line, 1);

        }