1. Fuco
  2. .emacs.d

Source

.emacs.d / vendor / smartparens / smartparens.el

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
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
;;; smartparens.el --- Autoinsert pairs of defined brackets and wrap regions

;; Copyright (C) 2012 Matus Goljer

;; Author: Matus Goljer <matus.goljer@gmail.com>
;; Maintainer: Matus Goljer <matus.goljer@gmail.com>
;; Created: 17 Nov 2012
;; Version: 1.0
;; Keywords: abbrev convenience editing
;; Package-Requires: ((dash "1.0.2"))
;; URL: https://github.com/Fuco1/smartparens

;; This file is not part of GNU Emacs.

;;; License:

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; See github readme at https://github.com/Fuco1/smartparens

;;; Code:

(require 'dash)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Variables

;;;###autoload
(defvar sp-keymap (make-sparse-keymap)
  "Keymap used for smartparens-mode.  Remaps all the trigger keys
to `self-insert-command'.  This means we lose some functionality
in some modes (like c-electric keys).")

(defvar sp-escape-char nil
  "Character used to escape quotes inside strings.")
(make-variable-buffer-local 'sp-escape-char)

(defvar sp-local-ban-insert-pair '()
  "For pairs on this list auto insertion is locally disabled in
specified modes.

List of elements of type (command . '(list of modes)).")

(defvar sp-global-ban-insert-pair '()
  "For pairs on this list auto insertion is disabled globally.

List of pair IDs.")

(defvar sp-local-allow-insert-pair '()
  "For pairs on this list auto insertion is locally enabled in
specified modes.  It is disabled in all other modes automatically.

List of elements of type (command . '(list of modes)).")

(defvar sp-local-ban-insert-pair-in-string '()
  "For pairs on this list auto insertion is locally disabled in
specific modes if the point is inside string, docstring or
comment.

List of elements of type (command . '(list of modes)).")

(defvar sp-global-ban-insert-pair-in-string '()
  "For pairs on this list auto insertion is disabled globally if
the point is inside string, docstring or comment.

List of pair IDs.")

(defvar sp-local-allow-insert-pair-in-string '()
  "For pairs on this list auto insertion is locally enabled in
specific modes if the point is inside string, docstring or
comment.  It is disabled in all other modes automatically.

List of elements of type (command . '(list of modes)).")

(defvar sp-local-ban-insert-pair-in-code '()
  "For pairs on this list auto insertion is locally disabled in
specific modes if the point is inside code.

List of elements of type (command . '(list of modes)).")

(defvar sp-global-ban-insert-pair-in-code '()
  "For pairs on this list auto insertion is disabled globally if
the point is inside code.

List of pair IDs.")

(defvar sp-local-allow-insert-pair-in-code '()
  "For pairs on this list auto insertion is locally enabled in
specific modes if the point is inside code.  It is disabled in all
other modes automatically.

List of elements of type (command . '(list of modes)).")

(defvar sp-pair-list '(
                       ("\\\\(" . "\\\\)") ;; emacs regexp parens
                       ("\\{"   . "\\}")
                       ("\\("   . "\\)")
                       ("\\\""  . "\\\"")
                       ("/*"    . "*/")
                       ("\""    . "\"")
                       ("'"     . "'")
                       ("("     . ")")
                       ("["     . "]")
                       ("{"     . "}")
                       ("`"     . "'") ;; tap twice for tex double quotes
                       )
  "List of pairs for auto-insertion or wrapping.  Maximum length
of opening or closing pair is 10 characters.")
(make-variable-buffer-local 'sp-pair-list)

(defvar sp-local-pair-list '()
  "List of pairs specific to a specific mode.  The pairs on this list
are not enabled globally.  Pairs in this list can override global
definitons.  For example default `' can be overriden with `` in
`markdown-mode'.

List of elements of type ('(open . close) modes).")

(defvar sp-tag-pair-list '(
                           ("<" . (
                                   ((sgml-mode html-mode) "<_>" "</_>" sp-match-sgml-tags)
                                   ))
                           ("\\b" . (
                                     ((latex-mode tex-mode) "\\begin{_}" "\\end{_}" identity)
                                     ))
                           )

  "List of tag pairs.  Some languages use more elaborate tag pairs,
such as html \"<span class=\"x\">something</span>\".  For these,
the standard wrap mechanism isn't sufficient.  Here, user can
define the syntax of opening and closing pair.  If they share the
same keyword, this is substituted for _ in the tag
definitions.  The transform-function can further transform the
substitution for closing tab, for example cutting out everything
after a space in html-tag.  Only one _ per tag is allowed.  If no _
is present in the closing tag, nothing is mirrored there.  If no _
is present in the opening tag, tag insertion mode is not entered
and the tags are simply inserted as text.

The internal format is a list of (open-trigger ((modes) open-tag
close-tag transform-funciton)) where:

open-trigger - the trigger that starts the tag insertion.

open-tag - format of the opening tag.  _ is replaced by the entered
text.

close-tag - format of the closing tag.  _ is replaced by the entered
text.

modes - list of modes where this wrapping is allowed.

transform-function - this function is called to perform a
transformation on text that will be substituted to closing tag.")

(defvar sp-last-operation nil
  "Symbol holding the last successful operation.")
(make-variable-buffer-local 'sp-last-operation)

(defvar sp-previous-point -1
  "Location of point before last command.  This is only updated
when some pair-overlay is active.  Do not rely on the value of
this variable anywhere else!")
(make-variable-buffer-local 'sp-previous-point)

(defvar sp-wrap-point nil
  "Save the value of point before attemt to wrap a region.  Used
for restoring the original state if the wrapping is
cancelled.")
(make-variable-buffer-local 'sp-wrap-point)

(defvar sp-wrap-mark nil
  "Save the value of point before attemt to wrap a region.  Used
for restoring the original state if the wrapping is
cancelled.")
(make-variable-buffer-local 'sp-wrap-mark)

(defvar sp-last-inserted-character ""
  "If wrapping is cancelled, these character are re-inserted to
the location of point before the wrapping.")
(make-variable-buffer-local 'sp-last-inserted-character)

(defvar sp-last-wrapped-region nil
  "List containing info about last wrapped region.  The content of the list is:
\(start-of-the-wrapped-region end-of-the-wrapped-region
length-of-opening-pair length-of-closing-pair\).  Start and end
positions include the newly added wrapping pair.")
(make-variable-buffer-local 'sp-last-wrapped-region)

(defvar sp-point-inside-string nil
  "t if point is inside a string.")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Customize & Mode definitions

(defgroup smartparens ()
  "Smartparens minor mode."
  :group 'editor)

;;;###autoload
(define-minor-mode smartparens-mode
  "Toggle smartparens mode"
  :init-value nil
  :lighter " SP"
  :group 'smartparens
  :keymap sp-keymap
  (if smartparens-mode
      (progn
        ;; setup local pair replacements
        (sp-update-local-pairs)
        (sp-update-pair-triggers)
        ;; set the escape char
        (dotimes (char 256)
          (unless sp-escape-char
            (if (= ?\\ (char-syntax char))
                (setq sp-escape-char (string char)))))
        (when (sp-delete-selection-p)
          (sp-init-delete-selection-mode-emulation))
        (run-hooks 'smartparens-enabled-hook))
    (run-hooks 'smartparens-disabled-hook)
    ))

(defun sp-update-pair-triggers ()
  "Update the `sp-keymap' to include all trigger keys.  Trigger
key is any character present in any pair.  Each trigger key must
map to `self-insert-command'."
  (let ((triggers (-distinct
            (split-string
             (apply #'concat
                    (--reduce-from (cons (car it)
                                         (cons (cdr it) acc))
                                   nil sp-pair-list))
             "" t))))
    (--each triggers (define-key sp-keymap it 'self-insert-command))))

;; TODO: we could remove pairs that are absolutely not allowed in this
;; mode here (those that are banned or only allowed elsewhere).  It
;; will save a lot on the various filtering tasks.  However, this will
;; be an issue only with hundreds of pairs
(defun sp-update-local-pairs ()
  "Update local pairs after removal or at mode initialization."
  (setq sp-pair-list (default-value 'sp-pair-list))
  (--each sp-local-pair-list
          (when (member major-mode (cdr it))
            (let ((open (caar it))
                  (close (cdar it)))
              (setq sp-pair-list
                    (--remove (equal open (car it)) sp-pair-list))
              (setq sp-pair-list
                    (sp-add-to-ordered-list (car it) sp-pair-list #'sp-order-pairs))))))

(defun sp-update-local-pairs-everywhere ()
  "Run `sp-update-local-pairs' in all buffers.  This is necessary
to update all the buffer-local definitions."
  (--each (buffer-list)
    (with-current-buffer it
      (when smartparens-mode
        (sp-update-local-pairs)))))

(defvar smartparens-enabled-hook nil
  "Called after `smartparens-mode' is turned on.")

(defvar smartparens-disabled-hook nil
  "Called after `smartparens-mode' is turned off.")

;; global custom
(defcustom sp-ignore-modes-list '(
                                  calc-mode
                                  dired-mode
                                  ibuffer-mode
                                  minibuffer-inactive-mode
                                  sr-mode
                                  )
  "Modes where smartparens mode is inactive if allowed globally."
  :type '(repeat symbol)
  :group 'smartparens)

;;;###autoload
(define-globalized-minor-mode smartparens-global-mode
  smartparens-mode
  turn-on-smartparens-mode)

;;;###autoload
(defun turn-on-smartparens-mode ()
  "Turn on `smartparens-mode'."
  (interactive)
  (unless (or (member major-mode sp-ignore-modes-list)
              (minibufferp))
    (smartparens-mode t)))

;;;###autoload
(defun turn-off-smartparens-mode ()
  "Turn off `smartparens-mode'."
  (interactive)
  (smartparens-mode nil))

;; insert custom
(defcustom sp-autoinsert-pair t
  "If non-nil, auto insert pairs.  See `sp-insert-pair'."
  :type 'boolean
  :group 'smartparens)

(defcustom sp-autoinsert-if-followed-by-same 2
  "Customizes behaviour of pair insertion if the point is followed by
the same opening pair as currently inserted pair.

The first option does not change the insertion behaviour and pairs are
inserted normally.  For example |() followed by ( would produce (|)().

The second option inserts the pair only if the opening pair
following point is not the same as currently inserted pair.  For
example |() followed by ( would produce (|().  If next character
isn't part of any pair, insert normally.

The third option behaves as second, but if the opening and closing
pairs are the same, and we are looking at the closing pair, insert the
whole pair.  For example \"|\" followed by \" produce \"\"|\"\".  This
is useful in modes where pairs of same characters have special
meaning, such as `markdown-mode' and * for italics and ** for bold."
  :type '(radio
          (const :tag "Insert the pair normally" 0)
          (const :tag "Insert the pair only if not followed by same" 1)
          (const :tag "Insert the pair only if not followed by same, but if the closing pair is the same as opening, insert new pair (useful for nested quote insertion)" 2)
          )
  :group 'smartparens)

(defcustom sp-autoinsert-if-followed-by-word nil
  "If non-nil, auto insert the whole pair even if point is followed by word.

For example |word followed by ( would produce (|)word.  If nil,
it would produce (|word."
  :type 'boolean
  :group 'smartparens)

(defcustom sp-autoinsert-quote-if-followed-by-closing-pair t
  "If non-nil, auto insert string quote pair even if the point is
followed by (any) closing pair.  This only activates if point is
inside a string.  In other words, if string is not closed and next
character is a closing pair.

For example, in a situation like this:

  [\"some text|]

after pressing \", one would probably want to insert the closing
quote, not a nested pair, to close the string literal in the array.
To enable such behaviour, set this variable to nil.

Note: Default value is set to t due to backward compatibility, even if
it is probably not the desired default setting."
  :type 'boolean
  :group 'smartparens)



(defcustom sp-autoskip-closing-pair t
  "If non-nil, skip the following closing pair.  See
`sp-skip-closing-pair' for more info."
  :type 'boolean
  :group 'smartparens)

(defcustom sp-cancel-autoskip-on-backward-movement t
  "If non-nil, autoskip of closing pair is cancelled not only
when point is moved outside of the pair, but also if the point
moved backwards.  See `sp-skip-closing-pair' for more info."
  :type 'boolean
  :group 'smartparens)

;; delete custom
(defcustom sp-autodelete-pair t
  "If non-nil, auto delete pairs.  See `sp-delete-pair'."
  :type 'boolean
  :group 'smartparens)

(defcustom sp-autodelete-closing-pair t
  "If non-nil, auto delete the whole closing-pair.  See `sp-delete-pair'."
  :type 'boolean
  :group 'smartparens)

(defcustom sp-autodelete-opening-pair t
  "If non-nil, auto delete the whole opening-pair.  See `sp-delete-pair'."
  :type 'boolean
  :group 'smartparens)

;; wrap custom
(defcustom sp-autowrap-region t
  "If non-nil, wrap the active region with pair.  See `sp-wrap-region' and `sp-wrap-region-init'"
  :type 'boolean
  :group 'smartparens)

(defcustom sp-autodelete-wrap t
  "If non-nil, auto delete both opening and closing pair of most
recent wrapping.  Deletion command must be the very first
command after the insertion, otherwise normal behaviour is
applied."
  :type 'boolean
  :group 'smartparens)

;; escaping custom
(defcustom sp-autoescape-string-quote t
  "If non-nil, autoescape string quotes if typed inside string."
  :type 'boolean
  :group 'smartparens)

(defcustom sp-autoescape-string-quote-if-empty nil
  "List of modes where the string quotes aren't escaped if the
string we're in is empty.  You can list modes where multiple
quote characters are used for multi-line strings, such as
`python-mode' to make the insertion less annoying (that is, three
times pressing \" would insert \"\"\"|\"\"\" instead of
\"\\\"\\\"|\\\"\\\"\")."
  :type '(repeat symbol)
  :group 'smartparens)

;; ui custom
(defcustom sp-highlight-pair-overlay t
  "If non-nil, auto-inserted pairs are highlighted until point
doesn't leave them."
  :type 'boolean
  :group 'smartparens)

(defcustom sp-highlight-wrap-overlay t
  "If non-nil, wrap overlays are highlighted during the process
of editing the wrapping pair."
  :type 'boolean
  :group 'smartparens)

(defcustom sp-highlight-wrap-tag-overlay t
  "If non-nil, wrap tag overlays are highlighted during the
process of editing the wrapping tag pair."
  :type 'boolean
  :group 'smartparens)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Selection mode emulation

(defun sp-delete-selection-p ()
  "Return t if `delete-selection-mode' or `cua-delete-selection' is enabled."
  (or (and (boundp 'delete-selection-mode) delete-selection-mode)
      (and (boundp 'cua-delete-selection) cua-delete-selection)))

(defun sp-cua-replace-region (&optional arg)
  "If `smartparens-mode' is on, emulate `self-insert-command',
else call `cua-replace-region'"
  (interactive "p")
  (if smartparens-mode
      (progn
        (setq this-command 'self-insert-command)
        (self-insert-command (or arg 1)))
    (cua-replace-region)))

(defun sp-init-delete-selection-mode-emulation ()
  "Initialize smartparens delete selection emulation.  The
original hooks are removed and handled by sp's pre-command
handler."
  ;;(interactive)
  ;;(setq sp-delete-selection-mode t)
  ;; make sure the `delete-selection-pre-hook' is not active and that
  ;; delsel is actually loaded.  We need the delete-selection-pre-hook
  ;; command!
  (when delete-selection-mode
    (remove-hook 'pre-command-hook 'delete-selection-pre-hook))
  ;; if cua-mode is active, replace the `self-insert-command' binding
  ;; and the cua--pre-command-handler hook.
  (when cua-mode
    (define-key cua--region-keymap [remap self-insert-command] 'sp-cua-replace-region)
    (remove-hook 'pre-command-hook 'cua--pre-command-handler)))

(defadvice cua-mode (after cua-mode-fix-selection activate)
  (when (and cua-mode)
    (define-key cua--region-keymap [remap self-insert-command] 'sp-cua-replace-region)
    (remove-hook 'pre-command-hook 'cua--pre-command-handler)))

(defadvice delete-selection-mode (after delete-selection-mode-fix-selection activate)
  (when (and delete-selection-mode)
    (remove-hook 'pre-command-hook 'delete-selection-pre-hook)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Misc functions

(defmacro !delete (elm list)
  "Destructive: Sets LIST to (delete ELM LIST)."
  `(setq ,list (delete ,elm ,list)))

(defmacro sp-with (arg &rest forms)
  "Adds ARG as last argument to each form.  This can be used on
most of the permission functions to automatically supply the mode
where we operate."
  `(progn
     ,@(mapcar (lambda (form) (append form (list arg))) forms)))

(defmacro sp-with-tag (arg &rest forms)
  "Adds ARG as first argument to each form.  This can be used on
most of the permission functions to automatically supply the
tag on which we want to operate."
  `(progn
     ,@(mapcar (lambda (form) (append (list (car form) arg) (cdr form))) forms)))

(font-lock-add-keywords 'emacs-lisp-mode '(("\\<sp-with\\>" . font-lock-keyword-face)) 'append)
(font-lock-add-keywords 'emacs-lisp-mode '(("\\<sp-with-tag\\>" . font-lock-keyword-face)) 'append)

(defmacro --last (form list)
  "Anaphoric form of `-last'."
  (let ((n (make-symbol "needle")))
    `(let (,n)
       (--each ,list
         (when ,form (setq ,n it)))
       ,n)))

(defun -last (pred list)
  "Return the last x in LIST where (PRED x) is non-nil, else nil."
  (--last (funcall pred it) list))

(defun reverse-string (str)
  "Reverse the string STR."
  (concat (reverse (append str nil))))

(defun sp-point-in-string (&optional p)
  "Return t if point is inside string or documentation string.  If
optional argument P is present, test this instead of point."
  (save-excursion
    (nth 3 (syntax-ppss p))))

(defun sp-point-in-comment (&optional p)
  "Return t if point is inside comment.  If optional argument P is
present, test this instead off point."
  (save-excursion
    (nth 4 (syntax-ppss p))))

(defun sp-point-in-string-or-comment (&optional p)
  "Return t if point is inside string, documentation string or a
comment.  If optional argument P is present, test this instead
of point."
  (or (sp-point-in-string p)
      (sp-point-in-comment p)))

(defun sp-single-key-description (event)
  "Return a description of the last event.  Replace all the function key symbols with garbage character (ň).

TODO: fix this!"
  (let ((original (single-key-description event)))
    (if (string-match-p "<.*?>" original)
        "ň" original)))

(defun sp-split-string (string by)
  "Split STRING on BY.  This simply calls `split-string' and if it
returns a list of length one, empty string is inserted to the
beginning."
  (let ((sp (split-string string by)))
    (if (not (cdr sp)) (cons "" sp) sp)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Adding/removing of pairs/bans/allows etc.

(defmacro sp-add-to-permission-list (open list &rest modes)
  "Add MODES to the pair with id OPEN in the LIST.  See
permissions system for more details."
  (let ((m (make-symbol "new-modes")))
    `(let ((,m (-flatten ,@modes)))
       (when ,m
         (let ((current (--first (equal ,open (car it)) ,list)))
           (if current
               (setcdr current (-union (cdr current) ,m))
             (!cons (cons ,open ,m) ,list)))))))

(defmacro sp-remove-from-permission-list (open list &rest modes)
  "Removes MODES from the pair with id OPEN in the LIST.  See
permissions system for more details.  If modes is nil, remove the
pair entirely."
  (let ((m (make-symbol "new-modes")))
    `(let ((,m (-flatten ,@modes)))
       (if ,m
           (let ((current (--first (equal ,open (car it)) ,list)))
             (when current
               (setcdr current (-difference (cdr current) ,m))
               (unless (cdr current)
                 (setq ,list (--remove (equal ,open (car it)) ,list)))))
         (setq ,list (--remove (equal ,open (car it)) ,list))))))

(defun sp-add-to-ordered-list (elm list order)
  "Add ELM to the LIST ordered by comparator ORDER.  The list is
ordered in descending order."
  (if (not list) (list elm)
  (if (funcall order elm (car list))
      (cons elm list)
      (cons (car list) (sp-add-to-ordered-list elm (cdr list) order)))))

(defun sp-order-pairs (a b)
  "Compare two pairs A and B by open pair length.  Return t if A
is leq to B."
    (>= (length (car a)) (length (car b))))

(defun sp-order-tag-pairs (a b)
  "Compare two tag pairs A and B by trigger length.  Return t if A is geq to B."
  (<= (length (car a)) (length (car b))))

(defun sp-add-pair (open close &rest banned-modes)
  "Add a pair formed by OPEN and CLOSE to the pair list.  See
variable `sp-pair-list' for current list.

Additional arguments are interpreted as modes where this pair
should be banned by default.  BANNED-MODES can also be a list."
  (unless (--any? (equal open (car it)) sp-pair-list)
    (setq-default sp-pair-list
                 (sp-add-to-ordered-list (cons open close) sp-pair-list #'sp-order-pairs))
    (sp-add-local-ban-insert-pair open banned-modes)
    (sp-update-pair-triggers)
    ;; we need to update local versions of sp-pair-list in all the buffers
    (sp-update-local-pairs-everywhere)
  ))

(defun sp-remove-pair (open)
  "Remove a pair from the pair list.  See variable `sp-pair-list'
for current list."
  (setq-default sp-pair-list
                (--remove (equal open (car it)) sp-pair-list))
  (sp-remove-local-ban-insert-pair open)
  (sp-remove-local-allow-insert-pair open)
  (sp-update-pair-triggers)
  (sp-update-local-pairs-everywhere)
  )

(defun sp-add-local-pair (open close &rest modes)
  "Add a pair to the local pair list.  Use this only if you need
to overload a global pair with the same ID.  If you wish to
limit a pair to a certain mode, add it globally and then set
the permissions with `sp-add-local-allow-insert-pair'."
  (prog1 (sp-add-to-permission-list (cons open close) sp-local-pair-list modes)
    (sp-update-local-pairs-everywhere)))

(defun sp-remove-local-pair (open &rest modes)
  "Remove a pair from the local pair list."
  (let ((m (-flatten modes)))
    (--each sp-local-pair-list
      (when (equal open (caar it))
        (setcdr it (-difference (cdr it) m))))
    (setq sp-local-pair-list (--remove (not (cdr it)) sp-local-pair-list))
    (sp-update-local-pairs-everywhere)))

(defun sp-add-tag-pair (trig open close transform mode &rest modes)
  "Add a tag pair.  This tag pair is triggered on TRIG in modes MODE,
wraps with OPEN and CLOSE.  If the CLOSE tag contains _ the
content of the opening tag is first transformed with the
TRANSFORM function.  If the TRANSFORM variable is nil, it
defaults to `identity'.

See `sp-tag-pair-list' for more info."
  (setq transform (or transform 'identity))
  ;; check if trigger is already present
  (let ((trigger (--first (equal trig (car it)) sp-tag-pair-list))
        (m (-flatten (cons mode modes))))
    (if trigger
        ;; we need to look if there is a pair with open/close already
        ;; defined.  If yes, add the modes to its list.  If not, we need
        ;; to create new entry
        (let ((current (--first
                        (and (equal open   (nth 1 it))
                             (equal close  (nth 2 it))
                             (eq transform (nth 3 it)))
                        (cdr trigger))))
          (if current
              (setcar current (-union (car current) m))
            ;; create new entry
            (setcdr trigger (cons (list m open close transform) (cdr trigger)))))
      ;; no trigger, add the whole structure
      (let ((s (cons trig (list (list m open close transform)))))
        (setq sp-tag-pair-list
              (sp-add-to-ordered-list s sp-tag-pair-list #'sp-order-tag-pairs))
        ))))

(defun sp-remove-tag-pair (trig mode &rest modes)
  "Remove a tag pair."
  (let ((trigger (--first (equal trig (car it)) sp-tag-pair-list))
        (m (-flatten (cons mode modes))))
    (when trigger
      ;; for each pair, we need to remove the modes from its mode list.
      (--each (cdr trigger)
        (setcar it (-difference (car it) m)))
      ;; remove the pairs with empty mode lists
      (let ((newpairs (--remove (not (car it)) (cdr trigger))))
        (if newpairs
            (setcdr trigger newpairs)
          ;; if there are no pairs left at all, remove the trigger too
          (setq sp-tag-pair-list (--remove (equal trig (car it)) sp-tag-pair-list)))
        ))))

(defun sp-add-ban-insert-pair (&rest open)
  "Add the pairs with ids in OPEN to the global insertion
banlist.  That means that these pairs will never be used for auto
insertion.  They can still be used for wrapping."
  (setq sp-global-ban-insert-pair (-union sp-global-ban-insert-pair (-flatten open))))

(defun sp-remove-ban-insert-pair (&rest open)
  "Remove the pairs with ids in OPEN from the global insertion
banlist."
  (setq sp-global-ban-insert-pair (-difference sp-global-ban-insert-pair (-flatten open))))

(defun sp-add-ban-insert-pair-in-string (&rest open)
  "Add the pairs with ids in OPEN to the global \"in string\"
insertion banlist.  That means that these pairs will never be used
for auto insertion if the point is inside string.  They can still
be used for wrapping."
  (setq sp-global-ban-insert-pair-in-string (-union sp-global-ban-insert-pair-in-string (-flatten open))))

(defun sp-remove-ban-insert-pair-in-string (&rest open)
  "Remove the pairs with ids in OPEN from the global \"in
string\" insertion banlist."
  (setq sp-global-ban-insert-pair-in-string (-difference sp-global-ban-insert-pair-in-string (-flatten open))))

(defun sp-add-ban-insert-pair-in-code (&rest open)
  "Add the pairs with ids in OPEN to the global \"in code\"
insertion banlist.  That means that these pairs will never be used
for auto insertion if the point is inside code.  They can still
be used for wrapping."
  (setq sp-global-ban-insert-pair-in-code (-union sp-global-ban-insert-pair-in-code (-flatten open))))

(defun sp-remove-ban-insert-pair-in-code (&rest open)
  "Remove the pairs with ids in OPEN from the global \"in
code\" insertion banlist."
  (setq sp-global-ban-insert-pair-in-code (-difference sp-global-ban-insert-pair-in-code (-flatten open))))

(defun sp-add-local-ban-insert-pair (open &rest modes)
  "Ban autoinsertion of pair with id OPEN in modes MODES.  See
`sp-insert-pair'."
  (sp-add-to-permission-list open sp-local-ban-insert-pair modes))

(defun sp-add-local-allow-insert-pair (open &rest modes)
  "Allow autoinsertion of pair with id OPEN in modes MODES.  See
`sp-insert-pair'."
  (sp-add-to-permission-list open sp-local-allow-insert-pair modes))

(defun sp-add-local-ban-insert-pair-in-string (open &rest modes)
  "Ban autoinsertion of pair with id OPEN in modes MODES if point
is inside string, docstring or comment.  See `sp-insert-pair'."
  (sp-add-to-permission-list open sp-local-ban-insert-pair-in-string modes))

(defun sp-add-local-allow-insert-pair-in-string (open &rest modes)
  "Allow autoinsertion og pair with id OPEN in MODES if point is
inside string, docstring or comment.  See `sp-insert-pair'."
  (sp-add-to-permission-list open sp-local-allow-insert-pair-in-string modes))

(defun sp-add-local-ban-insert-pair-in-code (open &rest modes)
  "Ban autoinsertion of pair with id OPEN in modes MODES if point
is inside code.  See `sp-insert-pair'."
  (sp-add-to-permission-list open sp-local-ban-insert-pair-in-code modes))

(defun sp-add-local-allow-insert-pair-in-code (open &rest modes)
  "Allow autoinsertion og pair with id OPEN in MODES if point is
inside code.  See `sp-insert-pair'."
  (sp-add-to-permission-list open sp-local-allow-insert-pair-in-code modes))

(defun sp-remove-local-ban-insert-pair (open &rest modes)
  "Remove previously set restriction on pair with id OPEN in
modes MODES.  If MODES is nil, remove all the modes."
  (sp-remove-from-permission-list open sp-local-ban-insert-pair modes))

(defun sp-remove-local-allow-insert-pair (open &rest modes)
  "Remove previously set restriction on pair with id OPEN in
modes MODES.  If MODES is nil, remove all the modes"
  (sp-remove-from-permission-list open sp-local-allow-insert-pair modes))

(defun sp-remove-local-ban-insert-pair-in-string (open &rest modes)
  "Remove previously set restriction on pair with id OPEN in
modes MODES if the point is inside string, docstring or
comment.  If MODES is nil, remove all the modes."
  (sp-remove-from-permission-list open sp-local-ban-insert-pair-in-string modes))

(defun sp-remove-local-allow-insert-pair-in-string (open &rest modes)
  "Remove previously set restriction on pair with id OPEN in
modes MODES if the point is inside string, docstring or
comment.  If MODES is nil, remove all the modes"
  (sp-remove-from-permission-list open sp-local-allow-insert-pair-in-string modes))

(defun sp-remove-local-ban-insert-pair-in-code (open &rest modes)
  "Remove previously set restriction on pair with id OPEN in
modes MODES if the point is inside code.  If MODES is nil,
remove all the modes."
  (sp-remove-from-permission-list open sp-local-ban-insert-pair-in-code modes))

(defun sp-remove-local-allow-insert-pair-in-code (open &rest modes)
  "Remove previously set restriction on pair with id OPEN in
modes MODES if the point is inside code.  If MODES is nil,
remove all the modes"
  (sp-remove-from-permission-list open sp-local-allow-insert-pair-in-code modes))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Overlay management

;; burlywood4
(defface sp-pair-overlay-face
  '((t (:background "#004a5d")))
  "The face used to highlight pair overlays."
  :group 'smartparens)

(defface sp-wrap-overlay-face
  '((t (:inherit sp-pair-overlay-face)))
  "The face used to highlight wrap overlays."
  :group 'smartparens)

(defface sp-wrap-tag-overlay-face
  '((t (:inherit sp-pair-overlay-face)))
  "The face used to highlight wrap tag overlays."
  :group 'smartparens)

(defvar sp-pair-overlay-list '()
  "List of overlays used for tracking inserted pairs.  When a pair
is inserted, an overlay is created over it.  When the user starts
typing the closing pair we will not insert it again.  If user
leaves the overlay, it is canceled and the insertion works again
as usual.")
(make-variable-buffer-local 'sp-pair-overlay-list)

(defvar sp-wrap-overlays nil
  "Cons pair of wrap overlays.")
(make-variable-buffer-local 'sp-wrap-overlays)

(defvar sp-wrap-tag-overlays nil
  "Cons pair of tag wrap overlays.")
(make-variable-buffer-local 'sp-wrap-tag-overlays)

(defvar sp-pair-overlay-keymap (make-sparse-keymap)
  "Keymap for the pair overlays.")
(define-key sp-pair-overlay-keymap (kbd "C-g") 'sp-remove-active-pair-overlay)

(defvar sp-wrap-overlay-keymap (make-sparse-keymap)
  "Keymap for the wrap overlays.")
(define-key sp-wrap-overlay-keymap (kbd "C-g") 'sp-wrap-cancel)

(defvar sp-wrap-tag-overlay-keymap (make-sparse-keymap)
  "Keymap for the wrap tag overlays.")
(define-key sp-wrap-tag-overlay-keymap (kbd "C-g") 'sp-wrap-tag-done)
(define-key sp-wrap-tag-overlay-keymap (kbd "C-a") 'sp-wrap-tag-beginning)
(define-key sp-wrap-tag-overlay-keymap (kbd "C-e") 'sp-wrap-tag-end)


(defun sp-point-in-overlay-p (overlay)
  "Return t if point is in OVERLAY."
  (and (< (point) (overlay-end overlay))
       (> (point) (overlay-start overlay))))

(defun sp-get-overlay-length (overlay)
  "Compute the length of OVERLAY."
  (- (overlay-end overlay) (overlay-start overlay)))

(defun sp-get-active-overlay (&optional type)
  "Get active overlay.  Active overlay is the shortest overlay at
point.  Optional argument TYPE restrict overlays to only those
with given type."
  (let ((overlays (overlays-at (point))))
    (when type
      (setq overlays (--filter (eq (overlay-get it 'type) type) overlays)))
    (cond
     ((not overlays) nil)
     ((not (cdr overlays)) (car overlays))
     (t
      (--reduce (if (< (sp-get-overlay-length it) (sp-get-overlay-length acc)) it acc) overlays)
      ))))

(defun sp-pair-overlay-create (start end id)
  "Create an overlay over the currently inserted pair for
tracking the position of the point."
  (let ((overlay (make-overlay start end nil nil t)))
    (overlay-put overlay 'priority 100)
    (overlay-put overlay 'keymap sp-pair-overlay-keymap)
    (overlay-put overlay 'pair-id id)
    (overlay-put overlay 'type 'pair)
    (!cons overlay sp-pair-overlay-list)
    (sp-pair-overlay-fix-highlight)
    (add-hook 'post-command-hook 'sp-pair-overlay-post-command-handler nil t)))

(defun sp-wrap-cancel (&optional can-delete)
  "Cancel the active wrapping."
  (interactive)
  (let ((oleft (car sp-wrap-overlays))
        (oright (cdr sp-wrap-overlays)))
    ;; kill the insides of the "pair" if `delete-selection-mode'
    ;; emulation is enabled
    (when (and (sp-delete-selection-p) can-delete)
      (kill-region (overlay-end oleft) (overlay-start oright))
      (setq sp-wrap-point (overlay-start oleft)))
    (delete-region (overlay-start oleft) (overlay-end oleft))
    (delete-region (overlay-start oright) (overlay-end oright))
    (delete-overlay oleft)
    (delete-overlay oright)
    (setq sp-wrap-overlays nil)
    (setq sp-previous-point -1)

    (goto-char sp-wrap-point)
    (when can-delete
      (insert sp-last-inserted-character))
  ))

(defun sp-pair-overlay-fix-highlight ()
  "Fix highlighting of the pair overlays.  Only the active overlay
should be highlighted."
  (--each (overlays-at (point)) (overlay-put it 'face nil))
  (let* ((active (sp-get-active-overlay))
         (type (and active (overlay-get active 'type))))
    (if active
        (cond
         ((eq 'wrap-tag type)
          (when sp-highlight-wrap-tag-overlay
            (overlay-put active 'face 'sp-wrap-tag-overlay-face)))
         ((eq 'pair type)
          (when sp-highlight-pair-overlay
            (overlay-put active 'face 'sp-pair-overlay-face))))
      ;; edge case where we're at the end of active overlay.  If
      ;; there is a wrap-tag overlay, restore it's face
      (when sp-wrap-tag-overlays
        (overlay-put (car sp-wrap-tag-overlays) 'face 'sp-wrap-tag-overlay-face))
      )))

(defun sp-pair-overlay-post-command-handler ()
  "Remove all pair overlays that doesn't have point inside them,
are of zero length, or if point moved backwards."
  ;; if the point moved backwards, remove all overlays
  (if (and sp-cancel-autoskip-on-backward-movement
           (< (point) sp-previous-point))
      (dolist (o sp-pair-overlay-list) (sp-remove-overlay o))
    ;; else only remove the overlays where point is outside them or
    ;; their length is zero
    (dolist (o (--remove (and (sp-point-in-overlay-p it)
                              (> (sp-get-overlay-length it) 0))
                         sp-pair-overlay-list))
      (sp-remove-overlay o)))
  (when sp-pair-overlay-list
    (setq sp-previous-point (point))))

(defun sp-remove-active-pair-overlay ()
  "Deactivate the active overlay.  See `sp-get-active-overlay'."
  (interactive)
  (let ((active-overlay (sp-get-active-overlay 'pair)))
    (when active-overlay
      (sp-remove-overlay active-overlay))))

(defun sp-remove-overlay (overlay)
  "Remove OVERLAY."
  ;; if it's not a pair overlay, nothing happens here anyway
  (!delete overlay sp-pair-overlay-list)
  ;; if we have zero pair overlays, remove the post-command hook
  (when (not sp-pair-overlay-list)
    (remove-hook 'post-command-hook 'sp-pair-overlay-post-command-handler t)
    ;; this is only updated when sp-pair-overlay-post-command-handler
    ;; is active.  Therefore, we need to reset this to 1.  If not, newly
    ;; created overlay could be removed right after creation - if
    ;; sp-previous-point was greater than actual point
    (setq sp-previous-point -1))
  (delete-overlay overlay)
  (sp-pair-overlay-fix-highlight))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Pair insertion/deletion/skipping

(defun sp-insert-pair-in-string-p (id mode)
  "Return t if we can insert pair ID in MODE inside string,
docstring or comment.  See `sp-insert-pair' for more info."
  (let ((local-ban-in-string (member mode (cdr (assoc id sp-local-ban-insert-pair-in-string))))
        (local-allow-in-string (cdr (assoc id sp-local-allow-insert-pair-in-string))))
    (cond
     (local-allow-in-string (member mode local-allow-in-string))
     ((member id sp-global-ban-insert-pair-in-string) nil)
     (local-ban-in-string nil)
     (t t))))

(defun sp-insert-pair-in-code-p (id mode)
  "Return t if we can insert pair ID in MODE inside code.  See
`sp-insert-pair' for more info."
  (let ((local-ban-in-code (member mode (cdr (assoc id sp-local-ban-insert-pair-in-code))))
        (local-allow-in-code (cdr (assoc id sp-local-allow-insert-pair-in-code))))
    (cond
     (local-allow-in-code (member mode local-allow-in-code))
     ((member id sp-global-ban-insert-pair-in-code) nil)
     (local-ban-in-code nil)
     (t t))))

(defun sp-insert-pair-p (id mode)
  "Return t if we can insert pair ID in MODE.  See
`sp-insert-pair' for more info."
  (let ((local-ban (member mode (cdr (assoc id sp-local-ban-insert-pair))))
        (local-allow (cdr (assoc id sp-local-allow-insert-pair))))
    (cond
     ;; if locally allowed, allow it.  If it's on local-allow list
     ;; automatically disable it in all non-specified modes
     (local-allow
      (if (member mode local-allow)
          (if (sp-point-in-string-or-comment)
              (sp-insert-pair-in-string-p id mode)
            (sp-insert-pair-in-code-p id mode))
        nil))
     ;; if globally disabled, disable
     ((member id sp-global-ban-insert-pair) nil)
     ;; if locally disabled, disable
     (local-ban nil)
     ;; test the "in string bans"
     ((sp-point-in-string-or-comment)
      (sp-insert-pair-in-string-p id mode))
     ;; if not in string, we must be in code
     (t (sp-insert-pair-in-code-p id mode))
      )))

(defun sp-post-command-hook-handler ()
  "Handle the situation after some command has executed."
  (when smartparens-mode
    ;; handle the wrap overlays
    (when sp-wrap-overlays
      (let* ((overlay (car sp-wrap-overlays))
             (start (overlay-start overlay))
             (end (overlay-end overlay))
             (p (point)))
        (when (or (< p sp-previous-point)
                  (> p end)
                  (< p start))
          (sp-wrap-cancel))))
    (when sp-wrap-overlays
      (setq sp-previous-point (point)))

    (unless (eq this-command 'self-insert-command)
      (setq sp-last-operation nil))))

(defmacro sp-setaction (action &rest forms)
  `(if (not action)
       (setq action (progn ,@forms))
     (progn ,@forms)))

(defadvice self-insert-command (around self-insert-command-adviced activate)
  (setq sp-point-inside-string (sp-point-in-string))

  ad-do-it

  (when smartparens-mode
    (let (op action)
      (if (= 1 (ad-get-arg 0))
          (progn
            (setq op sp-last-operation)
            (cond
             ((region-active-p)
              (sp-wrap-region-init))
             (sp-wrap-overlays
              (sp-wrap-region))
             (t
              (sp-setaction action (sp-insert-pair))
              (sp-setaction action (sp-skip-closing-pair))
              ;; if nothing happened, we just inserted a character, so
              ;; set the apropriate operation.  We also need to check
              ;; for `sp-self-insert-no-escape' not to overwrite
              ;; it.  See `sp-autoinsert-quote-if-followed-by-closing-pair'.
              (when (and (not action)
                         (not (eq sp-last-operation 'sp-self-insert-no-escape)))
                (setq sp-last-operation 'sp-self-insert))
              ;; if it was a quote, escape it
              (when (and (eq sp-last-operation 'sp-self-insert)
                         sp-point-inside-string
                         sp-autoescape-string-quote
                         (eq (preceding-char) ?\"))
                (save-excursion
                  (backward-char 1)
                  (insert sp-escape-char)))
              ))

            )
        (setq sp-last-operation 'sp-self-insert)
        ))))

(defun sp-delete-selection-mode-handle (&optional from-wrap)
  "Call the original `delete-selection-pre-hook'."
  (if smartparens-mode
      (cond
       ;; try the cua-mode emulation with `cua-delete-selection'
       ((and (boundp 'cua-mode) cua-mode
             (not (eq this-command 'self-insert-command)))
        (cua--pre-command-handler))
       ((and (boundp 'cua-mode) cua-mode from-wrap)
        (cua-replace-region))
       ;; if not self-insert, just run the hook from
       ;; `delete-selection-mode'
       ((and (boundp 'delete-selection-mode) delete-selection-mode
             (or from-wrap
                 (not (eq this-command 'self-insert-command))))
        (delete-selection-pre-hook)))
    ;; this handles the callbacks properly if the smartparens mode is
    ;; disabled.  Smartparens-mode adds advices on cua-mode and
    ;; delete-selection-mode that automatically remove the callbacks
    (cond
     ((and (boundp 'cua-mode) cua-mode
           (not (member 'pre-command-hook 'cua--pre-command-handler)))
      (cua--pre-command-handler))
     ((and (boundp 'delete-selection-mode) delete-selection-mode
           (not (member 'pre-command-hook 'delete-selection-pre-hook)))
      (delete-selection-pre-hook)))))

(defun sp-pre-command-hook-handler ()
  "Main handler of pre-command-hook.  Handle the
`delete-selection-mode' or `cua-delete-selection' stuff here."
  (sp-delete-selection-mode-handle))

(defun sp-wrap-region-init ()
  "Initialize the region wrapping."
  (when sp-autowrap-region
    ;; if we can't possibly form a wrap, just insert the char and do
    ;; nothing.  If `sp-delete-selection-p' is true, run
    ;; `sp-delete-selection-mode-handle' with t that means it was
    ;; called from withing wrapping procedure
    (if (--none? (string-prefix-p (sp-single-key-description last-command-event) (car it)) sp-pair-list)
        (let ((p (1- (point)))
              (m (mark)))
          ;; test if we can at least start a tag wrapping.  If not,
          ;; delete the region if apropriate
          (unless (sp-wrap-tag-region-init)
            (sp-delete-selection-mode-handle t)
            (when (and (sp-delete-selection-p)
                       (< m p)
                       (= (length (sp-single-key-description last-command-event)) 1))
              (insert (sp-single-key-description last-command-event)))))
      (let* ((p (1- (point))) ;; we want the point *before* the
                              ;; insertion of the character
             (m (mark))
             (ostart (if (> p m) m p))
             (oend (if (> p m) p m))
             (keys (mapcar 'sp-single-key-description (recent-keys)))
             (last-keys (apply #'concat (-take 10 (reverse keys))))
             ;;(last-keys "\"\"\"\"\"\"\"\"")
             (active-pair (--first (string-prefix-p (reverse-string (car it)) last-keys) sp-pair-list)))

        (deactivate-mark)
        ;; if we can wrap right away, do it without creating overlays,
        ;; we can save ourselves a lot of needless trouble :)
        (if active-pair
            (unless (sp-wrap-tag-region-init)
              (let* ((oplen (length (car active-pair)))
                     (cplen (length (cdr active-pair)))
                     (len (+ oplen cplen))
                     (strbound))
                (if (< p m)
                    (progn
                      ;; we delete the opening here to determine the
                      ;; string bounds... not pretty, but there's
                      ;; probably no better solution.
                      (delete-char -1)
                      (setq strbound (sp-get-quoted-string-bounds))
                      ;; and insert it right back
                      (insert (car active-pair))
                      (save-excursion
                        (goto-char m)
                        (insert (cdr active-pair))))
                  (delete-char (- 1))
                  (setq strbound (sp-get-quoted-string-bounds))
                  (insert (cdr active-pair))
                  (goto-char m)
                  (insert (car active-pair))
                  (goto-char (+ len p)))
                (setq sp-last-operation 'sp-wrap-region)
                (setq sp-last-wrapped-region
                      (if (< p m)
                          (list p (+ len m -1) oplen cplen)
                        (list m (+ len p) oplen cplen)))
                ;; only autoescape "" pair, so it has to be one-char
                ;; length, therefore we can handle it here
                (when (and (equal (car active-pair) "\"")
                           (equal (cdr active-pair) "\""))
                  (sp-wrap-region-autoescape strbound))
                sp-last-wrapped-region))

          ;; save the position and point so we can restore it on cancel.
          (setq sp-wrap-point p)
          (setq sp-wrap-mark m)

          ;; We need to remember what was removed in case wrap is
          ;; cancelled.  Then these characters are re-inserted.
          (setq sp-last-inserted-character (sp-single-key-description last-command-event))

          ;; if point > mark, we need to remove the character at the end and
          ;; insert it to the front.
          (when (> p m)
            (delete-char (- 1))
            (goto-char ostart)
            (insert sp-last-inserted-character)
            (setq oend (1+ oend)))

          (let* ((oleft (make-overlay ostart (1+ ostart) nil nil t))
                 (oright (make-overlay oend oend nil nil t)))

            ;; insert the possible pair into end overlay
            (let ((close-pair (cdr (--last (string-prefix-p
                                             sp-last-inserted-character
                                             (car it))
                                            sp-pair-list))))
               (when close-pair
                (save-excursion
                  (goto-char oend)
                  (insert close-pair))))

            (setq sp-wrap-overlays (cons oleft oright))
            (when sp-highlight-wrap-overlay
              (overlay-put oleft 'face 'sp-wrap-overlay-face)
              (overlay-put oright 'face 'sp-wrap-overlay-face))
            (overlay-put oleft 'priority 100)
            (overlay-put oright 'priority 100)
            (overlay-put oleft 'keymap sp-wrap-overlay-keymap)
            (overlay-put oleft 'type 'wrap)

            (goto-char (1+ ostart))
            ))))))

(defun sp-wrap-region ()
  "Wrap region."
  ;; this method is only called if there's an active region.  It should
  ;; never be called manually!
  (when sp-autowrap-region
    (let* ((keys (mapcar 'sp-single-key-description (recent-keys)))
           (last-keys (apply #'concat (-take 10 (reverse keys))))
           (oleft (car sp-wrap-overlays))
           (oright (cdr sp-wrap-overlays))
           )
      (setq sp-last-inserted-character
            (concat sp-last-inserted-character
                    (sp-single-key-description last-command-event)))
      (let* ((active-pair (--last (string-prefix-p
                                   sp-last-inserted-character
                                   (car it))
                                  sp-pair-list))
             (open-pair (car active-pair))
             (close-pair (cdr active-pair)))

        ;; call sp-wrap-tag-region-init here.  See if we can extend the
        ;; current wrap-beginning into a tag
        (unless (sp-wrap-tag-region-init)
          ;; update the close pair
          (if close-pair
              (save-excursion
                (delete-region (overlay-start oright) (overlay-end oright))
                (goto-char (overlay-start oright))
                (insert close-pair))
            ;; if we don't have any, it means there is no way to
            ;; complete the pair...  abort
            (sp-wrap-cancel t))

          ;; we've completed a pairing!
          (when (equal sp-last-inserted-character open-pair)
            (let ((s (overlay-start oleft))
                  (e (overlay-end oright))
                  (oplen (length open-pair))
                  (cplen (length close-pair)))
              (delete-overlay oleft)
              (delete-overlay oright)
              (setq sp-wrap-overlays nil)
              (setq sp-previous-point -1)
              (if (< sp-wrap-point sp-wrap-mark)
                  (goto-char (+ sp-wrap-point oplen))
                (goto-char (+ sp-wrap-point oplen cplen)))
              ;; update info for possible following delete
              (setq sp-last-operation 'sp-wrap-region)
              (setq sp-last-wrapped-region
                    (list s e oplen cplen))
              )))))))

(defun sp-wrap-tag-region-init ()
  "Init a region wrapping with a tag pair.  This is called from
`sp-wrap-region-init' or `sp-wrap-region' (usually on failure) to
see if the currently entered \"wrap\" can be extended as a
tag.  The tag always gets priority from the regular wrap."
  (when sp-autowrap-region
    ;; we can either enter tagwrapping from already present wrap or
    ;; from nothing (if the wrap-init failed to find any usable wrap)
    ;; or at failure (the entered wrap doesn't match any pair)
    (if sp-wrap-overlays ;; called from within the wrap-mode
        (let* ((oleft (car sp-wrap-overlays))
               (oright (cdr sp-wrap-overlays))
               (possible-tag (--first (string-prefix-p
                                       sp-last-inserted-character
                                       (car it)) sp-tag-pair-list))
               (active-tag (cdr (--first (member major-mode (car it)) (cdr possible-tag)))))
          (when active-tag
            ;; if we've found a tag trigger, enter the tag editing mode
            (if (eq (length sp-last-inserted-character) (length (car possible-tag)))
                (progn
                  (delete-region (overlay-start oright) (overlay-end oright))
                  (sp-wrap-tag-create-overlays possible-tag active-tag
                                               (overlay-start oleft)
                                               (-
                                                (overlay-start oright)
                                                (sp-get-overlay-length oleft)))
                  (delete-overlay oleft)
                  (delete-overlay oright)
                  (setq sp-wrap-overlays nil)
                  (setq sp-previous-point -1)) ;; do we need this?
              t) ;; return t as it is possible to extend current wrap
                 ;; into a tag insertion mode
            ))
      ;; here we need to look at the last inserted character
      (let* ((p (1- (point)))
             (m (mark))
             (ostart (if (> p m) m p))
             (oend (if (> p m) p m))
             (possible-tag (--first (string-prefix-p
                                     (sp-single-key-description last-command-event)
                                     (car it))
                                    sp-tag-pair-list))
             (active-tag (cdr (--first (member major-mode (car it)) (cdr possible-tag)))))
        (when active-tag
          (setq sp-last-inserted-character (sp-single-key-description last-command-event))
          (setq sp-wrap-point p)
          (setq sp-wrap-mark m)
          (when (> p m)
            (delete-char (- 1))
            (goto-char ostart)
            (insert sp-last-inserted-character)
            (setq oend (1+ oend)))
          (if (= 1 (length (car possible-tag)))
              ;; the tag is only 1 character long, we can enter
              ;; insertion mode right away
              ;; I don't know why it needs 1- here, but it does :D
              (sp-wrap-tag-create-overlays possible-tag active-tag ostart (1- oend))
            ;; we don't have a wrap, but we can maybe start a tag
            ;; wrap.  So just init the wrapping overlays as usual, and
            ;; let `sp-wrap-region' handle it
            (let* ((oleft (make-overlay ostart (1+ ostart) nil nil t))
                   (oright (make-overlay oend oend nil nil t)))
              (setq sp-wrap-overlays (cons oleft oright))
              (when sp-highlight-wrap-overlay
                (overlay-put oleft 'face 'sp-wrap-overlay-face)
                (overlay-put oright 'face 'sp-wrap-overlay-face))
              (overlay-put oleft 'priority 100)
              (overlay-put oright 'priority 100)
              (overlay-put oleft 'keymap sp-wrap-overlay-keymap)
              (overlay-put oleft 'type 'wrap)
              (goto-char (1+ ostart)))
            ))))))

(defun sp-wrap-tag-create-overlays (possible-tag active-tag ostart oend)
  "Create the wrap tag overlays.

OSTART is the start of the modified area, including the pair trigger string.

OEND is the end of the modified area, that is the end of the
wrapped region, exluding any existing possible wrap."
  (let* ((tag-open (sp-split-string (nth 0 active-tag) "_"))
         (tag-close (sp-split-string (nth 1 active-tag) "_"))
         (o (apply #'+ (mapcar #'length tag-open)))
         (c (apply #'+ (mapcar #'length tag-close))))
    ;; setup the wrap pairs
    ;; opening one
    (goto-char ostart)
    (delete-char (length (car possible-tag)))
    (insert (apply #'concat tag-open))
    (backward-char (length (cadr tag-open)))

    ;; closing one
    (save-excursion
      (goto-char (+ oend o))
      (insert (apply #'concat tag-close)))

    (if (cdr (split-string (nth 0 active-tag) "_"))
      (let ((oleft (make-overlay
                    (+ ostart (length (car tag-open)))
                    (+ ostart (length (car tag-open)))
                    nil nil t))
            (oright (make-overlay
                     (+ oend o (length (car tag-close)))
                     (+ oend o (length (car tag-close)))
                     nil nil t)))
        (setq sp-wrap-tag-overlays (cons oleft oright))
        (when sp-highlight-wrap-tag-overlay
          (overlay-put oleft 'face 'sp-wrap-tag-overlay-face)
          (overlay-put oright 'face 'sp-wrap-tag-overlay-face))
        (overlay-put oleft 'priority 100)
        (overlay-put oright 'priority 100)
        (overlay-put oleft 'keymap sp-wrap-tag-overlay-keymap)
        (overlay-put oleft 'type 'wrap-tag)
        (overlay-put oleft 'active-tag active-tag)
        (overlay-put oleft 'modification-hooks '(sp-wrap-tag-update))
        (overlay-put oleft 'insert-in-front-hooks '(sp-wrap-tag-update))
        (overlay-put oleft 'insert-behind-hooks '(sp-wrap-tag-update))
        (add-hook 'post-command-hook 'sp-wrap-tag-post-command-handler))
      ;; if the tag didn't have any substitution, that means we only
      ;; insert the "brackets" and not enter the tag-insertion mode.
      ;; Therefore we move the point to the original position, so it
      ;; behaves just like normal wrap
      (if (> sp-wrap-mark sp-wrap-point)
          (goto-char (+ sp-wrap-point o))
        (goto-char (+ sp-wrap-point o c))))
    (setq sp-last-operation 'sp-wrap-tag)))

(defun sp-wrap-tag-update (overlay after? beg end &optional length)
  (let* ((oleft (car sp-wrap-tag-overlays))
         (oright (cdr sp-wrap-tag-overlays))
         (active-tag (overlay-get oleft 'active-tag))
         (transform (nth 2 active-tag))
         (open (buffer-substring (overlay-start oleft) (overlay-end oleft)))
         )
    (when (string-match-p "_" (nth 1 active-tag))
      (save-excursion
        (delete-region (overlay-start oright) (overlay-end oright))
        (goto-char (overlay-start oright))
        (insert (funcall transform open))))))

(defun sp-wrap-tag-post-command-handler ()
  "Terminate the tag insertion mode if the point jumps out of the
tag overlay."
  (if (or (not sp-wrap-tag-overlays)
          (< (point) (overlay-start (car sp-wrap-tag-overlays)))
          (> (point) (overlay-end (car sp-wrap-tag-overlays))))
      (sp-wrap-tag-done)))

(defun sp-match-sgml-tags (tag)
  (let* ((split (split-string tag " "))
         (close (car split)))
    close))

(defun sp-wrap-tag-beginning ()
  "Move point to the beginning of the wrap tag editation area."
  (interactive)
  (goto-char (overlay-start (car sp-wrap-tag-overlays))))

(defun sp-wrap-tag-end ()
  "Move point to the end of the wrap tag editation area."
  (interactive)
  (goto-char (overlay-end (car sp-wrap-tag-overlays))))

(defun sp-wrap-tag-done ()
  "Finish editing of tag."
  (interactive)
  (let ((oleft (car sp-wrap-tag-overlays))
        (oright (cdr sp-wrap-tag-overlays)))
    (delete-overlay oleft)
    (delete-overlay oright)
    (setq sp-wrap-tag-overlays nil)
    (remove-hook 'post-command-hook 'sp-wrap-tag-post-command-handler)))

(defun sp-wrap-region-autoescape (strbound)
  "If we wrap a region with \"\" quotes, and the whole region was
inside a string, automatically escape the enclosing quotes.  If
we wrap a region that wasn't a string, automatically quote any
string quotes inside it.

This is internal function and should be only called after a
wrapping."
  (when sp-autoescape-string-quote
    (let ((lw sp-last-wrapped-region)
          (b (car sp-last-wrapped-region))
          (e (cadr sp-last-wrapped-region))
          was-beg)
      (cond
       ((and strbound
             (> b (car strbound))
             (< e (cdr strbound)))
        ;; the wrapped region is inside a string, escape the enclosing
        ;; quotes
        (save-excursion
          (goto-char b)
          (insert sp-escape-char)
          (goto-char e)
          (insert sp-escape-char))
        ;; update the sp-last-wrapped-region info to \" pair
        (setq sp-last-wrapped-region
              (list (car lw) (+ 2 (cadr lw)) 2 2)))
       (t
        (setq was-beg (< (point) e))
        (let ((num 0))
          (goto-char b)
          (while (search-forward-regexp "\\([^\\]\\)\"" (+ e -1 num) t)
            (setq num (1+ num))
            (replace-match "\\1\\\\\"" t))
          (setq sp-last-wrapped-region
                (list (car lw) (+ num (cadr lw)) 1 1))
          (if was-beg
              (goto-char (1+ b))
            (goto-char (+ e num)))
          ))))))

(defun sp-insert-pair ()
  "Automatically insert the closing pair if it is allowed in current
context.  It is determined in this order:

1. Global allow - all pairs are allowed by default in every mode.

2. Local ban - you can ban specific pair in specific modes.  See
`sp-add-local-ban-insert-pair'.

3. Global ban - you can globally ban specific pair.

4. Local allow - you can allow specific pair in specific
modes.  It is disabled in all other modes (as if you globally
banned it first).  See `sp-add-local-allow-insert-pair'.

Additionally, there is a possibility to disable insertion of
pairs inside strings, docstrings and comments or inside code.  The
order in which these are determined is following:

1. Is the pair allowed in this mode? (by the above mechanism)

2. Local ban inside strings - `sp-add-local-ban-insert-pair-in-string'.

3. Global ban - `sp-add-ban-insert-pair-in-string'.

4. Local allow - `sp-add-local-allow-insert-pair-in-string'.

The semantics are the same as above.  First, point position is
tested to determine if it is inside string.  If yes, the rules for
string restrictions are evaluated.  If not, restrictions for code
are evaluated.  The code versions end with \"in-code\" instead of
\"in-string\".

You can disable this feature completely for all modes and all pairs by
setting `sp-autoinsert-pair' to nil.

You can globally disable insertion of closing pair if point is
followed by the matching opening pair.  It is disabled by
default.  See `sp-autoinsert-if-followed-by-same' for more info.

You can globally disable insertion of closing pair if point is
followed by word.  It is disabled by default.  See
`sp-autoinsert-if-followed-by-word' for more info."
  (when sp-autoinsert-pair
    (let* ((keys (mapcar 'sp-single-key-description (recent-keys)))
           (last-keys (apply #'concat (-take 10 (reverse keys))))
           ;; (last-keys "\"\"\"\"\"\"\"\"\"\"\"\"")
           ;; we go through all the opening pairs and compare them to
           ;; last-keys.  If the opair is a prefix of last-keys, insert
           ;; the closing pair
           (active-pair (--first (string-prefix-p (reverse-string (car it)) last-keys) sp-pair-list))
           (open-pair (car active-pair))
           (close-pair (cdr active-pair)))
      (when (and active-pair
                 (not (eq sp-last-operation 'sp-skip-closing-pair))
                 (sp-insert-pair-p open-pair major-mode)
                 (if sp-autoinsert-if-followed-by-word t
                   (or (= (point) (point-max))
                       (not (and (eq (char-syntax (following-char)) ?w)
                                 (not (eq (following-char) ?\'))))))
                 (if sp-autoinsert-quote-if-followed-by-closing-pair t
                   (if (and (eq (char-syntax (preceding-char)) ?\")
                            ;; this is called *after* the character is
                            ;; inserted.  Therefore, if we are not in string, it
                            ;; must have been closed just now
                            (not (sp-point-in-string)))
                       (let* ((pair-list (--filter (and (sp-insert-pair-p (car it) major-mode)
                                                        ;; ignore pairs with same open/close
                                                        (not (string= (car it) (cdr it)))) sp-pair-list))
                              (pattern (regexp-opt (--map (cdr it) pair-list))))
                         ;; If we simply insert closing ", we also
                         ;; don't want to escape it.  Therefore, we
                         ;; need to set `sp-last-operation'
                         ;; accordingly to be checked in
                         ;; `self-insert-command' advice.
                         (if (looking-at pattern)
                             (progn (setq sp-last-operation 'sp-self-insert-no-escape) nil)
                           t))
                     t))
                 (cond
                  ((eq sp-autoinsert-if-followed-by-same 0) t)
                  ((eq sp-autoinsert-if-followed-by-same 1)
                   (not (looking-at (regexp-quote open-pair))))
                  ((eq sp-autoinsert-if-followed-by-same 2)
                   (or (not (looking-at (regexp-quote open-pair)))
                       (and (equal open-pair close-pair)
                            (eq sp-last-operation 'sp-insert-pair)
                            (save-excursion
                              (backward-char 1)
                              (looking-back (regexp-quote open-pair) (- (point) 10)))
                            )))
                  ))
        (insert close-pair)
        (backward-char (length close-pair))
        (sp-pair-overlay-create (- (point) (length open-pair))
                                (+ (point) (length close-pair))
                                open-pair)

        ;; we only autoescape if the pair is a single character string
        ;; delimiter.  More elaborate pairs are probably already
        ;; escaped.  We leave the responsibility to the user, since
        ;; it's not that common and the usecases might vary -> there's
        ;; no good "default" case.
        (when (and sp-autoescape-string-quote
                   sp-point-inside-string
                   (equal open-pair "\"")
                   (equal close-pair "\"")
                   (or (not sp-autoescape-string-quote-if-empty)
                       (not (memq major-mode sp-autoescape-string-quote-if-empty))
                       ;; test if the string is empty here
                       (not (and (equal (char-after (1+ (point))) ?\")
                                 (equal (char-after (- (point) 2)) ?\")))))
          (save-excursion
            (backward-char 1)
            (insert sp-escape-char)
            (forward-char 1)
            (insert sp-escape-char))
          (overlay-put (sp-get-active-overlay 'pair) 'pair-id "\\\""))

        (setq sp-last-operation 'sp-insert-pair)))))

(defun sp-skip-closing-pair ()
  "If point is inside an inserted pair, and the user only moved forward
with point (that is, only inserted text), if the closing pair is
typed, we shouldn't insert it again but skip forward.

For example, pressing ( is followed by inserting the pair (|).  If
we then type 'word' and follow by ), the result should be (word)|
instead of (word)|).

If the user moved backwards or outside the
pair, this behaviour is cancelled.  This behaviour can be globally
disabled by setting `sp-cancel-autoskip-on-backward-movement' to
nil.

This behaviour can be globally disabled by setting
`sp-autoskip-closing-pair' to nil."
  (when (and sp-autoskip-closing-pair
             sp-pair-overlay-list
             (sp-get-active-overlay 'pair))
    (let* ((overlay (sp-get-active-overlay 'pair))
           (open-pair (overlay-get overlay 'pair-id))
           (close-pair (cdr (assoc open-pair sp-pair-list)))
           ;; how many chars have we already typed
           (already-skipped (- (length close-pair) (- (overlay-end overlay) (point))))
           )
      ;; only if we're at the closing pair or inside it
      (when (>= already-skipped 0)
        ;; rest of yet-untyped close-pair
        (let ((close-pair-rest (substring close-pair already-skipped))
              (last last-command-event))
          (when (and (looking-at (regexp-quote close-pair-rest))
                     ;; start deletion only if point is not right
                     ;; after the opening pair *after* the potential
                     ;; closing character was inserted (if opening
                     ;; pair and closing pair are the same, it would
                     ;; delete it right after the insertion otherwise)
                     (> (- (point) (overlay-start overlay)) (length open-pair)))
            (if (equal (sp-single-key-description last) (substring close-pair-rest 0 1))
                (progn
                  (forward-char 1)
                  (delete-char (- 1))
                  (setq sp-last-operation 'sp-skip-closing-pair))
              ;; Charactar that is not part of the closing pair was
              ;; typed.  Only remove overlays if we're inside the
              ;; closing pair.  If we are at the beginning, we are
              ;; allowed to type other characters
              (when (> already-skipped 0)
                (dolist (o sp-pair-overlay-list) (sp-remove-overlay o)))
              )))))))

(defun sp-delete-pair (&optional arg)
  "Automatically delete opening or closing pair, or both, depending on
position of point.

If the point is inside an empty pair, automatically delete both.  That
is, [(|) turns to [|, [\{|\} turns to [|.  Can be disabled by setting
`sp-autodelete-pair' to nil.

If the point is behind a closing pair or behind an opening pair delete
it as a whole.  That is, \{\}| turns to \{|, \{| turns to |.  Can be
disabled by setting `sp-autodelete-closing-pair' and
`sp-autodelete-opening-pair' to nil."
  ;; NOTE: Only use delete-char inside this function, so we
  ;; don't activate the advice recursively!

  ;; only activate if argument is 1 (this is 0-th argument of the
  ;; delete-backward-char), otherwise the user wants to delete
  ;; multiple character, so let him do that
  (when (and (= arg 1)
             smartparens-mode)
    (if (and sp-autodelete-wrap
             (eq sp-last-operation 'sp-wrap-region))
        (let ((p (point))
              (s (nth 0 sp-last-wrapped-region))
              (e (nth 1 sp-last-wrapped-region))
              (o (nth 2 sp-last-wrapped-region))
              (c (nth 3 sp-last-wrapped-region)))
          ;; if the last operation was `sp-wrap-region', and we are at
          ;; the position of either opening or closing pair, delete the
          ;; just-inserted pair
          (cond
           ((= p (+ s o))
            (save-excursion
              (delete-char (- (1- o)))
              (goto-char (- e o -1))
              (delete-char (- c)))
            (setq sp-last-operation 'sp-delete-pair-wrap))
           ((= p e)
            (save-excursion
              (delete-char (- (1- c)))
              (goto-char s)
              (delete-char o))
            (setq sp-last-operation 'sp-delete-pair-wrap))))
      (let* ((p (point))
             (inside-pair (--first (and (looking-back (regexp-quote (car it)) (- p 10))
                                        (looking-at (regexp-quote (cdr it))))
                                   sp-pair-list))
             (behind-pair (--first (looking-back (regexp-quote (cdr it)) (- p 10)) sp-pair-list))
             (opening-pair (--first (looking-back (regexp-quote (car it)) (- p 10)) sp-pair-list)))
        (cond
         ;; we're just before the closing quote of a string.  If there
         ;; is an opening or closing pair behind the point, remove
         ;; it.  This is only really relevant if the pair ends in the
         ;; same character as string quote.  We almost never want to
         ;; delete it as an autopair (it would "open up the string").
         ;; So, word\"|" and <backspace> should produce word\|" or
         ;; word|" (if \" is autopair) instead of word\|.
         ((and (sp-point-in-string)
               (not (sp-point-in-string (1+ p)))
               (sp-point-in-string (1- p))) ;; the string isn't empty
          (cond ;; oh, you ugly duplication :/
           ((and behind-pair sp-autodelete-closing-pair)
            (delete-char (- (1- (length (car behind-pair)))))
            (setq sp-last-operation 'sp-delete-pair-closing))
           ((and opening-pair sp-autodelete-opening-pair)
            (delete-char (- (1- (length (car opening-pair)))))
            (setq sp-last-operation 'sp-delete-pair-opening))))
         ;; we're inside a pair
         ((and inside-pair sp-autodelete-pair)
          (delete-char (length (cdr inside-pair)))
          (delete-char (- (1- (length (car inside-pair)))))
          (setq sp-last-operation 'sp-delete-pair))
         ;; we're behind a closing pair
         ((and behind-pair sp-autodelete-closing-pair)
          (delete-char (- (1- (length (cdr behind-pair)))))
          (setq sp-last-operation 'sp-delete-pair-closing))
         ;; we're behind an opening pair and there's no closing pair
         ((and opening-pair sp-autodelete-opening-pair)
          (delete-char (- (1- (length (car opening-pair)))))
          (setq sp-last-operation 'sp-delete-pair-opening))
         )))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Navigation

;; TODO: this has a hardcoded limit of 10!
(defun sp-search-backward-regexp (regexp &optional bound noerror)
  "Works just like `search-backward-regexp', but returns the
longest possible match.  That means that searching for
\"defun|fun\" backwards would return \"defun\" instead of
\"fun\", which would be matched first.

This is an internal function.  Only use this for searching for
pairs!"
  (when (search-backward-regexp regexp bound noerror)
    (goto-char (match-end 0))
    (looking-back regexp 10 t)
    (goto-char (match-beginning 0))))

(defun sp-get-quoted-string-bounds ()
  "If the point is inside a quoted string, return its bounds."
  (when (nth 3 (syntax-ppss))
    (let ((open (save-excursion
                  (while (nth 3 (syntax-ppss))
                    (forward-char -1))
                  (1+ (point))))
          (close (save-excursion
                   (while (nth 3 (syntax-ppss))
                     (forward-char 1))
                   (1- (point)))))
      (cons open close))))

(defmacro sp-search-and-save-match (search-fn pattern bound res beg end str)
  "Save the last match info."
  `(progn
     (setq ,res (funcall ,search-fn ,pattern ,bound t))
     (when ,res
       (setq ,beg (match-beginning 0))
       (setq ,end (match-end 0))
       (setq ,str (match-string 0)))))

;; TODO: since this function is used for all the navigation, we should
;; optimaze it a lot! Get some elisp profiler!
(defun sp-get-sexp (&optional back)
  "Find the nearest balanced expression that is after point, or
before point if BACK is non-nil.  This also means, if the point
is inside an expression, this expression is returned.

For the moment, this function (ignores) pairs where the opening and
closing pair is the same, as it is impossible to correctly
determine the opening/closing relation without keeping track of
the content of the entire buffer.

If the search starts outside a string or comment, all subsequent
comments are skipped.  For example, if you have a standard
emacs-lisp defun header:

   (defun foo (bar)|
     \"doc string with (a balanced) expression\"
     (baz))

and the point is at |, the next returned sexp will be (baz).

If the search starts inside a string, it tries to find the first
balanced expression that is completely contained inside the
string or comment.  If no such expression exist, a warning is
raised (for example, when you comment out imbalanced expression).
However, if you start a search from within a string and the next
complete sexp lies completely outside, this is returned."
  (let* ((search-fn (if (not back) 'search-forward-regexp 'sp-search-backward-regexp))
         (pair-list (--filter (and (sp-insert-pair-p (car it) major-mode)
                                   (not (string= (car it) (cdr it)))) sp-pair-list))
         (pattern (regexp-opt (-flatten (--map (list (car it) (cdr it)) pair-list))))
         (in-string-or-comment (sp-point-in-string-or-comment))
         (string-bounds (and in-string-or-comment (sp-get-quoted-string-bounds)))
         (fw-bound (point-max))
         (bw-bound (point-min))
         (s nil) (e nil) (active-pair nil) (forward nil) (failure nil)
         (mb nil) (me nil) (ms nil) (r nil))
    (save-excursion
      (sp-search-and-save-match search-fn pattern (if back bw-bound fw-bound)
                                r mb me ms)
      (when (not (sp-point-in-string-or-comment))
        (setq in-string-or-comment nil))
      (unless in-string-or-comment
        (while (sp-point-in-string-or-comment)
          (sp-search-and-save-match search-fn pattern (if back bw-bound fw-bound)
                                    r mb me ms)))
      (when r
        (setq active-pair (--first (equal ms (car it)) pair-list))
        (if active-pair
            (progn
              (setq forward t)
              (setq s mb)
              (when back
                (forward-char (length (car active-pair)))))
          (setq active-pair (--first (equal ms (cdr it)) pair-list))
          (setq e me)
          (when (not back)
            (backward-char (length (cdr active-pair)))))
        (let* ((open (if forward (car active-pair) (cdr active-pair)))
               (close (if forward (cdr active-pair) (car active-pair)))
               (needle (regexp-opt (list (car active-pair) (cdr active-pair))))
               (search-fn (if forward 'search-forward-regexp 'search-backward-regexp))
               (depth 1)
               (eof (if forward 'eobp 'bobp))
               (b (if forward fw-bound bw-bound)))
          (while (and (> depth 0) (not (funcall eof)))
            (sp-search-and-save-match search-fn needle b r mb me ms)
            (if r
                (unless (or (and (not in-string-or-comment)
                                 (sp-point-in-string-or-comment))
                            ;; we need to check if the match isn't
                            ;; preceded by escape sequence.  This is a
                            ;; bit tricky to do right, so for now we
                            ;; just handle emacs-lisp ?\ character
                            ;; prefix
                            (and (member major-mode '(emacs-lisp-mode inferior-emacs-lisp-mode lisp-mode))
                                 (equal (buffer-substring (max 1 (- mb 2)) mb) "?\\")))
                  (if (equal ms open)
                      (setq depth (1+ depth))
                    (setq depth (1- depth))))
              (message "Search failed.  This means there is unmatched expression somewhere or we are at the beginning/end of file.")
              (setq depth -1)
              (setq failure t)))
          (if forward
              (setq e me)
            (setq s mb))
          (unless failure
            (cond
             ((or (and (sp-point-in-string-or-comment s) (not (sp-point-in-string-or-comment e)))
                  (and (not (sp-point-in-string-or-comment s)) (sp-point-in-string-or-comment e)))
              (message "Opening or closing pair is inside a string or comment and matching pair is outside (or vice versa).  Ignored.")
              nil)
             (t (list s e (if forward open close) (if forward close open))))
            ))))))

(defun sp-get-enclosing-sexp (&optional arg)
  "Return the balanced expression that wraps point at the same
level.  With ARG, ascend that many times.  This funciton expect
positive argument."
  (setq arg (or arg 1))
  (save-excursion
    (let ((n arg)
          (ok t))
      (while (and (> n 0) ok)
        (setq ok t)
        (let ((p (point)))
          (setq ok (sp-get-sexp))
          (cond
           ((and ok (= (car ok) p))
            (goto-char (cadr ok))
            (setq n (1+ n)))
           ((and ok (< (car ok) p))
            (goto-char (cadr ok)))
           (t
            (while (and ok (>= (car ok) p))
              (setq ok (sp-get-sexp))
              (when ok (goto-char (cadr ok)))))))
        (setq n (1- n)))
      ok)))

(defun sp-forward-sexp (&optional arg)
  "Move forward across one balanced expression.  With ARG, do it
that many times.  Negative arg -N means move backward across N
balanced expressions."
  (interactive "^p")
  (setq arg (or arg 1))
  (if (< arg 0)
      (sp-backward-sexp (- arg))
    (let* ((n arg)
           (ok t))
      (while (and ok (> n 0))
        (setq ok (sp-get-sexp))
        (setq n (1- n))
        (when ok (goto-char (cadr ok))))
      ok)))

(defun sp-backward-sexp (&optional arg)
  "Move backward across one balanced expression (sexp).
With ARG, do it that many times.  Negative arg -N means move
forward across N balanced expressions."
  (interactive "^p")
  (setq arg (or arg 1))
  (if (< arg 0)
      (sp-forward-sexp (- arg))
    (let* ((n arg)
           (ok t))
      (while (and ok (> n 0))
        (setq ok (sp-get-sexp t))
        (setq n (1- n))
        (when ok (goto-char (car ok))))
      ok)))

(defun sp-next-sexp (&optional arg)
  "Move forward to the beginning of next balanced expression.
With ARG, do it that many times.  If there is no next expression
at current level, jump one level up (effectively doing
`sp-backward-up-list').  Negative arg -N means move to the
beginning of N-th previous balanced expression."
  (interactive "^p")
  (setq arg (or arg 1))
  (if (> arg 0)
      (if (= arg 1)
          (let ((ok (sp-get-sexp)))
            (when ok
              (if (= (point) (car ok))
                  (progn (sp-forward-sexp 2)
                         (sp-backward-sexp))
                (goto-char (car ok))
                ok)))
        (sp-forward-sexp arg)
        (sp-backward-sexp))
    (sp-backward-sexp (- arg))))

(defun sp-previous-sexp (&optional arg)
  "Move backward to the end of previous balanced expression.
With ARG, do it that many times.  If there is no next
expression at current level, jump one level up (effectively
doing `sp-up-list').  Negative arg -N means move to the end of
N-th following balanced expression."
  (interactive "^p")
  (setq arg (or arg 1))
  (if (> arg 0)
      (if (= arg 1)
          (let ((ok (sp-get-sexp t)))
            (when ok
              (if (= (point) (cadr ok))
                  (progn (sp-backward-sexp 2)
                         (sp-forward-sexp))
                (goto-char (cadr ok))
                ok)))
        (sp-backward-sexp arg)
        (sp-forward-sexp))
    (sp-forward-sexp (- arg))))

(defun sp-down-sexp (&optional arg)
  "Move forward down one level of sexp.  With ARG, do this that
many times.  A negative argument means move backward but still
go down a level."
  (interactive "^p")
  (setq arg (or arg 1))
  (if (> arg 0)
      (let ((n arg)
            (ok t))
        (while (and ok (> n 0))
          (setq ok (sp-get-sexp))
          (setq n (1- n))
          (when ok (goto-char (+ (car ok) (length (nth 2 ok))))))
        ok)
    (let ((n (- arg))
          (ok t))
      (while (and ok (> n 0))
        (setq ok (sp-get-sexp t))
        (setq n (1- n))
        (when ok (goto-char (- (cadr ok) (length (nth 3 ok))))))
      ok)))

(defun sp-backward-down-sexp (&optional arg)
  "An alias for (sp-down-sexp (- (or arg 1))).  This function
expect positive argument.  See `sp-down-sexp'."
  (interactive "^p")
  (when (> arg 0)
    (sp-down-sexp (- (or arg 1)))))

(defun sp-up-sexp (&optional arg)
  "Move forward out of one level of parentheses.  With ARG, do
this that many times.  A negative argument means move backward
but still to a less deep spot."
  (interactive "^p")
  (setq arg (or arg 1))
  (let ((ok (sp-get-enclosing-sexp (abs arg))))
    (when ok
      (if (> arg 0) (goto-char (cadr ok))
        (goto-char (car ok))))
    ok))

(defun sp-backward-up-sexp (&optional arg)
  "An alias for (sp-up-sexp (- (or arg 1))).  This function
expect positive argument.  See `sp-up-sexp'."
  (interactive "^p")
  (when (> arg 0)
    (sp-up-sexp (- (or arg 1)))))

(defun sp-kill-sexp (&optional arg)
  "Kill the sexp (balanced expression) following point.  If
inside an expression, kill the topmost enclosing expression.
With ARG, kill that many sexps after point.  Negative arg -N
means kill N sexps before point.

 (foo |(abc) bar)  -> (foo bar)

 (foo (bar) | baz) -> |."
  (interactive "^p")
  (setq arg (or arg 1))
  (if (> arg 0)
      (let ((n arg)
            (ok t))
        (while (and (> n 0) ok)
          (setq ok (sp-get-sexp))
          (setq n (1- n))
          (when ok (kill-region (car ok) (cadr ok)))))
    (let ((n (- arg))
          (ok t))
      (while (and (> n 0) ok)
        (setq ok (sp-get-sexp t))
        (setq n (1- n))
        (when ok (kill-region (car ok) (cadr ok)))))))

(defun sp-backward-kill-sexp (&optional arg)
  "An alias for (sp-kill-sexp (- (or arg 1))).  This function
expect positive argument.  See `sp-kill-sexp'."
  (interactive "^p")
  (when (> arg 0)
    (sp-kill-sexp (- (or arg 1)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; "paredit" operations

(defmacro sp-generate-slurp-barf (fn-name doc-string)
  (let ((slurp (string-match-p "slurp" (symbol-name fn-name))))
    `(defun ,fn-name (&optional arg)
       ,doc-string
       (interactive "p")
       (setq arg (or arg 1))
       (let* ((pair-list (--filter (and (sp-insert-pair-p (car it) major-mode)
                                        (not (string= (car it) (cdr it)))) sp-pair-list))
              (opening (regexp-opt (--map (car it) pair-list)))
              (closing (regexp-opt (--map (cdr it) pair-list)))
              (all (regexp-opt (-concat '(" " "\t" "\n") (-flatten (--map (list (car it) (cdr it)) pair-list)))))
              (n (abs arg))
              (fw (> arg 0))
              (slupr-fn
               ,(if slurp '(if fw 'sp-forward-slurp-sexp-1 'sp-backward-slurp-sexp-1)
                  '(if fw 'sp-forward-barf-sexp-1 'sp-backward-barf-sexp-1)))
              (next-thing t))
         (while (and next-thing (> n 0))
           (save-excursion
             (setq next-thing (funcall slupr-fn opening closing all))
             (if next-thing
                 (let* ((close (nth (if fw 4 3) next-thing))
                        (gtold (nth (if fw 2 1) next-thing))
                        (del (* (if fw -1 1) (length close)))
                        (gtnew
                         ,(if slurp '(+ (car next-thing) (if fw del 0))
                            '(- (car next-thing) (if fw 0 del)))))
                   (goto-char gtold)
                   (delete-char del)
                   (goto-char gtnew)
                   (insert close)
                   (setq n (1- n)))
               (message "We can't slurp/barf without breaking strictly balanced expression. Ignored.")
               (setq n -1))))))))

(sp-generate-slurp-barf sp-forward-slurp-sexp
  "Add the S-expression following the current list into that list
by moving the closing delimiter.  If the current list is the last
in a parent list, extend that list (and possibly apply
recursively until we can extend a list or end of file).  If arg
is N, apply this function that many times.  If arg is negative
-N, extend the opening pair instead (that is, backward).

Examples:

 (foo |bar) baz   -> (foo |bar baz)

 [(foo |bar)] baz -> [(foo |bar) baz]

 [(foo |bar) baz] -> [(foo |bar baz)]")

(defun sp-backward-slurp-sexp (&optional arg)
  "Add the S-expression preceding the current list into that list
by moving the opening delimiter.  If the current list is the
first in a parent list, extend that list (and possibly apply
recursively until we can extend a list or beginning of file).  If
arg is N, apply this function that many times.  If arg is
negative -N, extend the closing pair instead (that is, forward).

Examples:

 foo (bar| baz)   -> (foo bar| baz)

 foo [(bar| baz)] -> [foo (bar| baz)]

 [foo (bar| baz)] -> [(foo bar| baz)]"
  (interactive "p")
  (sp-forward-slurp-sexp (- (or arg 1))))

(sp-generate-slurp-barf sp-forward-barf-sexp
  "Remove the last S-expression in the current list by moving the
closing delimiter.  If arg is N, barf that many expressions.  If
arg is negative -N, contract the opening pair instead.  If the
current list is empty, do nothing.

Examples:

  (foo bar| baz)   -> (foo bar|) baz

  (foo| [bar baz]) -> (foo|) [bar baz]")

(defun sp-backward-barf-sexp (&optional arg)
  "Remove the first S-expression in the current list by moving
the opening delimiter.  If arg is N, barf that many expressions.
If arg is negative -N, contract the closing pair instead.  If the
current list is empty, do nothing.

Examples:

  (foo bar| baz)   -> foo (bar| baz)

  ([bar baz] |foo) -> [bar baz] (|foo)"
  (interactive "p")
  (sp-forward-barf-sexp (- (or arg 1))))


;; TODO: slurp/barf doesn't work well if the point is inside a string
;; while barfing/slurping
(defmacro sp-slurp-sexp-1 (dir skip-fn prev-char look-fn this-fn limit-fn symbol-fn)
  "Internal.  DIR is the direction, t means forward, nil
backward.  SKIP-FN is a function that skips to next meaningful
token.  PREV-CHAR returns previous logical character.  LOOK-FN is
`looking-at' or `looking-back' depending on direction.  THIS-FN
is name of \"this\" function for recursive call.  LIMIT-FN is
either `car' or `cadr' that retrieves opening or closing position
of enclosing sexp.  SYMBOL-FN is a function that skips a symbol
that will be slurped."
  `(let ((enc (sp-get-enclosing-sexp)))
     (when enc
       (goto-char (,limit-fn enc))
       (,skip-fn t)
       (cond
        ;; if we're looking back at a string, extend here
        ((eq (,prev-char) ?\")
         (cons (point) enc))
        ;; if we're looking at the end of another sexp, call recursively again
        ((,look-fn ,(if dir closing opening))
         (,this-fn opening closing all))
        ;; if we're looking at opening, wrap this expression
        ((,look-fn ,(if dir opening closing))
         (let ((ok (sp-get-sexp ,(not dir))))
           (when ok (cons (,limit-fn ok) enc))))
        ;; otherwise forward a symbol and return point after that
        (t
         (,symbol-fn all)
         (cons (point) enc))))))

(defmacro sp-barf-sexp-1 (dir skip-fn prev-char look-fn symbol-fn)
  "Internal.  DIR is the direction, t means forward, nil
backward.  SKIP-FN is a function that skips to next meaningful
token.  PREV-CHAR returns previous logical character.  LOOK-FN is
`looking-at' or `looking-back' depending on direction.  SYMBOL-FN
is a function that skips a symbol that will be barfed."
  `(let ((enc (sp-get-enclosing-sexp)))
     (when enc
       ,(if dir '(goto-char (- (cadr enc) (length (nth 3 enc))))
          '(goto-char (+ (car enc) (length (nth 2 enc)))))
       (,skip-fn t)
       (cond
        ;; if we're looking back at a string, extend here
        ((eq (,prev-char) ?\")
         (,skip-fn nil t)
         (cons (point) enc))
        ;; if we're looking at opening, wrap this expression
        ((,look-fn ,(if dir 'closing 'opening))
         (let ((ok (sp-get-sexp ,dir)))
           (when ok
             (goto-char (,(if dir 'car 'cadr) ok))
             (,skip-fn nil t)
             (cons (point) enc))))
        ;; otherwise forward a symbol and return point after that
        (t
         (,symbol-fn all)
         (,skip-fn nil t)
         (cons (point) enc))))))

(defun sp-forward-slurp-sexp-1 (opening closing all)
  "Internal."
  (sp-slurp-sexp-1 t sp-skip-forward-to-meaningful
                   preceding-char
                   looking-at
                   sp-forward-slurp-sexp-1
                   cadr
                   sp-forward-symbol))

(defun sp-backward-slurp-sexp-1 (opening closing all)
  "Internal."
  (sp-slurp-sexp-1 nil sp-skip-backward-to-meaningful
                   char-after
                   looking-back
                   sp-backward-slurp-sexp-1
                   car
                   sp-backward-symbol))

(defun sp-forward-barf-sexp-1 (opening closing all)
  "Internal."
  (sp-barf-sexp-1 t sp-skip-backward-to-meaningful
                  char-after
                  looking-back
                  sp-backward-symbol))

(defun sp-backward-barf-sexp-1 (opening closing all)
  "Internal."
  (sp-barf-sexp-1 nil sp-skip-forward-to-meaningful
                  preceding-char
                  looking-at
                  sp-forward-symbol))

(defun sp-forward-symbol (what)
  "Skip forward one symbol.  WHAT is a regexp that defines symbol
delimiters.  Usually, symbol is defined as whitespace or open/close pair
delimited portion of text."
  (when (search-forward-regexp what nil t)
    (goto-char (match-beginning 0))))

(defun sp-backward-symbol (what)
  "Skip backward one symbol.  WHAT is a regexp that defines symbol
delimiters.  Usually, symbol is defined as whitespace or open/close pair
delimited portion of text."
  (when (sp-search-backward-regexp what nil t)
    (goto-char (match-end 0))))

(defmacro sp-skip-to-meaningful (next-char prev-char move-fn)
  "This macro implements forward/backward movement skipping
whitespace, comments and strings. NEXT-CHAR is a function that
return next char in the logical direction we're moving.
PREV-CHAR is a function that return previous char.  MOVE-FN is a
function that moves the point."
  `(let ((skip-string 2))
     (while (and (not (eobp))
                 (or (not after-string) (> skip-string 0))
                 (or (sp-point-in-string-or-comment)
                     (member (char-syntax (,next-char))
                             ,(if stop-at-string ''(?< ?> ?! ?| ?\ )
                                ''(?< ?> ?! ?| ?\  ?\")))))
       (when (and (eq (char-syntax (,next-char)) ?\" )
                  (not (eq (char-syntax (,prev-char)) ?\\)))
         (setq skip-string (1- skip-string)))
       (,move-fn 1))))

(defun sp-skip-forward-to-meaningful (&optional after-string stop-at-string)
  "Skip forward ignoring whitespace, comments and strings.  If
AFTER-STRING is non-nil, stop after first exiting a string.  If
STOP-AT-STRING is non-nil, stop before entering a string."
  (sp-skip-to-meaningful char-after preceding-char forward-char))

(defun sp-skip-backward-to-meaningful (&optional after-string stop-at-string)
  "Skip backward ignoring whitespace, comments and strings.  If
AFTER-STRING is non-nil, stop after first exiting a string.  If
STOP-AT-STRING is non-nil, stop before entering a string."
  (sp-skip-to-meaningful preceding-char char-after backward-char))

(defun sp-unwrap-sexp-1 (sexp)
  "Internal.  Unwraps expression."
  (let ((s (car sexp))
        (e (cadr sexp))
        (lo (length (nth 2 sexp)))
        (lc (length (nth 3 sexp))))
    (delete-region s (+ s lo))
    (delete-region (- e lo lc) (- e lo))))

(defun sp-unwrap-sexp (&optional arg)
  "Unwrap the following expression.  With arg N, unwrap Nth
expression as returned by `sp-forward-sexp'.  If arg is
negative -N, unwrap Nth expression backwards as returned by
`sp-backward-sexp'."
  (interactive "p")
  (setq arg (or arg 1))
  (let ((ok (save-excursion (sp-forward-sexp arg))))
    (when ok (sp-unwrap-sexp-1 ok))))

(defun sp-backward-unwrap-sexp (&optional arg)
  "Unwrap the previous expression.  With arg N, unwrap Nth
expression as returned by `sp-backward-sexp'.  If arg is
negative -N, unwrap Nth expression forward as returned by
`sp-forward-sexp'."
  (interactive "p")
  (sp-unwrap-sexp (- (or arg 1))))

(defun sp-splice-sexp (&optional arg)
  "Unwrap the current list.  With arg N, unwrap Nth list as
returned by applying `sp-up-sexp' N times.  This function
expect positive arg."
  (interactive "p")
  (setq arg (or arg 1))
  (let ((ok (sp-get-enclosing-sexp arg)))
    (when ok (sp-unwrap-sexp-1 ok))))

(defun sp-splice-sexp-killing-backward ()
  "Unwrap the current list and also kill all the content between
start of this list and the point.

Examples:

  (foo (let ((x 5)) | (sqrt n)) bar) -> (foo | (sqrt n) bar)"
  (interactive)
  (let ((ok (sp-get-enclosing-sexp 1)))
    (when ok
      (sp-unwrap-sexp-1 ok)
      (delete-region (car ok) (point)))))

(defun sp-splice-sexp-killing-forward ()
  "Unwrap the current list and also kill all the content between the
point and the end of this list.

Examples:

  (a (b c| d e) f) -> (a b c| f)"
  (interactive)
  (let ((ok (sp-get-enclosing-sexp 1)))
    (when ok
      (sp-unwrap-sexp-1 ok)
      (delete-region (point) (- (cadr ok) (length (nth 2 ok)) (length (nth 3 ok)))))))

(defun sp-forward-whitespace ()
  "Skip forward past the whitespace characters."
  (interactive)
  (skip-chars-forward " \t\n"))


(defun sp-backward-whitespace ()
  "Skip backward past the whitespace characters."
  (interactive)
  (skip-chars-backward " \t\n"))

(defun sp-split-sexp ()
  "Split the list or string the point is on into two."
  (interactive)
  (if (sp-point-in-string)
      (progn
        (forward-char (- (prog1 (sp-backward-whitespace) (insert "\""))))
        (save-excursion (sp-forward-whitespace) (insert "\"")))
    (let ((ok (sp-get-enclosing-sexp 1)))
      (when ok
        (forward-char (- (prog1 (sp-backward-whitespace) (insert (nth 3 ok)))))
        (save-excursion (sp-forward-whitespace) (insert (nth 2 ok)))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; show-smartparens-mode

(defgroup show-smartparens nil
  "Show smartparens minor mode."
  :group 'smartparens)

(defcustom sp-show-pair-delay 0.125
  "Time in seconds to delay before showing a matching pair."
  :type '(number :tag "seconds")
  :group 'show-smartparens)

(defface sp-show-pair-match-face
  '((((class color) (background light))
     :background "turquoise")       ; looks OK on tty (becomes cyan)
    (((class color) (background dark))
     :background "steelblue3")      ; looks OK on tty (becomes blue)
    (((background dark))
     :background "grey50")
    (t
     :background "gray"))
  "`show-smartparens-mode' face used for a matching pair."
  :group 'show-smartparens)

(defface sp-show-pair-mismatch-face
  '((((class color)) (:foreground "white" :background "purple"))
    (t (:inverse-video t)))
  "`show-smartparens-mode' face used for a mismatching pair."
  :group 'show-smartparens)

(defvar sp-show-pair-idle-timer nil)

(defvar sp-show-pair-overlays nil)

;;;###autoload
(define-minor-mode show-smartparens-mode
  "Toggle visualization of matching pairs.  When enabled, any
matching pair is highlighted after `sp-show-pair-delay' seconds
of Emacs idle time if the point is immediately in front or after
a pair.  This mode works similarly to `show-paren-mode', but
support custom pairs."
  :init-value nil
  :group 'show-smartparens
  (if show-smartparens-mode
      (unless sp-show-pair-idle-timer
        (setq sp-show-pair-idle-timer
              (run-with-idle-timer sp-show-pair-delay t
                                   'sp-show-pair-function)))
    (when sp-show-pair-overlays
      (sp-show-pair-delete-overlays))))

;;;###autoload
(define-globalized-minor-mode show-smartparens-global-mode
  show-smartparens-mode
  turn-on-show-smartparens-mode)

;;;###autoload
(defun turn-on-show-smartparens-mode ()
  "Turn on `show-smartparens-mode'."
  (interactive)
  (unless (or (member major-mode sp-ignore-modes-list)
              (minibufferp))
    (show-smartparens-mode t)))

;;;###autoload
(defun turn-off-show-smartparens-mode ()
  "Turn off `show-smartparens-mode'."
  (interactive)
  (show-smartparens-mode nil))

;; TODO: hardcoded limit 10
(defun sp-show-pair-function ()
  "Display the show pair overlays."
  (when show-smartparens-mode
    (let* ((pair-list (--filter (and (sp-insert-pair-p (car it) major-mode)
                                     (not (string= (car it) (cdr it)))) sp-pair-list))
           (opening (regexp-opt (--map (car it) pair-list)))
           (closing (regexp-opt (--map (cdr it) pair-list)))
           ok match)
      (cond
       ((looking-at opening)
        (setq match (match-string 0))
        (setq ok (sp-get-sexp))
        (if ok
            (sp-show-pair-create-overlays (car ok) (cadr ok)
                                          (length (nth 2 ok))
                                          (length (nth 3 ok)))
          (sp-show-pair-create-mismatch-overlay (point) (length match))))
       ((looking-back closing 10 t)
        (setq match (match-string 0))
        (setq ok (sp-get-sexp t))
        (if ok
            (sp-show-pair-create-overlays (car ok) (cadr ok)
                                          (length (nth 2 ok))
                                          (length (nth 3 ok)))
          (sp-show-pair-create-mismatch-overlay (- (point) (length match))
                                                (length match))))
       (sp-show-pair-overlays
        (sp-show-pair-delete-overlays)))
      )))

(defun sp-show-pair-create-overlays (start end olen clen)
  "Create the show pair overlays."
  (when sp-show-pair-overlays
    (sp-show-pair-delete-overlays))
  (let* ((oleft (make-overlay start (+ start olen) nil t nil))
         (oright (make-overlay (- end clen) end nil t nil)))
    (setq sp-show-pair-overlays (cons oleft oright))
    (overlay-put oleft 'face 'sp-show-pair-match-face)
    (overlay-put oright 'face 'sp-show-pair-match-face)
    (overlay-put oleft 'priority 1000)
    (overlay-put oright 'priority 1000)
    (overlay-put oleft 'type 'show-pair)))

(defun sp-show-pair-create-mismatch-overlay (start len)
  "Create the mismatch pair overlay."
  (when sp-show-pair-overlays
    (sp-show-pair-delete-overlays))
  (let ((o (make-overlay start (+ start len) nil t nil)))
    (setq sp-show-pair-overlays (cons o nil))
    (overlay-put o 'face 'sp-show-pair-mismatch-face)
    (overlay-put o 'priority 1000)
    (overlay-put o 'type 'show-pair)))

(defun sp-show-pair-delete-overlays ()
  "Remove both show pair overlays."
  (when sp-show-pair-overlays
    (when (car sp-show-pair-overlays)
      (delete-overlay (car sp-show-pair-overlays)))
    (when (cdr sp-show-pair-overlays)
      (delete-overlay (cdr sp-show-pair-overlays)))
    (setq sp-show-pair-overlays nil)))

;; global initialization
(sp-update-pair-triggers)
(defadvice delete-backward-char (before sp-delete-pair-advice activate)
  (sp-delete-pair (ad-get-arg 0)))
(add-hook 'post-command-hook 'sp-post-command-hook-handler)
(add-hook 'pre-command-hook 'sp-pre-command-hook-handler)

(provide 'smartparens)

;;; smartparens.el ends here