VS2010 Extensibility: Custom document formatting - c#

Good afternoon,
I've created a visual studio package that registers the Verilog language as a valid content type.
I've got syntax highlighting, outlining, smart indenting, etc all working.
However, I would like to be able to get Visual Studio to automatically format the entire document via Edit->Advanced->Format Document/Selection. Currently these options are invisible, and I expect that I have to let VS2010 know (somehow) that these methods can be called, and provide the correct methods to do this formatting.
I can't seem to find any reference to formatting in the VS2010 SDK and documentation. I was hoping that ISmartIndent would be the solution I was looking for, but it seems that this code only runs on an empty line, or when the enter key is pressed.
Does anyone have any tips or ideas on how I can solve this problem?
Thanks,
Giawa
Edit: I'm using the managed extension framework introduced with VS2010 to accomplish this. I'm writing in C# (and just added the c# tag to my question). Thanks

MEF is not the right way to accomplish the task of creating a language service. Instead, the Managed Package Framework (MPF) should be used to register the language service and perform tasks such as syntax highlighting, outlining, parsing, formatting, parsing, etc.
Since my question was about formatting, I'll cover a little bit of it in my answer. You must override the ReformatSpan method in the custom Source object that you've creating for your language service. There's a good example on the MSDN webpages for VS2005 (applicable to VS2010 as well).
You can also force formatting at any time by calling the ReformatSpan method directly. Here's a working example from my code:
Region region = service.GetRegionContainingLine((line > 0 ? line - 1 : 0));
if (region != null)
{
using (EditArray mgr = new EditArray(this, service.LastActiveTextView, true, "Reformat Brace"))
this.ReformatSpan(mgr, region.ToSpan());
}
Thanks to #James McNellis for pointing me in the correct direction.

Here you go: http://msdn.microsoft.com/en-us/library/ee197665.aspx

Related

How / Why can visual studio give suggestions / hints while making a Regex string?

First, a little context as to what I mean. I've recently started learning some basics of Regex and wanted to try it in .NET. In Visual Studio 2019, while working in C#, I can make a Regex object. I was astonished and amazed when I saw that Visual Studio is actually giving me hints as to the syntax of the "Regex language" (so to speak), which it will also color appropriately. Here is a picture of what I mean:
With that in mind, my questions is: Does this happen just because it is built-in to Visual Studio, to show this when editing this particular argument of Regex? Or, if not, how and where exactly is it stated how it should give hints for the string? Is it some sort of advanced <Summary> like tagging?
Can I, for example, implement something like that for my classes so that custom hints are given out when making strings in my classes' methods?
Actually, what you saw is all the Intellisense that VS provides for Regex expressions.
And Intellisense that VS itself provides to the Regex expression is limited. And those are all.
Besides, Intellisense is a built-in tool of VS and we cannot get an easy way to change the build-in tool of VS unless you write your own vs extension that extends the Intellisense.
As a suggestion, you can search on the VS Marketplace to search if anyone has published such extension.
I have found that Resharper extension(It is a paid extension but the new user can use 30 days for free) has a powerful feature for Regex expressions.
See this document. It provides the better Intellisense and also has the feature to verify the regular expression.
In addition, if these still do not meet your requirements and you want to add some custom features, I suggest you could suggest a feature about your ideas to the DC Forum.
Also, you can share the link here and anyone including us will vote it so that it will get more Microsoft's attention.

how to use C# compiler to analyze text in a textbox? (possible lexical analysis)

Im writing a simple code editor just like visual studio code editor.
btw i have a textbox and wanna know how can i underline syntactical errors?
i`v searched the web, but did not find something usefull. any one got any refernce of documentation for C# compiler to help me in this topic?
thanks all and sorry for my bad english..
If you're doing this for a real-world scenario, there are good commercial options available. You need to look at using the CodeDom classes which can take your input text and convert it into an object model which can then be compiled into an assembly.
If there are compiler errors, they will be returned as a collection of CompilerError objects. These will tell you the line number, character number, and error message, so you can display the error.
There are significant drawbacks to using CodeDom, however. It is older technology and has not been updated to keep pace with the language changes so there are limitations in what it can parse. If you want to write your own parser, you need to look at language tools like lexx and yacc or Roslyn.
With a simple textbox control you certainly cannot do that. At least you need to use a RichTextBox control (comes in a variety of flavors, for WPF, WinForms, from Office...), to do some code formatting. As a first exercise, I would suggest you try to color keywords in your editor. That's a fairly easy task (and error recovery is not a problem) and may show you how to use the control.

Syntax Highlighting of an Embedded Language in Visual Studio 2012

I'm using C# and Visual Studio 2012 to implement syntax highlighting of a language embedded in html (much like ASP code inside <% %>). So far, I've found out that I need to use IProjectionBuffer to achieve this, but there are no examples of how to do this using MEF, apart from a somewhat vague description here: http://msdn.microsoft.com/en-us/library/dd885240.aspx#projection. I tried to assign spans of text from the ITextBuffer that is "imported" through MEF to an IProjectionBuffer, but it had no effect.
Does anybody have any ideas as to how to proceed?
There is a built in feature for this purpose I think. I used to deal with text highlighting in C# code with MEF with tags. I think you shold start with Text.Classification.
There is a lack of documentation sadly, but I think you should build a lexer or somthing similar for the lingual part MSDN:DLR (features) may can help you,
The DLR allows language implementers to avoid creating lexical
analyzers, parsers, semantic analyzers, code generators, and other
tools that they traditionally had to create themselves.
detect the delimiters, and color it through classification.
Here is an example project to customize C# code displaying.

Development of simple C# application for understanding Resharper Open APIs

I wanted to start developing plugins for Resharper using its Open API.
As there is very less documentation available, for starters I wanted to develop a simple C# application to extract the class details (eg. class name, number of methods in a class etc), so that I can understand the working of Resharper library and the in-built functions it provides.
It would be ideal if I can extract these details and print it on the console, for ease of testing.
Thanks.
in terms of documentation, there is some info available on the Developer Wiki, with more to come. You might also want to check out the ReSharper Extensibility Guide, which is a bit oudated but still relevant.
As for your question of how to examine the file structure - guess what - you don't even need the API! Here's what you need to do:
Start Visual Studio using the /ReSharper.Internal key. This will enhance the ReSharper top-level menu with an Internal section.
Pick ReSharper-->Internal-->PSI Viewer. This will pop up a form similar to the following:
Now, click the Create button, which will let you create a file, statement, expression or member declaration.
The bottom pane will then illustrate the parsed structure and let you navigate it.
Good luck!
If you want to parse the code yourself, that's a bit more complicated. The following is a rough outline of how you could go about parsing a file.
var buffer = new StringBuffer(sourceCode);
var lexer = LexerFactory.CreateLexer(buffer);
var defines = EmptyArray<PreProcessingDirective>.Instance; // assume there are none
var parser = new CSharpParser(lexer, defines);
var file = parser.ParseFile() as CSharpFile;
Now you can use file to navigate the code structure.
BTW, I strongly recommend using F#. It's made for this sort of thing.

How to quickly code and run small C# code

There are times when I want to test new code from the forums or when I need to help my friends with specific C# problem. The problem is I don't want to create new "project" in Visual Studio each time just to code/run only this small code.
Java & Eclipse IDE comes up with "Scrapbook" feature which allows the execution of arbitrary Java expressions. What are the choices for C# programmers?
Snippet Compiler is great for this.
LINQPad is also good for testing out all sorts of C#, F# or VB code, not just LINQ queries.
EDIT
I suppose it's time that I mention that Snippet Compiler hasn't been updated in over five years, and is therefore no longer the best option.
However, I undersold LINQPad originally. As Will Dean mentioned in the comments, LINQPad is excellent for all sorts of code, not just LINQ queries. In fact, it has become an indispensable tool for me. I use it daily, not only to quickly test out short snippets, but for relatively complex mini programs. Its advanced output formatting makes it extremely easy to quickly examine intermediate and final results.
A bit late to the party, but I came here while searching for this myself.
The best suitable solution for me was using the C# Interactive-window inside Visual Studio 2015 or later.
You can access it by opening it via View > Other Windows > C# Interactive, or by selecting some c# code and clicking on Execute in Interactive in the right-click context menu.
Here is a link on how to use it: http://dailydotnettips.com/2016/01/12/use-c-interactive-window-for-your-coding-experiment-in-visual-studio-2015/
I know it works in VS2015, I don't think it works in older versions.
The website .NET Fiddle seems like a nice option. It has code completion, code timing, and NuGet Package integration.
From their site:
We are a group of .NET developers who are sick and tired of starting
Visual Studio, creating a new project and running it, just to test
simple code or try out samples from other developers.
This tool was inspired by http://jsfiddle.net, which is just awesome.
In particular, I recommend trying out their MVC mode. On the left side of the screen choose Project Type: MVC.
Here's what I do:
Go to Tools->Options->ProjectsAndSolutions, and disable "Save new projects when created".
Fire up a new VS, Ctrl-Shift-N to create a project, and use that.
Use C# Express to have something that launches more quickly and has less clutter, but still enough power to do most things.
I usually use csc directly from the command line
C:\Users\Greg>csc /o- /debug+
Test.cs
You can run a lot of things in the Immediate window (Debug >> Windows >> Immediate)
For example, you can run the following:
System.IO.File.WriteAllText(#"c:\temp\blah.txt", "Hi there!");
Check also Snippy and the Snippy Addin for Reflector
There's also the interactive C# shell, built on top of Mono:
http://mono-project.com/CsharpRepl
That's similar to what other languages have (for example, irb with Ruby)
Have a look at Introducing the Microsoft “Roslyn” CTP.
The "C# Interactive" window is perfect for this.
Late in here, but if you also want to share the code with others, then .NET Fiddle is the best I have tried so far. For offline solutions, LINQPad definitely would have my vote as well, and not just for LINQ queries.
I just use the scratch console application project that I've defined for just this purpose. I cut out whatever is in the main program and go to town. If I decide that I need to keep whatever I've prototyped, I create a new project and copy to it. Since I do this all the time, the project's always in my recent-projects list, too.
I use a batch file (csc.bat):
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc %1 %2 %3 %4 %5 %6 %7 %8 %9
For vb.net I use this batch file(vbc.bat):
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\vbc %1 %2 %3 %4 %5 %6 %7 /r:system.windows.forms.dll /r:system.data.dll /r:system.dll
For example: C:>csc testit.cs
Each will create a .net .exe file.
This solution is not so good for Windows Forms applications, however.
RoslynPad - nice lightweight open-source alternative to LINQPad.
RoslynPad, https://roslynpad.net/
GitHub: https://github.com/aelij/RoslynPad
This is something I've never liked about visual studio. One thing (and probally the only thing) I miss from VB6 was the ability to create a project, and run it without saving it or anything. Was great for just what you said.
I typically have at least one or two scrap projects of each type, (Console, Winforms, and Web), that I just rotate and use. This way I'm not always creating new projects.
you could have a look into C# Scripting.
C# scripting
this is ment to allow you to build fast scripts without the use of the IDE.
HTH
bones
I always keep a copy of Express Edition running; this can execute and debug projects without needing a proper file location (as long as you don't hit save). Does the job for me...
Try SharpDevelop. It doesn't contain everything, but is good for quick examples. You can open a solution and easily swap out the code to test something else. In the project properties you can change a solution from console to window app via a combobox selection. You can easily translate your code from C# to Boo, Python, Ruby or VB, or from any of these languages to another, starting with whatever your source is. Therefore, if you go looking for a problem solution on the web and can't find one in VB - but do find one in C#, you may be able to convert it.
There is an online web C# compiler and executor: http://www.compileonline.com/compile_csharp_online.php
You can try using ScriptCS. It uses the Roslyn compiler to create a scripting language using C#.
Visual Studio should be a better choice, but it is too heavy. Some simple tests, I often try here.
https://learn.microsoft.com/zh-cn/learn/modules/csharp-write-first/2-exercise-hello-world
or use linqpad and vscode
https://www.linqpad.net/
https://code.visualstudio.com/

Categories