vimclojure / vim / autoload / vimclojure.vim

The default branch has multiple heads

   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
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
" Part of Vim filetype plugin for Clojure
" Language:     Clojure
" Maintainer:   Meikel Brandmeyer <mb@kotka.de>

let s:save_cpo = &cpo
set cpo&vim

function! vimclojure#WarnDeprecated(old, new)
	echohl WarningMsg
	echomsg a:old . " is deprecated! Use " . a:new . "!"
	echomsg "eg. let " . a:new . " = <desired value here>"
	echohl None
endfunction

" Configuration
if !exists("g:vimclojure#FuzzyIndent")
	let vimclojure#FuzzyIndent = 0
endif

if !exists("g:vimclojure#FuzzyIndentPatterns")
	let vimclojure#FuzzyIndentPatterns = "with.*,def.*,let.*"
endif

if !exists("g:vimclojure#HighlightBuiltins")
	if exists("g:clj_highlight_builtins")
		call vimclojure#WarnDeprecated("g:clj_highlight_builtins",
					\ "vimclojure#HighlightBuiltins")
		let vimclojure#HighlightBuiltins = g:clj_highlight_builtins
	else
		let vimclojure#HighlightBuiltins = 1
	endif
endif

if exists("g:clj_highlight_contrib")
	echohl WarningMsg
	echomsg "clj_highlight_contrib is deprecated! It's removed without replacement!"
	echohl None
endif

if !exists("g:vimclojure#DynamicHighlighting")
	if exists("g:clj_dynamic_highlighting")
		call vimclojure#WarnDeprecated("g:clj_dynamic_highlighting",
					\ "vimclojure#DynamicHighlighting")
		let vimclojure#DynamicHighlighting = g:clj_dynamic_highlighting
	else
		let vimclojure#DynamicHighlighting = 0
	endif
endif

if !exists("g:vimclojure#ParenRainbow")
	if exists("g:clj_paren_rainbow")
		call vimclojure#WarnDeprecated("g:clj_paren_rainbow",
					\ "vimclojure#ParenRainbow")
		let vimclojure#ParenRainbow = g:clj_paren_rainbow
	else
		let vimclojure#ParenRainbow = 0
	endif
endif

if !exists("g:vimclojure#WantNailgun")
	if exists("g:clj_want_gorilla")
		call vimclojure#WarnDeprecated("g:clj_want_gorilla",
					\ "vimclojure#WantNailgun")
		let vimclojure#WantNailgun = g:clj_want_gorilla
	else
		let vimclojure#WantNailgun = 0
	endif
endif

if !exists("g:vimclojure#NailgunServer")
	let vimclojure#NailgunServer = "127.0.0.1"
endif

if !exists("g:vimclojure#NailgunPort")
	let vimclojure#NailgunPort = "2113"
endif

if !exists("g:vimclojure#UseErrorBuffer")
	let vimclojure#UseErrorBuffer = 1
endif

if !exists("g:vimclojure#SetupKeyMap")
	let vimclojure#SetupKeyMap = 1
endif

if !exists("g:vimclojure#SearchThreshold")
	let vimclojure#SearchThreshold = 100
endif

function! vimclojure#ReportError(msg)
	if g:vimclojure#UseErrorBuffer
		let buf = g:vimclojure#ResultWindow.New(g:vimclojure#ResultBuffer)
		call buf.showText(a:msg)
		wincmd p
	else
		echoerr substitute(a:msg, '\n\(\t\?\)', ' ', 'g')
	endif
endfunction

function! vimclojure#EscapePathForOption(path)
	let path = fnameescape(a:path)

	" Hardcore escapeing of whitespace...
	let path = substitute(path, '\', '\\\\', 'g')
	let path = substitute(path, '\ ', '\\ ', 'g')

	return path
endfunction

function! vimclojure#AddPathToOption(path, option)
	let path = vimclojure#EscapePathForOption(a:path)
	execute "setlocal " . a:option . "+=" . path
endfunction

function! vimclojure#AddCompletions(ns)
	let completions = split(globpath(&rtp, "ftplugin/clojure/completions-" . a:ns . ".txt"), '\n')
	if completions != []
		call vimclojure#AddPathToOption('k' . completions[0], 'complete')
	endif
endfunction

function! ClojureExtractSexprWorker() dict
	let pos = [0, 0]
	let start = getpos(".")

	if getline(start[1])[start[2] - 1] == "("
				\ && vimclojure#util#SynIdName() =~ 'clojureParen' . self.level
		let pos = [start[1], start[2]]
	endif

	if pos == [0, 0]
		let pos = searchpairpos('(', '', ')', 'bW' . self.flag,
					\ 'vimclojure#util#SynIdName() !~ "clojureParen\\d"')
	endif

	if pos == [0, 0]
		throw "Error: Not in a s-expression!"
	endif

	return [pos, vimclojure#util#Yank('l', 'normal! "ly%')]
endfunction

" Nailgun part:
function! vimclojure#ExtractSexpr(toplevel)
	let closure = {
				\ "flag"  : (a:toplevel ? "r" : ""),
				\ "level" : (a:toplevel ? "0" : '\d'),
				\ "f"     : function("ClojureExtractSexprWorker")
				\ }

	return vimclojure#util#WithSavedPosition(closure)
endfunction

function! vimclojure#BufferName()
	let file = expand("%")
	if file == ""
		let file = "UNNAMED"
	endif
	return file
endfunction

" Key mappings and Plugs
function! vimclojure#MakeProtectedPlug(mode, plug, f, args)
	execute a:mode . "noremap <Plug>Clojure" . a:plug . "."
				\ . " :<C-U>call vimclojure#ProtectedPlug(function(\""
				\ . a:f . "\"), [ " . a:args . " ])<CR>"
endfunction

function! vimclojure#MakeCommandPlug(mode, plug, f, args)
	execute a:mode . "noremap <Plug>Clojure" . a:plug . "."
				\ . " :<C-U>call vimclojure#ProtectedPlug("
				\ . " function(\"vimclojure#CommandPlug\"),"
				\ . " [ function(\"" . a:f . "\"), [ " . a:args . " ]])<CR>"
endfunction

function! vimclojure#MapPlug(mode, keys, plug)
	if exists("g:vimclojure#SetupKeyMap" . a:plug)
		execute "let doSetup = g:vimclojure#SetupKeyMap" . a:plug
	else
		let doSetup = g:vimclojure#SetupKeyMap
	endif

	if doSetup && !hasmapto("<Plug>Clojure" . a:plug . ".", a:mode)
		execute a:mode . "map <buffer> <unique> <silent> <LocalLeader>" . a:keys
					\ . " <Plug>Clojure" . a:plug . "."
	endif
endfunction

if !exists("*vimclojure#CommandPlug")
	function vimclojure#CommandPlug(f, args)
		if exists("b:vimclojure_loaded")
					\ && !exists("b:vimclojure_namespace")
					\ && g:vimclojure#WantNailgun == 1
			unlet b:vimclojure_loaded
			call vimclojure#InitBuffer("silent")
		endif

		if exists("b:vimclojure_namespace")
			call call(a:f, a:args)
		elseif g:vimclojure#WantNailgun == 1
			let msg = "VimClojure could not initialise the server connection.\n"
						\ . "That means you will not be able to use the interactive features.\n"
						\ . "Reasons might be that the server is not running or that there is\n"
						\ . "some trouble with the classpath.\n\n"
						\ . "VimClojure will *not* start the server for you or handle the classpath.\n"
						\ . "There is a plethora of tools like ivy, maven, gradle and leiningen,\n"
						\ . "which do this better than VimClojure could ever do it."
			throw msg
		endif
	endfunction
endif

if !exists("*vimclojure#ProtectedPlug")
	function vimclojure#ProtectedPlug(f, args)
		try
			return call(a:f, a:args)
		catch /.*/
			call vimclojure#ReportError(v:exception)
		endtry
	endfunction
endif

" A Buffer...
if !exists("g:vimclojure#SplitPos")
	let vimclojure#SplitPos = "top"
endif

if !exists("g:vimclojure#SplitSize")
	let vimclojure#SplitSize = ""
endif

let vimclojure#Object = {}

function! vimclojure#Object.New(...) dict
	let instance = copy(self)
	let instance.prototype = self

	call call(instance.Init, a:000, instance)

	return instance
endfunction

function! vimclojure#Object.Init() dict
endfunction

function! vimclojure#Object.isA(type) dict
	return self.prototype is a:type
endfunction

let vimclojure#Buffer = copy(vimclojure#Object)
let vimclojure#Buffer["__superObjectNew"]  = vimclojure#Buffer["New"]
let vimclojure#Buffer["__superObjectInit"] = vimclojure#Buffer["Init"]

let vimclojure#BufferNr = 0

function! vimclojure#Buffer.New(...) dict
	let nr = g:vimclojure#BufferNr
	let bufname = printf("vimclojure_buffer_%06d", nr)
	let g:vimclojure#BufferNr += 1

	execute "badd" bufname
	execute "buffer!" bufname

	return call(self.__superObjectNew, a:000, self)
endfunction

function! vimclojure#Buffer.Init() dict
	call self.__superObjectInit()
	let b:vimclojure_buffer = self
	let self._buf = bufnr("%")
endfunction

function! vimclojure#Buffer.showText(text) dict
	if type(a:text) == type("")
		" XXX: Opening the box of the pandora.
		" 2012-01-09: Adding Carriage Returns here.
		let text = split(a:text, '\r\?\n')
	else
		let text = a:text
	endif
	call append(line("$"), text)
endfunction

function! vimclojure#Buffer.clear() dict
	1
	normal! "_dG
endfunction

function! vimclojure#Buffer.goHere() dict
	if bufnr("%") != self._buf
		execute "buffer!" self._buf
	endif
endfunction

function! vimclojure#Buffer.close() dict
	execute "bdelete!" self._buf
endfunction

function! vimclojure#NoOp(...) dict
endfunction

let vimclojure#NullBuffer = copy(vimclojure#Object)
let vimclojure#NullBuffer.showText = function("vimclojure#NoOp")
let vimclojure#NullBuffer.clear    = function("vimclojure#NoOp")
let vimclojure#NullBuffer.goHere   = function("vimclojure#NoOp")
let vimclojure#NullBuffer.close    = function("vimclojure#NoOp")

let vimclojure#Window = copy(vimclojure#Object)
let vimclojure#Window["__superObjectNew"] = vimclojure#Window["New"]
let vimclojure#Window["__superObjectInit"] = vimclojure#Window["Init"]

function! vimclojure#Window.New(...) dict
	if g:vimclojure#SplitPos == "left" || g:vimclojure#SplitPos == "right"
		let o_sr = &splitright
		if g:vimclojure#SplitPos == "left"
			set nosplitright
		else
			set splitright
		end
		execute printf("%svsplit", g:vimclojure#SplitSize)
		let &splitright = o_sr
	else
		let o_sb = &splitbelow
		if g:vimclojure#SplitPos == "bottom"
			set splitbelow
		else
			set nosplitbelow
		end
		execute printf("%ssplit", g:vimclojure#SplitSize)
		let &splitbelow = o_sb
	endif

	return call(self.__superObjectNew, a:000, self)
endfunction

function! vimclojure#Window.Init(buftype) dict
	call self.__superObjectInit()
	let w:vimclojure_window = self
	let self._buffer = a:buftype.New()
endfunction

function! vimclojure#Window.goHere() dict
	let wn = self.findThis()
	if wn == -1
		echoerr 'A crisis has arisen! Cannot find my window.'
	endif
	execute wn . "wincmd w"
	call self._buffer.goHere()
endfunction

function! vimclojure#Window.resize() dict
	call self.goHere()
	let size = line("$")
	if size < 3
		let size = 3
	endif
	execute "resize " . size
endfunction

function! vimclojure#Window.showText(text) dict
	call self.goHere()
	call self._buffer.showText(a:text)
endfunction

function! vimclojure#Window.showOutput(output) dict
	call self.goHere()
	if a:output.value == 0
		if a:output.stdout != ""
			call self._buffer.showText(a:output.stdout)
		endif
		if a:output.stderr != ""
			call self._buffer.showText(a:output.stderr)
		endif
	else
		call self._buffer.showText(a:output.value)
	endif
endfunction

function! vimclojure#Window.clear() dict
	call self.goHere()
	call self._buffer.clear()
endfunction

function! vimclojure#Window.close() dict
	call self._buffer.close()
endfunction

function! vimclojure#Window.findThis() dict
	for w in range(1, winnr("$"))
		if type(getwinvar(w, "vimclojure_window")) == type({})
			if getwinvar(w, "vimclojure_window") == self
				return w
			endif
		endif
	endfor

	return -1
endfunction

" The transient buffer, used to display results.
let vimclojure#ResultWindow = copy(vimclojure#Window)
let vimclojure#ResultWindow["__superWindowNew"]   = vimclojure#ResultWindow["New"]
let vimclojure#ResultWindow["__superWindowClose"] = vimclojure#ResultWindow["close"]

function! vimclojure#ResultWindow.New(buftype, ...) dict
	if exists("t:vimclojure_result_window")
		" Otherwise the result window was closed.
		if t:vimclojure_result_window.findThis() != -1
			call t:vimclojure_result_window.goHere()

			if !t:vimclojure_result_window._buffer.isA(a:buftype)
				let t:vimclojure_result_window._buffer = a:buftype.New()
			else
				call t:vimclojure_result_window.clear()
			endif

			return t:vimclojure_result_window
		else
			unlet t:vimclojure_result_window
		endif
	endif

	let instance = call(self.__superWindowNew, [a:buftype] + a:000, self)
	let b:vimclojure_result_buffer = 1
	let t:vimclojure_result_window = instance

	augroup VimClojure
		autocmd BufDelete <buffer> call g:vimclojure#ResultWindow.Demote(
					\ getbufvar(eval(expand("<abuf>")), "vimclojure_buffer"))
	augroup END

	return instance
endfunction

" Remove the buffer object from the window. The buffer is removed
" automatically be Vim, when it is removed from the window.
function! vimclojure#ResultWindow.Demote(buffer) dict
	if exists("t:vimclojure_result_window")
		if t:vimclojure_result_window._buffer is a:buffer
			let t:vimclojure_result_window._buffer =
						\ g:vimclojure#NullBuffer.New()
		endif
	endif
endfunction

function! vimclojure#ResultWindow.close() dict
	unlet t:vimclojure_result_window
	call self.__superWindowClose()
endfunction

function! vimclojure#ResultWindow.CloseWindow() dict
	if exists("t:vimclojure_result_window")
		call t:vimclojure_result_window.close()
	endif
endfunction

"function! s:InvalidateResultBufferIfNecessary(buf)
"	" FIXME: This is incorrect.
"	if exists("t:vimclojure_result_window")
"				\ && t:vimclojure_result_window._buffer._buf == a:buf
"		let t:vimclojure_result_window.close()
"	endif
"endfunction

"augroup VimClojureResultWindow
"	au BufDelete * call s:InvalidateResultWindowIfNecessary(expand("<abuf>"))
"augroup END

let vimclojure#ResultBuffer = copy(vimclojure#Buffer)
let vimclojure#ResultBuffer["__superBufferInit"]  = vimclojure#ResultBuffer.Init
let vimclojure#ResultBuffer["__superBufferClear"] = vimclojure#ResultBuffer.clear

function! vimclojure#ResultBuffer.Init() dict
	call self.__superBufferInit()
	setlocal noswapfile
	setlocal buftype=nofile
	setlocal bufhidden=wipe

	call vimclojure#MapPlug("n", "p", "CloseResultBuffer")

	call self.clear()
endfunction

function! vimclojure#ResultBuffer.clear() dict
	call self.__superBufferClear()
	let leader = exists("g:maplocalleader") ? g:maplocalleader : "\\"
	call append(0, "; Use " . leader . "p to close this buffer!")
endfunction

" A special result buffer for clojure output.
let vimclojure#ClojureResultBuffer = copy(vimclojure#ResultBuffer)
let vimclojure#ClojureResultBuffer["__superResultBufferInit"] =
			\ vimclojure#ResultBuffer["Init"]
let vimclojure#ClojureResultBuffer["__superResultBufferShowText"] =
			\ vimclojure#ResultBuffer["showText"]

function! vimclojure#ClojureResultBuffer.Init(...) dict
	call self.__superResultBufferInit()
	set filetype=vimclojure.clojure
	if a:0 == 1
		let b:vimclojure_namespace = a:1
	else
		let b:vimclojure_namespace = "user"
	endif
endfunction

function! vimclojure#ClojureResultBuffer.showText(text) dict
	call self.__superResultBufferShowText(a:text)
	normal G
endfunction

" Nails
if !exists("vimclojure#NailgunClient")
	let vimclojure#NailgunClient = "ng"
endif

function! ClojureShellEscapeArgumentsWorker() dict
	set noshellslash
	return map(copy(self.vals), 'shellescape(v:val)')
endfunction

function! vimclojure#ShellEscapeArguments(vals)
	let closure = {
				\ 'vals': a:vals,
				\ 'f'   : function("ClojureShellEscapeArgumentsWorker")
				\ }

	return vimclojure#util#WithSavedOption('shellslash', closure)
endfunction

function! vimclojure#ExecuteNailWithInput(nail, input, ...)
	if type(a:input) == type("")
		let input = split(a:input, '\n', 1)
	else
		let input = a:input
	endif

	let inputfile = tempname()
	try
		call writefile(input, inputfile)

		let cmdline = vimclojure#ShellEscapeArguments(
					\ [g:vimclojure#NailgunClient,
					\   '--nailgun-server', g:vimclojure#NailgunServer,
					\   '--nailgun-port', g:vimclojure#NailgunPort,
					\   'vimclojure.Nail', a:nail]
					\ + a:000)
		let cmd = join(cmdline, " ") . " <" . inputfile
		" Add hardcore quoting for Windows
		if has("win32") || has("win64")
			let cmd = '"' . cmd . '"'
		endif

		let output = system(cmd)

		if v:shell_error
			throw "Error executing Nail! (" . v:shell_error . ")\n" . output
		endif
	finally
		call delete(inputfile)
	endtry

	execute "let result = " . substitute(output, '\n$', '', '')
	return result
endfunction

function! vimclojure#ExecuteNail(nail, ...)
	return call(function("vimclojure#ExecuteNailWithInput"), [a:nail, ""] + a:000)
endfunction

function! vimclojure#ShowResult(result)
	let buf = g:vimclojure#ResultWindow.New(g:vimclojure#ResultBuffer)
	call buf.showOutput(a:result)
	wincmd p
endfunction

function! vimclojure#ShowClojureResult(result, nspace)
	let buf = g:vimclojure#ResultWindow.New(g:vimclojure#ClojureResultBuffer)
	let b:vimclojure_namespace = a:nspace
	call buf.showOutput(a:result)
	wincmd p
endfunction

function! vimclojure#DocLookup(word)
	if a:word == ""
		return
	endif

	let doc = vimclojure#ExecuteNailWithInput("DocLookup", a:word,
				\ "-n", b:vimclojure_namespace)
	call vimclojure#ShowResult(doc)
endfunction

function! vimclojure#FindDoc()
	let pattern = input("Pattern to look for: ")
	let doc = vimclojure#ExecuteNailWithInput("FindDoc", pattern)
	call vimclojure#ShowResult(doc)
endfunction

let s:DefaultJavadocPaths = {
			\ "java" : "http://java.sun.com/javase/6/docs/api/",
			\ "org/apache/commons/beanutils" : "http://commons.apache.org/beanutils/api/",
			\ "org/apache/commons/chain" : "http://commons.apache.org/chain/api-release/",
			\ "org/apache/commons/cli" : "http://commons.apache.org/cli/api-release/",
			\ "org/apache/commons/codec" : "http://commons.apache.org/codec/api-release/",
			\ "org/apache/commons/collections" : "http://commons.apache.org/collections/api-release/",
			\ "org/apache/commons/logging" : "http://commons.apache.org/logging/apidocs/",
			\ "org/apache/commons/mail" : "http://commons.apache.org/email/api-release/",
			\ "org/apache/commons/io" : "http://commons.apache.org/io/api-release/"
			\ }

if !exists("vimclojure#JavadocPathMap")
	let vimclojure#JavadocPathMap = {}
endif

for k in keys(s:DefaultJavadocPaths)
	if !has_key(vimclojure#JavadocPathMap, k)
		let vimclojure#JavadocPathMap[k] = s:DefaultJavadocPaths[k]
	endif
endfor

if !exists("vimclojure#Browser")
	if has("win32") || has("win64")
		let vimclojure#Browser = "start"
	elseif has("mac")
		let vimclojure#Browser = "open"
	else
		" some freedesktop thing, whatever, issue #67
		let vimclojure#Browser = "xdg-open"
	endif
endif

function! vimclojure#JavadocLookup(word)
	let word = substitute(a:word, "\\.$", "", "")
	let path = vimclojure#ExecuteNailWithInput("JavadocPath", word,
				\ "-n", b:vimclojure_namespace)

	if path.stderr != ""
		call vimclojure#ShowResult(path)
		return
	endif

	let match = ""
	for pattern in keys(g:vimclojure#JavadocPathMap)
		if path.value =~ "^" . pattern && len(match) < len(pattern)
			let match = pattern
		endif
	endfor

	if match == ""
		echoerr "No matching Javadoc URL found for " . path.value
	endif

	let url = g:vimclojure#JavadocPathMap[match] . path.value
	call system(join([g:vimclojure#Browser, url], " "))
endfunction

function! vimclojure#SourceLookup(word)
	let source = vimclojure#ExecuteNailWithInput("SourceLookup", a:word,
				\ "-n", b:vimclojure_namespace)
	call vimclojure#ShowClojureResult(source, b:vimclojure_namespace)
endfunction

function! vimclojure#MetaLookup(word)
	let meta = vimclojure#ExecuteNailWithInput("MetaLookup", a:word,
				\ "-n", b:vimclojure_namespace)
	call vimclojure#ShowClojureResult(meta, b:vimclojure_namespace)
endfunction

function! vimclojure#GotoSource(word)
	let pos = vimclojure#ExecuteNailWithInput("SourceLocation", a:word,
				\ "-n", b:vimclojure_namespace)

	if pos.stderr != ""
		call vimclojure#ShowResult(pos)
		return
	endif

	if !filereadable(pos.value.file)
		let file = globpath(&path, pos.value.file)
		if file == ""
			echoerr pos.value.file . " not found in 'path'"
			return
		endif
		let pos.value.file = file
	endif

	execute "edit " . pos.value.file
	execute pos.value.line
endfunction

" Evaluators
function! vimclojure#MacroExpand(firstOnly)
	let [unused, sexp] = vimclojure#ExtractSexpr(0)
	let ns = b:vimclojure_namespace

	let cmd = ["MacroExpand", sexp, "-n", ns]
	if a:firstOnly
		let cmd = cmd + [ "-o" ]
	endif

	let expanded = call(function("vimclojure#ExecuteNailWithInput"), cmd)

	call vimclojure#ShowClojureResult(expanded, ns)
endfunction

function! vimclojure#RequireFile(all)
	let ns = b:vimclojure_namespace
	let all = a:all ? "-all" : ""

	let require = "(require :reload" . all . " :verbose '". ns. ")"
	let result = vimclojure#ExecuteNailWithInput("Repl", require, "-r")

	call vimclojure#ShowClojureResult(result, ns)
endfunction

function! vimclojure#RunTests(all)
	let ns = b:vimclojure_namespace

	let result = call(function("vimclojure#ExecuteNailWithInput"),
				\ [ "RunTests", "", "-n", ns ] + (a:all ? [ "-a" ] : []))

	call vimclojure#ShowClojureResult(result, ns)
endfunction

function! vimclojure#EvalFile()
	let content = getbufline(bufnr("%"), 1, line("$"))
	let file = vimclojure#BufferName()
	let ns = b:vimclojure_namespace

	let result = vimclojure#ExecuteNailWithInput("Repl", content,
				\ "-r", "-n", ns, "-f", file)

	call vimclojure#ShowClojureResult(result, ns)
endfunction

function! vimclojure#EvalLine()
	let theLine = line(".")
	let content = getline(theLine)
	let file = vimclojure#BufferName()
	let ns = b:vimclojure_namespace

	let result = vimclojure#ExecuteNailWithInput("Repl", content,
				\ "-r", "-n", ns, "-f", file, "-l", theLine)

	call vimclojure#ShowClojureResult(result, ns)
endfunction

function! vimclojure#EvalBlock()
	let file = vimclojure#BufferName()
	let ns = b:vimclojure_namespace

	let content = vimclojure#util#Yank("l", 'normal! gv"ly')
	let result = vimclojure#ExecuteNailWithInput("Repl", content,
				\ "-r", "-n", ns, "-f", file, "-l", line("'<") - 1)

	call vimclojure#ShowClojureResult(result, ns)
endfunction

function! vimclojure#EvalToplevel()
	let file = vimclojure#BufferName()
	let ns = b:vimclojure_namespace
	let [pos, expr] = vimclojure#ExtractSexpr(1)

	let result = vimclojure#ExecuteNailWithInput("Repl", expr,
				\ "-r", "-n", ns, "-f", file, "-l", pos[0] - 1)

	call vimclojure#ShowClojureResult(result, ns)
endfunction

function! ClojureEvalParagraphWorker() dict
	normal! }
	return line(".")
endfunction

function! vimclojure#EvalParagraph()
	let file = vimclojure#BufferName()
	let ns = b:vimclojure_namespace
	let startPosition = line(".")

	let closure = { 'f' : function("ClojureEvalParagraphWorker") }

	let endPosition = vimclojure#util#WithSavedPosition(closure)

	let content = getbufline(bufnr("%"), startPosition, endPosition)
	let result = vimclojure#ExecuteNailWithInput("Repl", content,
				\ "-r", "-n", ns, "-f", file, "-l", startPosition - 1)

	call vimclojure#ShowClojureResult(result, ns)
endfunction

" The Repl
let vimclojure#Repl = copy(vimclojure#Window)
let vimclojure#Repl["__superWindowNew"]   = vimclojure#Repl.New
let vimclojure#Repl["__superWindowInit"]  = vimclojure#Repl.Init
let vimclojure#Repl["__superWindowClear"] = vimclojure#Repl.clear

let vimclojure#Repl._history = []
let vimclojure#Repl._historyDepth = 0
let vimclojure#Repl._replCommands = [ ",close", ",st", ",ct", ",toggle-pprint" ]

" Simple wrapper to allow on demand load of autoload/vimclojure.vim.
function! vimclojure#StartRepl(...)
	let ns = a:0 > 0 ? a:1 : "user"
	call g:vimclojure#Repl.New(ns)
endfunction

" FIXME: Ugly hack. But easier than cleaning up the buffer
" mess in case something goes wrong with repl start.
function! vimclojure#Repl.New(namespace, ...) dict
	let replStart = vimclojure#ExecuteNail("Repl", "-s",
				\ "-n", a:namespace)
	if replStart.stderr != ""
		call vimclojure#ReportError(replStart.stderr)
		return
	endif

	let instance = call(self.__superWindowNew,
				\ [g:vimclojure#Buffer, a:namespace] + a:000,
				\ self)
	let instance._id = replStart.value.id
	call vimclojure#ExecuteNailWithInput("Repl",
				\ "(require 'clojure.stacktrace)",
				\ "-r", "-i", instance._id)

	return instance
endfunction

function! vimclojure#Repl.Init(buftype, namespace) dict
	call self.__superWindowInit(a:buftype)

	let self._prompt = a:namespace . "=>"

	setlocal buftype=nofile
	setlocal noswapfile

	call append(line("$"), ["Clojure", self._prompt . " "])

	let b:vimclojure_repl = self

	set filetype=vimclojure.clojure
	let b:vimclojure_namespace = a:namespace

	if !hasmapto("<Plug>ClojureReplEnterHook.", "i")
		imap <buffer> <silent> <CR> <Plug>ClojureReplEnterHook.
	endif
	if !hasmapto("<Plug>ClojureReplEvaluate.", "i")
		imap <buffer> <silent> <C-CR> <Plug>ClojureReplEvaluate.
	endif
	if !hasmapto("<Plug>ClojureReplHatHook.", "n")
		nmap <buffer> <silent> ^ <Plug>ClojureReplHatHook.
	endif
	if !hasmapto("<Plug>ClojureReplUpHistory.", "i")
		imap <buffer> <silent> <C-Up> <Plug>ClojureReplUpHistory.
	endif
	if !hasmapto("<Plug>ClojureReplDownHistory.", "i")
		imap <buffer> <silent> <C-Down> <Plug>ClojureReplDownHistory.
	endif

	normal! G
	startinsert!
endfunction

function! vimclojure#Repl.isReplCommand(cmd) dict
	for candidate in self._replCommands
		if candidate == a:cmd
			return 1
		endif
	endfor
	return 0
endfunction

function! vimclojure#Repl.doReplCommand(cmd) dict
	if a:cmd == ",close"
		call vimclojure#ExecuteNail("Repl", "-S", "-i", self._id)
		call self.close()
		stopinsert
	elseif a:cmd == ",st"
		let result = vimclojure#ExecuteNailWithInput("Repl",
					\ "(vimclojure.util/pretty-print-stacktrace *e)", "-r",
					\ "-i", self._id)
		call self.showOutput(result)
		call self.showPrompt()
	elseif a:cmd == ",ct"
		let result = vimclojure#ExecuteNailWithInput("Repl",
					\ "(vimclojure.util/pretty-print-causetrace *e)", "-r",
					\ "-i", self._id)
		call self.showOutput(result)
		call self.showPrompt()
	elseif a:cmd == ",toggle-pprint"
		let result = vimclojure#ExecuteNailWithInput("Repl",
					\ "(set! vimclojure.repl/*print-pretty* (not vimclojure.repl/*print-pretty*))", "-r",
					\ "-i", self._id)
		call self.showOutput(result)
		call self.showPrompt()
	endif
endfunction

function! vimclojure#Repl.showPrompt() dict
	call self.showText(self._prompt . " ")
	normal! G
	startinsert!
endfunction

function! vimclojure#Repl.clear() dict
	call self.__superWindowClear()
	call self.showPrompt()
endfunction

function! vimclojure#Repl.getCommand() dict
	let ln = line("$")

	while getline(ln) !~ "^" . self._prompt && ln > 0
		let ln = ln - 1
	endwhile

	" Special Case: User deleted Prompt by accident. Insert a new one.
	if ln == 0
		call self.showPrompt()
		return ""
	endif

	let cmd = vimclojure#util#Yank("l", ln . "," . line("$") . "yank l")

	let cmd = substitute(cmd, "^" . self._prompt . "\\s*", "", "")
	let cmd = substitute(cmd, "\n$", "", "")
	return cmd
endfunction

function! vimclojure#ReplDoEnter()
	execute "normal! a\<CR>x"
	normal! ==x
	if getline(".") =~ '^\s*$'
		startinsert!
	else
		startinsert
	endif
endfunction

function! vimclojure#Repl.enterHook() dict
	let lastCol = {}

	function lastCol.f() dict
		normal! g_
		return col(".")
	endfunction

	if line(".") < line("$") || col(".") < vimclojure#util#WithSavedPosition(lastCol)
		call vimclojure#ReplDoEnter()
		return
	endif

	let cmd = self.getCommand()

	" Special Case: Showed prompt (or user just hit enter).
	if cmd =~ '^\(\s\|\n\)*$'
		execute "normal! a\<CR>"
		startinsert!
		return
	endif

	if self.isReplCommand(cmd)
		call self.doReplCommand(cmd)
		return
	endif

	let result = vimclojure#ExecuteNailWithInput("CheckSyntax", cmd,
				\ "-n", b:vimclojure_namespace)
	if result.value == 0 && result.stderr == ""
		call vimclojure#ReplDoEnter()
	elseif result.stderr != ""
		call vimclojure#ShowResult(result)
	else
		let result = vimclojure#ExecuteNailWithInput("Repl", cmd,
					\ "-r", "-i", self._id)
		call self.showOutput(result)

		let self._historyDepth = 0
		let self._history = [cmd] + self._history

		let namespace = vimclojure#ExecuteNailWithInput("ReplNamespace", "",
					\ "-i", self._id)
		let b:vimclojure_namespace = namespace.value
		let self._prompt = namespace.value . "=>"

		call self.showPrompt()
	endif
endfunction

function! vimclojure#Repl.hatHook() dict
	let l = getline(".")

	if l =~ "^" . self._prompt
		let [buf, line, col, off] = getpos(".")
		call setpos(".", [buf, line, len(self._prompt) + 2, off])
	else
		normal! ^
	endif
endfunction

function! vimclojure#Repl.upHistory() dict
	let histLen = len(self._history)
	let histDepth = self._historyDepth

	if histLen > 0 && histLen > histDepth
		let cmd = self._history[histDepth]
		let self._historyDepth = histDepth + 1

		call self.deleteLast()

		call self.showText(self._prompt . " " . cmd)
	endif

	normal! G$
endfunction

function! vimclojure#Repl.downHistory() dict
	let histLen = len(self._history)
	let histDepth = self._historyDepth

	if histDepth > 0 && histLen > 0
		let self._historyDepth = histDepth - 1
		let cmd = self._history[self._historyDepth]

		call self.deleteLast()

		call self.showText(self._prompt . " " . cmd)
	elseif histDepth == 0
		call self.deleteLast()
		call self.showText(self._prompt . " ")
	endif

	normal! G$
endfunction

function! vimclojure#Repl.deleteLast() dict
	normal! G

	while getline("$") !~ self._prompt
		normal! dd
	endwhile

	normal! dd
endfunction

" Highlighting
function! vimclojure#ColorNamespace(highlights)
	for [category, words] in items(a:highlights)
		if words != []
			execute "syntax keyword clojure" . category . " " . join(words, " ")
		endif
	endfor
endfunction

" Omni Completion
function! vimclojure#OmniCompletion(findstart, base)
	if a:findstart == 1
		let line = getline(".")
		let start = col(".") - 1

		while start > 0 && line[start - 1] =~ '\w\|-\|\.\|+\|*\|/'
			let start -= 1
		endwhile

		return start
	else
		let slash = stridx(a:base, '/')
		if slash > -1
			let prefix = strpart(a:base, 0, slash)
			let base = strpart(a:base, slash + 1)
		else
			let prefix = ""
			let base = a:base
		endif

		if prefix == "" && base == ""
			return []
		endif

		let completions = vimclojure#ExecuteNail("Complete",
					\ "-n", b:vimclojure_namespace,
					\ "-p", prefix, "-b", base)
		return completions.value
	endif
endfunction

function! vimclojure#InitBuffer(...)
	if exists("b:vimclojure_loaded")
		return
	endif
	let b:vimclojure_loaded = 1

	if g:vimclojure#WantNailgun == 1
		if !exists("b:vimclojure_namespace")
			" Get the namespace of the buffer.
			if &previewwindow
				let b:vimclojure_namespace = "user"
			else
				try
					let content = getbufline(bufnr("%"), 1, line("$"))
					let namespace =
								\ vimclojure#ExecuteNailWithInput(
								\   "NamespaceOfFile", content)
					if namespace.stderr != ""
						throw namespace.stderr
					endif
					let b:vimclojure_namespace = namespace.value
				catch /.*/
					if a:000 == []
						call vimclojure#ReportError(
									\ "Could not determine the Namespace of the file.\n\n"
									\ . "This might have different reasons. Please check, that the ng server\n"
									\ . "is running with the correct classpath and that the file does not contain\n"
									\ . "syntax errors. The interactive features will not be enabled, ie. the\n"
									\ . "keybindings will not be mapped.\n\nReason:\n" . v:exception)
					endif
				endtry
			endif
		endif
	endif
endfunction

function! vimclojure#AddToLispWords(word)
	execute "setlocal lw+=" . a:word
endfunction

function! vimclojure#ToggleParenRainbow()
	highlight clear clojureParen1
	highlight clear clojureParen2
	highlight clear clojureParen3
	highlight clear clojureParen4
	highlight clear clojureParen5
	highlight clear clojureParen6
	highlight clear clojureParen7
	highlight clear clojureParen8
	highlight clear clojureParen9

	let g:vimclojure#ParenRainbow = !g:vimclojure#ParenRainbow

	if g:vimclojure#ParenRainbow != 0
		if &background == "dark"
			highlight clojureParen1 ctermfg=yellow      guifg=orange1
			highlight clojureParen2 ctermfg=green       guifg=yellow1
			highlight clojureParen3 ctermfg=cyan        guifg=greenyellow
			highlight clojureParen4 ctermfg=magenta     guifg=green1
			highlight clojureParen5 ctermfg=red         guifg=springgreen1
			highlight clojureParen6 ctermfg=yellow      guifg=cyan1
			highlight clojureParen7 ctermfg=green       guifg=slateblue1
			highlight clojureParen8 ctermfg=cyan        guifg=magenta1
			highlight clojureParen9 ctermfg=magenta     guifg=purple1
		else
			highlight clojureParen1 ctermfg=darkyellow  guifg=orangered3
			highlight clojureParen2 ctermfg=darkgreen   guifg=orange2
			highlight clojureParen3 ctermfg=blue        guifg=yellow3
			highlight clojureParen4 ctermfg=darkmagenta guifg=olivedrab4
			highlight clojureParen5 ctermfg=red         guifg=green4
			highlight clojureParen6 ctermfg=darkyellow  guifg=paleturquoise3
			highlight clojureParen7 ctermfg=darkgreen   guifg=deepskyblue4
			highlight clojureParen8 ctermfg=blue        guifg=darkslateblue
			highlight clojureParen9 ctermfg=darkmagenta guifg=darkviolet
		endif
	else
		highlight link clojureParen1 clojureParen0
		highlight link clojureParen2 clojureParen0
		highlight link clojureParen3 clojureParen0
		highlight link clojureParen4 clojureParen0
		highlight link clojureParen5 clojureParen0
		highlight link clojureParen6 clojureParen0
		highlight link clojureParen7 clojureParen0
		highlight link clojureParen8 clojureParen0
		highlight link clojureParen9 clojureParen0
	endif
endfunction

" Epilog
let &cpo = s:save_cpo
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.