summaryrefslogtreecommitdiffstats
path: root/autoload/fsharp.vim
blob: 5d8bb79d1ddf9748e057d2d85bde38f5ccde835c (plain) (blame)
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
if polyglot#init#is_disabled(expand('<sfile>:p'), 'fsharp', 'autoload/fsharp.vim')
  finish
endif

" Vim autoload functions
if exists('g:loaded_autoload_fsharp')
    finish
endif
let g:loaded_autoload_fsharp = 1

let s:cpo_save = &cpo
set cpo&vim


" basic setups

let s:script_root_dir = expand('<sfile>:p:h') . "/../"

if has('nvim-0.5')
    lua ionide = require("ionide")
endif

function! s:prompt(msg)
    let height = &cmdheight
    if height < 2
        set cmdheight=2
    endif
    echom a:msg
    let &cmdheight = height
endfunction


" FSAC payload interfaces

function! s:PlainNotification(content)
    return { 'Content': a:content }
endfunction

function! s:TextDocumentIdentifier(path)
    let usr_ss_opt = &shellslash
    set shellslash
    let uri = fnamemodify(a:path, ":p")
    if uri[0] == "/"
        let uri = "file://" . uri
    else
        let uri = "file:///" . uri
    endif
    let &shellslash = usr_ss_opt
    return { 'Uri': uri }
endfunction

function! s:Position(line, character)
    return { 'Line': a:line, 'Character': a:character }
endfunction

function! s:TextDocumentPositionParams(documentUri, line, character)
    return {
        \ 'TextDocument': s:TextDocumentIdentifier(a:documentUri),
        \ 'Position':     s:Position(a:line, a:character)
        \ }
endfunction

function! s:DocumentationForSymbolRequest(xmlSig, assembly)
    return {
        \ 'XmlSig': a:xmlSig,
        \ 'Assembly': a:assembly
        \ }
endfunction

function! s:ProjectParms(projectUri)
    return { 'Project': s:TextDocumentIdentifier(a:projectUri) }
endfunction

function! s:WorkspacePeekRequest(directory, deep, excludedDirs)
    return {
        \ 'Directory': fnamemodify(a:directory, ":p"),
        \ 'Deep': a:deep,
        \ 'ExcludedDirs': a:excludedDirs
        \ }
endfunction

function! s:WorkspaceLoadParms(files)
    let prm = []
    for file in a:files
        call add(prm, s:TextDocumentIdentifier(file))
    endfor
    return { 'TextDocuments': prm }
endfunction

function! s:FsdnRequest(query)
    return { 'Query': a:query }
endfunction


" LSP functions

function! s:call(method, params, cont)
    if g:fsharp#backend == 'languageclient-neovim'
        call LanguageClient#Call(a:method, a:params, a:cont)
    elseif g:fsharp#backend == 'nvim'
        let key = fsharp#register_callback(a:cont)
        call luaeval('ionide.call(_A[1], _A[2], _A[3])', [a:method, a:params, key])
    endif
endfunction

function! s:notify(method, params)
    if g:fsharp#backend == 'languageclient-neovim'
        call LanguageClient#Notify(a:method, a:params)
    elseif g:fsharp#backend == 'nvim'
        call luaeval('ionide.notify(_A[1], _A[2])', [a:method, a:params])
    endif
endfunction

function! s:signature(filePath, line, character, cont)
    return s:call('fsharp/signature', s:TextDocumentPositionParams(a:filePath, a:line, a:character), a:cont)
endfunction
function! s:signatureData(filePath, line, character, cont)
    return s:call('fsharp/signatureData', s:TextDocumentPositionParams(a:filePath, a:line, a:character), a:cont)
endfunction
function! s:lineLens(projectPath, cont)
    return s:call('fsharp/lineLens', s:ProjectParms(a:projectPath), a:cont)
endfunction
function! s:compilerLocation(cont)
    return s:call('fsharp/compilerLocation', {}, a:cont)
endfunction
function! s:compile(projectPath, cont)
    return s:call('fsharp/compile', s:ProjectParms(a:projectPath), a:cont)
endfunction
function! s:workspacePeek(directory, depth, excludedDirs, cont)
    return s:call('fsharp/workspacePeek', s:WorkspacePeekRequest(a:directory, a:depth, a:excludedDirs), a:cont)
endfunction
function! s:workspaceLoad(files, cont)
    return s:call('fsharp/workspaceLoad', s:WorkspaceLoadParms(a:files), a:cont)
endfunction
function! s:project(projectPath, cont)
    return s:call('fsharp/project', s:ProjectParms(a:projectPath), a:cont)
endfunction
function! s:fsdn(signature, cont)
    return s:call('fsharp/fsdn', s:FsdnRequest(a:signature), a:cont)
endfunction
function! s:f1Help(filePath, line, character, cont)
    return s:call('fsharp/f1Help', s:TextDocumentPositionParams(a:filePath, a:line, a:character), a:cont)
endfunction
function! fsharp#documentation(filePath, line, character, cont)
    return s:call('fsharp/documentation', s:TextDocumentPositionParams(a:filePath, a:line, a:character), a:cont)
endfunction
function! s:documentationSymbol(xmlSig, assembly, cont)
    return s:call('fsharp/documentationSymbol', s:DocumentationForSymbolRequest(a:xmlSig, a:assembly), a:cont)
endfunction


" FSAC configuration

" FSharpConfigDto from https://github.com/fsharp/FsAutoComplete/blob/master/src/FsAutoComplete/LspHelpers.fs
"
" * The following options seems not working with workspace/didChangeConfiguration
"   since the initialization has already completed?
"     'AutomaticWorkspaceInit',
"     'WorkspaceModePeekDeepLevel',
"
" * Changes made to linter/unused analyzer settings seems not reflected after sending them to FSAC?
"
let s:config_keys_camel =
    \ [
    \     {'key': 'AutomaticWorkspaceInit', 'default': 1},
    \     {'key': 'WorkspaceModePeekDeepLevel', 'default': 2},
    \     {'key': 'ExcludeProjectDirectories', 'default': []},
    \     {'key': 'keywordsAutocomplete', 'default': 1},
    \     {'key': 'ExternalAutocomplete', 'default': 0},
    \     {'key': 'Linter', 'default': 1},
    \     {'key': 'UnionCaseStubGeneration', 'default': 1},
    \     {'key': 'UnionCaseStubGenerationBody'},
    \     {'key': 'RecordStubGeneration', 'default': 1},
    \     {'key': 'RecordStubGenerationBody'},
    \     {'key': 'InterfaceStubGeneration', 'default': 1},
    \     {'key': 'InterfaceStubGenerationObjectIdentifier', 'default': 'this'},
    \     {'key': 'InterfaceStubGenerationMethodBody'},
    \     {'key': 'UnusedOpensAnalyzer', 'default': 1},
    \     {'key': 'UnusedDeclarationsAnalyzer', 'default': 1},
    \     {'key': 'SimplifyNameAnalyzer', 'default': 0},
    \     {'key': 'ResolveNamespaces', 'default': 1},
    \     {'key': 'EnableReferenceCodeLens', 'default': 1},
    \     {'key': 'EnableAnalyzers', 'default': 0},
    \     {'key': 'AnalyzersPath'},
    \     {'key': 'DisableInMemoryProjectReferences', 'default': 0},
    \     {'key': 'LineLens', 'default': {'enabled': 'never', 'prefix': ''}},
    \     {'key': 'UseSdkScripts', 'default': 1},
    \     {'key': 'dotNetRoot'},
    \     {'key': 'fsiExtraParameters', 'default': []},
    \ ]
let s:config_keys = []

function! s:toSnakeCase(str)
    let sn = substitute(a:str, '\(\<\u\l\+\|\l\+\)\(\u\)', '\l\1_\l\2', 'g')
    if sn == a:str | return tolower(a:str) | endif
    return sn
endfunction

function! s:buildConfigKeys()
    if len(s:config_keys) == 0
        for key_camel in s:config_keys_camel
            let key = {}
            let key.snake = s:toSnakeCase(key_camel.key)
            let key.camel = key_camel.key
            if has_key(key_camel, 'default')
                let key.default = key_camel.default
            endif
            call add(s:config_keys, key)
        endfor
    endif
endfunction

function! fsharp#getServerConfig()
    let fsharp = {}
    call s:buildConfigKeys()
    for key in s:config_keys
        if exists('g:fsharp#' . key.snake)
            let fsharp[key.camel] = g:fsharp#{key.snake}
        elseif exists('g:fsharp#' . key.camel)
            let fsharp[key.camel] = g:fsharp#{key.camel}
        elseif has_key(key, 'default') && g:fsharp#use_recommended_server_config
            let g:fsharp#{key.snake} = key.default
            let fsharp[key.camel] = key.default
        endif
    endfor
    return fsharp
endfunction

function! fsharp#updateServerConfig()
    let fsharp = fsharp#getServerConfig()
    let settings = {'settings': {'FSharp': fsharp}}
    call s:notify('workspace/didChangeConfiguration', settings)
endfunction

function! fsharp#loadConfig()
    if exists('s:config_is_loaded')
        return
    endif

    if !exists('g:fsharp#fsautocomplete_command')
        let s:fsac = fnamemodify(s:script_root_dir . "fsac/fsautocomplete.dll", ":p")
        let g:fsharp#fsautocomplete_command =
            \ ['dotnet', s:fsac,
                \ '--background-service-enabled'
            \ ]
    endif
    if !exists('g:fsharp#use_recommended_server_config')
        let g:fsharp#use_recommended_server_config = 1
    endif
    call fsharp#getServerConfig()
    if !exists('g:fsharp#automatic_workspace_init')
        let g:fsharp#automatic_workspace_init = 1
    endif
    if !exists('g:fsharp#automatic_reload_workspace')
        let g:fsharp#automatic_reload_workspace = 1
    endif
    if !exists('g:fsharp#show_signature_on_cursor_move')
        let g:fsharp#show_signature_on_cursor_move = 1
    endif
    if !exists('g:fsharp#fsi_command')
        let g:fsharp#fsi_command = "dotnet fsi"
    endif
    if !exists('g:fsharp#fsi_keymap')
        let g:fsharp#fsi_keymap = "vscode"
    endif
    if !exists('g:fsharp#fsi_window_command')
        let g:fsharp#fsi_window_command = "botright 10new"
    endif
    if !exists('g:fsharp#fsi_focus_on_send')
        let g:fsharp#fsi_focus_on_send = 0
    endif
    if !exists('g:fsharp#backend')
        if has('nvim-0.5')
            if exists('g:LanguageClient_loaded')
                let g:fsharp#backend = "languageclient-neovim"
            else
                let g:fsharp#backend = "nvim"
            endif
        else
            let g:fsharp#backend = "languageclient-neovim"
        endif
    endif

    " backend configuration
    if g:fsharp#backend == 'languageclient-neovim'
        if !exists('g:LanguageClient_serverCommands')
            let g:LanguageClient_serverCommands = {}
        endif
        if !has_key(g:LanguageClient_serverCommands, 'fsharp')
            let g:LanguageClient_serverCommands.fsharp = {
                \ 'name': 'fsautocomplete',
                \ 'command': g:fsharp#fsautocomplete_command,
                \ 'initializationOptions': {},
                \}
            if g:fsharp#automatic_workspace_init
                let g:LanguageClient_serverCommands.fsharp.initializationOptions = {
                    \ 'AutomaticWorkspaceInit': v:true,
                    \}
            endif
        endif

        if !exists('g:LanguageClient_rootMarkers')
            let g:LanguageClient_rootMarkers = {}
        endif
        if !has_key(g:LanguageClient_rootMarkers, 'fsharp')
            let g:LanguageClient_rootMarkers.fsharp = ['*.sln', '*.fsproj', '.git']
        endif
    elseif g:fsharp#backend == 'nvim'
        if !exists('g:fsharp#lsp_auto_setup')
            let g:fsharp#lsp_auto_setup = 1
        endif
        if !exists('g:fsharp#lsp_recommended_colorscheme')
            let g:fsharp#lsp_recommended_colorscheme = 1
        endif
        if !exists('g:fsharp#lsp_codelens')
            let g:fsharp#lsp_codelens = 1
        endif

    else
        if g:fsharp#backend != 'disable'
            echoerr "[FSAC] Invalid backend: " . g:fsharp#backend
        endif
    endif

    " FSI keymaps
    if g:fsharp#fsi_keymap == "vscode"
        if has('nvim')
            let g:fsharp#fsi_keymap_send   = "<M-cr>"
            let g:fsharp#fsi_keymap_toggle = "<M-@>"
        else
            let g:fsharp#fsi_keymap_send   = "<esc><cr>"
            let g:fsharp#fsi_keymap_toggle = "<esc>@"
        endif
    elseif g:fsharp#fsi_keymap == "vim-fsharp"
        let g:fsharp#fsi_keymap_send   = "<leader>i"
        let g:fsharp#fsi_keymap_toggle = "<leader>e"
    elseif g:fsharp#fsi_keymap == "custom"
        let g:fsharp#fsi_keymap = "none"
        if !exists('g:fsharp#fsi_keymap_send')
            echoerr "g:fsharp#fsi_keymap_send is not set"
        elseif !exists('g:fsharp#fsi_keymap_toggle')
            echoerr "g:fsharp#fsi_keymap_toggle is not set"
        else
            let g:fsharp#fsi_keymap = "custom"
        endif
    endif

    let s:config_is_loaded = 1
endfunction


" handlers for notifications

let s:handlers = {
    \ 'fsharp/notifyWorkspace': 'fsharp#handle_notifyWorkspace',
    \ }

function! s:registerAutocmds()
    if g:fsharp#backend == 'nvim' && g:fsharp#lsp_codelens
        augroup FSharp_AutoRefreshCodeLens
            autocmd!
            autocmd CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh()
        augroup END
    endif
    if g:fsharp#backend != 'disable'
        augroup FSharp_OnCursorMove
            autocmd!
            autocmd CursorMoved *.fs,*.fsi,*.fsx  call fsharp#OnCursorMove()
        augroup END
    endif
endfunction

function! fsharp#initialize()
    echom '[FSAC] Initialized'
    if g:fsharp#backend == 'languageclient-neovim'
        call LanguageClient_registerHandlers(s:handlers)
    endif
    call fsharp#updateServerConfig()
    call s:registerAutocmds()
endfunction


" nvim-lsp specific functions

" handlers are picked up by ionide.setup()
function! fsharp#get_handlers()
    return s:handlers
endfunction

let s:callbacks = {}

function! fsharp#register_callback(fn)
    if g:fsharp#backend != 'nvim'
        return -1
    endif
    let rnd = reltimestr(reltime())
    let s:callbacks[rnd] = a:fn
    return rnd
endfunction

function! fsharp#resolve_callback(key, arg)
    if g:fsharp#backend != 'nvim'
        return
    endif
    if has_key(s:callbacks, a:key)
        let Callback = s:callbacks[a:key]
        call Callback(a:arg)
        call remove(s:callbacks, a:key)
    endif
endfunction


" .NET/F# specific operations

let s:workspace = []

function! fsharp#handle_notifyWorkspace(payload) abort
    let content = json_decode(a:payload.content)
    if content.Kind == 'projectLoading'
        echom "[FSAC] Loading" content.Data.Project
        let s:workspace = uniq(sort(add(s:workspace, content.Data.Project)))
    elseif content.Kind == 'workspaceLoad' && content.Data.Status == 'finished'
        echom printf("[FSAC] Workspace loaded (%d project(s))", len(s:workspace))
        call fsharp#updateServerConfig()
    endif
endfunction


function! s:load(arg)
    call s:workspaceLoad(a:arg, v:null)
endfunction

function! fsharp#loadProject(...)
    let prjs = []
    for proj in a:000
        call add(prjs, fnamemodify(proj, ':p'))
    endfor
    call s:load(prjs)
endfunction

function! fsharp#showLoadedProjects()
    for proj in s:workspace
        echo "-" proj
    endfor
endfunction

function! fsharp#reloadProjects()
    if len(s:workspace) > 0
        call s:workspaceLoad(s:workspace, v:null)
    else
        echom "[FSAC] Workspace is empty"
    endif
endfunction

function! fsharp#OnFSProjSave()
    if &ft == "fsharp_project" && exists('g:fsharp#automatic_reload_workspace') && g:fsharp#automatic_reload_workspace
        call fsharp#reloadProjects()
    endif
endfunction

function! fsharp#showSignature()
    function! s:callback_showSignature(result)
        let result = a:result
        if exists('result.result.content')
            let content = json_decode(result.result.content)
            if exists('content.Data')
                echo substitute(content.Data, '\n\+$', ' ', 'g')
            endif
        endif
    endfunction
    call s:signature(expand('%:p'), line('.') - 1, col('.') - 1, function("s:callback_showSignature"))
endfunction

function! fsharp#OnCursorMove()
    if g:fsharp#show_signature_on_cursor_move
        call fsharp#showSignature()
    endif
endfunction

function! fsharp#showF1Help()
    let result = s:f1Help(expand('%:p'), line('.') - 1, col('.') - 1)
    echo result
endfunction

function! s:hover()
    if g:fsharp#backend == 'languageclient-neovim'
        call LanguageClient#textDocument_hover()
    elseif g:fsharp#backend == 'nvim'
        lua vim.lsp.buf.hover()
    endif
endfunction

function! fsharp#showTooltip()
    function! s:callback_showTooltip(result)
        let result = a:result
        if exists('result.result.content')
            let content = json_decode(result.result.content)
            if exists('content.Data')
                call s:hover()
            endif
        endif
    endfunction
    " show hover only if signature exists for the current position
    call s:signature(expand('%:p'), line('.') - 1, col('.') - 1, function("s:callback_showTooltip"))
endfunction


" FSAC update utils

function! s:update_win()
    echom "[FSAC] Downloading FSAC. This may take a while..."
    let script = s:script_root_dir . "install.ps1"
    call system('powershell -ExecutionPolicy Unrestricted ' . script . " update")
endfunction

function! s:update_unix()
    echom "[FSAC] Downloading FSAC. This may take a while..."
    let zip = s:script_root_dir . "fsac.zip"
    call system(
        \ 'curl -fLo ' . zip .  ' --create-dirs ' .
        \ '"https://github.com/fsharp/FsAutoComplete/releases/latest/download/fsautocomplete.netcore.zip"'
        \ )
    if v:shell_error == 0
        call system('unzip -o -d ' . s:script_root_dir . "/fsac " . zip)
        call system('find ' . s:script_root_dir . '/fsac' . ' -type f -exec chmod 777 \{\} \;')
        echom "[FSAC] Updated FsAutoComplete"
    else
        echom "[FSAC] Failed to update FsAutoComplete"
    endif
endfunction

function! fsharp#updateFSAC(...)
    if has('win32') && !has('win32unix')
        call s:update_win()
    else
        call s:update_unix()
    endif
endfunction


" FSI integration

let s:fsi_buffer = -1
let s:fsi_job    = -1
let s:fsi_width  = 0
let s:fsi_height = 0

function! s:win_gotoid_safe(winid)
    function! s:vimReturnFocus(window)
        call win_gotoid(a:window)
        redraw!
    endfunction
    if has('nvim')
        call win_gotoid(a:winid)
    else
        call timer_start(1, { -> s:vimReturnFocus(a:winid) })
    endif
endfunction

function! s:get_fsi_command()
    let cmd = g:fsharp#fsi_command
    for prm in g:fsharp#fsi_extra_parameters
        let cmd = cmd . " " . prm
    endfor
    return cmd
endfunction

function! fsharp#openFsi(returnFocus)
    if bufwinid(s:fsi_buffer) <= 0
        let fsi_command = s:get_fsi_command()
        if exists('*termopen') || exists('*term_start')
            let current_win = win_getid()
            execute g:fsharp#fsi_window_command
            if s:fsi_width  > 0 | execute 'vertical resize' s:fsi_width | endif
            if s:fsi_height > 0 | execute 'resize' s:fsi_height | endif
            " if window is closed but FSI is still alive then reuse it
            if s:fsi_buffer >= 0 && bufexists(str2nr(s:fsi_buffer))
                exec 'b' s:fsi_buffer
                normal G
                if !has('nvim') && mode() == 'n' | execute "normal A" | endif
                if a:returnFocus | call s:win_gotoid_safe(current_win) | endif
            " open FSI: Neovim
            elseif has('nvim')
                let s:fsi_job = termopen(fsi_command)
                if s:fsi_job > 0
                    let s:fsi_buffer = bufnr("%")
                else
                    close
                    echom "[FSAC] Failed to open FSI."
                    return -1
                endif
            " open FSI: Vim
            else
                let options = {
                \ "term_name": "F# Interactive",
                \ "curwin": 1,
                \ "term_finish": "close"
                \ }
                let s:fsi_buffer = term_start(fsi_command, options)
                if s:fsi_buffer != 0
                    if exists('*term_setkill') | call term_setkill(s:fsi_buffer, "term") | endif
                    let s:fsi_job = term_getjob(s:fsi_buffer)
                else
                    close
                    echom "[FSAC] Failed to open FSI."
                    return -1
                endif
            endif
            setlocal bufhidden=hide
            normal G
            if a:returnFocus | call s:win_gotoid_safe(current_win) | endif
            return s:fsi_buffer
        else
            echom "[FSAC] Your (neo)vim does not support terminal".
            return 0
        endif
    endif
    return s:fsi_buffer
endfunction

function! fsharp#toggleFsi()
    let fsiWindowId = bufwinid(s:fsi_buffer)
    if fsiWindowId > 0
        let current_win = win_getid()
        call win_gotoid(fsiWindowId)
        let s:fsi_width = winwidth('%')
        let s:fsi_height = winheight('%')
        close
        call win_gotoid(current_win)
    else
        call fsharp#openFsi(0)
    endif
endfunction

function! fsharp#quitFsi()
    if s:fsi_buffer >= 0 && bufexists(str2nr(s:fsi_buffer))
        if has('nvim')
            let winid = bufwinid(s:fsi_buffer)
            if winid > 0 | execute "close " . winid | endif
            call jobstop(s:fsi_job)
        else
            call job_stop(s:fsi_job, "term")
        endif
        let s:fsi_buffer = -1
        let s:fsi_job = -1
    endif
endfunction

function! fsharp#resetFsi()
    call fsharp#quitFsi()
    return fsharp#openFsi(1)
endfunction

function! fsharp#sendFsi(text)
    if fsharp#openFsi(!g:fsharp#fsi_focus_on_send) > 0
        " Neovim
        if has('nvim')
            call chansend(s:fsi_job, a:text . "\n" . ";;". "\n")
        " Vim 8
        else
            call term_sendkeys(s:fsi_buffer, a:text . "\<cr>" . ";;" . "\<cr>")
            call term_wait(s:fsi_buffer)
        endif
    endif
endfunction

" https://stackoverflow.com/a/6271254
function! s:get_visual_selection()
    let [line_start, column_start] = getpos("'<")[1:2]
    let [line_end, column_end] = getpos("'>")[1:2]
    let lines = getline(line_start, line_end)
    if len(lines) == 0
        return ''
    endif
    let lines[-1] = lines[-1][: column_end - (&selection == 'inclusive' ? 1 : 2)]
    let lines[0] = lines[0][column_start - 1:]
    return lines
endfunction

function! s:get_complete_buffer()
    return join(getline(1, '$'), "\n")
endfunction

function! fsharp#sendSelectionToFsi() range
    let lines = s:get_visual_selection()
    exec 'normal' len(lines) . 'j'
    let text = join(lines, "\n")
    return fsharp#sendFsi(text)
endfunction

function! fsharp#sendLineToFsi()
    let text = getline('.')
    exec 'normal j'
    return fsharp#sendFsi(text)
endfunction

function! fsharp#sendAllToFsi()
    let text = s:get_complete_buffer()
    return fsharp#sendFsi(text)
endfunction

let &cpo = s:cpo_save
unlet s:cpo_save

" vim: sw=4 et sts=4