public int OnAfterOpenSolution(object aPUnkReserved, int aFNewSolution) { Workspaces.Loader.LoadAsync().Wait(); var to_do = LanguageServer.Module.Compile(); foreach (var t in to_do) { var w = t.FullFileName; IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(w); if (vstv == null) { continue; } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { continue; } var buffer = wpftv.TextBuffer; var att = buffer.Properties.GetOrCreateSingletonProperty(() => new AntlrVSIX.AggregateTagger.AntlrClassifier(buffer)); att.Raise(); } return(VSConstants.S_OK); }
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); } }
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); } }
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); } }
private void RenameCallback(object sender, EventArgs e) { try { // Highlight the symbol, reposition it to the beginning of it. // Every character changes all occurrences of the symbol. SnapshotSpan span = AntlrLanguagePackage.Instance.Span; int curLoc = span.Start.Position; var buf = span.Snapshot.TextBuffer; var file_name = buf.GetFFN().Result; if (file_name == null) { return; } var document = Workspaces.Workspace.Instance.FindDocument(file_name); var ref_pd = ParserDetailsFactory.Create(document); if (ref_pd == null) { return; } var sym = LanguageServer.Module.GetDocumentSymbol(curLoc, document); if (sym == null) { return; } var locations = LanguageServer.Module.FindRefsAndDefs(curLoc, document); List <SnapshotSpan> wordSpans = new List <SnapshotSpan>(); var results = new List <Entry>(); foreach (var loc in locations) { if (global::Options.POptions.GetBoolean("RestrictedDirectory")) { string p1 = System.IO.Path.GetDirectoryName(file_name); string p2 = System.IO.Path.GetDirectoryName(loc.Uri.FullPath); if (p1 != p2) { continue; } } var w = new Entry() { FileName = loc.Uri.FullPath, Start = loc.Range.Start.Value, End = loc.Range.End.Value }; results.Add(w); } // Call up the rename dialog box. In another thread because // of "The calling thread must be STA, because many UI components require this." // error. Application.Current.Dispatcher.Invoke((Action) delegate { RenameDialogBox inputDialog = new RenameDialogBox(sym.name); if (inputDialog.ShowDialog() == true) { var new_name = inputDialog.Answer; var files = results.Select(r => r.FileName).OrderBy(q => q).Distinct(); foreach (var f in files) { var per_file_results = results.Where(r => r.FileName == f); per_file_results.Reverse(); var fitem = Workspaces.Workspace.Instance.FindDocument(f); var pd = ParserDetailsFactory.Create(fitem); IVsTextView vstv2 = IVsTextViewExtensions.FindTextViewFor(f); if (vstv2 == null) { // File has not been opened before! Open file in editor. IVsTextViewExtensions.ShowFrame(f); vstv2 = IVsTextViewExtensions.FindTextViewFor(f); } IWpfTextView wpftv2 = vstv2.GetIWpfTextView(); ITextBuffer tb = wpftv2.TextBuffer; using (var edit = tb.CreateEdit()) { ITextSnapshot cc2 = tb.CurrentSnapshot; foreach (var e2 in per_file_results) { SnapshotSpan ss2 = new SnapshotSpan(cc2, e2.Start, 1 + e2.End - e2.Start); SnapshotPoint sp2 = ss2.Start; edit.Replace(ss2, new_name); } edit.Apply(); } } } }); //AntlrVSIX.Package.Menus.ResetMenus(); } catch (Exception exception) { Logger.Log.Notify(exception.StackTrace); } }