summaryrefslogtreecommitdiffstats
path: root/runtime/ftplugin/ocaml.vim
blob: 8b88d8d00176758d52143b189f4a72b1052f7af3 (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
" Language:    OCaml
" Maintainer:  David Baelde        <firstname.name@ens-lyon.org>
"              Mike Leary          <leary@nwlink.com>
"              Markus Mottl        <markus.mottl@gmail.com>
"              Pierre Vittet       <pierre-vittet@pvittet.com>
"              Stefano Zacchiroli  <zack@bononia.it>
"              Vincent Aravantinos <firstname.name@imag.fr>
"              Riley Bruins <ribru17@gmail.com> ('commentstring')
" URL:         https://github.com/ocaml/vim-ocaml
" Last Change:
"              2013 Oct 27 - Added commentstring (MM)
"              2013 Jul 26 - load default compiler settings (MM)
"              2013 Jul 24 - removed superfluous efm-setting (MM)
"              2013 Jul 22 - applied fixes supplied by Hirotaka Hamada (MM)
"              2024 May 23 - added space in commentstring (RB)

if exists("b:did_ftplugin")
  finish
endif
let b:did_ftplugin=1

" Use standard compiler settings unless user wants otherwise
if !exists("current_compiler")
  :compiler ocaml
endif

" some macro
if exists('*fnameescape')
  function! s:Fnameescape(s)
    return fnameescape(a:s)
  endfun
else
  function! s:Fnameescape(s)
    return escape(a:s," \t\n*?[{`$\\%#'\"|!<")
  endfun
endif

" Error handling -- helps moving where the compiler wants you to go
let s:cposet=&cpoptions
set cpo&vim

" Comment string
setlocal comments=sr:(*\ ,mb:\ ,ex:*)
setlocal comments^=sr:(**,mb:\ \ ,ex:*)
setlocal commentstring=(*\ %s\ *)

" Add mappings, unless the user didn't want this.
if !exists("no_plugin_maps") && !exists("no_ocaml_maps")
  " (un)commenting
  if !hasmapto('<Plug>Comment')
    nmap <buffer> <LocalLeader>c <Plug>LUncomOn
    xmap <buffer> <LocalLeader>c <Plug>BUncomOn
    nmap <buffer> <LocalLeader>C <Plug>LUncomOff
    xmap <buffer> <LocalLeader>C <Plug>BUncomOff
  endif

  nnoremap <buffer> <Plug>LUncomOn gI(* <End> *)<ESC>
  nnoremap <buffer> <Plug>LUncomOff :s/^(\* \(.*\) \*)/\1/<CR>:noh<CR>
  xnoremap <buffer> <Plug>BUncomOn <ESC>:'<,'><CR>`<O<ESC>0i(*<ESC>`>o<ESC>0i*)<ESC>`<
  xnoremap <buffer> <Plug>BUncomOff <ESC>:'<,'><CR>`<dd`>dd`<

  nmap <buffer> <LocalLeader>s <Plug>OCamlSwitchEdit
  nmap <buffer> <LocalLeader>S <Plug>OCamlSwitchNewWin

  nmap <buffer> <LocalLeader>t <Plug>OCamlPrintType
  xmap <buffer> <LocalLeader>t <Plug>OCamlPrintType
endif

" Let % jump between structure elements (due to Issac Trotts)
let b:mw =         '\<let\>:\<and\>:\(\<in\>\|;;\)'
let b:mw = b:mw . ',\<if\>:\<then\>:\<else\>'
let b:mw = b:mw . ',\<\(for\|while\)\>:\<do\>:\<done\>'
let b:mw = b:mw . ',\<\(object\|sig\|struct\|begin\)\>:\<end\>'
let b:mw = b:mw . ',\<\(match\|try\)\>:\<with\>'
let b:match_words = b:mw

let b:match_ignorecase=0

function! s:OcpGrep(bang,args) abort
  let grepprg = &l:grepprg
  let grepformat = &l:grepformat
  let shellpipe = &shellpipe
  try
    let &l:grepprg = "ocp-grep -c never"
    setlocal grepformat=%f:%l:%m
    if &shellpipe ==# '2>&1| tee' || &shellpipe ==# '|& tee'
      let &shellpipe = "| tee"
    endif
    execute 'grep! '.a:args
    if empty(a:bang) && !empty(getqflist())
      return 'cfirst'
    else
      return ''
    endif
  finally
    let &l:grepprg = grepprg
    let &l:grepformat = grepformat
    let &shellpipe = shellpipe
  endtry
endfunction
command! -bar -bang -complete=file -nargs=+ Ocpgrep exe s:OcpGrep(<q-bang>, <q-args>)

" switching between interfaces (.mli) and implementations (.ml)
if !exists("g:did_ocaml_switch")
  let g:did_ocaml_switch = 1
  nnoremap <Plug>OCamlSwitchEdit :<C-u>call OCaml_switch(0)<CR>
  nnoremap <Plug>OCamlSwitchNewWin :<C-u>call OCaml_switch(1)<CR>
  fun OCaml_switch(newwin)
    if (match(bufname(""), "\\.mli$") >= 0)
      let fname = s:Fnameescape(substitute(bufname(""), "\\.mli$", ".ml", ""))
      if (a:newwin == 1)
        exec "new " . fname
      else
        exec "arge " . fname
      endif
    elseif (match(bufname(""), "\\.ml$") >= 0)
      let fname = s:Fnameescape(bufname("")) . "i"
      if (a:newwin == 1)
        exec "new " . fname
      else
        exec "arge " . fname
      endif
    endif
  endfun
endif

" Folding support

" Get the modeline because folding depends on indentation
let lnum = search('^\s*(\*:o\?caml:', 'n')
let s:modeline = lnum? getline(lnum): ""

" Get the indentation params
let s:m = matchstr(s:modeline,'default\s*=\s*\d\+')
if s:m != ""
  let s:idef = matchstr(s:m,'\d\+')
elseif exists("g:omlet_indent")
  let s:idef = g:omlet_indent
else
  let s:idef = 2
endif
let s:m = matchstr(s:modeline,'struct\s*=\s*\d\+')
if s:m != ""
  let s:i = matchstr(s:m,'\d\+')
elseif exists("g:omlet_indent_struct")
  let s:i = g:omlet_indent_struct
else
  let s:i = s:idef
endif

" Set the folding method
if exists("g:ocaml_folding")
  setlocal foldmethod=expr
  setlocal foldexpr=OMLetFoldLevel(v:lnum)
endif

let b:undo_ftplugin = "setlocal efm< foldmethod< foldexpr<"
	\ . "| unlet! b:mw b:match_words b:match_ignorecase"


" - Only definitions below, executed once -------------------------------------

if exists("*OMLetFoldLevel")
  let &cpoptions = s:cposet
  unlet s:cposet
  finish
endif

function s:topindent(lnum)
  let l = a:lnum
  while l > 0
    if getline(l) =~ '\s*\%(\<struct\>\|\<sig\>\|\<object\>\)'
      return indent(l)
    endif
    let l = l-1
  endwhile
  return -s:i
endfunction

function OMLetFoldLevel(l)

  " This is for not merging blank lines around folds to them
  if getline(a:l) !~ '\S'
    return -1
  endif

  " We start folds for modules, classes, and every toplevel definition
  if getline(a:l) =~ '^\s*\%(\<val\>\|\<module\>\|\<class\>\|\<type\>\|\<method\>\|\<initializer\>\|\<inherit\>\|\<exception\>\|\<external\>\)'
    exe 'return ">' (indent(a:l)/s:i)+1 '"'
  endif

  " Toplevel let are detected thanks to the indentation
  if getline(a:l) =~ '^\s*let\>' && indent(a:l) == s:i+s:topindent(a:l)
    exe 'return ">' (indent(a:l)/s:i)+1 '"'
  endif

  " We close fold on end which are associated to struct, sig or object.
  " We use syntax information to do that.
  if getline(a:l) =~ '^\s*end\>' && synIDattr(synID(a:l, indent(a:l)+1, 0), "name") != "ocamlKeyword"
    return (indent(a:l)/s:i)+1
  endif

  " Folds end on ;;
  if getline(a:l) =~ '^\s*;;'
    exe 'return "<' (indent(a:l)/s:i)+1 '"'
  endif

  " Comments around folds aren't merged to them.
  if synIDattr(synID(a:l, indent(a:l)+1, 0), "name") == "ocamlComment"
    return -1
  endif

  return '='
endfunction

" Vim support for OCaml .annot files
"
" Last Change: 2007 Jul 17
" Maintainer:  Vincent Aravantinos <vincent.aravantinos@gmail.com>
" License:     public domain
"
" Originally inspired by 'ocaml-dtypes.vim' by Stefano Zacchiroli.
" The source code is quite radically different for we not use python anymore.
" However this plugin should have the exact same behaviour, that's why the
" following lines are the quite exact copy of Stefano's original plugin :
"
" <<
" Executing Ocaml_print_type(<mode>) function will display in the Vim bottom
" line(s) the type of an ocaml value getting it from the corresponding .annot
" file (if any).  If Vim is in visual mode, <mode> should be "visual" and the
" selected ocaml value correspond to the highlighted text, otherwise (<mode>
" can be anything else) it corresponds to the literal found at the current
" cursor position.
"
" Typing '<LocalLeader>t' (LocalLeader defaults to '\', see :h LocalLeader)
" will cause " Ocaml_print_type function to be invoked with the right
" argument depending on the current mode (visual or not).
" >>
"
" If you find something not matching this behaviour, please signal it.
"
" Differences are:
"   - no need for python support
"     + plus : more portable
"     + minus: no more lazy parsing, it looks very fast however
"
"   - ocamlbuild support, ie.
"     + the plugin finds the _build directory and looks for the
"       corresponding file inside;
"     + if the user decides to change the name of the _build directory thanks
"       to the '-build-dir' option of ocamlbuild, the plugin will manage in
"       most cases to find it out (most cases = if the source file has a unique
"       name among your whole project);
"     + if ocamlbuild is not used, the usual behaviour holds; ie. the .annot
"       file should be in the same directory as the source file;
"     + for vim plugin programmers:
"       the variable 'b:_build_dir' contains the inferred path to the build
"       directory, even if this one is not named '_build'.
"
" Bonus :
"   - latin1 accents are handled
"   - lists are handled, even on multiple lines, you don't need the visual mode
"     (the cursor must be on the first bracket)
"   - parenthesized expressions, arrays, and structures (ie. '(...)', '[|...|]',
"     and '{...}') are handled the same way

  " Copied from Stefano's original plugin :
  " <<
  "      .annot ocaml file representation
  "
  "      File format (copied verbatim from caml-types.el)
  "
  "      file ::= block *
  "      block ::= position <SP> position <LF> annotation *
  "      position ::= filename <SP> num <SP> num <SP> num
  "      annotation ::= keyword open-paren <LF> <SP> <SP> data <LF> close-paren
  "
  "      <SP> is a space character (ASCII 0x20)
  "      <LF> is a line-feed character (ASCII 0x0A)
  "      num is a sequence of decimal digits
  "      filename is a string with the lexical conventions of O'Caml
  "      open-paren is an open parenthesis (ASCII 0x28)
  "      close-paren is a closed parenthesis (ASCII 0x29)
  "      data is any sequence of characters where <LF> is always followed by
  "           at least two space characters.
  "
  "      - in each block, the two positions are respectively the start and the
  "        end of the range described by the block.
  "      - in a position, the filename is the name of the file, the first num
  "        is the line number, the second num is the offset of the beginning
  "        of the line, the third num is the offset of the position itself.
  "      - the char number within the line is the difference between the third
  "        and second nums.
  "
  "      For the moment, the only possible keyword is \"type\"."
  " >>


" 1. Finding the annotation file even if we use ocamlbuild

    " In:  two strings representing paths
    " Out: one string representing the common prefix between the two paths
  function! s:Find_common_path (p1,p2)
    let temp = a:p2
    while matchstr(a:p1,temp) == ''
      let temp = substitute(temp,'/[^/]*$','','')
    endwhile
    return temp
  endfun

    " After call:
    "
    "  Following information have been put in s:annot_file_list, using
    "  annot_file_name name as key:
    " - annot_file_path :
    "                       path to the .annot file corresponding to the
    "                       source file (dealing with ocamlbuild stuff)
    " - _build_path:
    "                       path to the build directory even if this one is
    "                       not named '_build'
    " - date_of_last annot:
    "                       Set to 0 until we load the file. It contains the
    "                       date at which the file has been loaded.
  function! s:Locate_annotation()
    let annot_file_name = s:Fnameescape(expand('%:t:r')).'.annot'
    if !exists ("s:annot_file_list[annot_file_name]")
      silent exe 'cd' s:Fnameescape(expand('%:p:h'))
      " 1st case : the annot file is in the same directory as the buffer (no ocamlbuild)
      let annot_file_path = findfile(annot_file_name,'.')
      if annot_file_path != ''
        let annot_file_path = getcwd().'/'.annot_file_path
        let _build_path = ''
      else
        " 2nd case : the buffer and the _build directory are in the same directory
        "      ..
        "     /  \
        "    /    \
        &qu