Inside F#

Brian's thoughts on F# and .NET

F# Depth Colorizer for VS2012 now available

Posted by Brian on June 24, 2012

The F# Depth Colorizer for VS2012 makes it easy to see the nesting-depth of your F# code and ensure that control constructs are properly indented.  Compare:


The left screenshot shows how code appears by default.  Are the ‘try’ and ‘with’ keyword aligned?  It can be hard to tell at-a-glance.  The right screenshot has the F# Depth Colorizer installed; small changes in background color at each level of nesting/indent highlight various code blocks and make it easy to see where the indents are.

This extension to Visual Studio 2012 parses F# code as you type and interactively updates the background colorization to match the actual parsed structure of the code.  It understands the full F# 3.0 language syntax.

This extension is a free VSIX on the Visual Studio Gallery, so it is easy to download and try out.  Once installed, it will appear on the Visual Studio 2012 ‘Tools\Extensions and Updates…’ menu:


where you can easily remove it if you decide it’s not for you.

Are you using the new ‘dark’ theme colors in VS2012?  Not a problem, the extension can detect dark default colors, and switches to a more appropriate color set for highlighting in the dark theme:


Like the extension, but don’t like the default colors?  You can change them.  UI is not my strong point, so unfortunately the colors are only configurable via the registry (rather than some pretty color-editor GUI).  Here is the registry entry for the default light-theme colors:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Text Editor\FSharpDepthColorizer\Light]

and dark-theme colors:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Text Editor\FSharpDepthColorizer\Dark]

(You can save these registry examples to a file “foo.reg”, run the “foo.reg” file to install those keys, and then use the “regedit” tool to inspect/change the values. Be careful when modifying your registry!)

The DepthN values are strings of six numbers, representing two sets of RGB values, e.g.

DepthN = R1, G1, B1, R2, G2, B2

where N is the depth of the nesting of the source code structure, the RGB1 values are the color of the left edge of the highlight (intention is to provide more visual contrast at the edge), and the RGB2 values are the main color for highlighting that nesting depth.

Note that this is a new extension specifically designed for VS2012 (currently at the RC ‘Release Candidate’ stage); if you are using VS2010, then you’ll need to use the older version of this tool instead, linked here.

Posted in Uncategorized | Leave a Comment »

Visual F# 3.0 Beta

Posted by Brian on February 29, 2012

The Beta of Visual Studio 11 was published today, which includes the Beta of F# 3.0.  See today’s F# blog for the high-level details.

I’ll hopefully end my blog-drought with a few posts in the coming weeks covering some details about some of the new language features in F# 3.0 and IDE features in VS11.  In the meantime, I’d encourage you to grab the bits and try out F# in VS11 Beta!

Happy F# programming!

Posted in Uncategorized | 1 Comment »

Gotcha explained

Posted by Brian on January 28, 2011

Last time I posted a “gotcha” snippet, asking what this F# code prints:

    type MyVector(x:int, y:int, z:int) =

        // expose the values as an array
        member this.Values = [| x; y; z |]

    let v = new MyVector(1,2,3)
    v.Values.[0] <- 42
    printfn "%d" v.Values.[0]

It prints “1”.  To see why, let’s look at the corresponding C# code, in all its verbosity:

    class MyVector

        int x, y, z;
        public MyVector(int x, int y, int z)
            this.x = x;
            this.y = y;
            this.z = z;
        // expose the values as an array
        public int[] Values
            get { return new[] { x, y, z }; }
    class Program
        static void Main(string[] args)
            var v = new MyVector(1, 2, 3);
            v.Values[0] = 42;

The C# code, being more explicit, makes things a little more obvious.  “Values” is a getter property, whose body creates a new array, and so every time you refer to “.Values”, a fresh array is created that contains the 3 integers that were passed into the constructor.  So the line that assigns the value 42 assigns it into a fresh array that is then immediately dropped on the floor.

This probably isn’t what is desired.  If we want “Values” to expose a single instance of a mutable array, then we can easily do so, by creating that array instance in the class constructor and returning that same instance each time people refer to the property.  In C#:

    class MyVector

        int[] a;
        public MyVector(int x, int y, int z)
            this.a = new[] { x, y, z };
        // expose the values as an array
        public int[] Values
            get { return a; }
    class Program
        static void Main(string[] args)
            var v = new MyVector(1, 2, 3);
            v.Values[0] = 42;

and in F#:

    type MyVector(x:int, y:int, z:int) =

        let a = [| x; y; z |]
        // expose the values as an array
        member this.Values = a

    let v = new MyVector(1,2,3)
    v.Values.[0] <- 42
    printfn "%d" v.Values.[0]

I see people occasionally stumble on this in a variety of ways; the fact that F# property getter syntax (and overall syntax) is so succinct makes it easier to forget that the body of the member is code that will run each time the member is referenced.  One-time initialization should be moved to the constructor (the let/do section prior to the members; see this blog for a primer on the F# class/interface syntax).

Every language has its own little gotchas; at work those on the C# team still fall into the trap described here, and so it is fun to josh each other about the minor warts in our respective languages.  :)

Posted in Uncategorized | 4 Comments »

Come work on F#!

Posted by Brian on January 26, 2011

In case you haven’t heard, the F# team is hiring.  Want to work in Redmond as an F# developer, or a program manager, or a different developer?  (Or perhaps just search with keyword “F#”, for other F#-related jobs at Microsoft.)  See also Don’s blogs for info on applying.  There’s also a contract position in the UK for applied F#.

Since I dislike code-free blogs, I’ll leave you with a quick code snippet.  Ask yourself, what does this code print?  (Then try it.)

    type MyVector(x:int, y:int, z:int) =

        // expose the values as an array
        member this.Values = [| x; y; z |]

    let v = new MyVector(1,2,3)
    v.Values.[0] <- 42
    printfn "%d" v.Values.[0]

A hint: it illustrates a “gotcha” people sometimes hit when first learning the syntax for writing F# property getters.

Posted in Uncategorized | 4 Comments »

Source code for F# XmlDoc extension

Posted by Brian on December 4, 2010

I’ve just published the code for another VSIX extension; this one auto creates xml documentation boilerplate when you type triple-slash.  For example, if you have the code:

type SomeType() =
     member this.Foo(x:int, s:string) = 
         printfn "%d: %s" x s

and you type “///” anywhere on the blank line before “Foo”, then you get

type SomeType() =
     /// <summary>
     /// </summary>
     /// <param name="x"></param>
     /// <param name="s"></param>
     member this.Foo(x:int, s:string) = 
         printfn "%d: %s" x s

with your cursor sitting conveniently between the summary tags.  And if instead you type “///” above the type declaration, you get

/// <summary>
/// </summary>
type SomeType() =
     member this.Foo(x:int, s:string) = 
         printfn "%d: %s" x s

Get the idea?  Just type “///” on a blank line right before a member, type, or module-scoped let (before any attributes, if there are any), and you get a blank xmldoc template (if there wasn’t already an xmldoc there).

I don’t plan to put this one on the gallery, as I’m not too interested in maintaining it.  You can grab the the source from github, set the VSIX project as the startup project, and build it yourself.  (If someone is interested in refining/publishing it, you can contact me directly.) 

The source code is simple, and structured just like my previous extension.  There are two projects. “MyFSParser” is (again) just the parser code ripped from the F# compiler, with about 130 new lines of code at the end of MyParsing.fs that computes information about every xml-doc-able entity in a file.  “FSXmlDocVSIX” is the editor extension that, in a mere 120 lines of code in Program.fs, intercepts keypresses and does some special logic when you press ‘/’ to see if you just typed “///” on a blank line above an xml-doc-able, and if so, dumps extra stuff into your editor buffer.  It’s really simple; if you ever wanted to look at a straightforward extension to the Visual Studio editor, this is a good code sample.

Posted in Uncategorized | 4 Comments »

Source code for F# Depth Colorizer extension

Posted by Brian on November 21, 2010

I’ve published the source code for the F# Depth Colorizer.  You can get the code from github.  The code is available under the Apache 2.0 License.

Here’s a quick overview of what’s there.  There is a Visual Studio 2010 solution with two projects. 

  • The “MyFSParser” project is a library that parses F# source code and yields “range” information about where source code constructs begin and end.  It is basically a free-standing version of the front half of the F# compiler, followed by about 350 lines of my own code for munging and publishing range information from the abstract syntax tree (AST) produced by the F# compiler front end.
  • The “VSIXColorizer” project is a Visual Studio extension that plug into the editor, listens for changes in the test buffer, re-parses the source, gets the range information, tags editor ‘spans’ with the semantic depth information, and then draws adornments on the screen for the portions of the file in view.  It’s also about 350 lines of code.

Of course all the code is written in F#.  This is a nice sample that demonstrates both the simple Visual Studio extensibility model that makes it easy to craft editor extensions, as well as the kinds of things you can do when you leverage the F# compiler source to do the “heavy lifting” to parse F# code for you.

In order to provide a little more guidance, I made a couple screencasts, about 10 minutes each, where I give a (rambling) walkthrough of each of the projects.  You won’t learn all the fine details about how the compiler code or my code works, but you will get an overview of the structure and see some of the important methods/functions and how the pieces fit together.  Here is the video about the parser and here is the video about the colorizer.

I’ve already started working on another editor extension that reuses the parser library code, and so in another week or two hopefully I’ll share that too.  I hope this is good “seed code” to help you leverage the F# compiler source and Visual Studio extensibility to do your own cool stuff!

Posted in Uncategorized | 6 Comments »

A quick standalone app to edit colors for the F# colorizer

Posted by Brian on November 20, 2010

What kind of fool posts a cool extension for colorizing F# source code structure, but then only lets you configure the colors by editing the registry (and then having to restart Visual Studio to see if the new colors look ok)?

Oh, that was me.  :)

Like I said in the previous blog, I don’t have the skills to design a good GUI to edit the colors or figure out the most discoverable place in VS to edit them.  But maybe you do!  And so in the spirit of sharing source, here’s a crummy (but working) standalone app for experimenting with the colors.  A screenshot is suggestive:


Basically, you can click on one of the rectangles, and then use the buttons to change the R/G/B values of the left-edge color or the main color.  And once you have colors you like, you can click a different button which prints out a .reg file you can use to install those colors.  (The app only reads the registry, it does not write it, so you have to copy-paste the text from the console window, save it to a .reg file, and run it if you want to install your updated colors.)

Anyway, the code is below.  Just throw this in an F# Console Application, add references to the WPF assemblies (PresentationCore, PresentationFramework, System.Xaml, System.Xml, UIAutomationTypes, and WindowsBase), press Ctrl-F5 to build and run and you’re off to the races.  Feel free to steal all this code to build your own better app/extension, or just to use to build your own attractive color schemes.  The code is just a quick ugly hack, but hopefully you can work with it.

And yes, I’ll be releasing the code for the actual editor colorizer extension soon, I just want to finish tidying it up a little.  (Thanks to those who have already left feedback and pointed out minor bugs!)

Quickie code for app to manage editing colors:

open System.Windows 
open System.Windows.Controls
open System.Windows.Data
open System.Windows.Media 
open System.Windows.Shapes 
open Microsoft.Win32 
type IIndexable<'a> =
    abstract member Item : int -> 'a
let makeBinding(sourceObj:obj, sourcePath:string, converter:'T->'U, 
                targetObj:DependencyObject, targetDependencyProperty:DependencyProperty) =
    let b = new System.Windows.Data.Binding()
    b.Source <- sourceObj
    b.Path <- new System.Windows.PropertyPath(sourcePath)
    b.Converter <- 
        { new System.Windows.Data.IValueConverter with
            member this.Convert(v, targetType, param, culInfo) =
                box(converter (unbox v))
            member this.ConvertBack(v, targetType, param, culInfo) =
                raise <| new System.NotImplementedException() }
    BindingOperations.SetBinding(targetObj, targetDependencyProperty, b) |> ignore
type MyWindow() as this =
    inherit Window()
    static let selectedRectangleNumber = 
        DependencyProperty.Register("SelectedRectangleNumber", typeof<int>, typeof<MyWindow>, 
            new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender, 
                new PropertyChangedCallback(fun depObj ea -> 
                    match box depObj, box ea.NewValue with 
                    | (:? MyWindow as w), (:? int as x) -> w.TriggerSelectedRectangleNumberChanged(x) 
                    | _ -> ())))
    let selectedChanged = new Event<Handler<int>,int>()
    let getNum() = this.GetValue(MyWindow.SelectedRectangleNumber) :?> int
    let setNum(n) = this.SetValue(MyWindow.SelectedRectangleNumber, n)
    let colors =
            let key = Registry.CurrentUser.OpenSubKey(
                @"Software\Microsoft\VisualStudio\10.0\Text Editor\FSharpDepthColorizer")
            Array.init 10 (fun i -> key.GetValue(sprintf "Depth%d" i) :?> string)
            |> (fun s -> let [|r1;g1;b1;r2;g2;b2|] = s.Split[|','|] |> byte
        with e ->
            [|  // greyscale colors
    // why the SolidColorBrush below? 
    // to have a DependencyObject to data-bind... there is probably a cleaner way, but oh well
    let edgeColors = colors |> (fun (r,g,b,_,_,_) -> SolidColorBrush(Color.FromRgb(r,g,b)))
    let mainColors = colors |> (fun (_,_,_,r,g,b) -> SolidColorBrush(Color.FromRgb(r,g,b)))
    let brushes = 
        let makeGradientStop(b:SolidColorBrush, pct) =
            let gs = new GradientStop(b.Color, pct)
            makeBinding(b, "Color", (fun (c:Color) -> c), gs, GradientStop.ColorProperty)
        { new IIndexable<Brush> with 
            member this.Item depth =
                upcast new LinearGradientBrush(
                    new GradientStopCollection( 
                        makeGradientStop(edgeColors.[depth], 0.0)
                        makeGradientStop(mainColors.[depth], 0.01)
                        makeGradientStop(mainColors.[depth], 1.0)
                        |] ), new Point(0.0, 0.5), new Point(1.0, 0.5)) }
    let printCurrentSettings() =
        printfn "Windows Registry Editor Version 5.00"
        printfn ""
        printfn "[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor\FSharpDepthColorizer]"
        for i in 0..9 do
            let ec = edgeColors.[i].Color
            let mc = mainColors.[i].Color
            printfn "\"Depth%d\"=\"%d,%d,%d,%d,%d,%d\"" i ec.R ec.G ec.B mc.R mc.G mc.B 
    let mkButton(colors:SolidColorBrush[], text, dr, dg, db) =
        let b = new Button()
        b.Content <- text
        b.Click.Add(fun _ -> colors.[getNum()].Color <- 
                                Color.FromRgb(colors.[getNum()].Color.R + byte dr, 
                                              colors.[getNum()].Color.G + byte dg, 
                                              colors.[getNum()].Color.B + byte db))
    let mkButtonPanel(colors:SolidColorBrush[],text,dr,dg,db,f) =
        let panel = new StackPanel(Orientation = Orientation.Horizontal)
        let tb = new TextBlock()
        selectedChanged.Publish.Add(fun _ ->
            makeBinding(colors.[getNum()], "Color", (fun (c:Color) -> f(c).ToString()), 
                        tb, System.Windows.Controls.TextBlock.TextProperty))
        panel.Children.Add(mkButton(colors, text+" down",-dr,-dg,-db)) |> ignore
        panel.Children.Add(tb) |> ignore
        panel.Children.Add(mkButton(colors, text+" up",dr,dg,db)) |> ignore
        let leftPanel = new StackPanel(Orientation = Orientation.Vertical)
        leftPanel.Children.Add(mkButtonPanel(edgeColors,"edge R",2,0,0,(fun c->c.R))) |> ignore
        leftPanel.Children.Add(mkButtonPanel(edgeColors,"edge G",0,2,0,(fun c->c.G))) |> ignore
        leftPanel.Children.Add(mkButtonPanel(edgeColors,"edge B",0,0,2,(fun c->c.B))) |> ignore
        leftPanel.Children.Add(mkButtonPanel(mainColors,"main R",2,0,0,(fun c->c.R))) |> ignore
        leftPanel.Children.Add(mkButtonPanel(mainColors,"main G",0,2,0,(fun c->c.G))) |> ignore
        leftPanel.Children.Add(mkButtonPanel(mainColors,"main B",0,0,2,(fun c->c.B))) |> ignore
        let printButton = new Button(Content="Print current settings to console")
        printButton.Click.Add(fun _ -> printCurrentSettings())
        leftPanel.Children.Add(printButton) |> ignore
        let mainPanel = new StackPanel(Orientation = Orientation.Horizontal)
        mainPanel.Children.Add(leftPanel) |> ignore
        let canvas = new Canvas()
        for i in 0..mainColors.Length-1 do
            let rect = new Rectangle(Width=600., Height=500., Fill = brushes.[i])
            rect.MouseDown.Add(fun _ -> setNum(i))
            Canvas.SetLeft(rect, (float i)*30.)
            Canvas.SetTop(rect, (float i)*30.)
            Canvas.SetZIndex(rect, i)
            canvas.Children.Add(rect) |> ignore
        let rect = new Rectangle(Width=600., Height=40.)
        selectedChanged.Publish.Add(fun _ -> rect.Fill <- brushes.[getNum()])
        Canvas.SetLeft(rect, 0.)
        Canvas.SetTop(rect, (float mainColors.Length)*30. + 20.)
        Canvas.SetZIndex(rect, mainColors.Length)
        canvas.Children.Add(rect) |> ignore
        mainPanel.Children.Add(canvas) |> ignore
        this.Content <- mainPanel
    member private this.TriggerSelectedRectangleNumberChanged(x:int) = selectedChanged.Trigger(this, x)
    static member SelectedRectangleNumber = selectedRectangleNumber 
    (new Application()).Run(MyWindow()) |> ignore

Posted in Uncategorized | 4 Comments »

F# source code structural colorizer available

Posted by Brian on November 18, 2010

Last week I mentioned the editor extension I am working on, and now it’s available for you to try out!  You can obtain the F# Depth Colorizer from the Visual Studio Gallery.  It’s a one-click install; once installed you’ll see it listed when you bring up the “Tools\Extension Manager” menu in Visual Studio:


Once installed, the structure of your code will be highlighted in the editor, like this


or like this


rather than plain old code like this


Get the idea?  As suggested by the first two screenshots, the colors are configurable.  A good UI for configuring the colors was beyond me, so the colors are configurable via a registry setting.  (EDIT: see also here) If you don’t have the registry entry, you get the “greyscale” colors from the first screenshot by default.  Those greyscale colors could be represented via the following registry entry:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor\FSharpDepthColorizer]

Alternatively, the red-blue colors from the second screenshot are:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor\FSharpDepthColorizer]

and more generally, the extension will look for the those registry keys.  (You can save these registry examples to a file “foo.reg” and then run the “foo.reg” file to install those keys, or use the “regedit” tool to inspect/change the values.  Be careful when modifying your registry!)

The DepthN values are strings of six numbers, representing two sets of RGB values, e.g.

DepthN = R1, G1, B1, R2, G2, B2

where N is the depth of the nesting of the source code structure, the RGB1 values are the color of the left edge of the highlight (intention is to provide more visual contrast at the edge), and the RGB2 values are the main color for highlighting that nesting depth.  There must be 10 depths, if you go deeper, the tool cycles around:


where the colors are getting darker until it’s gone 10 deep and cycles back around to using the lightest pink color from that color set.

I’ll publish the source code for this VSIX extension soon. (EDIT: It’s posted, see here.)   For now, I’d encourage you to try it out; you can leave feedback on my blog or on the gallery.  Enjoy!

(Much thanks to Noah who helped me write the editor portion of the extension.  Thanks to many people who did beta testing and offered useful feedback.)

Posted in Uncategorized | 14 Comments »

The F# compiler source release: making it easy to write cool Visual Studio extensions

Posted by Brian on November 12, 2010

In case you’ve been hiding under a rock and haven’t heard, the F# compiler was recently released under the Apache 2.0 license; see Don’s blog for the details.  This source code release gives you the freedom to use the F# compiler code how you like, and so of course as a developer who likes using Visual Studio, I decided to take a crack at a Visual Studio extension that I’ve always wanted to write.

The basic idea is an editor extension that uses background colorization to show the “control flow depth” of F# code.  A screenshot is a little suggestive:


but in order to really describe it, I made a video (about 6 minutes long), linked below.

The idea is simple; the F# compiler code already knows how to do all the heavy lifting of parsing source code and creating a parse tree (an abstract syntax tree, or “AST”), and the AST knows all the info about code structure and e.g. that this expression starts in this line/column and ends in this other line/column.  So I just take the tree and turn it into some useful “depth and span” information, which I then use from a Visual Studio editor extension to add color adornments in the editor.

This is still under development, but I plan to publish the extension on the Visual Studio Gallery, and publish the source code when I’m done.

Anyway, check out the video here.  I’m interested to hear what people think, and hope this inspires others to try their hand at leveraging the F# compiler code to write cool tools and extensions.

Posted in Uncategorized | 4 Comments »

PDC is just around the corner…

Posted by Brian on October 26, 2010

For those of you attending Microsoft’s Professional Developers Conference, I hope you’ll stop by the F# “Ask the Experts” table at lunchtime on Thursday or Friday to say hello and ask some interesting questions about F#!  For those of you who won’t be in Redmond this week, all of the PDC content can be watched live online (or recorded afterwards), so there’s no reason for you to miss out on all the great talks.

Don’s F# talk entitled “The Future of F#: Data and Services at your Finger Tips” is scheduled during the final timeslot on Friday afternoon, so of course readers of this blog will want to check that out.  Windows Phone 7 will be another hot topic at PDC; I have been trying really hard to get my hands on a phone, so that I can show off some F# apps running on the phone at the Experts table, but so far I’ve only met dead ends.  I’ve still got another 36 hours or so, and I haven’t given up on that yet.  Smile

Regarding general F# news… I recently saw F# get some love on HackerNews, and PDC will be sure to generate some more F# buzz this week.  And I think perhaps there’s some more F# news in store soon after PDC as well.  So now is a good time to have your finger on the pulse of the F# community; Planet F# or Rick Minerich’s blog are good ways to keep up with the F# highlights.  On the other hand, if you’re relatively new to the world of F#, you might prefer reading Getting started with F#.

In completely unrelated news, I recently posted an answer to Best explanation for Languages without Null on StackOverflow that has easily become my highest-upvoted-answer ever.  Undoubtedly the large bounty on the question helped attract eyeballs… regardless of why, I’m pleased that my thoughts on this topic garnered so much attention.  (It makes up at least a tiny bit for my lack of substantive blogging of late; this is my fifth post in a row that’s light on code or novel ideas.  I hope to have some meatier/code-ful topics to blog about soon.)

Enough rambling for now – enjoy PDC this week!

Posted in Uncategorized | 3 Comments »