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

* Preface

This is my attempt of getting my configuration organized with literate programming and =org-babel=. I took the workflow I'm following from [[https://github.com/larstvei][@larstvei]]. The idea is that the =init.el= file will replace itself on the first execution with the tangled version of this file. This first version will also be byte-compiled. This means that all changes are to be made on the =init.org= file *always*. The initial contents of the =init.el= are:

#+BEGIN_SRC elisp :tangle no
;; We can't tangle without org!
(require 'org)

;; Follow symlinks
(setq vc-follow-symlinks t)

;; Open the configuration
(find-file (concat user-emacs-directory "init.org"))

;; Tangle it
(org-babel-tangle)

;; Load it
(load-file (concat user-emacs-directory "init.el"))

;; Finally byte-compile it
(byte-compile-file (concat user-emacs-directory "init.el"))
#+END_SRC

There is no reason to track the =init.el= file, and no reason to change this file. In order to ensure this, make sure to apply the following command after cloning:

#+BEGIN_SRC sh :tangle no
git update-index --assume-unchanged emacs/init.el
#+END_SRC

From now on our code will be tangled, meaning that it will go into the final =init.el= file. For starters, let's have a good header:

#+BEGIN_SRC elisp
;;; init.el --- init file -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2016-2020 Miquel Sabaté Solà <mikisabate@gmail.com>
;;
;; Author: Miquel Sabaté Solà <mikisabate@gmail.com>
;; Version: 0.1
;; Package-Requires: ((emacs "25.3"))
;; Keywords: convenience, extensions, files, frames, mail, matching, terminals, tools, vc, wp
;; URL: https://github.com/mssola/dotfiles
;;
;; This file is not part of GNU Emacs.
;;
;; 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:
;;
;; This file has been autogenerated by `org-mode', by tangling what I had in my
;; init.org.
;;
;; NOTE DO NOT MODIFY THIS FILE.  All changes should go into init.org.

;;; Code:
#+END_SRC

Moreover, in order to avoid manually tangling and compiling the =init.org= file
on each change, the following function is provided:

#+BEGIN_SRC elisp
(defun tangle-init ()
  "If the current buffer is 'init.org' the code-blocks are
  tangled, and the tangled file is compiled. Morever, an init.html is generated."

  (when (or (equal (buffer-file-name)
                   (expand-file-name (concat user-emacs-directory "init.org")))
            (string-suffix-p "dotfiles/.emacs.d/init.org" (buffer-file-name)))

    ;; Avoid running hooks when tangling
    (let ((prog-mode-hook nil))
      (org-babel-tangle)
      (byte-compile-file (concat user-emacs-directory "init.el"))
      (remove-hook 'emacs-lisp-mode-hook 'soria-theme-purple-identifiers)
      (org-html-export-to-html)
      (add-hook 'emacs-lisp-mode-hook 'soria-theme-purple-identifiers))))

(add-hook 'after-save-hook 'tangle-init)
#+END_SRC

As you can see, this function will tangle and compile the resulting =init.el= file, and it will also produce an HTML version of it. This HTML version will be pushed into my [[http://jo.mssola.com][personal site]] thanks to a git [[https://github.com/mssola/dotfiles/blob/master/.emacs.d/pre-push][pre-push]] hook. The resulting version being hosted [[http://jo.mssola.com/static/init.html][here]].

Other than that, I run GNU Emacs in server mode, but I don't use systemd for that. Instead, I'm using the =-a= argument of =emacsclient= with an empty string. This instructs =emacsclient= to spawn a new server if there isn't one already. This means that the first time around it will take some time, but in the next time everything will be alright. All this is handled outside of this configuration, by adding some handy scripts like =e= and =emacsclient-a-nw= that can be found inside of the =bin= directory from my dotfiles, and that they are later picked up by various config files such as =.bashrc=, =.gitconfig=, =i3= and such.

* Introduction

I'm using GNU Emacs 27, but everything should be working since GNU Emacs 24. There are some exceptions to this (e.g. webkit support), but these cases are individually handled. In the following block we define some handy constants that will be used throughout this configuration in order to support multiple versions of GNU Emacs. Moreover, this block also checks the version being used and errors out if you are using a GNU Emacs that is just too old for this configuration.

#+BEGIN_SRC elisp
(defconst EMACS-25-OR-LATER (>= emacs-major-version 25)
  "Whether we are using GNU Emacs 25.x")

(defconst EMACS-26-OR-LATER (>= emacs-major-version 26)
  "Whether we are using GNU Emacs 26.x")

(defconst EMACS-27-OR-LATER (>= emacs-major-version 27)
  "Whether we are using GNU Emacs 27.x")

(let ((minver "25.3")
      (recver "26.1"))
  (when (version< emacs-version minver)
    (error "Don't be a cheap bastard and upgrade to at least GNU Emacs v%s" minver))

  (when (version< emacs-version recver)
    (message "Your GNU Emacs is a bit old and some functionality will be disabled.  Consider upgrading to at least v%s" recver)))
#+END_SRC

After that, we do the same for the operating system:

#+BEGIN_SRC elisp
(defconst IS-LINUX (eq system-type 'gnu/linux)
  "Current system is GNU/Linux")

(defconst IS-MAC (eq system-type 'darwin)
  "Current system is MacOS")

(unless (or IS-LINUX IS-MAC)
  (error "This configuration has been checked only on GNU/Linux and MacOS"))
#+END_SRC

Now, here we have a little hack that has been popularized by the community but that I originally took from [[https://github.com/purcell][@purcell]] and later refined by looking at [[https://github.com/hlissner/doom-emacs][doom-emacs]]: let's temporarily reduce garbage collection so startup time is lower. That is, we disable GC and later we enable it back again after GNU Emacs is done evaluating our =init.el= file. This is done so GC does not interfere with the evaluation of a rather big file (and the evaluation of the /many/ packages being installed), and so we gain a good 0.4s in my workstation.

That being said, all of this is done in the =early-init.el= file for GNU Emacs 27 and later, so we have this gain as soon as possible.

#+BEGIN_SRC elisp
(unless EMACS-27-OR-LATER
  (defconst mssola-initial-gc-cons-threshold gc-cons-threshold
    "Initial value of `gc-cons-threshold' at start-up time.")

  (defconst mssola-initial-gc-cons-percentage gc-cons-percentage
    "Initial value of `gc-cons-percentage' at start-up time.")

  ;; Completely disable the GC by having a ginormous threshold.
  (setq gc-cons-threshold most-positive-fixnum
        gc-cons-percentage 0.6))

;; Enable the GC back again to its previous values. This should also be set here
;; for GNU Emacs 27 and later because the early-init.el purposely does not
;; fiddle with this hook.
(add-hook 'after-init-hook
          (lambda ()
            (setq gc-cons-threshold mssola-initial-gc-cons-threshold
                  gc-cons-percentage mssola-initial-gc-cons-percentage)))
#+END_SRC

There are some packages that expect us to have a =user-full-name= and a =user-mail-address= defined. Let's do it now so from now on these packages can get these values right:

#+BEGIN_SRC elisp
(setq user-full-name "Miquel Sabaté Solà"
      user-mail-address "mikisabate@gmail.com")
#+END_SRC

* Lisp packages
** Custom packages

Some years ago I came up with a shell script named [[https://github.com/mssola/g][g]] that deals with path shortcuts. I use this script a *lot* in the shell, and it occurred to me that it would be quite handy to also have a version of it en Emacs Lisp. I don't use it very often (because I usually navigate by projects), but when I do use it it's pretty darn useful. So, before we start dealing with packaging in general, let's compile it now and bind it to @@html:<kbd>M-g</kbd>@@.

#+BEGIN_SRC elisp
(if (file-exists-p (concat user-emacs-directory "lisp/g.elc"))
    (let ((load-prefer-newer t))
      (load-file (concat user-emacs-directory "lisp/g.elc")))
  (byte-compile-file (concat user-emacs-directory "lisp/g.el") t))

(global-set-key (kbd "M-g") 'g)
#+END_SRC

** use-package

GNU Emacs has a built-in packaging utility, =package=, and we rely on that heavily. Now it's the time to setup the repositories (or «package archives», as they are called in GNU Emacs), and initialize packaging. Before doing that, though, let's take a couple of things into account:

1. Since GNU Emacs 27.x I handle this through the =early-init.el= file.
2. GNU Emacs 26.2 had a nasty bug when it comes to gnutls that was work-arounded by setting an algorithm priority.

These are the two main weird things you will see from an otherwise pretty standard code block:

#+BEGIN_SRC elisp
(unless EMACS-27-OR-LATER
  (require 'package)

  (when (version= "26.2" emacs-version)
    (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3"))

  (setq package-archives
        '(("gnu" . "https://elpa.gnu.org/packages/")
          ("MELPA Stable" . "https://stable.melpa.org/packages/")
          ("MELPA"        . "https://melpa.org/packages/")
          ("org" .  "https://orgmode.org/elpa/"))
        package-archive-priorities
        '(("MELPA Stable" . 15)
          ("org"          . 10)
          ("gnu"          . 5)
          ("MELPA"        . 0)))

  (package-initialize))
#+END_SRC

After that has been done we could go around calling =(package-install 'package)= like crazy. However, the community has come up with some tooling around it that makes its usage more appealing. There are quite a lot of options, but I'm sticking with [[https://github.com/jwiegley/use-package][use-package]], simply because it's the first one that I looked into and that filled my needs. With this package I will be able to make sure that all my packages are installed properly in a rather clean way.

#+BEGIN_SRC elisp
(unless (package-installed-p 'use-package)
  (package-refresh-contents)
  (package-install 'use-package))

(require 'use-package)
#+END_SRC

* General
** GUI

Over the years I've come to appreciate more and more minimalistic GUIs. That is, I don't want too many things distracting me from I care the most: text. As you will see, I disable basically every possible GUI element out there. For starters, let's disable the menu, scroll and tool bars.

#+BEGIN_SRC elisp
(menu-bar-mode -1)
(when (fboundp 'set-scroll-bar-mode)
  (set-scroll-bar-mode nil))
(when (fboundp 'tool-bar-mode)
  (tool-bar-mode -1))
(when (fboundp 'tooltip-mode)
  (tooltip-mode 0))
#+END_SRC

We have nuked the scroll bar, but we have to scroll anyways, so let's tune the relevant variables so this experience is as smooth as possible:

#+BEGIN_SRC elisp
(setq scroll-margin 0
      scroll-conservatively 100000
      scroll-preserve-screen-position 1)
#+END_SRC

That being said, and as to not lose some relevant information hinted by these elements, let's put some additional info into the modeline. That is, let's enable there line, column and size indications.

#+BEGIN_SRC elisp
(line-number-mode 1)
(column-number-mode 1)
(size-indication-mode 1)
#+END_SRC

At this point we have basically cleared away everything between our eyes and the text, but in some cases (i.e. programming) it's useful to have line numbers inside of the window as well. In particular, I've grown quite fond of relative line numbers, which was supported by Vim a long time ago and landed in GNU Emacs 26.1. Let's enable them now (don't worry, you can always toggle that by pressing @@html:<kbd>C-c L</kbd>@@):

#+BEGIN_SRC elisp
(when EMACS-26-OR-LATER
  (add-hook 'prog-mode-hook 'display-line-numbers-mode)
  (setq display-line-numbers-type 'relative)
  (global-set-key (kbd "C-c L") 'display-line-numbers-mode))
#+END_SRC

Now it's the time to talk about the frame title and the icon title. That is, what should GNU Emacs tell the WM which title to display for the window (notice the difference between the concepts of "window" and "frame" in GNU Emacs and the rest of the world). In my case, I like a format like "<login>: <path>" (e.g. "mssola: ~/src/something-cool/main.c"). If we are not editing a file, then the name of the buffer is displayed (e.g. "mssola: *scratch*").

#+BEGIN_SRC elisp
(setq frame-title-format
      (setq icon-title-format '((:eval (concat (user-real-login-name) ": "
                                               (if (buffer-file-name)
                                                   (abbreviate-file-name (buffer-file-name))
                                                 "%b"))))))
#+END_SRC

The final element of the GUI to talk about is the modeline. I've tried in the past to come up with something fancy from my own, but =doom-modeline= is simply way cooler than anything I've tried to setup. Thus, I'm sticking with it. Furthermore, this modeline has a dependency, =all-the-icons=, that needs to download some fonts in order to work. These fonts will be automatically installed to the proper destination if they do not exist yet (unless we are in non-interactive mode). Other than that, =doom-modeline= is quite hackable, but here I only tweak a couple of options when it comes to the display of some of the icons.

#+BEGIN_SRC elisp
(use-package all-the-icons
  :ensure t
  :config
  ;; Check if the fonts have been already been installed. If that is not the
  ;; case, then install it now. The path detection is based from
  ;; all-the-icons.el.
  (let* ((font-dest (if IS-LINUX
                        (concat (or (getenv "XDG_DATA_HOME")
                                    (concat (getenv "HOME") "/.local/share"))
                                "/fonts/")
                      (if IS-MAC
                          (concat (getenv "HOME") "/Library/Fonts/")
                        nil)))
         (ttf-path (concat font-dest "all-the-icons.ttf")))

    ;; If we were able to detect the OS and we don't have a the file installed,
    ;; try to do it now (unless we are running in non-interactive mode).
    (when (and font-dest (not (file-exists-p ttf-path)) (not noninteractive))
      (message "Installing fonts...")
      (all-the-icons-install-fonts))))

(use-package doom-modeline
  :ensure t
  :after all-the-icons
  :init
  ;; We are using the default values except for a couple of values, mainly
  ;; around icons.
  (setq doom-modeline-height 20
        doom-modeline-mu4e t
        doom-modeline-persp-name nil
        doom-modeline-major-mode-icon nil
        doom-modeline-modal-icon t
        doom-modeline-icon t
        doom-modeline-buffer-file-name-style 'relative-from-project)

  ;; And finally enable it.
  (doom-modeline-mode 1))
#+END_SRC

Finally, do not resize the frame when a newly set font is different than the system's default. This does not hit us and it allows some performance gains: around 0.3s when starting GNU Emacs in GUI mode, but negligible when in text mode.

#+BEGIN_SRC elisp
(setq frame-inhibit-implied-resize t)
#+END_SRC

** Basic editing configuration

Now that the GUI is all nice and well, let's configure a bit our editting experience (just a bit, because most of the heavy lifting will be done via packages). First of all, and I cannot stress this enough, use UTF-8 *always*:

#+BEGIN_SRC elisp
  (prefer-coding-system 'utf-8)
  (set-default-coding-systems 'utf-8)
  (set-terminal-coding-system 'utf-8)
  (set-keyboard-coding-system 'utf-8)
  (set-language-environment 'utf-8)
#+END_SRC

GNU Emacs modes typically provide a standard means to change the indentation width (e.g. c-basic-offset), and that will inevitably conflict with the "tabs vs spaces" question and the myriad of code conventions for each programming language. We will deal with all this [[sec:tabsvsspaces][later]]. For this reason we will disable this right now:

#+BEGIN_SRC elisp
(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)
#+END_SRC

As for word wrapping and filling we will take a conservative default, and later we will discard it for some modes. For example, it makes sense to perform auto-fill in =text-mode= (which includes =org-mode=), but there is no point of doing it in source code.

#+BEGIN_SRC elisp
;; Maximum 80 columns (except in text-mode, which includes org mode)
(setq-default fill-column 80)
(setq-default auto-fill-function 'do-auto-fill)

;; Do not break lines
(set-default 'truncate-lines t)
#+END_SRC

It's pretty bananas that I have to say it, but if I've pressed a key when selecting text, I want that text to be nuked and replaced with whatever I've typed. This will be overriden anyways with =evil-mode=, but let's do this now just in case =evil-mode= is disabled or something.

#+BEGIN_SRC elisp
;; Delete the selection with a keypress.
(delete-selection-mode t)
#+END_SRC

There are uncivilized barbarians that do not delete trailing whitespaces. This is not my case.

#+BEGIN_SRC elisp
(add-hook 'before-save-hook #'delete-trailing-whitespace)
#+END_SRC

And finally, let's make the cursor a little more relevant. For starters, the default of the cursor blinking is plain idiotic. Secondly, I don't want special highlighting for the current line. And finally, I'd like matching parenthesis to say something whenever the cursor is on top of one of them.

#+BEGIN_SRC elisp
(blink-cursor-mode 0)
(global-hl-line-mode -1)
(show-paren-mode 1)
#+END_SRC

** Font and theme

I'm using "Droid Sans Mono" simply because I've grown used to it.

#+BEGIN_SRC elisp
(defconst mssola-font
  (if IS-MAC "Droid Sans Mono-12" "Droid Sans Mono Dotted for Powerline-10")
  "The font to be used.")

(add-to-list 'default-frame-alist `(font . ,mssola-font))

;; Emacs in daemon mode does not like `set-face-attribute` because this is only
;; applied if there is a frame in place, which doesn't happen when starting the
;; daemon. Thus, we should call that after the frame has been created (e.g. by
;; emacsclient).  See:
;; https://lists.gnu.org/archive/html/help-gnu-emacs/2015-03/msg00016.html
(add-hook 'after-make-frame-functions-hook
          (lambda ()
            (set-face-attribute 'default t :font mssola-font)))
#+END_SRC

I've hacked my own theme called [[https://github.com/mssola/soria][soria]]. This theme combines the vim theme [[http://www.vim.org/scripts/script.php?script_id=2140][xoria256]] with the [[http://opensuse.github.io/branding-guidelines/][openSUSE branding guidelines]]. This theme lives directly inside of my =~/.emacs.d= directory because I link it from the local copy I have of its git repository.

#+BEGIN_SRC elisp
(load-theme 'soria t)
#+END_SRC

Moreover, let's also enable =highlight-numbers-mode=, so all numbers (regardless of the format) are properly highlighted:

#+BEGIN_SRC elisp
(use-package highlight-numbers
  :ensure t
  :config
  (add-hook 'prog-mode-hook 'highlight-numbers-mode))
#+END_SRC

When hacking your own theme, sometimes you want to know what face is the one that you see on the screen right now. This function from [[https://github.com/thblt/DotFiles][@thblt]] allows me to get exactly that and it's bound to @@html:<kbd>C-c f</kbd>@@:

#+BEGIN_SRC elisp
(defun mssola-face-at-point (pos)
  "Writes a message with the name of the face at the current point.  The POS
  argument contains the current position of the cursor."

  (interactive "d")

  (let ((face (or (get-char-property (point) 'read-face-name)
                  (get-char-property (point) 'face))))
    (if face (message "Face: %s" face) (message "No face at %d" pos))))

(global-set-key (kbd "C-c f") 'mssola-face-at-point)
#+END_SRC

** General global key bindings

Now, this section is full of general miscellaneous stuff. First of all, use =kill-this-buffer= instead of =kill-buffer=, which is utterly pointless when interacting with GNU Emacs as a user. Moreover, I'm using the similar @@html:<kbd>C-x K</kbd>@@ as a binding for killing the current buffer and window.

#+BEGIN_SRC elisp
(global-set-key (kbd "C-x k") 'kill-this-buffer)
(global-set-key (kbd "C-x K") 'kill-buffer-and-window)
#+END_SRC

Window navigation and management is done through =evil-mode=, which basically sets up everything as in the Vim world. That being said, there are a couple of functions that fall out of =evil='s scope which I previously setup with =evil-leader=: creating a window on the right, and creating a window on the right and directly moving to it. This can be done with GNU Emacs' default bindings, but they are not really intuitive, and Vim's default behavior is also not satisfactory. The solution adopted is to trash =vc-mode= and remove its @@html:<kbd>C-x v</kbd>@@ binding, since I never use this mode (which is pointless with =magit= enabled), and it follows the same key chord as I used in my =evil-leader= times. Thus, we have @@html:<kbd>C-x v</kbd>@@ for creating a window on the right, and @@html:<kbd>C-x V</kbd>@@ for creating a window on the right and moving to it.

#+BEGIN_SRC elisp
(global-set-key (kbd "C-x v") 'split-window-right)
(global-set-key (kbd "C-x V") (lambda () (interactive) (split-window-right) (other-window 1)))
#+END_SRC

Disable @@html:<kbd>C-z</kbd>@@, which will be later on be picked up by =evil-mode= configuration as the escape sequence. This is here to make sure that it will be disabled even if =evil-mode= is not on.

#+BEGIN_SRC elisp
  (global-unset-key (kbd "C-z"))
#+END_SRC

Also disable the @@html:<kbd>C-x i</kbd>@@ binding, since I've never used the default behavior, and it will be used as a prefix for inferior modes (e.g. =ielm=).

#+BEGIN_SRC elisp
  (global-unset-key (kbd "C-x i"))
#+END_SRC

Disable all the Fn keys.

#+BEGIN_SRC elisp
  (dotimes (i 12) (global-unset-key (kbd (format "<f%d>" (+ i 1)))))
#+END_SRC

Disable overwrite-mode.

#+BEGIN_SRC elisp
  (define-key global-map [(insert)] nil)
#+END_SRC

Kill GNU Emacs by hitting @@html:<kbd>C-x r q</kbd>@@ (mnemonic /Really quit/).

#+BEGIN_SRC elisp
  (global-set-key (kbd "C-x r q") 'kill-emacs)
#+END_SRC

** Others

Revert buffers automatically when underlying files are changed externally.

#+BEGIN_SRC elisp
  (global-auto-revert-mode t)
#+END_SRC

Follow symlinks.

#+BEGIN_SRC elisp
  (setq vc-follow-symlinks t)
#+END_SRC

Remove the initial message from the scratch buffer.

#+BEGIN_SRC elisp
  (setq initial-scratch-message nil)
#+END_SRC

No backups: they are more of a nuisance that an actual help...

#+BEGIN_SRC elisp
  (setq-default make-backup-files nil)
  (setq-default auto-save-default nil)
#+END_SRC

... but at least save the list of recently opened files (list available by pressing @@html:<kbd>C-x C-r</kbd>@@).

#+BEGIN_SRC elisp
(require 'recentf)

(recentf-mode 1)
(global-set-key "\C-x\ \C-r" 'recentf-open-files)

;; Save the list every 5 minutes
(run-at-time nil (* 5 60) 'recentf-save-list)
#+END_SRC

No welcome screen:

#+BEGIN_SRC elisp
  (setq-default inhibit-startup-message t)
#+END_SRC

Enable y/n answer:

#+BEGIN_SRC elisp
  (fset 'yes-or-no-p 'y-or-n-p)
#+END_SRC

Save custom-variables somewhere else:

#+BEGIN_SRC elisp
  (setq custom-file (expand-file-name "custom.el" user-emacs-directory))
  (if (file-exists-p custom-file)
      (load custom-file))
#+END_SRC

There is somewhere someone who likes to be interrupted with stupid beep sounds. That sorry soul is not me.

#+BEGIN_SRC elisp
(setq ring-bell-function 'ignore)
#+END_SRC

* Calendar

This section used to be more lively because of =evil-mode=, but since I also included =evil-collection= this was largely simplified. Thus, the calendar configuration is only about the week start day and its global key binding @@html:<kbd>M-c</kbd>@@.

#+BEGIN_SRC elisp
(defvar calendar-week-start-day 1)
(global-set-key (kbd "M-c") 'calendar)
#+END_SRC

* General purpose defuns

In this section I stow general purpose functions. Right now there is only one of such kind, =emacs-init-time=, which is useful when debugging the initialization process:

#+BEGIN_SRC elisp
(defun emacs-init-time ()
  "Redefine the `emacs-init-time' function so it is more detailed.
Idea taken from @purcell."

  (interactive)

  (let ((init-time
         (float-time (time-subtract after-init-time before-init-time))))
    (message "%.3fs" init-time)))
#+END_SRC

* Projects

In my case GNU Emacs works in projects (with some exceptions). Working in projects means that I should be able to access them with a simple key binding regardless on how and from where I've started GNU Emacs. This is accomplished mainly with =projectile=. My configuration for it is not too fancy:

#+BEGIN_SRC elisp
(use-package projectile
  :ensure t
  :config
  (setq projectile-dynamic-mode-line nil)
  (projectile-mode 1))
#+END_SRC

Other than that, the silver searcher is quite convenient as well. Ayo silver!

#+BEGIN_SRC elisp
(use-package ag
  :ensure t
  :config
  (setq ag-reuse-buffers t
        ag-reuse-window t))
#+END_SRC

* Completion

Now, completion is pretty important for lazy bastards like me. It comes in two flavors: =helm= and =company=.

** Helm

Helm is a big beast, and it will help me go through stuff like projects, IRC channels, files, commands, etc.

#+BEGIN_SRC elisp
(use-package helm
  :ensure t
  :config
  (setq projectile-completion-system 'helm)

  ;; Allow the search pattern to be on the header. Taken from this Reddit thread:
  ;; https://www.reddit.com/r/emacs/comments/3asbyn/new_and_very_useful_helm_feature_enter_search/
  (setq helm-echo-input-in-header-line t)

  (defun helm-hide-minibuffer-maybe ()
    "Hide the minibuffer if we are in a Helm session"

    (when (with-helm-buffer helm-echo-input-in-header-line)
      (let ((ov (make-overlay (point-min) (point-max) nil nil t)))
        (overlay-put ov 'window (selected-window))
        (overlay-put ov 'face (let ((bg-color (face-background 'default nil)))
                                `(:background ,bg-color :foreground ,bg-color)))
        (setq-local cursor-type nil))))

  (add-hook 'helm-minibuffer-set-up-hook 'helm-hide-minibuffer-maybe)
  (setq helm-split-window-inside-p t)

  ;; Preview files with tab
  (define-key helm-map (kbd "<tab>") 'helm-execute-persistent-action)

  ;; Show available options
  (define-key helm-map (kbd "C-a")  'helm-select-action)

  ;; Some vim-like bindings
  (define-key helm-map (kbd "C-j") 'helm-next-line)
  (define-key helm-map (kbd "C-k") 'helm-previous-line)

  ;; Use Helm for the M-x combo.
  (global-set-key (kbd "M-x") 'helm-M-x))
#+END_SRC

The combination of =helm= and the =ag= package is also pretty useful:

#+BEGIN_SRC elisp
(use-package helm-ag
  :ensure t
  :after helm)
#+END_SRC

Last but not least, the =helm-projectile= is the definitive combo for selecting projects, which will be available with the @@html:<kbd>M-p</kbd>@@ key binding:

#+BEGIN_SRC elisp
(use-package helm-projectile
  :ensure t
  :after helm
  :config
  (helm-projectile-on)

  ;; Define M-p as a way to quickly list all the available projects.
  (with-eval-after-load 'evil
    (define-key evil-normal-state-map (kbd "M-p")
      'helm-projectile-switch-project)))
#+END_SRC

I use @@html:<kbd>C-p</kbd>@@ as the binding for listing relevant files. This binding works either by using =helm-projectile= or the regular =helm-find= function. As a final touch, this binding also works for listing channels in ERC buffers.

#+BEGIN_SRC elisp
(defun mssola-erc-helm-buffer-list ()
  "Returns a list with the ERC buffers."
  (mapcar 'buffer-name (erc-buffer-list)))

(defconst mssola-helm-source-erc-channel-list
      '((name . "ERC Channels")
        (candidates . mssola-erc-helm-buffer-list)
        (action . switch-to-buffer)))

(defun mssola-erc-helm-switch-buffer ()
  "Use helm to select an active ERC buffer."

  (interactive)

  (helm :sources '(mssola-helm-source-erc-channel-list)
        :buffer "*helm-erc-channels*"))

(defun mssola-find-file ()
  "Call the proper Helm function for finding files."

  (interactive)

  (if (string= major-mode "erc-mode")
      (mssola-erc-helm-switch-buffer)
    (condition-case nil
        (helm-projectile-find-file)
      (error
       (helm-find-files nil)))))

(with-eval-after-load 'evil
  (define-key evil-normal-state-map (kbd "C-p") 'mssola-find-file))
#+END_SRC

Similarly, =helm-ag= has two functions for applying =ag= (depending on whether we are in a known project, or we are out in the open). I'm binding to @@html:<kbd>C-c C-s</kbd>@@ a function that calls to the proper function.

#+BEGIN_SRC elisp
(defun mssola-helm-ag ()
  "Call the right ag command for helm-ag."

  (interactive)

  (condition-case nil
      (helm-ag-project-root)
    (error (helm-ag))))

(global-set-key (kbd "C-c C-s") 'mssola-helm-ag)
#+END_SRC

** TODO Company

* Edit
** General

In this section I define some useful packages for editing. First of all, one of the coolest packages out there is =undo-tree=. It allows you to navigate through the undo history in a tree (because GNU Emacs is cool and keeps track of undo actions in a tree structure instead of in a stack). This package is included in recent versions of GNU Emacs.

#+BEGIN_SRC elisp
(with-eval-after-load 'undo-tree
  (global-undo-tree-mode 1)

  (setq undo-tree-visualizer-diff t
        undo-tree-visualizer-timestamps t
        undo-tree-visualizer-relative-timestamps t))
#+END_SRC

A recurring issue in speeches and presentations is that when showing something with your editor, you have to increase/decrease the fonts. I use the =default-text-scale= package for this. The bindings are @@html:<kbd>C-+</kbd>@@ and @@html:<kbd>C--</kbd>@@ which perform the expected thing.

#+BEGIN_SRC elisp
  (use-package default-text-scale
    :ensure t
    :config
    (global-set-key (kbd "C-+") 'default-text-scale-increase)
    (global-set-key (kbd "C--") 'default-text-scale-decrease))
#+END_SRC

Some languages use some delimiters a lot (e.g. lisp languages and parenthesis). For this reason I'm using the =rainbow-delimiters= package, which properly highlights each level in a different way (provided that your theme supports it).

#+BEGIN_SRC elisp
  (use-package rainbow-delimiters
    :ensure t)
#+END_SRC

Enable =electric-pair-mode=, which automatically closes pairs like brackets:

#+BEGIN_SRC elisp
(electric-pair-mode 1)
#+END_SRC

=YASnippet= allows people to define shortcuts for writing some common blocks. Moreover, it comes with a set of builtin snippets already.

#+BEGIN_SRC elisp
(use-package yasnippet
  :ensure t
  :init (yas-global-mode)
  :config
  (yas-global-mode 1))
#+END_SRC


=move-text= is a small package that allows you to move lines with a keybinding. This might be feasible with =evil-mode=, but still this might help when you want to move lines and keep the default registry empty:

#+BEGIN_SRC elisp
(use-package move-text
  :ensure t
  :bind
  (("M-k" . move-text-up)
   ("M-j" . move-text-down)))
#+END_SRC

Enable word wrap and disable =auto-fill-mode= when in =text-mode= (which includes modes such as =org-mode=). Even if simple, this involves doing some heavy lifting in =evil-mode= so commands act accordingly. With the elisp-fu shown below everything should run happily as it should.

#+BEGIN_SRC elisp
(setq-default word-wrap t)
(add-hook 'text-mode-hook (lambda ()
                            (visual-line-mode 1)
                            (auto-fill-mode -1)))

(defun mssola-end-of-line (&rest args)
  "Cycle through visual lines until we reach the real end of line.

This function is meant to be a replacement of the default `end-of-line' function
and the one from Evil mode.  It moves the cursor to the end of the visual line
according to ARGS.  If the cursor is already at the end of the visual line, then
it moves down to the next visual line and then it moves the cursor to the end of
the visual line.  If the cursor is already at the end of the real line, then it
does nothing.  Note that this behavior only applies when in `visual-line' mode.
If this is not the case, then this function is synonimous to `end-of-line'."

  (interactive)

  (let ((orig-point (point))
        (real-eol nil))

    (end-of-visual-line args)

    (when (and line-move-visual
               (= orig-point (point)))
      (save-excursion (progn
                        (let ((line-move-visual nil))
                          (end-of-line))
                        (setq real-eol (= orig-point (point)))))
      (when (not real-eol)
        (end-of-visual-line 2)))))

(with-eval-after-load 'evil
  ;; The advice around `evil-next-line' and `evil-previous-line' has been taken
  ;; from https://stackoverflow.com/a/32660401

  ;; Make evil-next-line (up arrow and k, consider visual-line-mode).
  (defun evil-next-line--check-visual-line-mode (orig-fun &rest args)
    (if line-move-visual
        (apply 'evil-next-visual-line args)
      (apply orig-fun args)))

  (advice-add 'evil-next-line :around 'evil-next-line--check-visual-line-mode)

  ;; Make evil-previous-line (down arrow and j, consider visual-line-mode).
  (defun evil-previous-line--check-visual-line-mode (orig-fun &rest args)
    (if line-move-visual
        (apply 'evil-previous-visual-line args)
      (apply orig-fun args)))

  (advice-add 'evil-previous-line :around 'evil-previous-line--check-visual-line-mode))
#+END_SRC

** Spell checking

Basic =flycheck= configuration:

#+BEGIN_SRC elisp
(use-package let-alist
  :ensure t)

(use-package flycheck
  :ensure t
  :config
  (add-hook 'after-init-hook 'global-flycheck-mode)

  ;; Only show the errors buffer if it isn't there and if I'm saving the
  ;; buffer.
  (setq flycheck-emacs-lisp-load-path 'inherit)
  (setq flycheck-check-syntax-automatically '(mode-enabled save))
  (setq flycheck-display-errors-function
    #'flycheck-display-error-messages-unless-error-list))
#+END_SRC

Enable spell checking generally for any text-related mode:

#+BEGIN_SRC elisp
(dolist (hook '(erc-mode-hook org-mode-hook text-mode-hook))
  (add-hook hook (lambda () (flyspell-mode 1))))
#+END_SRC

Also check the spelling of comments in programming languages:

#+BEGIN_SRC elisp
(dolist (mode '(emacs-lisp-mode-hook
                inferior-lisp-mode-hook
                python-mode-hook
                js-mode-hook
                go-mode-hook
                ruby-mode-hook
                rust-mode-hook
                php-mode-hook
                c-mode-common-hook))
  (add-hook mode
            '(lambda ()
               (flyspell-prog-mode))))
#+END_SRC

Let's use =<f8>= for checking words, and =M-<f8>= for moving into the next highlighted word:

#+BEGIN_SRC elisp
(global-set-key (kbd "<f8>") 'ispell-word)

(defun flyspell-check-next-highlighted-word ()
  "Custom function to spell check next highlighted word"
  (interactive)

  ;; If we are in org mode, unfold everything, since flyspell does not work
  ;; smoothly with folded stuff.
  (when (string= major-mode "org-mode")
    (outline-show-all))

  (flyspell-goto-next-error)
  (ispell-word))

(global-set-key (kbd "M-<f8>") 'flyspell-check-next-highlighted-word)
#+END_SRC

If possible, use [[https://hunspell.github.io/][hunspell]] instead of aspell. This program is used by LibreOffice, Firefox, etc. so it's pretty reliable and it supports rather complex languages such as Hungarian. The language being picked is the one from =LC_ALL= and similar environment variables. You can change that by setting =ispell-local-dictionary= and similar:

#+BEGIN_SRC elisp
(cond
 ((executable-find "hunspell")
  (setq ispell-program-name "hunspell")
  (setq ispell-really-hunspell t))

 ((executable-find "aspell")
  (setq ispell-program-name "aspell")))
#+END_SRC

Moreover, let's use [[https://github.com/languagetool-org/languagetool][languagetool]] for further checks:

#+BEGIN_SRC elisp
(use-package langtool
  :ensure t)

(let ((lt-path "/usr/share/languagetool"))
  (setq langtool-language-tool-jar (concat lt-path "/languagetool-commandline.jar")
        langtool-mother-tongue "ca"))

(when (fboundp 'langtool-check)
  (global-set-key (kbd "<f9>") 'langtool-check-buffer)
  (global-set-key (kbd "M-<f9>") 'langtool-correct-buffer))
#+END_SRC

Let flyspell be performant:

#+BEGIN_SRC elisp
(defvar flyspell-issue-message-flag nil)
#+END_SRC

** Abbreviations

An interesting GNU Emacs feature is the configurability of abbreviations. I only need abbrevs for some modes, and I'd like everything to run silently:

#+BEGIN_SRC elisp
(setq abbrev-file-name "~/.emacs.d/abbrevs.el"
      save-abbrevs 'silent)

(dolist (hook '(erc-mode-hook org-mode-hook text-mode-hook)) (add-hook hook #'abbrev-mode))
#+END_SRC

** Misc

Sometimes you begin typing a prefix, but then you forget the following chord. For this reason =which-key= was created. It will show the available commands for the current chord as a list (and beautified with =helm=).

#+BEGIN_SRC elisp
(use-package which-key
  :ensure t
  :config
  (which-key-mode))
#+END_SRC

For some modes it is important to count the number of words in the text. For this, we have =wc-mode=.

#+BEGIN_SRC elisp
  (use-package wc-mode
    :ensure t)
#+END_SRC

Editing files as root is a bit of a pain because usually the root user doesn't have the same configuration as the current one, and attempting to do so can be messy. So, instead of that, we could advice the =find-file= function so if the file is not writable by the current user, then GNU Emacs will ask for editing this same file as root:

#+BEGIN_SRC elisp
(defadvice find-file (after find-file-sudo activate)
  "Find file as root if necessary."
  (if (and buffer-file-name
           (not (file-writable-p buffer-file-name)))
    (if (yes-or-no-p "Do you want to edit this file as root?")
        (find-alternate-file (concat "/sudo:root@localhost:" buffer-file-name)))))
#+END_SRC

=bool-flip= is a very simple utility that toggles truthy/falsey values.

#+BEGIN_SRC elisp
(use-package bool-flip
  :ensure t
  :config
  (global-set-key (kbd "C-c b") 'bool-flip-do-flip))
#+END_SRC

* Dired

[[https://www.gnu.org/software/emacs/manual/html_node/emacs/Dired.html][Dired]] (Directory Editor) is a pretty interesting mode, since it allows you to treat the file system as something that can be edited as if it was just text. It's pretty powerful but I have to admit that my muscle memory brings me to the terminal every time, so I don't really use it. That being said, whenever I use it I want some tweaks to apply:

#+BEGIN_SRC elisp
(setq dired-dwim-target t
      dired-omit-mode nil
      dired-recursive-copies 'always
      dired-recursive-deletes 'always
      delete-old-versions t)
#+END_SRC

Also enable =dired-x= which brings some cool stuff like =dired-jump=:

#+BEGIN_SRC elisp
(require 'dired-x)
#+END_SRC

And now instruct dired mode how to attach files when using =mu4e=. This is pretty important because it's the only way I've found in which I can attach documents into =mu4e= buffers. This is taken from the [[https://www.djcbsoftware.nl/code/mu/mu4e/Dired.html#Dired][mu4e documentation]] and it's available by typing @@html:<kbd>C-c RET C-a</kbd>@@.

#+BEGIN_SRC elisp
  (require 'gnus-dired)

  ;; Make the `gnus-dired-mail-buffers' function also work on message-mode derived
  ;; modes, such as mu4e-compose-mode.
  (defun gnus-dired-mail-buffers ()
    "Return a list of active message buffers."

    (let (buffers)
      (save-current-buffer
        (dolist (buffer (buffer-list t))
          (set-buffer buffer)
          (when (and (derived-mode-p 'message-mode)
                  (null message-sent-message-via))
            (push (buffer-name buffer) buffers))))
      (nreverse buffers)))

  (setq gnus-dired-mail-mode 'mu4e-user-agent)
  (add-hook 'dired-mode-hook 'turn-on-gnus-dired-mode)
#+END_SRC

* Evil

Forgive me, [[https://stallman.org/saint.html][Father]], for I have sinned. I've been exposed to modal editing through Vim, and that has changed how I view editing for the foreseeable future. Because of this, I use Evil. The following blocks include some heavy-lifting so Evil and GNU Emacs work without hitting each other, and it also includes some Evil extensions.

First of all, let's define some variables that should be applied before we enter into =evil= itself. For example, we are going to get rid of GNU Emacs' @@html:<kbd>C-u</kbd>@@ binding because we are going to count a-la Vim. This means that @@html:<kbd>C-u</kbd>@@ can return to its Vim behavior: scroll up in normal mode, and delete to the indentation level in insert mode.

#+BEGIN_SRC elisp
(defvar evil-want-C-u-scroll t)
(defvar evil-want-C-u-delete t)
#+END_SRC

Second of all, @@html:<kbd>C-w</kbd>@@ will be the prefix for window management in normal mode, but for insert mode in Vim it meant killing a word. Let's keep that:

#+BEGIN_SRC elisp
(defvar evil-want-C-w-delete t)
#+END_SRC

Now that it has been set, we can tell =use-package= to install and configure =evil=. Let's take the following under consideration first:

1. Window navigation is prefixed with @@html:<kbd>C-w</kbd>@@ and then it uses the @@html:<kbd>C-j</kbd>@@, @@html:<kbd>C-k</kbd>@@, @@html:<kbd>C-l</kbd>@@ and @@html:<kbd>C-h</kbd>@@ bindings for moving around, and @@html:<kbd>C-w</kbd>@@ as a way of moving into other windows more generally. These are the defaults in Vim, but I used to override them with alternatives that had some conflicts (e.g. with the help command). All in all, let's stick with Vim's defaults here.
2. @@html:<kbd>C-a</kbd>@@ and @@html:<kbd>C-e</kbd>@@ are blessed as the bindings for moving the cursor to the beginning and to the end of the line respectively. This will be applied everywhere. The simple explanation for this is consistency: we will have the same binding regardless of the mode. Furthermore, these have the advantage of being the default GNU Emacs bindings for this movements, so all the default bindings of GNU Emacs aren't that shitty after all!
3. @@html:<kbd>C-2</kbd>@@ is the equivalent of executing @@html:<kbd>@ q</kbd>@@. This requires a bit of history. In my Vim times I recorded all my macros on the @@html:<kbd>q</kbd>@@ register out of simplicity: I've never had to store multiple macros for a single operation, and simply pressing that key twice got the job done in a really fast way. That being said, that was also done because then I executed the macro with @@html:<kbd>C-q</kbd>@@, but this is a key binding that I cherrish in GNU Emacs. Thus, I've moved this binding a bit up into @@html:<kbd>C-2</kbd>@@, which has the mnemonic of "where the @ symbol is".
4. I shamelessly use @@html:<kbd>C-s</kbd>@@ for saving the current buffer regardless of the current mode. In fact, from insert mode it's a way of saving the current buffer and getting back into normal mode. It's just easier and faster this way, no matter what Vim gurus might tell ya!

Thus, my configuration enforces what has been mentioned above, and it also sets the initial states for some modes:

#+BEGIN_SRC elisp
(use-package evil
  :ensure t
  :init
  ;; Needed by evil-collection
  (setq evil-want-integration t
        evil-want-keybinding nil)
  :config
  ;; Let's bring back some evil-window mappings into good ol' Vim defaults.
  (define-key evil-window-map (kbd "C-h") #'evil-window-left)
  (define-key evil-window-map (kbd "C-j") #'evil-window-down)
  (define-key evil-window-map (kbd "C-k") #'evil-window-up)
  (define-key evil-window-map (kbd "C-l") #'evil-window-right)
  (define-key evil-window-map (kbd "C-w") #'other-window)

  ;; Go back to Emacs' bindings on beginning/end of line.
  (eval-after-load "evil-maps"
    (dolist (map '(evil-motion-state-map
                   evil-insert-state-map
                   evil-emacs-state-map))
      (define-key (eval map) "\C-a" 'crux-move-beginning-of-line)
      (define-key (eval map) "\C-e" #'mssola-end-of-line)))

  ;; I store macros on the <q> register for convenience, so I used to use the
  ;; <C-q> combo to execute this macro in Vim. In Emacs though, this combo is
  ;; reserved to a rather useful function, and I'd like to keep it that way. So,
  ;; now the mapping is set to <C-2> (mnemonic: where the @ symbol is). Moreover,
  ;; it's applied as many times as specified by the numeric prefix argument.
  (define-key evil-normal-state-map (kbd "C-2")
    (lambda (n)
      (interactive "p")
      (evil-execute-macro n "@q")))

  ;; C-s: switch to normal mode and save the buffer. I know :)
  (define-key evil-normal-state-map (kbd "C-s") 'save-buffer)
  (define-key evil-insert-state-map (kbd "C-s")
    (lambda () (interactive) (save-buffer) (evil-force-normal-state)))

  (evil-mode 1)

  ;; Use the proper initial evil state for the following modes.
  (evil-set-initial-state 'help-mode 'normal)
  (evil-set-initial-state 'debugger-mode 'normal)
  (evil-set-initial-state 'describe-mode 'normal)
  (evil-set-initial-state 'Buffer-menu-mode 'normal)
#+END_SRC

If Evil was properly loaded, then make sure that the following Evil-related packages are installed and configured as well.

For example, instead of hacking our own escape sequence, let's use =evil-escape= for that. This has the advantage of maintainability: before I had to make sure that my escape sequence was being applied correctly for all modes and that no mode replaced my sequence afterwards. In particular, we will set @@html:<kbd>C-z</kbd>@@ as an escape key. This is because in Vim there was @@html:<kbd>C-c</kbd>@@ for this as well (which was convenient because you always have the pinky on the @@html:<kbd>Caps Lock</kbd>@@ key anyway, since that is remapped as a @@html:<kbd>Control</kbd>@@ key). That being said, that key binding is super duper important in GNU Emacs, and you really don't want to mess around with it. Now, if you remember correctly, we have disabled this key binding before (because the bound function to it is simply absurd, and more so on =i3= and similar WM), so we can use this binding for this task. Moreover, the @@html:<kbd>C-g</kbd>@@ key binding has also been setup as an escape sequence in modes were it makes sense.

#+BEGIN_SRC elisp
(use-package evil-escape
  :ensure t
  :after evil
  :init
  (setq evil-escape-excluded-states '(normal visual multiedit emacs motion))
  (evil-define-key* '(insert replace visual operator) 'global "\C-g" #'evil-escape)
  :config
  ;; no `evil-escape' in minibuffer
  (add-hook 'evil-escape-inhibit-functions #'minibufferp)

  (evil-escape-mode +1)

  (define-key key-translation-map (kbd "C-z") [escape])
  (define-key evil-operator-state-map (kbd "C-z") 'evil-escape))
#+END_SRC

A handy Vim plugin that has made it into Evil is =evil-surround=, which defines a new text object for surrounding characters (e.g. change a string from having double quotes with single quotes in a single command).

#+BEGIN_SRC elisp
  (use-package evil-surround
    :ensure t
    :config
    (global-evil-surround-mode 1))
#+END_SRC

Next is another Vim plugin that has been ported to Evil: =evil-commentary=. This package defines a new motion for comments, which is bound to @@html:<kbd>gc</kbd>@@. So, for example, @@html:<kbd>gcc</kbd>@@ will comment the current line, regardless of the programming language.

#+BEGIN_SRC elisp
  (use-package evil-commentary
    :ensure t
    :config
    (evil-commentary-mode t))
#+END_SRC

Add Vim-like keybindings to as many modes as possible. Note that this list is not exhaustive, since some of these modes are better off with specific packages (e.g. =evil-magit=), and in some cases my bindings feel more intuitive to me (e.g. =woman=):

#+BEGIN_SRC elisp
(use-package evil-collection
  :ensure t
  :after evil
  :config
  ;; Doing this one by one so it's not too bloated.
  (evil-collection-init 'ag)
  (evil-collection-init 'calendar)
  (evil-collection-init 'dired)
  (evil-collection-init 'help)
  (evil-collection-init 'mu4e))
#+END_SRC

Last but not least, =evil-numbers= brings a couple of bindings available on Vim into Evil: @@html:<kbd>C-c +</kbd>@@ for increasing a number, and @@html:<kbd>C-c -</kbd>@@ for decreasing it.

#+BEGIN_SRC elisp
  (use-package evil-numbers
    :ensure t
    :config
    (define-key evil-normal-state-map (kbd "C-c +") 'evil-numbers/inc-at-pt)
    (define-key evil-normal-state-map (kbd "C-c -") 'evil-numbers/dec-at-pt)))
#+END_SRC

* Git

[[https://magit.vc/][Magit]] is a git porcelain inside GNU Emacs. I've grown really fond of it, since it makes some git operations dead easier and faster to perform (e.g. rebasing). Moreover, some other commands are way prettier and more useful with Magit (e.g. the =log= command, staging, showing diffs, etc). So right now my situation is that I use Magit most of the time, and bare git when I want to do something fishy. Some notes on this setup:

1. I set @@html:<kbd>C-x g</kbd>@@ as a binding for =magit-status= and @@html:<kbd>C-c l</kbd>@@ as a binding for =magit-log-buffer-file=. These are the most useful =magit= entries.
2. I install =evil-magit=, which could've been replaced by =evil-collection= but it really falls short. Thus, I keep this package and insist on my bindings around moving through windows.

#+BEGIN_SRC elisp
(use-package magit
  :ensure t
  :config
  (global-set-key (kbd "C-x g") 'magit-status)
  (global-set-key (kbd "C-c l") 'magit-log-buffer-file)

  (with-eval-after-load 'evil
    (use-package evil-magit
      :ensure t)))

#+END_SRC

=git-timemachine= is a package that goes hand-in-hand with Magit, and it provides a very easy way to go through the history of a file (while providing ways of jumping into Magit). You can enter it with @@html:<kbd>C-x t m</kbd>@@ (hopefully the mnemonic is self-evident).

#+BEGIN_SRC elisp
(use-package git-timemachine
  :ensure t
  :bind (("C-x t m" . git-timemachine-toggle)))
#+END_SRC

* Email

I use [[http://www.djcbsoftware.nl/code/mu/][mu]] and [[http://www.djcbsoftware.nl/code/mu/mu4e.html][mu4e]] to manage my email. =mu= is the indexer itself, and =mu4e= is the interface for GNU Emacs. The configuration for this has been taken mainly from the documentation, plus some cool remarks on Reddit. This configuration makes quite some assumptions. Read the =emacs/README.org= file as provided in my [[https://github.com/mssola/dotfiles][dotfiles]] project to get more details.

I'm using [[https://build.opensuse.org/package/show/server:mail/maildir-utils][this package from OBS]] to install =mu= and =mu4e=, which installs things globally. Moreover, because of this, I expect =mu= to be on its latest and shiniest release always.

=mu= only takes care of the indexing part, but the retrieval of emails is handled via =mbsync= which I take from [[https://build.opensuse.org/package/show/server:mail/isync][obs://server:mail]] and that is configured with [[https://github.com/mssola/dotfiles/blob/master/.mbsyncrc][this file]]. The sending is done through the =smtpmail-send-it= function, which is built in GNU Emacs. This part is not optimal since it blocks the GNU Emacs instance whenever we are sending en email. I plan to look into =msmtp= as soon as possible.

#+BEGIN_SRC elisp
(unless (file-directory-p "/usr/share/emacs/site-lisp/mu4e")
  (message "Skipping mu4e because it's not installed."))

(when (file-directory-p "/usr/share/emacs/site-lisp/mu4e")
  (require 'mu4e)

  (when (version< mu4e-mu-version "1.4.0")
    (warn "You need at least mu 1.4.0 to get things working..."))

  (when (featurep 'mu4e)
#+END_SRC

Set =mu4e= as the default user agent. This will be picked up by =compose-mail=.

#+BEGIN_SRC elisp
(setq mail-user-agent 'mu4e-user-agent)
#+END_SRC

Now we can set some SMTP settings which are independent of each context. That being said, I plan on investigating the usage of tools such as =msmtp=, so maybe these variables will fade away once I move into that kind of setup.

#+BEGIN_SRC elisp
  (setq message-send-mail-function 'smtpmail-send-it
        starttls-use-gnutls t)
#+END_SRC

After that, I am defining some functions that will be used in various parts of the configuration. Some observations:

- =mssola-smtp= is expected to be called only by each context. This will set the different variables properly for each context. This is rather ugly, since you could use the =:var= keyword on each context, but on the other hand this might be removed once we move into =msmtp= or something of that sorts.
- =mu4e-message-maildir-matches= and =suse-refile-folder= are just helper functions for the different contexts.

#+BEGIN_SRC elisp
(defun mssola-smtp (server port)
  "Set SMTP variables depending on the given SERVER and PORT."

  (require 'smtpmail)

  (setq smtpmail-default-smtp-server server
        smtpmail-smtp-server server
        message-send-mail-function 'smtpmail-send-it
        smtpmail-smtp-service port))

;; https://www.reddit.com/r/emacs/comments/47t9ec/share_your_mu4econtext_configs/d0fsih6
(defun mu4e-message-maildir-matches (msg rx)
  "Returns true if the maildir of MSG matches the given regexp RX."

  (when rx
    (if (listp rx)
        ;; if rx is a list, try each one for a match
        (or (mu4e-message-maildir-matches msg (car rx))
            (mu4e-message-maildir-matches msg (cdr rx)))
      ;; not a list, check rx
      (string-match rx (mu4e-message-field msg :maildir)))))

(defun suse-refile-folder (key)
  "Returns the refile folder for the given SUSE account in the KEY arg"

  (if (string= key "susecom")
      (setq archives-dir "/Arxiu/")
    (setq archives-dir "/Archives/"))
  (concat "/" key archives-dir
          (format-time-string "%Y" (current-time))))
#+END_SRC

Depending on the context, it's better a signature or another:

#+BEGIN_SRC elisp
(defun mssola-mu4e-signature (key)
  "Returns a string containing the mail signature for the given KEY."

  (if (string= key "ajuntament")
      (concat
       "Miquel Sabaté Solà,\n"
       "Regidor de Joventut, Participació ciutadana i Transparència\n"
       "\n"
       "Ajuntament de Capellades\n"
       "Carrer de Ramon Godó, 9, 08786 - Capellades\n"
       "Tel. 93 801 10 01 – mòbil 677 12 72 07\n"
       "sabatesm@capellades.cat\n")
    (concat
     "Miquel Sabaté Solà,\n"
     "PGP: 4096R / 1BA5 3C7A C93D CA2A CFDF DA97 96BE 8C6F D89D 6565\n")))
#+END_SRC

Now it's time to define the different contexts that I have. Defining contexts this way is relatively new (since mu 0.9.16). The different contexts are quite self-explanatory (and quite boring to look at).

#+BEGIN_SRC elisp
(setq mu4e-contexts
      `(
        ;; GMail
        ,(make-mu4e-context
          :name "gmail"
          :enter-func (lambda ()
                        (mu4e-message "Switching to gmail.com")
                        (setq mu4e-compose-signature (mssola-mu4e-signature "gmail"))
                        (setq mu4e-sent-messages-behavior 'delete)
                        (mssola-smtp "smtp.gmail.com" 587))
          :match-func (lambda (msg)
                        (when msg
                          (mu4e-message-maildir-matches msg "^/gmail")))
          :vars '(
                  (user-mail-address     . "mikisabate@gmail.com")
                  (mu4e-reply-to-address . "mikisabate@gmail.com")
                  (mu4e-drafts-folder    . "/gmail/Drafts")
                  (mu4e-sent-folder      . "/gmail/Sent")
                  (mu4e-refile-folder    . "/gmail/All")
                  (mu4e-trash-folder     . "/gmail/Trash")))

        ;; City hall
        ,(make-mu4e-context
          :name "ajuntament"
          :enter-func (lambda ()
                        (mu4e-message "Switching to mail.diba.cat")
                        (setq mu4e-compose-signature (mssola-mu4e-signature "ajuntament"))
                        (setq mu4e-sent-messages-behavior 'sent)
                        (mssola-smtp "mail.diba.cat" 587)
                        (setq smtpmail-local-domain "capellades.cat"))
          :match-func (lambda (msg)
                        (when msg
                          (mu4e-message-maildir-matches msg "^/ajuntament")))
          :vars '(
                  (user-mail-address     . "sabatesm@capellades.cat")
                  (mu4e-reply-to-address . "sabatesm@capellades.cat")
                  (mu4e-drafts-folder    . "/ajuntament/Esborranys")
                  (mu4e-sent-folder      . "/ajuntament/Elements enviats")
                  (mu4e-refile-folder    . "/ajuntament/Arxiu")
                  (mu4e-trash-folder     . "/ajuntament/Elements suprimits")))

        ;; suse.com
        ,(make-mu4e-context
          :name "comsuse"
          :enter-func (lambda ()
                        (mu4e-message "Switching to suse.com")
                        (setq mu4e-compose-signature (mssola-mu4e-signature "comsuse"))
                        (setq mu4e-sent-messages-behavior 'sent)
                        (mssola-smtp "smtp.office365.com" 587))
          :match-func (lambda (msg)
                        (when msg
                          (mu4e-message-maildir-matches msg "^/susecom")))
          :vars `(
                  (user-mail-address     . "msabate@suse.com")
                  (mu4e-reply-to-address . "msabate@suse.com")
                  (mu4e-drafts-folder    . "/susecom/Esborranys")
                  (mu4e-sent-folder      . "/susecom/Elements enviats")
                  (mu4e-refile-folder    . ,(suse-refile-folder "susecom"))
                  (mu4e-trash-folder     . "/susecom/Elements suprimits")))

        ;; suse.de
        ,(make-mu4e-context
          :name "desuse"
          :enter-func (lambda ()
                        (mu4e-message "Switching to suse.de")
                        (setq mu4e-compose-signature (mssola-mu4e-signature "desuse"))
                        (setq mu4e-sent-messages-behavior 'sent)
                        (mssola-smtp "imap.suse.de" 587))
          :match-func (lambda (msg)
                        (when msg
                          (mu4e-message-maildir-matches msg "^/susede")))
          :vars `(
                  (user-mail-address     . "msabate@suse.de")
                  (mu4e-reply-to-address . "msabate@suse.de")
                  (mu4e-drafts-folder    . "/susede/Drafts")
                  (mu4e-sent-folder      . "/susede/Sent")
                  (mu4e-refile-folder    . ,(suse-refile-folder "susede"))
                  (mu4e-trash-folder     . "/susede/Trash")))))
#+END_SRC

If mu4e cannot figure things out, ask me:

#+BEGIN_SRC elisp
  (setq mu4e-context-policy 'ask)
  (setq mu4e-compose-context-policy 'ask)
#+END_SRC

You can setup bookmarks, which are a way to perform a search with a single key chord. I define pretty standard ones:

#+BEGIN_SRC elisp
(setq mu4e-bookmarks
      '(("maildir:/gmail/inbox OR maildir:/susecom/inbox OR maildir:/susede/inbox OR maildir:/ajuntament/inbox" "Inbox Folders" ?n)
        ("maildir:/gmail/Sent OR maildir:/susecom/Elements\\ enviats OR maildir:/susede/Sent OR maildir:/ajuntament/Elements\\ enviats" "Sent Folders" ?s)
        ("flag:unread AND NOT flag:trashed" "Unread messages" ?u)
        ("date:today..now" "Today's messages" ?t)))
#+END_SRC

Sign outgoing emails always. This used to be pretty straight forward, but since GNU Emacs 27.x we have to set some variables to make the sender happier.

#+BEGIN_SRC elisp
;; For some reason, as of GNU Emacs 27.x, I need to define the default openpgp
;; signer so it can automatically pick my only key I have for signing.
(when EMACS-27-OR-LATER
  (setq mml-secure-openpgp-signers '("0x96BE8C6FD89D6565")
        mml-secure-openpgp-sign-with-sender t))

(add-hook 'message-send-hook 'mml-secure-message-sign-pgpmime)
#+END_SRC

To avoid UID clashes we have to set this variable. See [[http://pragmaticemacs.com/emacs/fixing-duplicate-uid-errors-when-using-mbsync-and-mu4e/][this]].

#+BEGIN_SRC elisp
  (setq mu4e-change-filenames-when-moving t)
#+END_SRC

Miscellaneous settings, nothing too interesting (e.g. format flowed, fetcher command, attachment directory, etc).

#+BEGIN_SRC elisp
(setq mu4e-html2text-command "w3m -T text/html"
      mu4e-attachment-dir  "~/Downloads"
      mu4e-headers-date-format "%Y-%m-%d %H:%M"
      message-citation-line-format "%N @ %Y-%m-%d %H:%M %Z:\n"
      message-citation-line-function 'message-insert-formatted-citation-line
      message-kill-buffer-on-exit t
      mu4e-get-mail-command "mbsync -aqV"
      mu4e-update-interval 600
      mu4e-compose-dont-reply-to-self t
      mu4e-compose-format-flowed t
      mu4e-view-show-addresses t
      mu4e-headers-skip-duplicates t
      mu4e-headers-include-related t
      mu4e-headers-auto-update t)
#+END_SRC

The headers to show in the headers list a pair of a field and its width, with `nil' meaning 'unlimited' (better only use that for the last field). These are the defaults:

#+BEGIN_SRC elisp
  (setq mu4e-headers-fields
        '( (:date          .  18)
           (:mailing-list  .  15)
           (:from-or-to    .  20)
           (:subject       .  nil)))
#+END_SRC

Add as a header action to toggle gnus mode for the view mode. I'm doing this because this is way better to visualize attached .eml emails.

#+BEGIN_SRC elisp
(defun mssola-toggle-gnus-mode (_msg)
  "Toggle gnus on view mode from now on."
  (if mu4e-view-use-gnus
      (setq mu4e-view-use-gnus nil)
    (setq mu4e-view-use-gnus t)))

(add-to-list 'mu4e-headers-actions
   '("gnus mode toggle" . mssola-toggle-gnus-mode) t)
#+END_SRC

Show images:

#+BEGIN_SRC elisp
  (setq mu4e-view-show-images t
        mu4e-view-image-max-width 800)

  ;; Use imagemagick, if available
  (when (fboundp 'imagemagick-register-types)
    (imagemagick-register-types))
#+END_SRC

Correct some key bindings that are screwed up by =evil-mode=:

#+BEGIN_SRC elisp
(evil-define-key 'normal mu4e-view-mode-map
  ";" 'mu4e-context-switch
  "e" 'mu4e-view-save-attachment
  "F" 'mu4e-compose-forward)
#+END_SRC

As of 0.9.18 and GNU Emacs 25, the =mu4e-action-with-xwidget= can be used to render an HTML message with Webkit.

#+BEGIN_SRC elisp
(when EMACS-25-OR-LATER
  (add-to-list 'mu4e-view-actions '("webkit" . mu4e-action-view-with-xwidget)))
#+END_SRC

Look for =mu4e-msg2pdf= in the exec path. The reason for this is that the OBS package installs mu's =toys= into the exec path, but =mu4e= doesn't really count on it.

#+BEGIN_SRC elisp
  (let ((exec (locate-file "msg2pdf" exec-path exec-suffixes)))
    (if exec
        (setq mu4e-msg2pdf exec)))
#+END_SRC

Adding hooks for composing and viewing messages. These include stuff like enabling =visual-line-mode=, enabling =epa-mail-mode= so it's easier to encrypt/decrypt emails, determining which evil state to enter in, etc.

#+BEGIN_SRC elisp
  (defun mssola-compose-mode ()
    "My settings for message composition."

    ;; If we are composing an email from scratch, it's more convenient to be in
    ;; insert mode. Otherwise start with normal mode.
    (with-eval-after-load 'evil
      (if mu4e-compose-parent-message
          (evil-set-initial-state 'mu4e-compose-mode 'normal)
        (evil-set-initial-state 'mu4e-compose-mode 'insert)))

    ;; Guess hard newlines
    (use-hard-newlines t 'guess)

    ;; So it's easy to encrypt/decrypt emails.
    (epa-mail-mode))

  (add-hook 'mu4e-compose-mode-hook 'mssola-compose-mode)

  ;; I want to read messages in the format that the sender used. I'm also
  ;; enabling epa-mail-mode, so it's easy to decrypt received emails.
  (add-hook 'mu4e-view-mode-hook
            (lambda ()
              (epa-mail-mode)
              (visual-line-mode 1)))
#+END_SRC

=mu4e-alert= is needed by =doom-modeline= in order to inform incoming emails into the modeline. So let's install it now:

#+BEGIN_SRC elisp
(use-package mu4e-alert
  :ensure t
  :config
  (add-hook 'after-init-hook #'mu4e-alert-enable-mode-line-display)
  (setq mu4e-alert-interesting-mail-query
        (concat
         "(maildir:/gmail/inbox OR maildir:/susecom/inbox OR maildir:/susede/inbox OR maildir:/ajuntament/inbox) "
         "AND flag:unread AND NOT flag:trashed"))
  (setq mu4e-alert-email-notification-types '(count)))
#+END_SRC

And finally we define @@html:<kbd>C-c m</kbd>@@ as the entrypoint to =mu4e=:

#+BEGIN_SRC elisp
;; The trailing parenthesis closes the "(when (featurep 'mu4e)" statement from
;; the very beginning ;-)
(global-set-key (kbd "C-c m") 'mu4e)))
#+END_SRC

* org

[[https://orgmode.org/][org-mode]] is one of the most well-known "killing features" of GNU Emacs, but I have to admit that I don't use it to its full potential. Instead, I've organized myself in my own dirty way: with org files, but out from the whole agenda/capture workflow. That's why you will see that my current configuration is more about general settings on how to write individual org files, and how to export them.

** General settings

Let's set some basic org variables. That is, where my org files reside, how tabs should act and no indentation (I don't use those fancy bullets that some people install either, I find them tedious and a waste of blank space). On another note, I have my org directory shared with my [[https://nextcloud.com/][Nextcloud]] instance, so all my org files are available everywhere.

#+BEGIN_SRC elisp
(setq org-src-tab-acts-natively t
      org-confirm-babel-evaluate nil
      org-agenda-files '("~/org/")
      org-edit-src-content-indentation 0)

(setq org-todo-keywords
      '((sequence "TODO(t)"  "|"  "DONE(d!)")
        (sequence "IDEA(i)"  "WORKING(w)"  "|"  "USED(u@/!)"  "DISCARDED(x@/!)")))

(setq org-todo-keyword-faces
      '(("TODO"      . org-todo)
        ("IDEA"      . font-lock-constant-face)
        ("WORKING"   . font-lock-constant-face)
        ("DONE"      . org-done)
        ("USED"      . org-done)
        ("DISCARDED" . org-done)))
#+END_SRC

I believe I don't use =org-log=, but when I tried it I liked the following settings:

#+BEGIN_SRC elisp
(setq org-log-done t
      org-log-redeadline (quote time)
      org-log-reschedule (quote time))
#+END_SRC

** Publishing

Publishing is for me one of the most important features of =org-mode= and I abuse it a *lot*. For instance, my =init.org= file needs to be exported into HTML if I want it [[http://jo.mssola.com/static/init.html][online]]. That is done in combination with =htmlize=, which allows org to export to HTML in a better way (e.g. allowing code blocks to be converted into HTML as well, so we can properly colorize it).

#+BEGIN_SRC elisp
(use-package htmlize
  :ensure t
  :after org)
#+END_SRC

With that already established, we can tweak some relevant variables so HTML is exported properly with all the full potential of =htmlize=:

#+BEGIN_SRC elisp
(setq org-src-fontify-natively t
      org-html-include-timestamps nil
      org-html-toplevel-hlevel 2
      org-html-htmlize-output-type 'css
      org-export-with-section-numbers nil
      org-export-with-sub-superscripts nil
      org-export-htmlize-output-type 'css)
#+END_SRC

Another important format to export to is ODT. In order to do so, I instruct =org-mode= to follow the given template:

#+BEGIN_SRC elisp
(setq org-odt-styles-file "~/Documents/Templates/mssola.ott")
#+END_SRC

And finally, another crucial format is PDF, which uses LaTeX underneath. Therefore, it's a good idea to sort out LaTeX in order to get PDFs right:

#+BEGIN_SRC elisp
(require 'ox-latex)

(unless (boundp 'org-latex-classes)
  (setq org-latex-classes nil))

(add-to-list 'org-latex-classes
             '("article"
               "\\documentclass{article}"
               ("\\section{%s}" . "\\section*{%s}")
               ("\\subsection{%s}" . "\\subsection*{%s}")
               ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
               ("\\paragraph{%s}" . "\\paragraph*{%s}")
               ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
#+END_SRC

After all that, we can have other esoteric exporters, like the one that exports into man pages which is funny enough:

#+BEGIN_SRC elisp
(require 'ox-man)
#+END_SRC

Not using the following function that much, but I've had a couple of instances where I wanted to toggle =org-publish-current-file= on save:

#+BEGIN_SRC elisp
(defun toggle-org-publish-current-file-on-save ()
  (interactive)
  (if (memq 'org-publish-current-file after-save-hook)
      (progn
        (remove-hook 'after-save-hook 'org-publish-current-file t)
        (message "Disabled org-publish-current-file for current buffer..."))
    (add-hook 'after-save-hook 'org-publish-current-file nil t)
    (message "Enabled org-publish-current-file for current buffer...")))
#+END_SRC

Last but not least, hide the "Footnotes: " title on footnotes:

#+BEGIN_SRC elisp
(setq org-html-footnotes-section "<div id=\"footnotes\">
<!-- Hack: %s -->
<div id=\"text-footnotes\">
%s
</div>
</div>")
#+END_SRC

** Profiles

I organize myself in what I call "profiles". That is a really bare-bones and hacky way to mock =org-agenda=, but I found it quite useful. As you will see, I have an org file that takes into account the whole week, and another that organizes the year itself. The week file is called a "minimal" profile, and the other is the "monthly" one. Then, you can pick your own profile or choose the default one. The default one is taken with the @@html:<kbd>C-c C-o</kbd>@@ binding, and you can choose with the @@html:<kbd>C-c M-o</kbd>@@ binding. It's nothing too fancy, but I like it.

#+BEGIN_SRC elisp
;; Variables

(defvar mssola-org-profiles
  '(("minimal" . mssola-org-minimal)
    ("monthly" . mssola-org-monthly))
  "Defined profiles for organization matters.")

(defvar mssola-org-default-profile "minimal"
  "The default profile for mssola-org.")

;; Profiles

(defun mssola-org-minimal ()
  "Load a minimal set of files."
  (find-file (concat (file-name-as-directory org-directory) "setmana.org")))

(defun mssola-org-monthly ()
  "Load a set of files useful for monthly planning."
  (find-file (concat (file-name-as-directory org-directory) "setmana.org"))
  (split-window-right)
  (windmove-right)
  (find-file (concat (file-name-as-directory org-directory) "any.org"))
  (windmove-left))

;; Functions

(defun mssola-org (&optional profile)
  "Setup a frame for organizational matters.
PROFILE is the profile to be picked when given.  If it's not given, then the
user will be prompted to provide it."
  (interactive)

  (delete-other-windows)
  (unless profile
    (setq profile (completing-read "Give me the profile: "
                                   (mapcar 'car mssola-org-profiles) nil t)))
  (funcall (cdr (assoc profile mssola-org-profiles))))

(defun mssola-org-default ()
  "Setup a frame for organizational matters given a default profile has been set."
  (interactive)

  (mssola-org mssola-org-default-profile))

(define-key global-map (kbd "C-c C-o") #'mssola-org-default)
(define-key global-map (kbd "C-c M-o") #'mssola-org)
#+END_SRC

** Other

As you will notice, this document is full of <kbd> HTML tags, which if you look into the raw document you will see that it's a tag which is pretty cumbersome to insert. I'm not mad, I have the following function to do the heavy lifting (which has been taken by this [[http://emacs.stackexchange.com/questions/2206/i-want-to-have-the-kbd-tags-for-my-blog-written-in-org-mode][StackExchange answer]]). This is available in =org-mode= with the key binding @@html:<kbd>C-c k</kbd>@@.

#+BEGIN_SRC elisp
(defun endless/insert-key (key)
  "Ask for a key then insert its description.
Will work on both org-mode and any mode that accepts plain html."
  (interactive "kType key sequence: ")
  (let* ((is-org-mode (derived-mode-p 'org-mode))
         (tag (if is-org-mode
                  "@@html:<kbd>%s</kbd>@@"
                "<kbd>%s</kbd>")))
    (if (null (equal key "\r"))
        (insert
         (format tag (help-key-description key nil)))
      (insert (format tag ""))
      (forward-char (if is-org-mode -8 -6)))))

(define-key org-mode-map "\C-ck" #'endless/insert-key)
#+END_SRC

** TODO shortcut for making an org link, and transforming a link into a proper org link
** TODO make it work with evil
** TODO Proper keybindings for quick access.

* writer-mode

There is this handy minor mode I've built which is [[https://github.com/mssola/writer-mode][writer-mode]]. This is under development, so I load it from my own local development path:

#+BEGIN_SRC elisp
(let ((writer-source (concat (getenv "HOME") "/src/github.com/mssola/writer-mode")))
  (when (file-directory-p writer-source)
    ;; Call `make build', which will, in turn, byte-compile all the relevant files.
    (let ((default-directory writer-source))
      (shell-command "make build"))

    ;; Then load the byte-compiled files.
    (let ((list (directory-files writer-source t ".elc$"))
          (load-prefer-newer t))
      (while list
        (load-file (car list))
        (setq list (cdr list))))

    ;; Declare that =writer-mode= has been loaded.
    (setq writer-mode-loaded t)))
#+END_SRC

After that, I can configure it further. For example, I want @@html:<kbd>f1</kbd>@@ and @@html:<kbd>f2</kbd>@@ to export my current project into PDF and ODT respectively:

#+BEGIN_SRC elisp
(when (boundp 'writer-mode-loaded)
  (define-key org-mode-map (kbd "<f1>") 'writer-org-export-to-pdf)
  (define-key org-mode-map (kbd "<f2>") 'writer-org-export-to-odt))
#+END_SRC

* IRC

I'm using [[https://www.gnu.org/software/emacs/manual/html_mono/erc.html][ERC]] for IRC, even though it's been quite a lot since we have used IRC at work (now we are using other chat alternatives). Anyhow, it's good to still have it here.

#+BEGIN_SRC elisp
(use-package erc
  :config
#+END_SRC

First of all, let's add some basic modules:

#+BEGIN_SRC elisp
  (dolist (mod '(autojoin track truncate))
    (add-to-list 'erc-modules mod))
#+END_SRC

Now we can set all your typical =erc= variables. There is nothing too interesting here.

#+BEGIN_SRC elisp
(setq erc-hide-list '("PART")
      erc-prompt (lambda () (concat (buffer-name) ">"))
      erc-track-exclude-types '("JOIN" "NICK" "PART" "QUIT" "MODE")
      erc-server-coding-system '(utf-8 . utf-8)
      erc-kill-buffer-on-part t
      erc-kill-queries-on-quit t
      erc-kill-server-buffer-on-quit t
      erc-fill-column 100
      erc-fill-prefix ""
      erc-timestamp-format "[%H:%M] "
      erc-insert-timestamp-function 'erc-insert-timestamp-left
      erc-insert-away-timestamp-function 'erc-insert-timestamp-left
      erc-hide-timestamps nil
      erc-whowas-on-nosuchnick t
      erc-public-away-p nil
      erc-echo-notice-always-hook '(erc-echo-notice-in-minibuffer)
      erc-auto-set-away nil
      erc-autoaway-message "%i seconds out..."
      erc-away-nickname "msabate"
      erc-enable-logging t
      erc-query-on-unjoined-chan-privmsg t
      erc-prompt-for-password nil)
#+END_SRC

Let's log messages whenever I receive/send them. The other option is to only do that on =/quit= or =/part=, but it's better to be safe than sorry.

#+BEGIN_SRC elisp
  (require 'erc-log)
  (erc-log-enable)

  (setq erc-log-channels-directory "~/.emacs.d/erc"
        erc-save-buffer-on-part nil
        erc-save-queries-on-quit nil
        erc-log-write-after-send t
        erc-log-write-after-insert t)
#+END_SRC

Servers and channels to auto-join:

#+BEGIN_SRC elisp
  (setq erc-autojoin-channels-alist
        '(("irc.freenode.net" "#gnu" "#emacs")
          ("irc.nue.suse.com" "#suse" "#docker")))
#+END_SRC

Use the =erc-hl-nicks= package, so highlight support for nicknames is better.

#+BEGIN_SRC elisp
(use-package erc-hl-nicks
  :ensure t
  :init
  (with-eval-after-load 'erc
    (add-to-list 'erc-modules 'hl-nicks)))
#+END_SRC

I want to have a desktop notification whenever someone mentions my name. For this, I'm using the =erc-notifications= package which is built in =erc= since GNU Emacs 24.3.

#+BEGIN_SRC elisp
(with-eval-after-load 'erc
  (setq erc-notifications-icon
        (concat
         "/usr/share/emacs/"
         (format "%s.%s" emacs-major-version emacs-minor-version)
         "/etc/images/icons/hicolor/24x24/apps/emacs.png"))
  (add-to-list 'erc-modules 'notifications))
#+END_SRC

At this point, we can safely update all the loaded ERC modules.

#+BEGIN_SRC elisp
  (add-hook 'erc-connect-pre-hook
            (lambda (_x) (erc-update-modules)))
#+END_SRC

Start some modules which won't do it by default. Moreover, according to the [[https://www.emacswiki.org/emacs/ErcFilling][wiki]] =auto-fill-mode= should be disabled if I'm using =erc-fill-mode=.

#+BEGIN_SRC elisp
  (add-hook 'erc-mode-hook
            '(lambda ()
               (erc-track-mode t)
               (auto-fill-mode -1)
               (erc-log-mode 1)
               (erc-autojoin-mode 1)))
#+END_SRC

And now define a function to connect to both IRC servers, which is bound to @@html:<kbd>C-c i</kbd>@@.

#+BEGIN_SRC elisp
  (defun mssola-erc ()
    "Join pre-specified servers and channels."

    (interactive)

    (erc :server "irc.freenode.net" :port 6667 :nick "mssola")
    (erc-tls :server "irc.nue.suse.com" :port 6697 :nick "mssola"))

  (global-set-key (kbd "C-c i") 'mssola-erc))
#+END_SRC

* Languages
** General

First of all, define a function that identifies some warning keywords (e.g. TODO). This function can then be applied to the proper mode.

#+BEGIN_SRC elisp
  (defun warnings-mode-hook ()
    "Hook for enabling the warning face on strings with a warning prefix."

    (font-lock-add-keywords nil
      '(("\\(XXX\\|FIXME\\|TODO\\|HACK\\|NOTE\\|BUG\\)"
      1 font-lock-warning-face prepend))))
#+END_SRC

Text mode is not a programming language, but it's used quite often in this context too. In this case, I want =wc-mode= activated.

#+BEGIN_SRC elisp
  (add-hook 'text-mode-hook (lambda () (wc-mode 1)))
#+END_SRC

** Tabs vs spaces
<<sec:tabsvsspaces>>

Tabs or spaces? [[https://www.emacswiki.org/emacs/TabsSpacesBoth][Both]]. The =smart-tabs-mode= has the philosophy of: tabs for indentation, spaces for alignment. This is only applied in languages where I'm usings tabs for indentation (C, C++ and Go).

#+BEGIN_SRC elisp
  (use-package smart-tabs-mode
    :ensure t
    :config
    (smart-tabs-add-language-support golang go-mode-hook
      ((c-indent-line . c-basic-offset)
       (c-indent-region . c-basic-offset)))
    (smart-tabs-insinuate 'c 'c++ 'golang))
#+END_SRC

** Shell

GNU Emacs already comes with =shell-mode= out of the box, and it's quite fine. That being said, I'd also like to add =bats-mode=:

#+BEGIN_SRC elisp
(use-package bats-mode
  :ensure t)
#+END_SRC

** Lisp

Emacs lisp needs =rainbow-delimiters= so the amount of parenthesis is less confusing. Moreover, I'm also enabling =eldoc-mode= and the aforementioned =warnings-mode-hook=.

#+BEGIN_SRC elisp
  (add-hook 'emacs-lisp-mode-hook
            (lambda ()
              (eldoc-mode 1)
              (warnings-mode-hook)
              (rainbow-delimiters-mode 1)
              ; https://github.com/jhenahan/emacs.d/blob/master/emacs-init.org#emacs-lisp
              (setq mode-name "ξ")))
#+END_SRC

Configure =ielm= with the proper ELisp utilities. As mentioned earlier, all these inferior modes are prefixed with @@html:<kbd>C-x i</kbd>@@ (mnemonic: "inferior"). =ielm= in particular is bound to @@html:<kbd>C-x i e</kbd>@@ and @@html:<kbd>C-x i l</kbd>@@, which follow the mnemonics "Emacs Lisp" and "Lisp" (I use both interchangeably, that's why I bind =ielm= twice).

#+BEGIN_SRC elisp
(use-package ielm
  :config
  (add-hook 'ielm-mode-hook #'eldoc-mode)
  (add-hook 'ielm-mode-hook #'rainbow-delimiters-mode)
  (global-set-key (kbd "C-x i e") 'ielm)
  (global-set-key (kbd "C-x i l") 'ielm))
#+END_SRC

Add =rainbow-delimiters= and =warnings-mode-hook= also for =lisp-mode= (that is, for Common Lisp and other variants, not Emacs Lisp):

#+BEGIN_SRC elisp
(add-hook 'lisp-mode-hook
          (lambda ()
            (warnings-mode-hook)
            (rainbow-delimiters-mode 1)
            (setq mode-name "λ")))
#+END_SRC

** C and C++

I have plans of bringing the extremely aptly named [[https://github.com/Sarcasm/irony-mode][irony-mode]] into my setup, but I haven't had the time for it yet. This mode implements a Clang backend through LSP in which you can power up GNU Emacs into being a fully featured C/C++ IDE. But as I said, I haven't looked into it yet, so for now let's just require the =warnings-mode-hook= function and the usage of tabs instead of spaces.

#+BEGIN_SRC elisp
;; Note that C-common includes languages with a similar syntax of C.
(add-hook 'c-mode-common-hook 'warnings-mode-hook)

;; C
(add-hook 'c-mode-hook
  (lambda () (setq indent-tabs-mode t)))

;; C++
(add-hook 'c++-mode-hook
  (lambda () (setq indent-tabs-mode t)))
#+END_SRC

The =clang-format+= package supersedes the =clang-format.el= file from the Clasp authors and it adds all the nuts and bolts to have =clang-format= work for the whole file automatically:

#+BEGIN_SRC elisp
(use-package clang-format+
  :ensure t
  :config
  (add-hook 'c-mode-common-hook #'clang-format+-mode))
#+END_SRC

CMake for y'all.

#+BEGIN_SRC elisp
  (use-package cmake-mode
    :ensure t
    :config

    (setq auto-mode-alist
          (append
           '(("CMakeLists\\.txt\\'" . cmake-mode))
           '(("\\.cmake\\'" . cmake-mode))
           auto-mode-alist))

    (use-package cmake-font-lock
      :ensure t
      :config

      (add-hook 'cmake-mode-hook 'cmake-font-lock-activate)
      (add-hook 'yaml-mode-hook 'warnings-mode-hook)))
#+END_SRC

** Ruby

Even if Ruby is one of my favorite languages and I use it very often, I don't do much about it in my configuration. I just include warning keywords and disallow the automatic including of the encoding magic comment:

#+BEGIN_SRC elisp
(use-package ruby-mode
  :config
  (setq ruby-insert-encoding-magic-comment nil)
  (add-hook 'ruby-mode-hook #'subword-mode)
  (add-hook 'ruby-mode-hook 'warnings-mode-hook))
#+END_SRC

That being said, give me the inferior mode for it (which following the aforementioned logic for inferior modes, it's bound to @@html:<kbd>C-x i r</kbd>@@):

#+BEGIN_SRC elisp
(use-package inf-ruby
  :ensure t
  :config
  (add-hook 'ruby-mode-hook #'inf-ruby-minor-mode)
  (global-set-key (kbd "C-x i r") 'inf-ruby))
#+END_SRC

** Go

My =golang= setup isn't that complicated either. As always, I include the =warnings-mode= hook. Other than that I've put some glue into the various golang tools available out there. This includes stuff like the usage of =goimports=, =gofmt= on save, among many other useful things.

#+BEGIN_SRC elisp
  (defun mssola-go-mode ()
    "My configuration for Go mode."

    ; Use goimports instead of go-fmt
    (setq gofmt-command "goimports")

    ; Call Gofmt before saving
    (add-hook 'before-save-hook 'gofmt-before-save)

    ; Integration flycheck with Go
    (add-to-list 'load-path
      (concat (getenv "GOPATH") "/src/github.com/dougm/goflymake"))
    (require 'go-flycheck)

    (setq indent-tabs-mode t)

    ; eldoc support
    (use-package go-eldoc
      :ensure t
      :config
      (require 'go-eldoc)))

  ;; Go
  (use-package go-mode
    :ensure t
    :config

    (add-hook 'go-mode-hook 'warnings-mode-hook)
    (add-hook 'go-mode-hook 'go-eldoc-setup)
    (add-hook 'go-mode-hook 'mssola-go-mode))
#+END_SRC

** Python

Install =elpy= as the environment for Python support:

#+BEGIN_SRC elisp
(use-package elpy
  :ensure t
  :config
  (advice-add 'python-mode :before 'elpy-enable)
  (when (require 'flycheck nil t)
    (setq elpy-modules (delq 'elpy-module-flymake elpy-modules))
    (add-hook 'elpy-mode-hook 'flycheck-mode)))
#+END_SRC

Automatically use =autopep8= on save:

#+BEGIN_SRC elisp
(use-package py-autopep8
  :ensure t
  :config
  (add-hook 'elpy-mode-hook 'py-autopep8-enable-on-save))
#+END_SRC

** Rust

Install =rust-mode= and add some hooks to make it friendlier.

#+BEGIN_SRC elisp
(use-package rust-mode
  :ensure t
  :config

  (add-hook 'before-save-hook
            #'(lambda ()
                (when (eq major-mode 'rust-mode)
                  (rust-format-buffer))))

  (use-package flycheck-rust
    :ensure t
    :config

    (add-hook 'flycheck-mode-hook #'flycheck-rust-setup)))
#+END_SRC

** Other markup languages.

In here I put some markup languages which are not org. That is, markdown and YAML. I don't do anything crazy with YAML, but for Markdown I have =markdown-preview-mode=, which allows me to preview a markdown document into HTML live (in combination with =markdown-calibre=, which is the tool available for openSUSE).

#+BEGIN_SRC elisp
  ;; Markdown mode with preview mode in the browser.
  (use-package markdown-mode
    :ensure t
    :config

    ;; This is the one that I got from openSUSE.
    (custom-set-variables
      '(markdown-command "/usr/bin/markdown-calibre"))

    ;; Preview mode does its things through websockets, so it's a requirement.
    ;; After that, we can safely require it.
    (use-package websocket
      :ensure t
      :config
      (use-package markdown-preview-mode
        :ensure t)))

  ;; YAML
  (use-package yaml-mode
    :ensure t
    :config

    (add-hook 'yaml-mode-hook 'warnings-mode-hook))
#+END_SRC

** Web-related stuff.

Slim, SCSS and such shenanigans...

#+BEGIN_SRC elisp
(use-package slim-mode
  :ensure t)

(use-package scss-mode
  :ensure t
  :config

  (setq scss-compile-at-save nil)
  (add-hook 'scss-mode-hook 'warnings-mode-hook))

(use-package coffee-mode
  :ensure t)
#+END_SRC

Languages specific for backend code like PHP, and =web-mode=, which provides a bundle of features which are interesting for web-related stuff.

#+BEGIN_SRC elisp
(use-package php-mode
  :ensure t)

(use-package web-mode
  :ensure t
  :config

  (add-to-list 'auto-mode-alist '("\\.erb\\'" . web-mode))
  (add-to-list 'auto-mode-alist '("\\.jinja\\'" . web-mode))
  (add-to-list 'auto-mode-alist '("\\.html?\\'" . web-mode))

  (setq web-mode-markup-indent-offset 2
        web-mode-css-indent-offset 2
        web-mode-code-indent-offset 2)

  (use-package vue-mode
    :ensure t
    :config
    (setq mmm-submode-decoration-level 0)))
#+END_SRC

The =json-reformat= package provides functions for reformatting JSON strings. It happens from time to time that I have to read JSON output from responses, and it can be frustrating without proper formatting.

#+BEGIN_SRC elisp
(use-package json-reformat
  :ensure t)
#+END_SRC

** Devops

The new cool kids in the block (oh well, not so new anymore!). Here we have support for Dockerfiles, Hashicorp tooling, and Saltstack.

#+BEGIN_SRC elisp
(use-package dockerfile-mode
  :ensure t
  :config

  (add-to-list 'auto-mode-alist '("Dockerfile" . dockerfile-mode)))

(use-package terraform-mode
  :ensure t
  :config

  (terraform-format-on-save-mode))

(use-package hcl-mode
  :ensure t)

(use-package salt-mode
  :ensure t)
#+END_SRC

** Others

The [[https://github.com/mssola/soria][soria]] theme has the =soria-theme-purple-identifiers= hook. This hook instructs the theme to use purple for identifiers instead of the default color. This is a remnant from my Vim times, and I only apply it to some languages (random criteria really).

#+BEGIN_SRC elisp
  (dolist (lang-hook '(ruby-mode-hook
                       php-mode-hook
                       perl-mode-hook
                       emacs-lisp-mode-hook))
    (add-hook lang-hook 'soria-theme-purple-identifiers))
#+END_SRC

** LaTeX

Let's use [[https://www.gnu.org/software/auctex/][Auctex]] for LaTeX files. There are people doing crazy stuff with it. I keep it really simple because I don't have to face so many LaTeX files nowadays.

#+BEGIN_SRC elisp
(use-package tex
  :ensure auctex
  :config
  (setq TeX-auto-save t)
  (setq TeX-parse-self t)
  (setq-default TeX-master nil))
#+END_SRC

* WoMan

=WoMan= is a package that is included inside of GNU Emacs by default and that takes care of visualizing man pages. I don't do much here, I just tell =WoMan= to fill all the frame, and setup @@html:<kbd>C-h C-m</kbd>@@ as the key binding for it:

#+BEGIN_SRC elisp
(setq woman-fill-frame t)
(define-key 'help-command (kbd "C-m") #'woman)
#+END_SRC

* Misc

Install a set of useful functions from [[https://github.com/bbatsov][@bbatsov]]. The bindings are following Emacs style instead of being more Vim-like on purpose. For now we have the following bindings:

| Binding                         | Description                                                                                                                    |
|---------------------------------+--------------------------------------------------------------------------------------------------------------------------------|
| @@html:<kbd>C-c d</kbd>@@       | Delete the current file and its buffer. Note that this might not work well inside of a git project with staged stuff.          |
| @@html:<kbd>C-c r</kbd>@@       | Rename the current file and its buffer. In order to take this into effect you will have to change the file and save it though. |
| @@html:<kbd>C-c n</kbd>@@       | Cleanup the whole buffer or just a selected region.                                                                            |
| @@html:<kbd>C-backspace</kbd>@@ | Kill a given line backwards. That is, this is the reverse of Vim's @@html:<kbd>D</kbd>@@ in normal mode.                       |
| @@html:<kbd>C-a</kbd>@@         | The beginning of line has been remapped into crux's one, which takes indentation into account.                                 |
| @@html:<kbd>C-c o</kbd>@@       | Open the given resource as it would with plain =xdg-open=.                                                                     |

#+BEGIN_SRC elisp
(use-package crux
  :ensure t
  :config

  (global-set-key (kbd "C-c d") 'crux-delete-file-and-buffer)
  (global-set-key (kbd "C-c r") 'crux-rename-file-and-buffer)
  (global-set-key (kbd "C-c n") 'crux-cleanup-buffer-or-region)
  (global-set-key (kbd "C-<backspace>") 'crux-kill-line-backwards)
  (global-set-key [remap move-beginning-of-line] 'crux-move-beginning-of-line)
  (global-set-key (kbd "C-c o") 'crux-open-with))
#+END_SRC

** Screencast

Some utilities when recording my GNU Emacs adventures. First of all, =keycast= shows the keys being pressed in the mode line (it requires GNU Emacs 25.1 minimum). Moreover, we have =gif-screencast=, which allows you to record your GNU Emacs activity and saves it into a gif (unless you have specified the =XDG_VIDEOS_DIR=, it will use =~/Videos/emacs/<name>.gif=). =gif-keycast= requires GNU Emacs 26.1 or above:

#+BEGIN_SRC elisp
(if EMACS-25-OR-LATER
  (use-package keycast
    :ensure t))

(if EMACS-26-OR-LATER
  (use-package gif-screencast
    :ensure t
    :config
    (with-eval-after-load 'gif-screencast
      (define-key gif-screencast-mode-map (kbd "<f8>") 'gif-screencast-toggle-pause)
      (define-key gif-screencast-mode-map (kbd "<f9>") 'gif-screencast-stop))

    (global-set-key (kbd "<f7>") 'mssola-screencast)))
#+END_SRC

Last but not least, I use a wrapper to start a screencast, which is bound to @@html:<kbd>f7</kbd>@@. In order to pause the screencast you can press @@html:<kbd>f8</kbd>@@, and to completely stop it you can use @@html:<kbd>f9</kbd>@@:

#+BEGIN_SRC elisp
(defun mssola-screencast ()
  "Start keycast-mode and then start a gif screencast."

  (interactive)

  (if EMACS-26-OR-LATER
      (progn
        (keycast-mode)
        (gif-screencast))
    (error "Requires 26.1 or later.")))
#+END_SRC

** Emojis

Display emojis in buffer!

#+BEGIN_SRC elisp
(use-package emojify
  :ensure t
  :config

  (add-hook 'after-init-hook #'global-emojify-mode)
  (setq emojify-composed-text-p nil)
  (setq emojify-emoji-styles '(unicode github)))
#+END_SRC

* Installation

The installation process of my GNU Emacs configuration should already be handled by the =install.sh= script that can be found in the root of this project. If you want to do it manually:

- Create the =~/.emacs.d= directory if it has not been created yet.
- Copy the =init.el= into the =~/.emacs.d= directory. This is the only file that should be copied instead of linked because it will get replaced on the first run by =org-babel=.
- Link the =init.org=, =custom.el=, =abbrevs.el= and =gtkrc= files into the =~/.emacs.d= directory.
- Create the =~/.emacs.d/lisp= subdirectory and link the =lisp/g.el= file there.
- Clone the [[https://github.com/mssola/soria][soria]] project and link the =soria-theme.el= file into the =~/.emacs.d= directory.

Other than that, in the =dependencies.sh= script you will be able to find the **runtime dependencies** that should be installed in order to get everything working. Note that this script assumes that you are running openSUSE, so don't run it blindly. All the software installed by this script has already been explained during this configuration.

* Credits

I've built this file by simply scavenging from other people's emacs.d/dotfiles repositories. I have taken lots of pieces from here and there, but most notably:

- [[https://github.com/ereslibre/dotfiles][@ereslibre]]
- [[https://github.com/dmacvicar/dotfiles][@dmacvicar]]
- [[https://github.com/bbatsov/emacs.d][@bbatsov]]
- [[https://github.com/aaronbieber/dotfiles][@aaronbieber]]
- [[https://github.com/purcell/emacs.d][@purcell]]
- [[https://github.com/sachac/.emacs.d][@sachac]] ([[http://pages.sachachua.com/.emacs.d/Sacha.html][HTML version]])
- [[https://github.com/larstvei/dot-emacs][@larstvei]]
- [[https://github.com/hlissner/doom-emacs][doom-emacs]]
- [[https://gitlab.com/protesilaos/dotfiles][@protesilaos]]

* License

#+BEGIN_SRC text :tangle no
  Copyright (C) 2014-2020 Miquel Sabaté Solà <mikisabate@gmail.com>

  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/>.
#+END_SRC