简体   繁体   中英

Format Document for F#

I'd like to format the document: give it indentation and stuff like that.

Ctrl K + Ctrl D/F in Visual Studio doesn't work for F#, does anybody have any workaround for that? It does work for C# though...

EDIT: What I'd like to do is to copy-paste some code from an external source. I usually use Ctrl K + Ctrl D to format it, and it works for C#. However, in an .fs file, it doesn't seem to work. On top of that, indentation seems to be pretty much a must-have for F#...

F# is indentation sensitive, so if you copy valid code from one location to another, the only thing that you might need to do is to make sure it has the right offset from the left side. For example, say you have:

let test () = 
  printfn "Hello world" // (*)

let another () = 
  for i in 0 .. 10 do
    test()              // (#)
  printfn "finished"

Now, if you wanted to copy the line (*) and use it instead of a call to test , just Copy & Paste would turn your code into the following:

let another () = 
  for i in 0 .. 10 do
  printfn "Hello world" // (*)
  printfn "finished"

This has a different meaning though! It repeates both of the printfn lines 10 times. So, instead what you would want to get is this:

let another () = 
  for i in 0 .. 10 do
    printfn "Hello world" // (*)
  printfn "finished"

The way to do Copy & Paste in Visual Studio to keep the same meaning of code is to paste the copied code as usual ( Ctrl + V ) and then, while the code is still selected, correct the indentation. To indent the code further use Tab and to indent it less far use Shift + Tab .

This way, you can use Copy and Paste for F# code just fine. You do not need to reformat the entire block, because valid F# code copied to another place will automatically be well formatted. You just need to fix the indentation.

Regarding the #light mode mentioned in comments - in earlier versions of F#, it was possible to use additional keywords and semicolons instead of indentation-sensitive mode. The modern indentation-sensitive style was called #light , but it is now default and you do not need to worry about the legacy style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM