-
Notifications
You must be signed in to change notification settings - Fork 2
/
init.el
2898 lines (2375 loc) · 111 KB
/
init.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; init.el --- Initialization file. -*- lexical-binding: t; -*-
;; Copyright (C) 2019-2024 Serghei Iakovlev <[email protected]>
;; Author: Serghei Iakovlev <[email protected]>
;; URL: https://github.com/sergeyklay/.emacs.d
;; Keywords: configuration, misc
;; This file is NOT part of Emacs.
;;;; License
;; This file 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 file 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 file. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Welcome to my GNU Emacs haven. This configuration is a reflection of my
;; desire for a "minimalist" yet powerful editing environment.
;;
;; I started this project on 4 March 2019 from this commit:
;; eb11ce25b0866508e023db4b8be6cca536cd3044
;;; Code:
;;;; Profiling and Debug for Emacs
(defconst emacs-debug-mode (or (getenv "DEBUG") init-file-debug)
"If non-nil, Emacs will be verbose.
Set DEBUG=1 in the command line or use --debug-init to enable this.")
;; Set the `debug-on-error' variable as per the runtime context:
;; - Enable debugging on error if Emacs is running in interactive mode, and the
;; custom variable `emacs-debug-mode' is true.
;; - Do not enable debugging on error in non-interactive mode, regardless of the
;; `emacs-debug-mode' value.
(setq-default debug-on-error (and (not noninteractive) emacs-debug-mode))
;; Measure the current start up time.
(add-hook
'emacs-startup-hook
(lambda ()
(message "Emacs ready in %s with %d garbage collections."
(format "%.2f seconds"
(float-time
(time-subtract after-init-time before-init-time)))
gcs-done)))
;;;; Personal Info
;; Used for `gnus', `erc', and so non.
(setopt user-full-name "Serghei Iakovlev")
;;;; Packages management
;; Package management in Emacs can be done in several ways. I personally like
;; classic one with `package.el'. Some will prefer straight.el, use-package,
;; and so on, but I haven't found the need for them.
(require 'package)
;; Setting up package archives.
(add-to-list 'package-archives '( "melpa" . "https://melpa.org/packages/") t)
;; Priorities. Default priority is 0.
(setq package-archive-priorities
'(("gnu" . 100)
("nongnu" . 50)
("melpa" . 10)))
;; Precompute activation actions to speed up startup.
(setq package-quickstart t)
;; Enable native compilation of packages upon their first load,
;; leveraging Emacs's native compilation feature for performance.
(setq package-native-compile t)
(package-initialize)
(defun ensure-package-installed (package)
"Ensure that PACKAGE is installed."
(unless (package-installed-p package)
(condition-case _err
(package-install package)
(error
(package-refresh-contents)
(package-install package))))
(package-installed-p package))
;; package.el updates the saved version of `package-selected-packages' correctly
;; only after `custom-file' has been loaded, which is a bug. We work around
;; this by adding the required packages to `package-selected-packages' after
;; startup is complete. This code borrowed from Steve Purcell configuration.
(defvar my-required-packages nil
"List of packages that were successfully installed.")
(defun my-note-selected-package (oldfun package &rest args)
"If OLDFUN reports PACKAGE was successfully installed, note that fact.
The package name is noted by adding it to
`my-required-packages'. This function is used as an
advice for `require-package', to which ARGS are passed."
(let ((available (apply oldfun package args)))
(prog1
available
(when available
(add-to-list 'my-required-packages package)))))
(advice-add 'ensure-package-installed :around 'my-note-selected-package)
(defconst my-selected-packages
'(anzu ; Show current match and total matches information
avy ; Jump to things in Emacs tree-style
benchmark-init ; Benchmarks for require and load calls
cask-mode ; Major mode for editing Cask files
company ; Code completion framework
consult ; Incremental narrowing framework
consult-flyspell ; Flyspell integration with `consult'
csv-mode ; CSV file editing mode
embark ; Contextual actions in buffers
embark-consult ; Embark integration with `consult'
envrc ; Environment variable manager for shell
erc-hl-nicks ; Nick highlighting in `erc' (IRC client)
flyspell-correct ; Correct spelling with popup menus
git-modes ; Modes for Git-related files
htmlize ; Convert buffer text to HTML
json-mode ; Major mode for editing JSON files
lsp-mode ; Language Server Protocol support
lsp-pyright ; LSP client leveraging pyright Python Language Server
lsp-ui ; UI enhancements for `lsp-mode'
magit ; The Git porcelain inside Emacs
marginalia ; Annotations for minibufer completions
markdown-mode ; Major mode for Markdown files
orderless ; Flexible completion style for minibufers
org-cliplink ; Capture clipboard URLs to `org-mode'
ox-hugo ; Blogging using `org-mode'
pass ; Interface to the Password Store
password-store ; Emacs interface for password-store
prescient ; Predictive sorting and filtering
rainbow-delimiters ; Color nested parentheses
rainbow-mode ; Colorize color values in buffers
sql-indent ; Indentation support for SQL
vertico ; Vertical interactive completion for minibuffers
vertico-prescient ; Prescient integration with `vertico'
which-key ; Display available keybindings
writegood-mode ; Improve writing style
yaml-mode ; Major mode for YAML files
yasnippet ; A template system for Emacs
web-mode) ; Web template editing mode for Emacs
"A list of packages that are selected for installation.")
;; Install packages as soon as possible.
(dolist (package my-selected-packages)
(ensure-package-installed package))
;;;; Benchmark
(require 'benchmark-init)
(add-hook 'after-init-hook #'benchmark-init/deactivate)
;;;; Setup keymap
;; Create and setup my own keyboard map.
;; For details see:
;; https://www.masteringemacs.org/article/mastering-key-bindings-emacs
(defvar my-keyboard-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd ";") #'comment-or-uncomment-region)
(define-key map (kbd "-") #'text-scale-decrease)
(define-key map (kbd "+") #'text-scale-increase)
;; because "+" needs "S-=" and I might forget to press shift
(define-key map (kbd "=") #'text-scale-increase)
map)
"My own keyboard map.")
;; As stated in the manual:
;;
;; A small number of keys are reserved for user-defined bindings, and should not
;; be used by modes, so key bindings using those keys are safer in this regard.
;; The reserved key sequences are those consisting of C-c followed by a letter
;; (either upper or lower case), and function keys F5 through F9 without
;; modifiers
(keymap-global-set "C-c s" my-keyboard-map)
;; Load `which-key' and enable `which-key-mode'.
(add-hook 'after-init-hook #'which-key-mode)
;; Increase the delay for which-key buffer to popup.
(setq-default which-key-idle-delay 1.5)
;;;; System Path
(cond
((eq system-type 'windows-nt)
(let ((chocolatey-bin "C:/ProgramData/chocolatey/bin"))
;; Only add the directory to `exec-path' if it exists
;; and is not already present
(when (and (file-directory-p chocolatey-bin)
(not (member chocolatey-bin exec-path)))
(add-to-list 'exec-path chocolatey-bin)))))
;;;; Common functions
(defun my-ensure-directory-exists (dir)
"Ensure that the directory DIR exists, create it if it doesn't."
(unless (file-exists-p dir)
(make-directory dir t)))
(defun my/switch-to-scratch ()
"Get a scratch buffer."
(interactive)
(let* ((name "*scratch*")
(buf (get-buffer name)))
(pop-to-buffer
(if (bufferp buf)
buf ; Existing scratch buffer
;; New scratch buffer
(with-current-buffer (get-buffer-create name)
(current-buffer))))))
(define-key my-keyboard-map (kbd "s") #'my/switch-to-scratch)
(defun my/insert-current-date-iso-8601 ()
"Insert the current date and time in ISO 8601 format (YYYY-MM-DDTHH:MM:SSZ)."
(interactive)
(insert (format-time-string "%Y-%m-%dT%H:%M:%SZ" (current-time) t)))
(define-key my-keyboard-map (kbd "D") #'my/insert-current-date-iso-8601)
(defun my/reload-current-mode ()
"Reload the current major mode.
This function temporarily switches the current buffer's major
mode to `fundamental-mode' and then back to the original major
mode. This is useful when you've re-evaluated a major mode's
definition (e.g., using `eval-buffer' on the mode's source file)
and want to apply the changes to the current buffer.
After modifying and evaluating your mode's source code, call this
function to refresh the mode in the mode related buffer and see
the changes take effect."
(interactive)
(let ((current-mode major-mode)
(load-prefer-newer t))
(fundamental-mode)
(when (locate-library (concat (symbol-name current-mode) ".el"))
(unload-feature current-mode)
(load (concat (symbol-name current-mode) ".el")))
(funcall current-mode)))
(global-set-key (kbd "C-<f5>") #'my/reload-current-mode)
;;;; Backup
;; Silently deletes excess backup versions.
(setq delete-old-versions t)
;; Make numeric backup versions unconditionally.
(setq version-control t)
;; Make backup files even in version controlled directories.
(setq vc-make-backup-files t)
;; Keep all backups in one directory.
(let ((my-backup-dir (expand-file-name "backup" user-emacs-directory)))
(setopt backup-directory-alist
`(("." . ,(file-name-as-directory my-backup-dir))))
(my-ensure-directory-exists my-backup-dir))
;;;; Auto-Saving
(let ((save-dir (expand-file-name "auto-save-list" user-emacs-directory)))
(setopt auto-save-file-name-transforms
`((".*" ,(concat (file-name-as-directory save-dir) "\\2") t)))
(setopt auto-save-list-file-name
(expand-file-name (format ".saves-%d-%s~" (emacs-pid) (system-name))
save-dir))
(my-ensure-directory-exists save-dir))
;;;; History
;; Set the maximum number of entries to save in the history. A larger value
;; allows for a more extensive history, which can be handy if you often need
;; to recall older entries.
(setopt history-length 1000)
;; Enable the removal of duplicate entries in the history.
(setopt history-delete-duplicates t)
;; Enable `save-place-mode' to save point position in files across sessions. It
;; ensures that you return to the exact spot where you left off, enhancing
;; workflow efficiency. Only enable in interactive mode.
(when (not noninteractive)
(add-hook 'after-init-hook #'save-place-mode))
;; Enable `savehist-mode', which automatically saves the minibuffer history
;; to a file and loads it on startup, preserving your history between sessions.
;; Only enable in interactive mode.
(when (not noninteractive)
(add-hook 'after-init-hook #'savehist-mode))
;; Enable `recentf-mode' to keep track of recently opened files.
;; Only enable in interactive mode.
(when (not noninteractive)
(add-hook 'after-init-hook #'recentf-mode))
(with-eval-after-load 'recentf
;; Set the maximum number of recent files to save.
(setopt recentf-max-saved-items 1000)
;; Update `recentf-exclude' to exclude specific paths and files
;; I din't need in the list.
(setopt recentf-exclude
`(,(temporary-file-directory)
,(concat (file-name-as-directory package-user-dir)
".*-autoloads\\.el\\'")))
;; Set up an idle timer to save the recent list every 3 minutes
(run-with-idle-timer (* 3 60) t #'recentf-save-list))
;;;; Sane defaults
;; Disable the startup screen, allowing for a quicker start directly into
;; your working environment.
(setq-default inhibit-startup-screen t)
;; Disable the creation of lockfiles on Windows, as they can cause issues
;; with file systems on that platform.
(setq-default create-lockfiles (not (member system-type '(windows-nt))))
;; Visually indicate empty lines after the buffer's end.
(setq-default indicate-empty-lines t)
;; Customize the format of the mode line to show line and column numbers
;; in the format "278:59".
(setq-default mode-line-position
'((line-number-mode ("%l" (column-number-mode ":%c")))))
;; Enable column number mode to display column numbers in the mode line.
(column-number-mode t)
;; Highlight trailing whitespace in text-mode and prog-mode.
(add-hook 'text-mode-hook (lambda () (setq show-trailing-whitespace t)))
(add-hook 'prog-mode-hook (lambda () (setq show-trailing-whitespace t)))
;; Set `source-directory' to the local Emacs source directory.
;; Used to understand and debug built-in Emacs functions.
(let ((src (if (eq system-type 'windows-nt)
"D:/src/emacs.git"
(expand-file-name "~/src/emacs.git"))))
;; Check if the directory exists and is
;; not remote before setting `source-directory`.
(when (and (file-directory-p src)
(not (file-remote-p src)))
(setopt source-directory src)))
;;;; Search
(defun my-isearch-exit-and-run (function)
"Exit `isearch' and run FUNCTION with the current `isearch' string."
(let ((query (if isearch-regexp
isearch-string
(regexp-quote isearch-string))))
(isearch-update-ring isearch-string isearch-regexp)
(isearch-exit)
(funcall function query)))
(defun my-occur-from-isearch ()
"Invoke `occur' using the current `isearch' string."
(interactive)
(my-isearch-exit-and-run #'occur))
(defun my-project-search-from-isearch ()
"Invoke `project-find-regexp' using the current `isearch' string."
(interactive)
(my-isearch-exit-and-run #'project-find-regexp))
;; Invoke `occur' using the current `isearch' string.
(define-key isearch-mode-map (kbd "C-o") #'my-occur-from-isearch)
;; Invoke `project-find-regexp' using the current `isearch' string.
(define-key isearch-mode-map (kbd "C-f") #'my-project-search-from-isearch)
;; Do incremental search forward for a symbol found near point.
(define-key isearch-mode-map (kbd "C-d") #'isearch-forward-symbol-at-point)
;; Jump to search results instead of having to do multiples C-s.
(define-key isearch-mode-map (kbd "C-j") #'avy-isearch)
;; Interactive replacement:
;; - M-% to call `anzu-isearch-query-replace'
;; - C-M-% to call `anzu-isearch-query-replace-regexp'
(define-key isearch-mode-map [remap isearch-query-replace]
#'anzu-isearch-query-replace)
(define-key isearch-mode-map [remap isearch-query-replace-regexp]
#'anzu-isearch-query-replace-regexp)
(defun my-isearch-start-from-region (orig-fn &rest args)
"Advice to start `isearch' with the active region or symbol at point.
This advice function enhances `isearch' commands by using the
current active region as the initial search string when
available. If the region is active and `transient-mark-mode' is
enabled, the region's content is used. Otherwise, the original
search behavior is preserved.
ORIG-FN is the original isearch function being advised.
ARGS are the arguments passed to the original isearch function."
(let ((search-string
(when (and transient-mark-mode mark-active (not (eq (mark) (point))))
(buffer-substring-no-properties (mark) (point)))))
;; Deactivate mark if a region was used for search initialization.
(when search-string
(isearch-update-ring search-string)
(deactivate-mark))
;; Call the original isearch function.
(apply orig-fn args)
;; Yank the search string if set.
(when search-string
(isearch-yank-string
(if isearch-regexp
search-string
(regexp-quote search-string))))))
;; Add the advice to all relevant isearch functions.
(dolist (fn '(isearch-forward
isearch-forward-regexp
isearch-backward
isearch-backward-regexp))
(advice-add fn :around #'my-isearch-start-from-region))
(defun my-occur-visit-result-and-close ()
"Visit the occurrence at point and close the Occur window."
(interactive)
(let ((pos (occur-mode-find-occurrence)))
(when pos
(quit-window)
(goto-char pos))))
;; Bind M-<return> to visit the occurrence and close the window.
(define-key occur-mode-map (kbd "M-<return>") #'my-occur-visit-result-and-close)
;; Enable `hl-line-mode` in `occur-mode` buffers.
(add-hook 'occur-mode-hook (lambda () (hl-line-mode 1)))
;; Use ripgrep if installed
(when (executable-find "rg")
(setopt xref-search-program 'ripgrep))
(defun my|xref-setup-environment ()
"Set up a tailored environment for `xref--xref-buffer-mode' buffers."
;; Enable `hl-line-mode' in `xref' buffers.
(hl-line-mode 1)
;; Bind M-<return> to visit the occurrence and close the window.
(define-key xref--xref-buffer-mode-map (kbd "M-<return>")
#'xref-quit-and-goto-xref))
(add-hook 'xref--xref-buffer-mode-hook #'my|xref-setup-environment)
;;;; Spell
(require 'ispell)
;; Automatically save the personal dictionary without asking for confirmation.
(setopt ispell-silently-savep t)
(when (eq system-type 'windows-nt)
(let ((dic-dir (or (getenv "DICPATH") "C:/Hunspell"))
(hunspell-bin (executable-find "hunspell")))
(when (and hunspell-bin (file-exists-p dic-dir))
;; Set environment variables for Hunspell
(unless (getenv "LANG") (setenv "LANG" "en_US"))
(unless (getenv "DICPATH") (setenv "DICPATH" dic-dir))
(defun my--build-dict-path (lang ext)
"Build the full path to the dictionary file for LANG and EXT."
(expand-file-name (concat lang ext) (file-name-as-directory dic-dir)))
;; Find all available .aff files in the dictionary directory
(let ((dict-files (directory-files dic-dir t "\\.aff$"))
dict-paths)
(dolist (dict-file dict-files)
;; Extract language code from file name
;; (e.g., "en_US" from "en_US.aff")
(let ((lang (file-name-base dict-file)))
;; Add dictionary to the alist if both .aff and .dic files exist
(when (file-exists-p (my--build-dict-path lang ".dic"))
(push (list lang (my--build-dict-path lang ".aff")) dict-paths))))
;; Set `ispell-hunspell-dict-paths-alist' dynamically
;; if there are valid dictionaries
(when dict-paths
(setq ispell-hunspell-dict-paths-alist dict-paths))
;; Use Hunspell as the spell checker. This should be set after
;; `ispell-hunspell-dict-paths-alist', "LANG" and "DICPATH" environment
;; variables due to `setopt' nature.
(setopt ispell-program-name hunspell-bin)))))
;; Configure the list of my dictionaries.
;; Note: Homebrew on macOS, and Chocolatey on Windows does not provide
;; dictionaries by default. You will need to install them manually.
(let ((valid-dicts (ispell-valid-dictionary-list))
(dicts-alist nil))
;; Add English dictionary
(when (member "en_US" valid-dicts)
;; Define the default dictionary to be used.
(setopt ispell-local-dictionary "en_US")
(push '("english" "[[:alpha:]]" "[^[:alpha:]]" "[']" t
("-d" "en_US") nil utf-8)
dicts-alist))
;; Add Polish dictionary
(let ((pl-dict (cond
((member "pl" valid-dicts) "pl")
((member "pl_PL" valid-dicts) "pl_PL")
(t nil))))
(when pl-dict
(push `("polish" "[[:alpha:]]" "[^[:alpha:]]" "[']" t
("-d" ,pl-dict) nil utf-8)
dicts-alist)))
;; Add Russian dictionary
(let ((ru-dict (cond
((member "ru-yeyo" valid-dicts) "ru-yeyo")
((member "russian-aot-ieyo" valid-dicts) "russian-aot-ieyo")
((member "ru_RU" valid-dicts) "ru_RU")
(t nil))))
(when ru-dict
(push `("russian" "[А-Яа-я]" "[^А-Яа-я]" "[-']" nil
("-d" ,ru-dict) nil utf-8)
dicts-alist)))
(setopt ispell-local-dictionary-alist dicts-alist))
;; Be silent when checking words to avoid unnecessary messages.
(setopt flyspell-issue-message-flag nil)
(with-eval-after-load 'flyspell
;; These keys are intended for `embark'
(dolist (key '("C-;" "C-," "C-."))
(unbind-key key flyspell-mode-map)))
;; Load `writegood-mode' and set up hooks.
(with-eval-after-load 'writegood-mode
(add-hook 'text-mode-hook #'writegood-mode)
(add-hook 'latex-mode-hook #'writegood-mode))
;;;; Security
(defconst my-gpg-program
(cond
((executable-find "gpg") "gpg")
((executable-find "gpg2") "gpg2")
(t nil))
"Path to the GPG program to use.
If neither gpg nor gpg2 is found, this is set to nil.")
;; Check if GPG is available, then set `epg-gpg-program',
;; otherwise display a warning.
(if my-gpg-program
(setq epg-gpg-program my-gpg-program)
(warn (concat "Neither gpg nor gpg2 is available. "
"Encryption and decryption features will not be available.")))
;; Initialize epa settings
(unless (eq (window-system) 'w32)
;; Set pinentry mode to loopback for all systems except Windows.
;; For more see "man 1 gpg" for the option "--pinentry-mode".
(setopt epg-pinentry-mode 'loopback))
;; GnuPG ID of your default identity.
(setq epg-user-id "1E0B5331219BEA88")
;; Specify the key to use for file encryption
;; Also used for `org-crypt-key' (see bellow).
(setq epa-file-encrypt-to `(,epg-user-id))
;; Enable automatic encryption/decryption of *.gpg files
(require 'epa-file)
;; Only enable `epa-file' if it's not already enabled
(unless (memq epa-file-handler file-name-handler-alist)
(epa-file-enable))
;; Setup `pass-view-mode' iff pass executable is available.
(when (executable-find "pass")
(my-ensure-directory-exists (expand-file-name "~/.password-store"))
(require 'pass)
(with-eval-after-load 'pass
;; Associate .gpg files in the pass directory with `pass-view-mode'.
(add-to-list
'auto-mode-alist (cons "~/.password-store/.*\\.gpg\\'" 'pass-view-mode))))
;;;; Calendar
;; Disable not used holidays
(setq-default holiday-hebrew-holidays nil)
(setq-default holiday-islamic-holidays nil)
(setq-default holiday-bahai-holidays nil)
(setq-default holiday-oriental-holidays nil)
(setq-default holiday-solar-holidays nil)
(setq-default holiday-christian-holidays nil)
(defconst my-polish-holidays
'((holiday-fixed 1 1 "Nowy Rok (Poland)")
(holiday-fixed 5 1 "Święto Pracy (Poland)")
(holiday-fixed 5 3 "Święto Konstytucji 3 Maja (Poland)")
(holiday-fixed 8 15 "Wniebowzięcie Najświętszej Maryi Panny (Poland)")
(holiday-fixed 11 1 "Wszystkich Świętych (Poland)")
(holiday-fixed 11 11 "Święto Niepodległości (Poland)")
(holiday-fixed 12 25 "Boże Narodzenie (Poland)")
(holiday-fixed 12 26 "Drugi dzień Bożego Narodzenia (Poland)"))
"Polish public holidays.")
(defvar my-ukrainian-holidays
'((holiday-fixed 1 1 "Новий рік (Ukraine)")
(holiday-fixed 1 7 "Різдво Христове (Ukraine)")
(holiday-fixed 3 8 "Міжнародний жіночий день (Ukraine)")
(holiday-fixed 4 1 "День гумору (Ukraine)")
(holiday-fixed 5 1 "День праці (Ukraine)")
(holiday-fixed 5 9 "День перемоги (Ukraine)")
(holiday-fixed 6 28 "День Конституції України (Ukraine)")
(holiday-fixed 8 24 "День Незалежності України (Ukraine)")
(holiday-fixed 10 1 "День захисників і захисниць України (Ukraine)")
(holiday-fixed 12 25 "Різдво Христове (Ukraine)"))
"Ukrainian public holidays.")
(defvar my-canadian-holidays
'((holiday-fixed 1 1 "New Year's Day (Canada)")
(holiday-fixed 7 1 "Canada Day (Canada)")
(holiday-float 9 1 1 "Labour Day (Canada)")
(holiday-float 10 1 2 "Thanksgiving Day (Canada)")
(holiday-fixed 12 25 "Christmas (Canada)")
(holiday-fixed 12 26 "Boxing Day (Canada)"))
"Canadian public holidays.")
(defvar my-us-holidays
'((holiday-fixed 1 1 "New Year's Day (US)")
(holiday-float 1 1 3 "Martin Luther King Jr. Day (US)")
(holiday-float 2 1 3 "Presidents' Day (US)")
(holiday-fixed 7 4 "Independence Day (US)")
(holiday-float 11 4 4 "Thanksgiving (US)")
(holiday-fixed 12 25 "Christmas (US)"))
"US public holidays.")
;; Define local holidays to be tracked.
(setq holiday-local-holidays
'((holiday-fixed 10 24 "Programmers' Day")
(holiday-fixed 3 8 "Women's Day")
(holiday-fixed 6 1 "Children's Day")
(holiday-fixed 9 10 "Teachers' Day")
(holiday-fixed 3 12 "Arbor Day")))
;; Define other holidays to be tracked.
(setq-default holiday-other-holidays
'((holiday-fixed 4 23 "World Book Day")
(holiday-fixed 2 14 "Valentine's Day")
(holiday-fixed 4 1 "April Fools' Day")
(holiday-fixed 10 31 "Halloween")
(holiday-sexp '(if (or (zerop (% year 400))
(and (% year 100) (zerop (% year 4))))
(list 9 12 year)
(list 9 13 year))
"World Programmers' Day")))
;; Customize `calendar-holidays' to include public holidays from various
;; countries. I work in a multinational company with teams based in different
;; regions, so it's useful to know when my colleagues have days off.
(setq-default calendar-holidays
`(,@my-polish-holidays
,@my-ukrainian-holidays
,@my-canadian-holidays
,@my-us-holidays
,@holiday-local-holidays
,@holiday-other-holidays))
;; Week starts on Monday.
(setq-default calendar-week-start-day 1)
;; I prefer read dates in 'year/month/day' format.
(setq-default calendar-date-style 'iso)
;; Prefer +0800 over CST.
(setq-default calendar-time-zone-style 'numeric)
;; Mark dates of holidays in the calendar window.
(setq-default calendar-mark-holidays-flag t)
;; Mark dates with diary entries, in the calendar window.
(setq-default calendar-mark-diary-entries-flag t)
;; Set the default latitude and longitude for calendar calculations. These
;; values are used to determine local sunrise/sunset times, moon phases, and
;; other location-dependent calendar features in Emacs.
(setq-default calendar-latitude 51.1)
(setq-default calendar-longitude 17.0)
;; Alist of time zones and places for `world-clock' to display for the same
;; reason as for `calendar-holidays' above.
(setq-default world-clock-list '(("Canada/Pacific" "Vancouver")
("America/New_York" "New York")
("Europe/Warsaw" "Warsaw")
("Europe/Kyiv" "Kyiv")))
;;;; Organization
(require 'org)
(with-eval-after-load 'org
;; Ensure the directory for Org files is exist.
(my-ensure-directory-exists org-directory)
;; Although I don't use `diary-file', Org-agenda still checks for its
;; existence even when `org-agenda-include-diary' is set to nil. This happens
;; due to internal checks tied to `org-agenda-diary-file'. Since I handle
;; recurring tasks differently within my Org files and don't need an
;; additional diary, I don't want to set `org-agenda-diary-file' to anything
;; meaningful. As a simple workaround, I just create an empty `diary-file' to
;; bypass these checks and keep Org-agenda running smoothly.
(unless (file-exists-p diary-file)
(make-empty-file diary-file)))
;; Associate .org, .org_archive and .txt files with `org-mode'.
(add-to-list 'auto-mode-alist
'("\\.\\(org\\|org_archive\\|txt\\)\\'" . org-mode))
;; When opening an Org file, start with all top-level headers collapsed.
(setq org-startup-folded t)
;; Automatically log the timestamp when a TODO is marked as DONE.
(setq org-log-done 'time)
;; Store notes and state changes in a drawer instead of cluttering the entry.
(setq org-log-into-drawer t)
;; Hide emphasis markers (e.g., bold, italics) to see styled text only.
(setq org-hide-emphasis-markers t)
;; Set the default width for inline images to 600 pixels.
(setq org-image-actual-width '(600))
;; Enforce TODO dependencies, blocking parent tasks from being marked DONE
;; if child tasks are still not completed.
(setq org-enforce-todo-dependencies t)
;; Modify only the agenda context in `org-fold-show-context-detail' without
;; altering the other default values.
(setq org-fold-show-context-detail
(cons '(agenda . lineage)
(assq-delete-all 'agenda org-fold-show-context-detail)))
;; Allow setting single tags without bringing up the tag selection menu.
(setq org-fast-tag-selection-single-key t)
;; Configure the languages supported in org-babel code blocks.
(org-babel-do-load-languages
'org-babel-load-languages
'((C . t)
(emacs-lisp . t)
(haskell . t)
(js . t)
(latex . t)
(lisp . t)
(makefile . t)
(org . t)
(python . t)
(scheme . t)
(shell . t)
(sql . t)
(calc . t)))
(defun my|org-setup-environment ()
"Set up a tailored environment for editing Org-mode buffers.
This function customizes the appearance and behavior of `org-mode' by
enabling modes and features that enhance the editing experience:
- Enables `visual-line-mode' for soft line wrapping, providing a more
natural reading and writing flow for long lines of text.
- Activates `org-indent-mode' to visually align text according to the
structure of the outline, improving readability.
- Displays inline images directly within the buffer when they are linked
in Org files, providing immediate visual feedback."
(visual-line-mode 1)
(org-indent-mode 1)
(org-display-inline-images 1))
;; Attach the environment setup to Org-mode.
(add-hook 'org-mode-hook #'my|org-setup-environment)
(defun my/switch-to-org ()
"Get a scratch buffer for the `org-mode'."
(interactive)
(let* ((name "*scratch-org*")
(buf (get-buffer name)))
(pop-to-buffer
(if (bufferp buf)
buf ; Existing scratch buffer
;; New scratch buffer
(with-current-buffer (get-buffer-create name)
(org-mode)
(goto-char (point-min))
;; Initial documentation displayed in *scratch-org* buffer.
(insert "# This buffer is for notes and Org ")
(insert "structure editing that are not saved.\n")
(insert "# To create a file, visit it with ")
(insert (format "%s and enter text in its buffer.\n\n"
(substitute-command-keys "\\[find-file]")))
(current-buffer))))))
(define-key my-keyboard-map (kbd "o") #'my/switch-to-org)
;; Standard actions
(global-set-key (kbd "C-c o l") #'org-store-link)
(global-set-key (kbd "C-c o b") #'org-switchb)
;;;;; Helpers
(defun my-org-get-created-date ()
"Retrieve the CREATED property if it exists, otherwise return nil.
This function utilizes Org-mode's built-in date parsing
capabilities by using `org-parse-time-string' to handle various
date formats. If no valid date is found, it returns nil."
(let* ((created (org-entry-get nil "CREATED" t))
(parsed-date (and created (org-parse-time-string created))))
(when (and parsed-date
;; Ensure that year, month, and day are all present
(nth 4 parsed-date)
(nth 5 parsed-date)
(nth 3 parsed-date))
(format "%04d-%02d-%02d"
(nth 5 parsed-date) ; Year
(nth 4 parsed-date) ; Month
(nth 3 parsed-date)))))
(defun my-org-sanitize-heading-for-id (heading)
"Sanitize the HEADING text to create a slug suitable for use as an ID.
Removes progress indicators, priority markers, links, timestamps,
non-alphanumeric characters and replaces spaces with hyphens."
(let ((slug (substring-no-properties heading)))
;; Replacements for common symbols
(setq slug (replace-regexp-in-string "&" "and" slug))
(setq slug (replace-regexp-in-string "\\." "dot" slug))
(setq slug (replace-regexp-in-string "\\+" "plus" slug))
;; Remove progress indicators like "[25%]" or "[2/7]"
(setq slug (replace-regexp-in-string "\\(\\[[0-9]+%\\]\\)" "" slug))
(setq slug (replace-regexp-in-string "\\(\\[[0-9]+/[0-9]+\\]\\)" "" slug))
;; Remove priority indicators like "[#A]"
(setq slug (replace-regexp-in-string "\\(\\[#[ABC]\\]\\)" "" slug))
;; Remove links but keep their descriptions
(setq slug (replace-regexp-in-string "\\[\\[\\(.+?\\)\\]\\[" "" slug t))
;; Remove timestamps (active and inactive)
(setq slug (replace-regexp-in-string
"<[12][0-9]\\{3\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\( .*?\\)?>"
"" slug t))
(setq slug (replace-regexp-in-string
"\\[[12][0-9]\\{3\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\( .*?\\)\\]"
"" slug t))
;; Replace spaces with hyphens and remove non-alphanumeric characters
(setq slug (replace-regexp-in-string "[^[:alnum:][:space:]-]" "" slug))
(setq slug (replace-regexp-in-string " +" "-" slug))
;; Remove trailing hyphens, downcase and trim length to 60 chars
(string-limit (downcase (replace-regexp-in-string "-+$" "" slug)) 60)))
(defun my-org-find-property (property)
"Find the position of the first occurrence of PROPERTY's value.
Return the position of the property's value, or nil if not found.
If narrowing is in effect, only search the visible part of the
buffer."
(save-excursion
(goto-char (point-min))
(let ((case-fold-search t)
(re (org-re-property property nil t nil)))
(catch 'exit
(while (re-search-forward re nil t)
(when (org-entry-get (point) property nil t)
(throw 'exit (match-beginning 3))))))))
(defun my/org-goto-id-property ()
"Move cursor to the start of the ID property value in Org heading."
(interactive)
(let ((drawer-pos nil)
(id-pos nil))
(save-excursion
(org-back-to-heading t)
(let ((case-fold-search t)
(start (point)))
(outline-next-visible-heading 1)
(save-restriction
(narrow-to-region start (point))
(setq id-pos (my-org-find-property "ID"))
(when id-pos
(goto-char id-pos)
(setq drawer-pos
(re-search-backward "^\\s-*:PROPERTIES:" nil t))))))
(when (and id-pos drawer-pos)
(org-show-entry)
(goto-char drawer-pos)
(org-flag-drawer nil)
(goto-char id-pos))))
(define-key my-keyboard-map (kbd "M-i") #'my/org-goto-id-property)
(defun my/org-generate-id ()
"Create a human-readable ID for the current entry and return it.
If the entry already has an ID, just return it. The function
generates a new ID by performing the following steps:
1. Retrieves the heading text of the current Org heading.
2. Sanitizes the heading text to form a slug suitable for an ID.
The sanitization process removes or replaces special
characters to create a clean, URL-friendly string.
3. Prepends the slug with a date prefix. The date is derived
from the CREATED property if it exists; otherwise, today's
date is used in the format YYYY-MM-DD.
4. Sets the generated ID as the ID property of the current
heading.
5. Updates the Org database of ID locations with the new ID and
the file location to ensure the ID can be tracked and
retrieved in the future.
The function returns the generated ID, or if an existing ID is
found, it returns the existing ID."
(interactive)
(unless (derived-mode-p 'org-mode)
(user-error "This function is intended to be used in Org-mode only"))
(org-with-point-at nil ; with nil refer to the entry at point
(let ((id (org-id-get)))
(cond
;; Check if the ID property already exists
((and id (stringp id) (string-match "\\S-" id))
id)
;; If not - retrieve the heading text and create a new ID
(t
(let* ((heading (nth 4 (org-heading-components)))
(clean-heading (my-org-sanitize-heading-for-id heading))
;; Use CREATED property if available, otherwise today's date
(date-prefix (or (my-org-get-created-date)
(format-time-string "%Y-%m-%d")))
(id (concat date-prefix "-" clean-heading)))
;; Set the ID property
(org-set-property "ID" id)
;; Add the ID with location FILE to the database of ID locations.
(org-id-add-location id (or org-id-overriding-file-name
(buffer-file-name (buffer-base-buffer))))
id))))))
(defun my/org-id-advice (&rest args)
"The advice to update Org ID locations.
This function accepts ARGS but does not use them directly.
It generates an Org ID if needed and updates the ID locations."
(my/org-generate-id)
(org-id-update-id-locations)
args)
(advice-add 'org-store-link :before #'my/org-id-advice)
(define-key my-keyboard-map (kbd "I") #'my/org-generate-id)
(defun my/org-mark-as-project ()
"Mark the current Org heading as a project.
This function ensures that the current heading:
1. Has the tag project
2. Has the property COOKIE_DATA set to todo recursive
3. Has a TODO keyword
4. Starts with a progress indicator [/]
This setup helps in organizing projects within Org Mode
and ensures that projects are easily identifiable and managed.
I find this approach particularly appealing, and I first learned
about it from an article by Karl Voit. The original function was
created by Karl, and this version is simply a refined and
optimized adaptation tailored to my specific needs. For origin
see: https://karl-voit.at/2019/11/03/org-projects/"
(interactive)
;; Try to move to a heading if not already there
(unless (org-at-heading-p)
(org-back-to-heading t)
(unless (org-at-heading-p)
(user-error
"No Org heading found. Please place the cursor at or near a heading")))