Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FSharpTextEditorCompletion.fs « MonoDevelop.FSharpBinding « fsharpbinding « external « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a04a5ac1ce1d0084440dd549a17d8c5d77d92ebf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
// --------------------------------------------------------------------------------------
// Provides IntelliSense completion for F# in MonoDevelop
// (this file implements MonoDevelop interfaces and calls 'LanguageService')
// --------------------------------------------------------------------------------------
namespace MonoDevelop.FSharp

open System
open System.Collections.Generic
open System.Text.RegularExpressions
open System.Threading.Tasks
open Microsoft.CodeAnalysis.Text
open Microsoft.FSharp.Compiler.SourceCodeServices
open MonoDevelop
open MonoDevelop.Core
open MonoDevelop.FSharp.Shared
open MonoDevelop.Ide
open MonoDevelop.Ide.CodeCompletion
open MonoDevelop.Ide.Editor
open MonoDevelop.Ide.Editor.Extension
open MonoDevelop.Ide.Gui
open MonoDevelop.Ide.TypeSystem
open ExtCore.Control

type FSharpCompletionContext(editor:TextEditor, baseContext:CodeCompletionContext) =
    inherit CodeCompletionContext()

    override x.GetCoordinatesAsync() =
        let line = editor.GetLine editor.CaretLine
        let marker = editor.GetLineMarkers line |> Seq.tryPick(Option.tryCast<SignatureHelpMarker>)

        let task = baseContext.GetCoordinatesAsync()

        match marker with
        | Some m ->
            let struct (x, y, lineHeight) = task.Result
            // We need to add the height of the signature help marker to the Y coordinate
            // The line height is the height of the text plus the height of the marker
            Task.FromResult struct (x, y + (lineHeight / 2), lineHeight)
        | None -> task

type FSharpCompletionWidget(editor:TextEditor, completionWidget:ICompletionWidget) =
    interface ICompletionWidget with
        member x.CaretOffset
            with get() = completionWidget.CaretOffset
            and set(offset) = completionWidget.CaretOffset <- offset
        member x.TextLength = completionWidget.TextLength
        member x.SelectedLength = completionWidget.SelectedLength
        member x.GetText(startOffset, endOffset) =
            completionWidget.GetText(startOffset, endOffset)
        member x.GetChar offset = completionWidget.GetChar offset
        member x.Replace(offset, count, text) = completionWidget.Replace(offset, count, text)
        member x.GtkStyle = completionWidget.GtkStyle
        member x.ZoomLevel = completionWidget.ZoomLevel
        member x.CreateCodeCompletionContext triggerOffset =
            let context = completionWidget.CreateCodeCompletionContext triggerOffset
            FSharpCompletionContext(editor, context,
                TriggerOffset = triggerOffset,
                TriggerLine = context.TriggerLine,
                TriggerLineOffset = context.TriggerLineOffset,
                TriggerWordLength = context.TriggerWordLength) :> _

        member x.CurrentCodeCompletionContext
            with get() = completionWidget.CurrentCodeCompletionContext
        member x.GetCompletionText ctx = completionWidget.GetCompletionText ctx
        member x.SetCompletionText (ctx, partialWord, completeWord) =
            completionWidget.SetCompletionText (ctx, partialWord, completeWord)
        member x.SetCompletionText (ctx, partialWord, completeWord, completeWordOffset) =
            completionWidget.SetCompletionText (ctx, partialWord, completeWord, completeWordOffset)
        [<CLIEvent>]
        member x.CompletionContextChanged = completionWidget.CompletionContextChanged

type FSharpMemberCompletionData(name, icon, symbol:FSharpSymbolUse, overloads:FSharpSymbolUse list) =
    inherit CompletionData(CompletionText = PrettyNaming.QuoteIdentifierIfNeeded name,
                           DisplayText = name,
                           DisplayFlags = DisplayFlags.DescriptionHasMarkup,
                           Icon = icon)

    let returnType (symbol:FSharpSymbolUse) =
        match symbol with
        | MemberFunctionOrValue m ->
            try
                Some m.ReturnParameter.Type
            with _ -> None
        | _ -> None

    /// Check if the datatip has multiple overloads
    override x.HasOverloads = not (List.isEmpty overloads)
    override x.GetRightSideDescription _selected =
        let formatType (t:FSharpType) =
            try "<small>" + syntaxHighlight (t.Format symbol.DisplayContext) + "</small>"
            with ex -> ""
        returnType symbol
        |> Option.map formatType
        |> Option.fill ""

    /// Split apart the elements into separate overloads
    override x.OverloadedData =
        overloads
        |> List.map (fun symbol -> FSharpMemberCompletionData(name, icon, symbol, []) :> CompletionData)
        |> ResizeArray.ofList :> _

    override x.CreateTooltipInformation (_smartWrap, cancel) =

        MonoDevelop.FSharp.SymbolTooltips.getTooltipInformation symbol
        |> StartAsyncAsTask cancel

    /// https://github.com/mono/monodevelop/issues/3798
    ///
    /// Determined that it is too difficult to detect all the occurrences of
    /// identifiers in F# code for the time being, so it is hard to determine that the
    /// popup should not be displayed. Given this, we should be far less aggressive
    /// about auto-committing (even when "Complete with Space or Punctuation" is
    /// switched on. This is a good default for C#, but a bad default for F#.)
    ///
    /// This behaviour roughly matches both VS on Windows and VS Code
    override x.IsCommitCharacter (keyChar, _partialWord) = keyChar = '.'

    override x.MuteCharacter(keyChar, _partialWord) =
        match keyChar with
        | ' ' ->
            // If the space bar is pressed, then we want to
            // cancel completion and insert the space character.
            // This matches VS2017 F# behaviour
            IdeApp.Workbench.ActiveDocument.Editor.InsertAtCaret " "
            true
        | _ -> false

    type SimpleCategory(text) =
        inherit CompletionCategory(text, null)
        override x.CompareTo other =
            if other = null then -1 else x.DisplayText.CompareTo other.DisplayText

    type Category(text, s:FSharpSymbol) =
        inherit CompletionCategory(text, null)

        let ancestry (e: FSharpEntity) =
            e.UnAnnotate()
            |> Seq.unfold (fun x -> x.BaseType
                                    |> Option.map (fun x -> let entity = x.TypeDefinition.UnAnnotate()
                                                            entity, entity))
            |> Seq.append (e.AllInterfaces
                           |> Seq.map (fun a -> a.TypeDefinition.UnAnnotate()))

        member x.Symbol = s
        override x.CompareTo other =
            match other with
            | null -> 1
            | :? Category as other ->
                match s, other.Symbol with
                | (:? FSharpEntity as aa), (:? FSharpEntity as bb) ->
                    let comparisonResult =
                        let aaAllBases = ancestry aa

                        match (aaAllBases |> Seq.tryFind (fun a -> a.IsEffectivelySameAs bb)) with
                        | Some _ ->  -1
                        | _ ->
                            let bbAllBases = ancestry bb
                            match (bbAllBases |> Seq.tryFind (fun a -> a.IsEffectivelySameAs aa)) with
                            | Some _ ->  1
                            | _ -> aa.DisplayName.CompareTo(bb.DisplayName)

                    comparisonResult
                | a, b -> a.DisplayName.CompareTo(b.DisplayName)
            | _ -> -1

type FsiMemberCompletionData(displayText, completionText, icon) =
    inherit CompletionData(CompletionText = completionText,
                           DisplayText = displayText,
                           DisplayFlags = DisplayFlags.DescriptionHasMarkup,
                           Icon = icon)

    let emptyTooltip = TooltipInformation()

    override x.CreateTooltipInformation (_smartWrap, cancel) =
        match FSharpInteractivePad.Fsi with
        | Some pad ->
            match pad.Session with
            | Some session ->
                // get completions from remote fsi process
                pad.RequestTooltip displayText

                async {
                        let! tooltip = Async.AwaitEvent (session.TooltipReceived)
                        match tooltip with
                        | MonoDevelop.FSharp.Shared.ToolTips.ToolTip (signature, xmldoc, footer) ->
                            let! tooltipInfo = SymbolTooltips.getTooltipInformationFromTip (signature, xmldoc, footer)
                            return tooltipInfo
                        | MonoDevelop.FSharp.Shared.ToolTips.EmptyTip ->
                            return emptyTooltip
                    }
                |> StartAsyncAsTask cancel
            | _ -> Task.FromResult emptyTooltip
        | _ -> Task.FromResult emptyTooltip

module Completion =
    type Context = {
        completionChar: char
        lineToCaret: string
        editor: TextEditor
        documentContext: DocumentContext
        triggerOffset: int
        column: int
        line: int
        ctrlSpace: bool
    }

    let (|InvalidToken|_|) context =
        let token = Tokens.getTokenAtPoint context.editor context.triggerOffset
        if Tokens.isInvalidCompletionToken token then
            Some InvalidToken
        else
            None

    let (|InsideBlockComment|_|) context =
        let leftCommentDelimiter = context.editor.Text.LastIndexOf("(*", context.triggerOffset)
        if leftCommentDelimiter = -1 then
            None
        else
            let rightCommentDelimiter = context.editor.Text.IndexOf("*)", leftCommentDelimiter)
            if rightCommentDelimiter = -1 || rightCommentDelimiter > context.triggerOffset then
                Some InsideBlockComment
            else
                None

    let (|InvalidCompletionChar|_|) context =
        if Char.IsLetter context.completionChar || context.ctrlSpace || context.completionChar = '.' || context.completionChar = '#' || context.completionChar = ' ' then
            None
        else
            Some InvalidCompletionChar

    let (|LiteralNumber|_|) context =
        if Regex.IsMatch(context.lineToCaret, "\s?[0-9]+[\w.]*$", RegexOptions.Compiled) then
            Some LiteralNumber
        else
            None

    let (|FunctionIdentifier|_|) context =
        if Regex.IsMatch(context.lineToCaret, "\s?(fun)\s+[^-]+$", RegexOptions.Compiled) then
            Some FunctionIdentifier
        else
            None

    let (|ModuleOrTypeIdentifier|_|) context =
        if Regex.IsMatch(context.lineToCaret, "\s?(module|type)\s+[^=]+$", RegexOptions.Compiled) then
            Some ModuleOrTypeIdentifier
        else
            None

    let (|DoubleDot|_|) context =
        if Regex.IsMatch(context.lineToCaret, "\[[^\]]+\.+$", RegexOptions.Compiled) then
            Some DoubleDot
        else
            None

    let (|Attribute|_|) context =
        if Regex.IsMatch(context.lineToCaret, "\[<\w+$", RegexOptions.Compiled) then
            Some Attribute
        else
            None

    let (|FilePath|_|) context =
        let matches = Regex.Matches(context.lineToCaret, "^\s*#(load|r)\s+@*\"([^\"]*)$", RegexOptions.Compiled)
        if matches.Count > 0 then
            Some (matches.[0].Groups.[1].Value, matches.[0].Groups.[2].Value.Replace(@"\\", @"\"))
        else
            None

    let (|OtherIdentifier|_|) context =
        if Regex.IsMatch(context.lineToCaret, "\s?(let!?|Some|override|member|for)\s+[^=:]*$", RegexOptions.Compiled) then
             Some OtherIdentifier
        else
            None

    let symbolToIcon (symbolUse:FSharpSymbolUse) =
        match symbolUse with
        | SymbolUse.ActivePatternCase _ -> Stock.Enum
        | SymbolUse.Field _ -> Stock.Field
        | SymbolUse.UnionCase _ -> IconId("md-type")
        | SymbolUse.Class _ -> Stock.Class
        | SymbolUse.Delegate _ -> Stock.Delegate
        | SymbolUse.Constructor _  -> Stock.Method
        | SymbolUse.Event _ -> Stock.Event
        | SymbolUse.Property _ -> Stock.Property
        | Function f ->
            if f.IsExtensionMember then IconId("md-extensionmethod")
            elif f.IsMember then IconId("md-method")
            else IconId("md-fs-field")
        | SymbolUse.Operator _ -> IconId("md-fs-field")
        | SymbolUse.ClosureOrNestedFunction _ -> IconId("md-fs-field")
        | SymbolUse.Val _ -> Stock.Field
        | SymbolUse.Enum _ -> Stock.Enum
        | SymbolUse.Interface _ -> Stock.Interface
        | SymbolUse.Module _ -> IconId("md-module")
        | SymbolUse.Namespace _ -> Stock.NameSpace
        | SymbolUse.Record _ -> Stock.Class
        | SymbolUse.Union _ -> IconId("md-type")
        | SymbolUse.ValueType _ -> Stock.Struct
        | SymbolUse.Entity _ -> IconId("md-type")
        | _ -> Stock.Event

    let symbolStringToIcon icon =
        match icon with
        | "ActivePatternCase" -> Stock.Enum
        | "Field" -> Stock.Field
        | "UnionCase" -> IconId("md-type")
        | "Class" -> Stock.Class
        | "Delegate" -> Stock.Delegate
        | "Constructor" -> Stock.Method
        | "Event" -> Stock.Event
        | "Property" -> Stock.Property
        | "ExtensionMethod" -> IconId("md-extensionmethod")
        | "Method" -> IconId("md-method")
        | "Operator" -> IconId("md-fs-field")
        | "ClosureOrNestedFunction" -> IconId("md-fs-field")
        | "Val" -> Stock.Field
        | "Enum" -> Stock.Enum
        | "Interface" -> Stock.Interface
        | "Module" -> IconId("md-module")
        | "Namespace" -> Stock.NameSpace
        | "Record" -> Stock.Class
        | "Union" -> IconId("md-type")
        | "ValueType" -> Stock.Struct
        | "Entity" -> IconId("md-type")
        | _ -> Stock.Event

    let tryGetCategory (symbolUse : FSharpSymbolUse) =
        let category =
            try
                match symbolUse with
                | SymbolUse.Constructor c ->
                    c.DeclaringEntity
                    |> Option.map (fun ent -> let un = ent.UnAnnotate()
                                              un.DisplayName, un)
                | SymbolUse.Event ev ->
                    ev.DeclaringEntity
                    |> Option.map (fun ent -> let un = ent.UnAnnotate()
                                              un.DisplayName, un)
                | SymbolUse.Property pr ->
                    pr.DeclaringEntity
                    |> Option.map (fun ent -> let un = ent.UnAnnotate()
                                              un.DisplayName, un)
                | SymbolUse.ActivePatternCase ap ->
                    if ap.Group.Names.Count > 1 then
                        ap.Group.DeclaringEntity
                        |> Option.map (fun enclosing -> let un = enclosing.UnAnnotate()
                                                        un.DisplayName, un)
                    else None
                | SymbolUse.UnionCase uc ->
                    if uc.UnionCaseFields.Count > 1 then
                        let ent = uc.ReturnType.TypeDefinition.UnAnnotate()
                        Some(ent.DisplayName, ent)
                    else None
                | SymbolUse.Function f ->
                    if f.IsExtensionMember then
                        let real = f.ApparentEnclosingEntity.UnAnnotate()
                        Some(real.DisplayName, real)
                    else
                        f.DeclaringEntity
                        |> Option.map (fun real -> let un = real.UnAnnotate()
                                                   un.DisplayName, un)
                | SymbolUse.Operator o ->
                    o.DeclaringEntity
                    |> Option.map (fun ent -> let un = ent.UnAnnotate()
                                              un.DisplayName, un)
                | SymbolUse.Pattern p ->
                    p.DeclaringEntity
                    |> Option.map (fun ent -> let un = ent.UnAnnotate()
                                              un.DisplayName, ent)
                | SymbolUse.Val v ->
                    v.DeclaringEntity
                    |> Option.map (fun ent -> let un  = ent.UnAnnotate()
                                              un.DisplayName, un)
                | SymbolUse.TypeAbbreviation ta ->
                    //TODO:  Check this is correct, I suspect we should return None here
                    let ent = ta.UnAnnotate()
                    Some (ent.DisplayName, ent)
                //The following have no logical parent to display
                //Theres no link to a parent type for a closure (FCS limitation)
                | SymbolUse.ClosureOrNestedFunction _cl -> None
                //The F# compiler does not currently expose an Entitys parent, only children
                //| Class _ | Delegate _ | Enum _ | Interface _ | Module _
                //| Namespace _ | Record _ | Union _ | ValueType _  -> None
                | _ -> None
            with exn -> None
        category

    let getCompletionData (symbols:FSharpSymbolUse list list) isInsideAttribute =
        let categories = Dictionary<string, Category>()
        let getOrAddCategory symbol id =
            match categories.TryGetValue id with
            | true, item -> item
            | _ -> let cat = Category(id, symbol)
                   categories.Add (id, cat)
                   cat

        let symbolToCompletionData (symbols : FSharpSymbolUse list) =
            match symbols with
            | head :: tail ->
                let completion =
                    if isInsideAttribute then
                        match head with
                        | SymbolUse.Attribute ent ->
                            let name = ent.DisplayName
                            let name =
                                if name.EndsWith("Attribute") then
                                    name.Remove(name.Length - 9)
                                else
                                    name
                            Some (FSharpMemberCompletionData(name, symbolToIcon head, head, tail) :> CompletionData)
                        | _ -> None
                    else
                        Some (FSharpMemberCompletionData(head.Symbol.DisplayName, symbolToIcon head, head, tail) :> CompletionData)

                match tryGetCategory head, completion with
                | Some (id, ent), Some comp ->
                    let category = getOrAddCategory ent id
                    comp.CompletionCategory <- category
                | _, _ -> ()

                completion
            | _ -> None

        symbols |> List.choose symbolToCompletionData

    let compilerIdentifiers =
        let icon = Stock.Literal
        let compilerIdentifierCategory = SimpleCategory "Compiler Identifiers"
        [ CompletionData("__LINE__", icon,
                         "Evaluates to the current line number, considering <tt>#line</tt> directives.",
                          CompletionCategory = compilerIdentifierCategory,
                          DisplayFlags = DisplayFlags.DescriptionHasMarkup)
          CompletionData("__SOURCE_DIRECTORY__", icon,
                         "Evaluates to the current full path of the source directory, considering <tt>#line</tt> directives.",
                          CompletionCategory = compilerIdentifierCategory,
                          DisplayFlags = DisplayFlags.DescriptionHasMarkup)
          CompletionData("__SOURCE_FILE__", icon,
                         "Evaluates to the current source file name and its path, considering <tt>#line</tt> directives.",
                          CompletionCategory = compilerIdentifierCategory,
                          DisplayFlags = DisplayFlags.DescriptionHasMarkup) ]

    let keywordCompletionData =
        Keywords.KeywordsWithDescription
        |> List.filter (fun (keyword, _) -> not (PrettyNaming.IsOperatorName keyword))
        |> List.map (fun (keyword, description) ->
            CompletionData(keyword, IconId("md-keyword"), description))

    let modifierCompletionData =
        [for keyValuePair in KeywordList.modifiers do
            yield CompletionData(keyValuePair.Key, IconId("md-keyword"),keyValuePair.Value) ]

    let parseLock = obj()

    let getFsiCompletions context =

        async {
            let { column = column
                  lineToCaret = lineToCaret
                  completionChar = completionChar } = context

            let result = CompletionDataList()

            match FSharpInteractivePad.Fsi with
            | Some pad ->
                match pad.Session with
                | Some session ->
                    // get completions from remote fsi process
                    pad.RequestCompletions lineToCaret column
                    let completions =
                        Async.AwaitEvent (session.CompletionsReceived)
                        |> Async.RunSynchronously
                        |> Array.map (fun c -> FsiMemberCompletionData(c.displayText, c.completionText, symbolStringToIcon c.icon))
                        |> Seq.cast<CompletionData>

                    result.AddRange completions
                    let _longName,residue = Parsing.findLongIdentsAndResidue(column, lineToCaret)
                    if completionChar <> '.' && result.Count > 0 then

                        LoggingService.logDebug "Completion: residue %s" residue
                        result.DefaultCompletionString <- residue
                        result.TriggerWordLength <- residue.Length

                    //TODO Use previous token and pattern match to detect whitespace
                    if Regex.IsMatch(lineToCaret, "(^|\s+|\()\w+$", RegexOptions.Compiled) then
                        // Add the code templates and compiler generated identifiers if the completion char is not '.'
                        CodeTemplates.CodeTemplateService.AddCompletionDataForMime ("text/x-fsharp", result)
                        result.AddRange compilerIdentifiers
                        result.AddRange keywordCompletionData
                    return result
                | None -> return result
            | None -> return result
        }

    let getCompletions context =
        async {
            try
                let {
                    line = line
                    column = column
                    documentContext = documentContext
                    lineToCaret = lineToCaret
                    completionChar = completionChar
                    editor = editor
                    ctrlSpace = ctrlSpace
                    } = context

                let! typedParseResults =
                    asyncMaybe {
                        let! document = documentContext.TryGetFSharpParsedDocument() |> async.Return

                        let shouldReparse() =
                            lineToCaret.Contains "=" || lineToCaret.Contains "->"

                        let isContiguousIdentifierCharSeq() =
                            let l = lineToCaret.LastIndexOf " "
                            seq { l+1..column-1 }
                            |> Seq.map(fun i -> lineToCaret.[i])
                            |> Seq.forall (fun c -> Char.IsLetterOrDigit c || c = '.' || c = '(')

                        if ctrlSpace || shouldReparse() || (isContiguousIdentifierCharSeq() |> not) then
                            LoggingService.logDebug "Completion: syncing parse results"
                            let projectFile = documentContext.Project |> function null -> document.FileName| proj -> proj.FileName.ToString()
                            document.ParsedLocation <- DocumentLocation(line, column) |> Some
                            document.ParsedLine <- editor.GetLineText(editor.CaretLine) |> Some
                            let! ast = languageService.ParseAndCheckFileInProject(projectFile, document.FileName, 0, editor.Text, true) |> Async.map Some
                            document.Ast <- ast
                            return ast
                        else
                            LoggingService.logDebug "Completion: got parse results from cache"
                            return! document.TryGetAst() |> async.Return
                    }

                let result = CompletionDataList()

                let addIdentCompletions() =
                    let (idents, residue) = Parsing.findLongIdentsAndResidue(column, lineToCaret)
                    if idents.IsEmpty then
                        let lineWithoutResidue = lineToCaret.[0..column-residue.Length-1]
                        if not (lineWithoutResidue.EndsWith ".") then
                            let tokens = Lexer.tokenizeLine lineWithoutResidue [||] 0 lineWithoutResidue Lexer.singleLineQueryLexState
                            let tokenToCompletion (token:FSharpTokenInfo) =
                                let displayText = lineToCaret.[token.LeftColumn..token.RightColumn]
                                CompletionData(displayText, IconId "md-fs-field", displayText, displayText)

                            // Add ident completions from the current line
                            // as the semantic parse might not be up to date
                            let lineCompletions =
                                tokens
                                |> List.filter (fun token -> token.TokenName = "IDENT")
                                |> List.map tokenToCompletion

                            result.AddRange (lineCompletions
                                             |> Seq.filter(fun r -> not (result.Exists(fun e -> e.DisplayText = r.DisplayText))))
                        result.DefaultCompletionString <- residue
                        result.TriggerWordLength <- residue.Length

                match typedParseResults with
                | None ->
                    addIdentCompletions()
                | Some tyRes ->
                    // Get declarations and generate list for MonoDevelop
                    let! symbols = tyRes.GetDeclarationSymbols(line, column, lineToCaret)
                    match symbols with
                    | Some (symbols, residue) ->
                        let isInAttribute =
                            match context with
                            | Attribute -> true
                            | _ -> false

                        let residue =
                            if residue = "" then
                                // Residue returned by GetDeclarationSymbols
                                // can be empty when it comes after an application
                                // such as DateTime.Now.ToString().Subs <-
                                // Here, we do a simple lookup for `Subs` in the above example.
                                Parsing.findResidue lineToCaret
                            else
                                residue

                        let data = getCompletionData symbols isInAttribute
                        result.AddRange data

                        if completionChar <> '.' && result.Count > 0 then
                            LoggingService.logDebug "Completion: residue %s" residue
                            result.DefaultCompletionString <- residue
                            result.TriggerWordLength <- residue.Length


                        //TODO Use previous token and pattern match to detect whitespace
                        if Regex.IsMatch(lineToCaret, "(^|\s+|\()\w+$", RegexOptions.Compiled) then
                            // Add the code templates and compiler generated identifiers if the completion char is not '.'
                            CodeTemplates.CodeTemplateService.AddCompletionDataForMime ("text/x-fsharp", result)
                            result.AddRange compilerIdentifiers

                            result.AddRange keywordCompletionData
                    | None -> addIdentCompletions()

                return result
            with
            | :? Threading.Tasks.TaskCanceledException ->
                return CompletionDataList()
            | e ->
                LoggingService.LogError ("FSharpTextEditorCompletion, An error occurred in CodeCompletionCommandImpl", e)
                return CompletionDataList()
        }

    let getCompletionList (completions: MonoDevelop.FSharp.Shared.PathCompletion) =
        let result = CompletionDataList()
        result.DefaultCompletionString <- completions.residue
        result.TriggerWordLength <- completions.residue.Length
        let completions =
            completions.paths
            |> Seq.map (fun path -> CompletionData(path))
        result.AddRange completions
        result

    let getModifiers context =
        let {
            column = column
            lineToCaret = lineToCaret
            ctrlSpace = ctrlSpace
            } = context

        let (_, residue) = Parsing.findLongIdentsAndResidue(column, lineToCaret)
        let result = CompletionDataList()
        result.DefaultCompletionString <- residue
        result.TriggerWordLength <- residue.Length
        // To prevent the "No completions found" when typing an identifier
        // here -> `let myident|`
        // but allow completions
        // here -> `let mutab|`
        // but not here -> `let m|`
        let filteredModifiers = modifierCompletionData
                                |> Seq.filter (fun c -> c.DisplayText.StartsWith(residue))
        if residue.Length > 1 || ctrlSpace then
            result.AddRange filteredModifiers
        result

    let codeCompletionCommandImpl(editor:TextEditor, documentContext:DocumentContext, context:CodeCompletionContext, ctrlSpace) =
        async {
            let line, col, lineStr = editor.GetLineInfoFromOffset context.TriggerOffset
            let completionContext = {
                completionChar = editor.GetCharAt(context.TriggerOffset - 1)
                lineToCaret = lineStr.[0..col-1]
                line = line
                column = col
                editor = editor
                triggerOffset = context.TriggerOffset
                ctrlSpace = ctrlSpace
                documentContext = documentContext
            }

            let! results = async {
                match completionContext with
                | FilePath (directive, path) ->
                    let workingFolder =
                        match documentContext |> Option.tryCast<FsiDocumentContext> with
                        | Some ctx -> ctx.WorkingFolder
                        | _ -> documentContext.GetWorkingFolder()

                    let completions = MonoDevelop.FSharp.Shared.Completion.getPathCompletion workingFolder directive path
                    return getCompletionList completions
                | InvalidToken
                | InsideBlockComment
                | InvalidCompletionChar
                | DoubleDot
                | LiteralNumber
                | FunctionIdentifier ->
                    return CompletionDataList()
                | ModuleOrTypeIdentifier
                | OtherIdentifier ->
                    return getModifiers completionContext
                | _ ->
                    if documentContext :? FsiDocumentContext then
                        return! getFsiCompletions completionContext
                    else
                        return! getCompletions completionContext
            }
            results.IsSorted <- true
            results.AutoCompleteEmptyMatch <- false
            results.AutoCompleteUniqueMatch <- ctrlSpace

            return results :> ICompletionDataList
        }

type FSharpParameterHintingData (symbol:FSharpSymbolUse) =
    inherit ParameterHintingData ()

    let getTooltipInformation symbol paramIndex =
        async {
            match symbol with
            | MemberFunctionOrValue _f ->
                let tooltipInfo = MonoDevelop.FSharp.SymbolTooltips.getParameterTooltipInformation symbol paramIndex
                return tooltipInfo
            | symbol ->
                LoggingService.LogDebug(sprintf "FSharpParameterHintingData - CreateTooltipInformation could not create tooltip for %A" symbol.Symbol)
                return null }

    override x.ParameterCount =
        MonoDevelop.FSharp.Shared.ParameterHinting.parameterCount symbol.Symbol

    override x.IsParameterListAllowed =
        MonoDevelop.FSharp.Shared.ParameterHinting.isParameterListAllowed symbol.Symbol

    override x.GetParameterName i =
        MonoDevelop.FSharp.Shared.ParameterHinting.getParameterName symbol.Symbol i

    /// Returns the markup to use to represent the method overload in the parameter information window.
    override x.CreateTooltipInformation (_editor, _context, paramIndex: int, _smartWrap:bool, cancel) =
        getTooltipInformation symbol (Math.Max(paramIndex, 0))
        |> StartAsyncAsTask cancel


type FsiParameterHintingData (tooltip: MonoDevelop.FSharp.Shared.ParameterTooltip) =
    inherit ParameterHintingData ()

    override x.ParameterCount =
       match tooltip with
       | MonoDevelop.FSharp.Shared.ParameterTooltip.ToolTip (_, _, parameters) -> parameters.Length
       | _ -> 0

    override x.IsParameterListAllowed =
        match tooltip with
        | MonoDevelop.FSharp.Shared.ParameterTooltip.ToolTip (_, _, parameters) -> parameters.Length > 0
        | _ -> false

    override x.GetParameterName i =
        match tooltip with
        | MonoDevelop.FSharp.Shared.ParameterTooltip.ToolTip (_, _, parameters) -> parameters.[i]
        | _ -> null

    /// Returns the markup to use to represent the method overload in the parameter information window.
    override x.CreateTooltipInformation (_editor, _context, paramIndex: int, _smartWrap:bool, cancel) =
        async {
                match tooltip with
                | MonoDevelop.FSharp.Shared.ParameterTooltip.ToolTip (signature, doc, parameters) ->
                    let signature, parameterName =
                        if paramIndex = -1 || paramIndex < parameters.Length - 1 then
                            Highlight.syntaxHighlight signature, null
                        else
                            let paramName = parameters.[paramIndex]
                            let lines =
                                String.getLines signature
                                |> Array.mapi (fun i line ->
                                                if i = paramIndex + 1 then
                                                    let regex = new System.Text.RegularExpressions.Regex(paramName)
                                                    regex.Replace(line, sprintf "_STARTUNDERLINE_%s_ENDUNDERLINE_" paramName, 1)
                                                else
                                                    line)
                            let signature = Highlight.syntaxHighlight (String.concat "\n" lines)
                            let signature = signature.Replace("_STARTUNDERLINE_", "<u>").Replace("_ENDUNDERLINE_", "</u>")

                            signature, parameters.[paramIndex]

                    return SymbolTooltips.getTooltipInformationFromSignature doc signature parameterName
                | _ -> return TooltipInformation()
            }
        |> StartAsyncAsTask cancel

module ParameterHinting =

    // Until we build some functionality around a reversing tokenizer that detect this and other contexts
    // A crude detection of being inside an auto property decl: member val Foo = 10 with get,$ set
    let isAnAutoProperty (_editor: TextEditor) _offset =
        false

    let getHints (editor:TextEditor, documentContext:DocumentContext, context:CodeCompletionContext) =
        async {
        try
            let docText = editor.Text
            let offset = context.TriggerOffset
            // Parse backwards, skipping (...) and { ... } and [ ... ] to determine the parameter index.
            // This is an approximation.
            let startOffset =
                let rec loop depth i =
                    if (i <= 0) then i else
                        let ch = docText.[i]
                        if ((ch = '(' || ch = '{' || ch = '[') && depth > 0) then loop (depth - 1) (i-1)
                        elif ((ch = ')' || ch = '}' || ch = ']')) then loop (depth+1) (i-1)
                        elif (ch = '(' || ch = '<') then i
                        else loop depth (i-1)
                loop 0 (offset-1)

            if docText = null || offset > docText.Length || startOffset < 0 || offset <= 0 || isAnAutoProperty editor offset
            then return ParameterHintingResult.Empty
            else
            LoggingService.LogDebug("FSharpTextEditorCompletion - HandleParameterCompletionAsync: Getting Parameter Info, startOffset = {0}", startOffset)

            if documentContext :? FsiDocumentContext then

                match FSharpInteractivePad.Fsi with
                | Some pad ->
                    match pad.Session with
                    | Some session ->
                        let _line, col, lineStr = editor.GetLineInfoFromOffset (startOffset)
                        pad.RequestParameterHint lineStr col
                        let tooltips =
                            Async.AwaitEvent (session.ParameterHintReceived)
                            |> Async.RunSynchronously

                        let hintingData =
                            tooltips
                            |> Array.map (fun meth -> FsiParameterHintingData (meth) :> ParameterHintingData)
                            |> ResizeArray.ofArray
                        if hintingData.Count > 0 then
                            return ParameterHintingResult(hintingData, ApplicableSpan = new TextSpan(startOffset, 0))
                        else
                            return ParameterHintingResult.Empty
                    | _ -> return ParameterHintingResult.Empty
                | _ -> return ParameterHintingResult.Empty
            else
            let filename = documentContext.Name

            // Try to get typed result - within the specified timeout
            let! methsOpt =
                async { let projectFile = documentContext.Project |> function null -> filename | project -> project.FileName.ToString()
                        let! tyRes = languageService.GetTypedParseResultWithTimeout (projectFile, filename, 0, docText, AllowStaleResults.MatchingSource, ServiceSettings.maximumTimeout, (fun() -> false) )
                        match tyRes with
                        | Some tyRes ->
                            let line, col, lineStr = editor.GetLineInfoFromOffset (startOffset)
                            let! allMethodSymbols = tyRes.GetMethodsAsSymbols (line, col, lineStr)
                            return allMethodSymbols
                        | None -> return None}

            match methsOpt with
            | Some(meths) when meths.Length > 0 ->
                LoggingService.logDebug "FSharpTextEditorCompletion: Getting Parameter Info: %d methods" meths.Length
                let hintingData =
                    meths
                    |> List.map (fun meth -> FSharpParameterHintingData (meth) :> ParameterHintingData)
                    |> ResizeArray.ofList

                return ParameterHintingResult(hintingData, ApplicableSpan = new TextSpan(startOffset, 0))
            | _ -> LoggingService.logWarning "FSharpTextEditorCompletion: Getting Parameter Info: no methods found"
                   return ParameterHintingResult.Empty
        with
        | :? Threading.Tasks.TaskCanceledException ->
            return ParameterHintingResult.Empty
        | ex ->
            LoggingService.LogError ("FSharpTextEditorCompletion: Error in HandleParameterCompletion", ex)
            return ParameterHintingResult.Empty
        }


    // Returns the index of the parameter where the cursor is currently positioned.
    // -1 means the cursor is outside the method parameter list
    // 0 means no parameter entered
    // > 0 is the index of the parameter (1-based)
    let getParameterIndex (editor:TextEditor, startOffset) =
        let cursor = editor.CaretOffset
        let i = startOffset // the original context
        if (i < 0 || i >= editor.Length || editor.GetCharAt (i) = ')') then -1
        //elif (i + 1 = cursor && (match editor.GetCharAt(i) with '(' | '<' -> true | _ -> false)) then 0
        else
            // The first character is a '('
            // Note this will be confused by comments.
            let rec loop depth i parameterIndex =
                if (i = cursor) then parameterIndex
                elif (i > cursor) then -1
                elif (i >= editor.Length) then  parameterIndex else
                let ch = editor.GetCharAt(i)
                if (ch = '(' || ch = '{' || ch = '[') then loop (depth+1) (i+1) parameterIndex
                elif ((ch = ')' || ch = '}' || ch = ']') && depth > 1 ) then loop (depth-1) (i+1) parameterIndex
                elif (ch = ',' && depth = 1) then loop depth (i+1) (parameterIndex+1)
                elif (ch = ')' || ch = '>') then -1
                else loop depth (i+1) parameterIndex
            loop 0 i 1

/// Implements text editor extension for MonoDevelop that shows F# completion
type FSharpTextEditorCompletion() =
    inherit CompletionTextEditorExtension()

    let mutable suppressParameterCompletion = false

    let isValidParamCompletionDecriptor (d:KeyDescriptor) =
        d.KeyChar = '(' || d.KeyChar = '<' || d.KeyChar = ',' || (d.KeyChar = ' ' && d.ModifierKeys = ModifierKeys.Control)

    let validCompletionChar c =
        c = '(' || c = ',' || c = '<'


    let emptyResult = Task.FromResult null

    override x.CompletionLanguage = "F#"
    override x.Initialize() =
        x.Editor.IndentationTracker <- FSharpIndentationTracker(x.Editor)
        x.CompletionWidget <- FSharpCompletionWidget(x.Editor, x.Editor.GetContent<ICompletionWidget>())
        base.Initialize()

    /// Provide parameter and method overload information when you type '(', '<' or ','
    override x.HandleParameterCompletionAsync (context, completionChar, token) =
        //TODO refactor computation to remove some return statements (clarity)
        if suppressParameterCompletion || not (validCompletionChar completionChar)
        then suppressParameterCompletion <- false
             System.Threading.Tasks.Task.FromResult(ParameterHintingResult.Empty)
        else
            ParameterHinting.getHints(x.Editor, x.DocumentContext, context)
            |> StartAsyncAsTask token

    override x.KeyPress (descriptor:KeyDescriptor) =
        suppressParameterCompletion <- not (isValidParamCompletionDecriptor descriptor)
        base.KeyPress (descriptor)

    override x.HandleCodeCompletionAsync(context, triggerInfo, token) =
        let ctrlSpace = triggerInfo.CompletionTriggerReason = CompletionTriggerReason.CompletionCommand
        if triggerInfo.CompletionTriggerReason = CompletionTriggerReason.CharTyped && triggerInfo.TriggerCharacter.Value = ' ' then
            emptyResult
        elif IdeApp.Preferences.EnableAutoCodeCompletion.Value || ctrlSpace then
            Completion.codeCompletionCommandImpl(x.Editor, x.DocumentContext, context, ctrlSpace)
            |> StartAsyncAsTask token
        else
            emptyResult


    override x.GetCurrentParameterIndex (startOffset: int, token) =
        async {
                return ParameterHinting.getParameterIndex(x.Editor, startOffset)
        }
        |> StartAsyncAsTask token