File: khalel.el

package info (click to toggle)
khalel 0.1.15-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 352 kB
  • sloc: lisp: 573; makefile: 2
file content (704 lines) | stat: -rw-r--r-- 27,599 bytes parent folder | download
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
;;; khalel.el --- Import, edit and create calendar events through khal -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2021 Hanno Perrey
;;
;; Author: Hanno Perrey <http://gitlab.com/hperrey>
;; Maintainer: Hanno Perrey <hanno@hoowl.se>
;; Created: september 10, 2021
;; Modified: june 12, 2025
;; Version: 0.1.15
;; Keywords: event, calendar, ics, khal
;; Homepage: https://gitlab.com/hperrey/khalel
;; Package-Requires: ((emacs "27.1"))
;;
;; 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 <https://www.gnu.org/licenses/>.
;;
;;; Commentary:
;;
;;  Khalel provides helper routines to import current events from a local
;;  calendar through the command-line tool khal into an org-mode file. Commands
;;  to edit and to capture new events allow modifications to the calendar.
;;  Changes to the local calendar can be transfered to remote CalDAV servers
;;  using the command-line tool vdirsyncer which can be called from within
;;  khalel.
;;
;;  First steps/quick start:
;;  - install, configure and run vdirsyncer
;;  - install and configure khal
;;  - customize the values for capture file and import file for khalel
;;  - call `khalel-add-capture-template' to set up a capture template
;;  - import events through `khalel-import-events',
;;    edit them through `khalel-edit-calendar-event' or create new ones through `org-capture'
;;  - consider adding the import org file to your org agenda to show current events there
;;
;;; Code:

;;;; Requirements

(require 'org)
(require 'ox-icalendar)
(require 'org-capture)

;;;; Customization

(defgroup khalel nil
  "Calendar import functions using khal."
  :group 'calendar)

(defgroup khalel-advanced nil
  "Advanced options for khal and khalel."
  :group 'khalel)

(defcustom khalel-khal-command "khal"
  "The command to run when executing khal.

When set to nil then it will be guessed."
  :group 'khalel
  :type 'string)

(defcustom khalel-khal-config nil
  "The configuration file to use when executing khal.

When set to nil then the default location
\($XDG_CONFIG_HOME/khal/config\) will be used."
  :group 'khalel-advanced
  :type 'string)

(defcustom khalel-default-calendar nil
  "The khal calendar to import into by default.

The calendar for a new event can be modified during the capture
process. Set to nil to get a prompt for one of the khal calendars
instead."
  :group 'khalel
  :type 'string)

(defcustom khalel-default-alarm "10"
  "The default time (in minutes) before an event to display an alarm.
Set to empty string to disable the alarm."
  :group 'khalel
  :type 'string)

(defcustom khalel-capture-key "e"
  "The key used for the `org-capture' template for events.

Run `khalel-add-capture-template' to register the template."
  :group 'khalel
  :type 'string)

(defcustom khalel-import-org-file (concat org-directory "calendar.org")
  "The file to import khal calendar entries into.

CAUTION: the file will be overwritten with each import! The
prompt for overwriting the file can be disabled by setting
`khalel-import-org-file-confirm-overwrite' to nil."
  :group 'khalel
  :type 'string)

(defcustom khalel-import-org-file-read-only 't
  "Whether or not the imported file should be configured as read-only.

As the file is overwritten on repeated imports, modifications would get
lost. If this variable is set to non-nil values, the file will have the
buffer-local variable `buffer-read-only' enabled. Otherwise, the file will
be read-writeable and the user is tasked to be cautious."
  :group 'khalel-advanced
  :type 'boolean)

(defcustom khalel-import-org-file-confirm-overwrite 't
  "When nil, always overwrite the org file into which events are imported.
Otherwise, ask for confirmation."
  :group 'khalel
  :type 'boolean)

(defcustom khalel-import-format "* {title} {cancelled} :{calendar}:\n\
:PROPERTIES:\n:CALENDAR: {calendar}\n\
:LOCATION: {location}\n\
:ID: {uid}\n\
:END:\n\
- When: <{start-date-long} {start-time}>--<{end-date-long} {end-time}>\n\
- Where: {location}\n\
- Description: {description}\n\
- URL: {url}\n- Organizer: {organizer}\n\n\
[[elisp:(khalel-edit-calendar-event)][Edit this event]]\
    [[elisp:(progn (khalel-run-vdirsyncer) (khalel-import-events))]\
[Sync and update all]]\n"
  "The format string to pass to khal when importing events.

See the documentation to khal for valid placeholders (in curly
brackets). The result should be properly formated \\='org-mode\\='
syntax."
  :group 'khalel-advanced
  :type  'string)

(defcustom khalel-import-org-file-header "#+TITLE: khalel imported calendar events\n
#+COLUMNS: %ITEM %TIMESTAMP %LOCATION %CALENDAR\n\n\
*NOTE*: this file has been generated by \
[[elisp:(khalel-import-events)][khalel-import-events]] \
and /any changes to this document will be lost on the next import/!
Instead, use =khalel-edit-calendar-event= or =khal edit= to edit the \
underlying calendar entries, then re-import them here.

You can use [[elisp:(khalel-run-vdirsyncer)][khalel-run-vdirsyncer]] \
to synchronize with remote calendars.

Consider adding this file to your list of agenda files so that events \
show up there.\n\n"
  "The header to insert into the org file when importing events."
  :group 'khalel-advanced
  :type  'string)

(defcustom khalel-import-start-date "today"
  "The start date of events to consider when import.
Can be given anything that will be understood by `org-read-date'.
Used as START argument to the khal date range."
  :group 'khalel
  :type 'string)

(defcustom khalel-import-end-date "+30d"
  "The end date of events to consider when import.
Can be given anything that will be understood by `org-read-date'.
Used as END argument to the khal date range."
  :group 'khalel
  :type 'string)

(defcustom khalel-vdirsyncer-command "vdirsyncer"
  "The command to run when executing vdirsyncer.

When set to nil then it will be guessed."
  :group 'khalel
  :type 'string)

(defcustom khalel-vdirsyncer-collections nil
  "Collections or pairs to pass to vdirsyncer \\='sync\\=' command.

This limits the synchronization to only those specified
collections or pairs when running `khalel-run-vdirsyncer'.
Multple collections must be separated by a space. Specify nil to
synchronize all available collections and pairs.

Examples:

\\='bob frank\\=': synchronize pairs bob and frank
\\='bob/first_collection\\=': synchronize collection first_collection from pair bob."
  :group 'khalel-advanced
  :type 'string)

(defcustom khalel-vdirsyncer-extra-options nil
  "Options to pass to vdirsyncer.

This allows to customize e.g. the verbosity level of vdirsyncer's output
or to pass specific configurations.

Examples:

\\='--verbosity DEBUG\\=': enable debugging output.
\\='--config FILE\\=': select a vdirsyncer configuration file to use."
  :group 'khalel-advanced
  :type 'string)

(define-obsolete-variable-alias 'khalel-update-upcoming-events-after-capture
  'khalel-import-events-after-capture "0.1.8")

(defcustom khalel-import-events-after-capture 't
  "Whether to automatically update the imported events after a new capture."
  :group 'khalel-advanced
  :type 'boolean)

(defcustom khalel-run-vdirsyncer-after-capture nil
  "Whether to automatically run vdirsyncer after a new capture."
  :group 'khalel-advanced
  :type 'boolean)

(defcustom khalel-import-events-after-vdirsyncer 't
  "Whether to automatically update the imported events after synchronization."
  :group 'khalel-advanced
  :type 'boolean)

(defcustom khalel-import-events-after-khal-edit 't
  "Whether to automatically update the imported events after editing an event."
  :group 'khalel-advanced
  :type 'boolean)

(make-obsolete-variable 'khalel-import-time-delta
                        "The import range is now controlled via start \
and end dates set\
via `khalel-import-start-date' and `khalel-import-end-date',\
respectively" "0.1.8")

(defvar khalel--khal-calendar-list nil
  "List of `khal' calendars known to khalel.\

Caches output of \\='khal printcalendars\\=' and updated via
`khalel-refresh-khal-calendar-list'.")

;;;; Commands

(make-obsolete 'khalel-import-upcoming-events 'khalel-import-events "0.1.8")

(defun khalel-import-events ()
  "Imports calendar entries by calling khal externally.

The time delta which determines how far into the future events
are imported is configured through `khalel-import-start-date'
and `khalel-import-end-date'.
CAUTION: The results are imported into the file
`khalel-import-org-file' which is overwritten to avoid adding
duplicate entries already imported previously. As default, the
file is configured to be read-only. This can be adjusted by
configuring `khalel-import-org-file-read-only'.

When a prefix argument is given, the import will be limited to
the calendar `khalel-default-calendar'. If this is nil then the
user is asked to specify a calendar to limit the export to
instead.

Please note that the resulting org file does not necessarily
include all information contained in the .ics files it is based
on. Khal only supports certain (basic) fields when creating lists.

Examples of missing fields are timezone information, categories,
alarms or settings for repeating events."
  (interactive)
  (let*
      ( ;; call khal directly.
       (khal-bin (or khalel-khal-command
                     (executable-find "khal")))
       (khal-cfg (when khalel-khal-config
                   `("-c" ,khalel-khal-config)))
       (khal-cal (when current-prefix-arg
                   (format "-a%s"
                           (khalel--get-calendar))))
       (khal-start (org-read-date nil nil khalel-import-start-date))
       (khal-end (org-read-date nil nil khalel-import-end-date))
       (dst (generate-new-buffer "*khal-output*"))
       (err (get-buffer-create "*khal-errors*"))
       (errfn (make-temp-file "khalel-khal-errors-"))
       ;; determine arguments for khal call
       (args
        (remq nil  ;; remove nil elements
              `(,khal-cfg "list" ,khal-cal "--format"
                          ,khalel-import-format
                          "--day-format" ""
                          ,khal-start ,khal-end)))
       (exitval (apply 'call-process khal-bin nil
                       (list dst errfn) nil
                       args)))
    (save-excursion
      (with-current-buffer err
        (goto-char (point-max))
        (insert-file-contents errfn))
      (with-current-buffer dst
          ;; Make sure org functions work correctly
          (org-mode)
          ;; cosmetic fix for all-day events w/o start or end times:
          ;; remove spaces after dates
          (goto-char (point-min))
          (while (re-search-forward "^\\(- When:.*?\\) \\(>--<.*\\) >" nil t)
            (replace-match "\\1\\2>" nil nil))
          ;; fix multi-line location property making property drawer invalid
          (goto-char (point-min))
          (while (re-search-forward "^:LOCATION: " nil t)
            (save-match-data
              (while (looking-at "\\(.*\\)\n\\([^:]\\)")
                (replace-match "\\1, \\2" nil nil))))
          ;; events that are scheduled as full-day and span multiple days will
          ;; also appear multiple times in the output of `khal list' but will
          ;; each keep the entire range in the time stamp. This results in
          ;; identical entries in the output file and multiple occurances in the
          ;; org-agenda. Filter these duplicates out here.
          (let ((content (khalel--get-buffer-content-list)))
            (with-temp-buffer
              (khalel--insert-import-file-header khal-start khal-end)
              (insert
               (mapconcat 'identity
                          (delete-dups content)
                          ""))
              (write-file khalel-import-org-file
                          khalel-import-org-file-confirm-overwrite)
          (message "Imported %d events from khal into %s"
                   (length (org-map-entries nil nil nil))
                   khalel-import-org-file)))))
    (if (/= 0 exitval)
        (message "khal exited with non-zero exit code; see buffer `*khal-errors*' for details.")
      (kill-buffer dst))
    ;; revert any buffer visisting the file
    (let ((buf (find-buffer-visiting khalel-import-org-file)))
      (when buf (with-current-buffer buf (revert-buffer :ignore-auto :noconfirm))))))


(defun khalel-export-org-subtree-to-calendar ()
  "Exports current subtree as ics file and into an external khal calendar.
An ID will be automatically be created and stored as property of
the subtree. See documentation of `org-icalendar-export-to-ics'
for details of the supported fields.

Note that the UID used in the ics file is based upon but not
identical to the ID of the org entry. Export of imported
entries will likely result in duplicates in the calendar.

Return t on success and nil otherwise."
  (interactive)
  (save-excursion
    ;; org-icalendar-export-to-ics doesn't reliably export the full event when
    ;; operating on a subtree only; narrowing the buffer, however, works fine
    (org-narrow-to-subtree)
    (let*
        ;; store IDs right away to avoid duplicates
        ((org-icalendar-store-UID 't)
         ;; create events from non-TODO entries with scheduled time
         (org-icalendar-use-scheduled '(event-if-not-todo))
         ;; work around a bug in org-element-cache-map in some Org mode versions
         ;; by disabling cache; for details see
         ;; https://orgmode.org/list/87pmau4fi3.fsf@hoowl.se
         (org-element-use-cache (and (version<= "9.6.1" (org-version))
                                     (bound-and-true-p org-element-use-cache)))
         (capturefn (buffer-file-name
                 (buffer-base-buffer)))
         (path (file-name-directory capturefn))
         (entriescal (org-entry-get nil "calendar"))
         (calendar (or
                    (when (and entriescal (string-match "[^[:blank:]]" entriescal)) entriescal)
                    (khalel--get-calendar)))
         ;; export to ics
         (ics (khalel--sanitize-ics
               (org-icalendar-export-to-ics nil nil 't)))
         ;; call khal import only if ics verification succeeds
         (import
          (or (khalel--verify-exported-ics ics)
              (khalel--khal-import calendar (concat path ics)))))
      (widen)
      (let ((exitstat (plist-get import :exit-status)))
        (when
            (/= 0 exitstat)
          (let ((buf (generate-new-buffer "*khalel-capture-errors*")))
            (khalel--make-temp-window buf 16)
            (with-current-buffer buf
              (insert
               (message
                (format
                 "%s failed on %s for calendar '%s' and exited with status %d\n"
                 (plist-get import :process)
                 ics
                 calendar
                 exitstat)))
              (insert "\n" (plist-get import :output) "\n")
              (insert
               (format
               "Once the issues in the captured entry (%s) \
are fixed, you can re-run the export \
by calling `khalel-export-org-subtree-to-calendar'"
               capturefn))
              (special-mode)))
          ;; show captured file to fix issues
          (find-file capturefn))
        (zerop exitstat)))))


(defun khalel-add-capture-template (&optional key)
  "Add an `org-capture' template with KEY for creating new events.
If argument is nil then `khalel-capture-key' will be used as
default instead. New events will be captured in a temporary file
and immediately exported to khal."
  (add-to-list 'org-capture-templates
               `(,(or key khalel-capture-key) "calendar event"
                 entry
                 (function khalel--make-temp-file)
                 ,(concat "* %?\nSCHEDULED: %^T\n:PROPERTIES:\n\
:CREATED: %U\n:CALENDAR: \n\
:CATEGORY: event\n:LOCATION: \n\
:APPT_WARNTIME: " khalel-default-alarm "\n:END:\n" )))
  (add-hook 'org-capture-before-finalize-hook
            #'khalel--capture-finalize-calendar-export)
  ;; do not store the ids in `org-id-locations-file'
  (advice-add 'org-id-add-location
              :around #'khalel--ignore-khal-captures-in-org-id-locations-file-a))


(defun khalel-run-vdirsyncer ()
  "Run vdirsyncer process to synchronize local calendar entries."
  (interactive)
  (let ((buf "*VDIRSYNCER-OUTPUT-BUFFER*")
        (vdirsyncer (or khalel-vdirsyncer-command
                        (executable-find "vdirsyncer"))))
    (with-output-to-temp-buffer buf
      (khalel--make-temp-window buf 16)
      (with-current-buffer buf
        (insert "Running " vdirsyncer "..\n\n"))
      (make-process
       :name "khalel-vdirsyncer-process"
       :buffer buf
       :command (remq nil (flatten-list
                           `(,vdirsyncer
                             ,(when khalel-vdirsyncer-extra-options
                                (split-string khalel-vdirsyncer-extra-options))
                             "sync"
                             ,(when khalel-vdirsyncer-collections
                                (split-string khalel-vdirsyncer-collections)))))
       :filter #'khalel--scroll-on-insert-filter
       :sentinel #'khalel--run-after-process))))


(defun khalel-edit-calendar-event ()
  "Edit the event at the cursor position using khal's interactive edit command.
Works on imported events and used their ID to search for the
  correct event to modify."
  (interactive)
  (let* ((buf (get-buffer-create "*khal-edit*"))
         (uid (org-entry-get nil "id")))
    (khalel--make-temp-window buf 16)
    (if (and uid (string-match "[^[:blank:]]" uid))
        (progn
          (set-process-sentinel
           (get-buffer-process (make-comint-in-buffer
                                "khal-edit" nil
                                khalel-khal-command nil
                                "edit" "--show-past" uid))
           #'khalel--run-after-process)
          (pop-to-buffer buf))
      (message "khalel: could not find ID associated with current entry."))))

(defun khalel-refresh-khal-calendar-list ()
  "Update list of known calendars via call to `khal printcalendars'."
  (interactive)
  (save-excursion
    (with-temp-buffer
      (apply #'call-process
             `(,(or khalel-khal-command
                   (executable-find "khal"))
               nil t nil
               ,@(when khalel-khal-config `("-c" ,khalel-khal-config))
               "printcalendars"))
      (setq khalel--khal-calendar-list
            (split-string
             (buffer-substring (point-min) (point-max))
             "[\f\t\n\r\v]+"
             't
             "[ ]+"))))
  khalel--khal-calendar-list)

;;;; Functions
(defun khalel--khal-import (cal ics)
  "Call `khal' with `import' command to import ICS file into calendar CAL."
  (let ((khal-bin (or khalel-khal-command
                       (executable-find "khal"))))
  (with-temp-buffer
                (list
                 :process khal-bin
                 :exit-status
                 (apply 'call-process
                        `(,khal-bin
                          nil t nil
                          ,@(when khalel-khal-config
                              `("-c" ,khalel-khal-config))
                          "import"
                          ,@(when cal
                              (list (format "-a%s" cal)))
                          "--batch"
                          ,ics))
                 :output
                 (buffer-string)))))

(defun khalel--get-calendar()
  "Return a \\='khal\\=' calendar.

This is either the default calendar set via
`khalel-default-calendar' or one of the ones available through
\\='khal\\='."
  ;; refresh cached list if needed
  (unless khalel--khal-calendar-list
    (khalel-refresh-khal-calendar-list))
  (or khalel-default-calendar
      ;; if only one calendar is known, take that
      (when (eql 1 (length khalel--khal-calendar-list))
        (car khalel--khal-calendar-list))
      ;; ask user to pick
      (khalel--ask-for-calendar)))


(defun khalel--ask-for-calendar()
  "Ask the user to select a khal calendar."
  (completing-read "Select a calendar: "
                 (or khalel--khal-calendar-list
                     (khalel-refresh-khal-calendar-list))
                 nil 'confirm))

(defun khalel--make-temp-file ()
  "Create and visit a temporary file for capturing and exporting events."
  (set-buffer (find-file-noselect (make-temp-file "khalel-capture-" nil "-tmp.org")))
  ;; mark buffer as new and appropriate to kill after capture process.
  (org-capture-put :new-buffer t)
  (org-capture-put :kill-buffer t))

(defun khalel--ignore-khal-captures-in-org-id-locations-file-a (fn &rest args)
  "Ignore khalel capture files when storing ids in the database of id locations.
FN is `org-id-add-location' that comes from advice and ARGS are
passed to it."
  (let ((file (cadr args)))
  (when (not
         (string-match-p "khalel-capture-.*-tmp\\.org"
                         (file-name-nondirectory file)))
         (apply fn args))))

(defun khalel--capture-finalize-calendar-export ()
  "Export current event capture.
To be added as hook to `org-capture-before-finalize-hook'."
  (let ((key  (plist-get org-capture-plist :key)))
    (when (and
           (not org-note-abort)
           (equal key khalel-capture-key))
      (save-excursion
        (goto-char (point-min))
        (if
            (not (khalel-export-org-subtree-to-calendar))
            ;; export finished with non-zero exit status,
            ;; do not clean up buffer/wconf to leave error msg intact and visible
            (progn
              (org-capture-put :new-buffer nil)
              (org-capture-put :kill-buffer nil)
              (org-capture-put :return-to-wconf (current-window-configuration)))
          (when
              khalel-import-events-after-capture
            (khalel-import-events))
          (when
              khalel-run-vdirsyncer-after-capture
            (khalel-run-vdirsyncer)))))))

(defun khalel--sanitize-ics (ics)
  "Remove some modifications to data fields in ICS file.

When exporting, `org-icalendar-export-to-ics' changes an entry's
ID, description and summary depending on the type of date (deadline, scheduled
or active/inactive timestamp) was discovered. Some are changed back
here where appropriate for our use case."
  (with-temp-file ics
    (insert-file-contents ics)
    (goto-char (point-min))
    (while (re-search-forward "^\\(SUMMARY:[[:blank:]]*\\)S: " nil t)
      (replace-match "\\1" nil nil))
    (goto-char (point-min))
    (while (re-search-forward "^\\(DESCRIPTION:[[:blank:]]*\\)S: " nil t)
      (replace-match "\\1" nil nil)))
  ics)


(defun khalel--verify-exported-ics (ics)
  "Check the exported ICS file for potential issues.

Return a plist with details of problems or nil if no issues were found."
  (let ((result nil))
  (with-temp-buffer
    (insert-file-contents ics)
    (goto-char (point-min))
    ;; make sure that the file contains a VEVENT
    (when (not (re-search-forward "^BEGIN:VEVENT" nil t))
      (setq result "`org-icalendar-export-to-ics' did not produce a VEVENT. Please check that the org heading contains a valid 'SCHEDULED: <TIMESTAMP>' line right after the heading.")))
  (and result (list
               :exit-status 1
               :process "org-icalendar-export-to-ics output verification"
               :output result))))

(defun khalel--get-buffer-content-list ()
  "Return the entire content of each subtree of the current buffer as a list."
  (let ((content-list '()) ; start with empty list
        (tab-width 8)) ; required for Org mode files
    (org-element-map (org-element-parse-buffer) 'headline
      (lambda (x)
        (let* ((begin (org-element-property :begin x))
               (end (org-element-property :end x))
               (content (buffer-substring begin end)))
          (push content content-list ))))
    (nreverse content-list)))

(defun khalel--insert-import-file-header (sdate edate)
  "Insert imported events file header information into current buffer.
SDATE and EDATE denote the start and end dates, respectively, of
the current import date range."
  (when khalel-import-org-file-read-only
    (insert "# -*- buffer-read-only: 1; -*-\n"))
  (insert khalel-import-org-file-header)
  (insert (format "*Events scheduled between %s and %s*:\n" sdate edate))
  (insert (format "/(Last import: %s)/\n\n" (current-time-string))))


(defun khalel--make-temp-window (buf height)
  "Create a temporary window with HEIGHT at the frame bottom displaying buffer BUF."
  (or (get-buffer-window buf 'visible)
      (let ((win
             (split-window
              (frame-root-window)
              (- (window-height (frame-root-window)) height))))
        (set-window-buffer win buf)
        (set-window-dedicated-p win t)
        win)))


(defun khalel--run-after-process (process event)
  "Check status of PROCESS at each EVENT and run tasks after process finished.

Ensures that process window is closed after successfully
finishing and runs import of events (if so configured via
`khalel-import-events-after-vdirsyncer' or
`khalel-import-events-after-khal-edit' for calls to `vdirsyncer'
and `khal edit', respectively).

In case of errors, a message with details will be displayed and
the process window will remain."
  (let ((exitstat (process-exit-status process))
        (buf (process-buffer process))
        (cmd (car (process-command process))))
    (if (= 0 exitstat)
        ;; process has finished successfully
        (progn
          (message "Process '%s' finished successfully." cmd)
          ;; close buffer (and window as it is dedicated)
          (when (get-buffer buf)
            (sit-for 2)
            (kill-buffer buf))
          ;; run import if so configured or this is an edit
          (when
              (or
               (and khalel-import-events-after-vdirsyncer (string-match-p khalel-vdirsyncer-command cmd))
               (and khalel-import-events-after-khal-edit (string-match-p khalel-khal-command cmd)))
            (khalel-import-events)))
      ;; otherwise, there was an issue
      (progn
        (message "Process '%s' (%s) failed: '%s' (exit status %d). See buffer '%s' for details."
                 cmd
                 (process-name process)
                 (substring event 0 -1) ;; remove newline character
                 exitstat
                 (buffer-name buf))))))


(defun khalel--scroll-on-insert-filter (proc string)
  "Insert output STRING of PROC and scroll respective window unless selected."
  (let* ((buf (process-buffer proc))
         (window (get-buffer-window buf 'visible)))
  (when (buffer-live-p buf)
    (with-current-buffer buf
      (let ((inhibit-read-only 't)) ;; temp buffer in help mode, ie. read-only
        (save-excursion
          (goto-char (point-max))
          (insert string))
        ;; scroll window if not currently selected
        (when (and window (not (equal (selected-window) window)))
          (set-window-point window (point-max))))))))


;;;; Footer
(provide 'khalel)
;;; khalel.el ends here