summaryrefslogtreecommitdiff
path: root/greader.el
blob: e6262decd7fbdc79e5069d8e2f5c3f75873a069a (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
;;; greader.el --- Gnamù reader, send buffer contents to a speech engine -*- lexical-binding: t; -*-

;; Copyright (C) 2017-2026  Free Software Foundation, Inc.

;; package-requires: ((emacs "26.1") (seq "2.24") (compat "29.1.4.5"))
;; Author: Michelangelo Rodriguez <michelangelo.rodriguez@gmail.com>
;; Keywords: tools, accessibility
;; URL: https://gitlab.com/michelangelo-rodriguez/greader

;; Version: 0.19.0

;; 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:

;; Greader reads aloud the current buffer continuously, moving the point while
;; reading proceeds.

;; It can be used in conjunction with emacspeak or speechd-el packages.
;; it doesn't substitute those packages, but integrates them, providing a
;; functionality that those lacks.
;; In addition to reading the buffer, Greader provides a timer for reading,
;; and a "sleep mode" when you are tired and you want simply relax yourself.
;; for further details, please see the "README" file.

;; To start using greader, you have to install espeak and/or speech-dispatcher,
;; and make sure those packages work correctly.

;; In order to read a buffer:
;; 'M-x greader-mode RET'
;; 'C-r SPC'

;;; Code:
(require 'seq)
(require 'view)
(defvar greader-dict-mode)
(defvar greader-dict-filters-mode)
(declare-function greader-dict--update nil)
(defvar greader-timer-mode)
(defvar greader-tired-mode)
(defvar greader-auto-tired-mode)

(require 'find-func)
(defvar-local greader-auto-tired-timer nil)
(defvar greader--auto-tired-buffer nil
  "Obsolete.  Kept for compatibility only.")
(make-obsolete-variable 'greader--auto-tired-buffer
                        "the buffer is now passed directly to the timer callback."
                        "0.19")
(defvar-local greader-last-point nil)
(defvar-local greader-tired-timer nil)
(defvar-local greader--tired-pending nil
  "Non-nil when tired-mode timer should be armed after soft-stop finishes.")
(defvar-local greader-timer-enabled-interactively nil)
(defvar-local greader-stop-timer 0)
(defvar-local greader-elapsed-timer 0)
(defvar-local greader-elapsed-time 0)
(defvar greader-filter-enabled nil)
(defvar greader-debug-buffer (get-buffer-create "spd-output")
  "Contains the buffer name for debugging purposes.")
(defvar greader-backend-action #'greader--default-action)
(defvar greader-status 'paused)
(defvar greader-synth-process nil)
(defvar-local greader-process-directory
  (file-name-directory (or load-file-name (find-library-name "greader")))
  "The directory where execution should start.")


(define-obsolete-variable-alias 'greader-before-get-sentence-functions
  'greader-before-get-sentence-hook
  "2023")
(defvar greader-before-get-sentence-hook nil
  "Hook run before getting a sentence.
Functions in this variable don't receive arguments.")

(defvar greader-after-get-sentence-functions nil
  "Hook run after getting a sentence.
Functions in this hook take a string as argument, and should modify
  that string that contains the sentence that will be read.
the function should return modified sentence, or original text if no operation
  was needed.")

(defun greader--call-functions-after-get-of-sentence (sentence)
  "Call functions in `greader-after-get-sentence-functions'.
Return SENTENCE, eventually modified by the functions."
  (let ((result sentence))
    (run-hook-wrapped 'greader-after-get-sentence-functions
                      (lambda (func)
                        (when (fboundp func)
	                  (setq result (funcall func result))
			  nil)))
    result))

(defvar greader-before-read-hook nil
  "Code to execute just before start of reading.")

(defvar greader-after-read-hook nil
  "Execute code just after reading a sentence.")

(defun greader-ensure-point-visible ()
  "Scroll the window so that the current point is visible.
This function is intended to be used in `greader-before-read-hook'."
  (unless (pos-visible-in-window-p)
    (recenter)))

(add-hook 'greader-before-read-hook #'greader-ensure-point-visible)

(define-obsolete-variable-alias 'greader-before-finish-hook
  'greader-before-finish-functions
  "2023")
(defvar greader-before-finish-functions nil
  "Code executed just after finishing reading of buffer.
Functions in this hook should return non-nil if at least one function
  returns non-nil, meaning that reading of buffer continues.
If all the functions called return nil, reading finishes normally.")

(defun greader--call-before-finish-functions ()
  "Return t if at least one of the function return t.
If all the functions in the hook return nil, this function return nil."
  (run-hook-with-args-until-success 'greader-before-finish-functions))

(defvar greader-after-stop-hook nil
  "Hook run just after tts is stopped.")

(defgroup
  greader
  nil
  "Greader customization."
  :group 'convenience)
(defcustom greader-hyphen-regex "[-‐]\n+[[:blank:]]*"
  "Regex to use when dehyphenation is needed."
  :type 'string
  :tag "greader hyphen regex")

(defcustom
  greader-backends
  '(greader-espeak greader-speechd greader-mac greader-piper)
  "A list of functions that are back-ends for greader.
If you have already customized this variable and saved it, and if a
new back-end was released or you have created yours, you should add
those new back-ends manually,  so if you want to keep yourself
updated on new back-ends, please check the pproject's repository."
  :type '(repeat function))

(defcustom
  greader-current-backend
  'greader-espeak
  "Greader back-end to use."
  :tag "greader current back-end"
  :type
  `(radio
    ,@(mapcar
       (lambda (backend)
	 `(function-item ,backend))
       greader-backends)))

(defcustom
  greader-auto-tired-mode-time
  "22"
  "Specifies the hour when tired mode will be activated automatically."
  :tag "greader-tired-mode start time"
  :type 'string)

(defcustom
  greader-auto-tired-time-end
  "07"
  "Specifies when auto tired mode should be disabled.
For more information on syntax, see documentation of
`greader-auto-tired-mode-time'."
  :tag "greader auto tired end time"
  :type 'string)

(defcustom
  greader-tired-time
  60
  "Auto tired mode.
Sets when, in seconds after a timer stop, the point must be moved
to the last position have you called command `greader-read'."
  :type 'integer
  :tag "greader seconds for tired mode")

(defcustom
  greader-soft-timer
  t
  "If enabled, reading of text will end not exactly at time expiration.
Instead, the sentence will be read completely."
  :tag "greader soft timer"
  :type 'boolean)

(defcustom
  greader-timer
  10
  "Minutes for timer to stop reading."
  :type 'integer
  :tag "time to stop reading")

(defcustom
  greader-debug
  nil
  "Enables debug information."
  :tag "enable debug"
  :type 'boolean)

(defcustom   greader-hook nil
  ;; FIXME: Can't see where it's run!
  "Hook run after mode activation.
Through this hook you can
customize your key definitions for greader, for example."
  :tag "greader-mode hook"
  :type 'hook)

(defcustom greader-move-to-next-chunk
  #'greader-forward-sentence
  "The function that moves the cursor for the next chunk of text.
For example if you have specified `sentence-at-point' function to get
the current chunk, you should specify `forward-sentence' for this
variable."
  :tag "greader move to next chunk function"
  :type 'function)

(defcustom greader-read-chunk-of-text
  #'greader-sentence-at-point
  "The function used to get the portion of text to read.
The variable `greader-move-to-next-chunk' must be set to a function that
moves the cursor to the same amount of text that is set in this
variable.  For example, if you specify a function that gets a
sentence, you should specify a function that moves to the next one."
  :type 'function
  :tag "greader get chunk of text function")
(defcustom greader-use-prefix t
  "Toggle on or off for use register feature.
if set to t, when you call function `greader-read', that function sets a
  register that points to the actual position in buffer.
  when you call again function `greader-read' with a prefix argument, the point
  is set at register position then reading starts from there."
  :type 'boolean
  :tag "use register")
(defvar greader-reading-mode)
(defvar greader-mode)
(defun greader-set-reading-keymap ()
  "Set greader's keymap when reading."
  (setq greader-mode nil)
  (setq greader-reading-mode t))

(defun greader-set-greader-keymap ()
  "Set greader's keymap when not reading."

  (setq greader-mode t)
  (setq greader-reading-mode nil))

(define-obsolete-variable-alias 'greader-map 'greader-mode-map "2022")

(defcustom greader-keymap-prefix "C-r"
  "The prefix for `greader-mode' commands."
  :type 'string
  :group 'greader)

(defvar greader-prefix-keymap
  (let ((map (make-sparse-keymap)))
    (define-key map (kbd "s")   #'greader-tired-mode)
    (define-key map (kbd "r")   #'isearch-backward)
    (define-key map (kbd "SPC") #'greader-read)
    (define-key map (kbd "l")   #'greader-set-language)
    (define-key map (kbd "t")   #'greader-timer-mode)
    (define-key map (kbd "f")   #'greader-get-attributes)
    (define-key map (kbd "b")   #'greader-change-backend)
    (define-key map (kbd "c") #'greader-compile-at-point)
    map))

(defvar greader-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map (kbd greader-keymap-prefix) greader-prefix-keymap)
    map))

(defvar greader-reading-map
  (let ((map (make-sparse-keymap)))
    (define-key map (kbd "SPC") #'greader-stop)
    (define-key map (kbd "p")   #'greader-toggle-punctuation)
    (define-key map (kbd ".")   #'greader-stop-with-timer)
    (define-key map (kbd "+")   #'greader-inc-rate)
    (define-key map (kbd "-")   #'greader-dec-rate)
    (define-key map (kbd "<left>")   #'greader-backward)
    (define-key map (kbd "<right>")   #'greader-forward)
    map))

(defvar greader-queue-mode)
;;;###autoload
(define-minor-mode greader-mode
  nil
  :lighter " greader"
  :group 'greader
  (cond
   (greader-mode
    (when greader-queue-mode
      (greader-queue-mode -1))
    (greader-load-backends))))
(defvar greader--current-buffer nil
  "This variable is used by `greader-reading-mode'
to know which buffer is currently being read.")

(defun greader-current-buffer-p (&optional buffer)
  "Return t if BUFFER is the current reading buffer, nil otherwise."
  (unless buffer
    (setq buffer (current-buffer)))
  (equal buffer greader--current-buffer))

(defun greader--set-current-buffer (&optional buffer)
  "Set `greader--current-buffer' using BUFFER.
If BUFFER is omitted or nil, use `current-buffer' as BUFFER."
  (unless buffer
    (setq buffer (current-buffer)))
  (unless greader--current-buffer
    (setq greader--current-buffer buffer)))

;;;###autoload
(define-minor-mode greader-reading-mode
  nil
  :interactive nil
  :keymap greader-reading-map
  :lighter " reading..."
  (if greader-reading-mode
      (progn
	(setq greader--current-buffer (current-buffer))
	(add-hook 'greader-before-get-sentence-hook #'greader--set-current-buffer))
    (setq greader--current-buffer nil)
    (remove-hook 'greader-before-get-sentence-hook #'greader--set-current-buffer)))

(defun greader-set-bookmark-for-greader ()
  "Imposta il segnalibro ad ogni interruzione della lettura."
  (when buffer-file-name
    (let ((inhibit-message t))
      (bookmark-set (buffer-name)))))
;;;###autoload
(define-minor-mode greader-auto-bookmark-mode
  "Enable automatic bookmarking.
Each time the reading of the buffer is stopped a bookmark is saved
when the buffer is visiting a file."
  :lighter " bk"
  :global t
  (if greader-auto-bookmark-mode
      (add-hook 'greader-after-stop-hook #'greader-set-bookmark-for-greader)
    (remove-hook 'greader-after-stop-hook #'greader-set-bookmark-for-greader)))
;; greader-region-mode is a non-interactive minor mode that deals with
;; read the active region instead of the entire buffer.
;; The current implementation of greader probably dictates that the
;; buffer needs to be temporarily narrowed when the region is
;; active, so that the functions that deal with obtaining the sentences
;; to read and move the point "believe" that that is all the
;; buffer to read.
(defvar greader-start-region nil
  "Start of region.")
(defvar greader-end-region nil
  "End of region.")

(defun greader--active-region-p ()
  "Return t if the region in the current buffer is active.
Active in this context means that the variables
  `greader-start-region' and `greader-end-region' are set appropriately."
  (if (and greader-start-region greader-end-region)
      t
    nil))

(defun greader-narrow ()
  "Narrow current buffer if region is active."
  (unless (buffer-narrowed-p)
    (narrow-to-region greader-start-region greader-end-region)))

;; This function widens the buffer, and is added to the
;; `greader-after-stop-hook' hook by `greader-region-mode'.
(defun greader-widen ()
  "Widen buffer and set greader-region variables to nil."
  (setq greader-start-region nil)
  (setq greader-end-region nil)
  (greader-region-mode -1)
  (widen))

;; This function places the point at the beginning of the active region.
(defun greader-set-point-to-start-of-region ()
  "Set the point to the beginning of the active region.
This only happens if the variables `greader-start-region' and
`greader-end-region' are set."
  (when (and greader-start-region greader-end-region)
    (goto-char greader-start-region)))

(define-minor-mode greader-region-mode
  "This mode activates when the region is active."
  :interactive nil
  (if greader-region-mode
      (progn
	(setq greader-start-region (region-beginning))
	(setq greader-end-region (region-end))
	(greader-narrow)
	(add-hook 'greader-after-stop-hook #'greader-widen)
	(add-hook 'greader-before-finish-functions #'greader-widen)
	(greader-set-point-to-start-of-region))
    (remove-hook 'greader-before-finish-functions #'greader-widen)
    (remove-hook 'greader-after-stop-hook #'greader-widen)))



(defun greader-set-register ()
  "Set the `?G' register to the point in current buffer."
  (when greader-use-prefix
    (point-to-register ?G)))

(defun greader-jump-to-register ()
  "Jump to register `?G' if `greader-use-prefix' is enabled."
  (when greader-use-prefix
    (jump-to-register ?G)))

(defun greader--get-backends ()
  "Return actual available back-ends, as a list of strings."
  (let (b)
    (dolist (greader-elem greader-backends nil)
      (setq b (append b `(,(get greader-elem 'greader-backend-name)))))
    b))

(defun greader-call-backend (command &optional arg)
  "Call backend passing it COMMAND and ARG.
\(internal use!\)."
  ;; FIXME: Use "--" in the name, then.

  (if arg
      (funcall greader-current-backend command arg)
    (funcall greader-current-backend command)))
(defun greader-load-backends ()
  "Load backends taken from `greader-backends'."
  (mapcar #'require greader-backends))
(greader-load-backends)

(defvar   greader-backend-filename
  (greader-call-backend 'executable))

(defvar greader-backend `(,greader-backend-filename))
(defvar greader-orig-buffer nil)
(defvar greader-dissoc-buffer "*Dissociation*")
(defvar greader-temp-function nil)
(defun greader-change-backend (&optional backend)
  "Change backend used for actually read the buffer.
If BACKEND is non-nil, it changes to BACKEND, else it cycles through
available backends."
  (interactive
   (list
    (if current-prefix-arg
	(completing-read "Back-end: " (greader--get-backends)))))
  (setq-local greader-current-backend
              (cond
	       ((functionp backend)
	        (if (memq backend greader-backends)
	            backend
	          (error "Not a greader's back-end: %S" backend)))
	       ((stringp backend)
                (let ((result nil))
                  (dolist (elem greader-backends result)
	            (if
	                (equal
	                 (get elem 'greader-backend-name) backend)
	                (setq result elem)))
	          (or result
	              (user-error "Not a greader's back-end: %S"
				  backend))))
	       (backend
	        (error "Backend should be a string or a function: %S"
		       backend))
	       (t
	        (car (or
		      (cdr
		       (memq greader-current-backend greader-backends))
	              greader-backends)))))
  (message "Current back-end is %s"
           (get greader-current-backend 'greader-backend-name)))



(defun greader-read-asynchronous (txt)
  "Read the text given in TXT."
  (if greader-debug
      (greader-debug "greader-read-asynchronous entered\n"))
  (run-hooks 'greader-before-read-hook)
  (greader-build-args)
  (setq txt (substring-no-properties txt))
  (if (and txt (greader-sentence-needs-dehyphenation txt))
      (setq txt (greader-dehyphenate txt)))
  (let* ((txt (concat " " txt))
         (backend (append greader-backend `(,txt)))
	 (default-directory greader-process-directory))
    (and (stringp txt)
	 (setq-local greader-synth-process (make-process
				            :name "greader-backend"
				            :sentinel #'greader-action
				            :filter
					    #'greader-process-filter
				            :command backend)))
    (if greader-debug
	(progn
	  (set-process-buffer greader-synth-process
			      greader-debug-buffer)
	  (greader-debug
	   (message "greader-read-asynchronous: %S" backend))))))

(defun greader-get-status ()
  "Return greader status."
  greader-status)

(defun greader-change-status (arg)
  "Change status of greader using ARG."
  (if greader-debug
      (greader-debug "greader-change-status entered"))
  (if (symbolp arg)
      (setq greader-status arg)
    (error "Status must be a symbol!")))

(defun greader-action (process event)
  "Sentinel for greader processes using PROCESS and EVENT."
  (if greader-debug
      (progn
	(greader-debug "greader-action entered.\n")
	(greader-debug (format "event: %S\n" event))))
  (funcall greader-backend-action process event))

(defun greader-tts-stop ()
  "Stop reading of current buffer."
  (set-process-sentinel greader-synth-process
			#'greader--default-action)
  (if
      (not
       (eq
	(greader-call-backend 'stop) 'not-implemented))
      (greader-call-backend 'stop))
  (delete-process greader-synth-process)
  (setq-local greader-backend-action #'greader--default-action))

(defun greader--default-action (&optional _process event)
  "Internal use.
Optional argument PROCESS
Optional argument EVENT ."
  (if greader-debug
      (greader-debug
       (format "greader--default-action entered.\nevent: %S\n" event)))
  (when (and greader-timer-mode (timerp greader-stop-timer))
    (greader-cancel-elapsed-timer)
    (greader-cancel-stop-timer)
    (greader-reset-elapsed-time)
    (setq-local greader-stop-timer 0)
    (when greader--tired-pending
      (setq-local greader--tired-pending nil)
      (greader-setup-tired-timer)))
  (greader-set-greader-keymap))

(defun greader-build-args ()
  "Build the string that will be passed to the back-end."
  (greader-reset)
  (let (args)
    (push (greader-call-backend 'rate) args)
    (when-let* ((lang (greader-call-backend 'lang)))
      (push lang args))
    (when-let* ((punc (greader-call-backend 'punctuation)))
      (push punc args))
    (when-let* ((extra (greader-call-backend 'extra)))
      (unless (eq extra 'not-implemented)
        (push extra args)))
    (setq greader-backend (append greader-backend
                                  (delete 'not-implemented (nreverse args))))))

(defun greader-reset ()
  "Reset greader."
  (setq greader-backend `(,(greader-call-backend 'executable))))

(defun greader-next-action (_process event)
  "Perform next action when reading.
Argument PROCESS .
Argument EVENT ."
  (if greader-debug
      (greader-debug (format "greader-next-action: %s" event)))
  (run-hooks 'greader-after-read-hook)
  (cond
   ((equal event "finished\n")
    (funcall greader-move-to-next-chunk)))
  (greader-read))

(defun greader-response-for-dissociate (&optional _prompt)
  "Return t to the caller until a condition is reached.
This function will be locally bound to `y.or-n-p' until
`dissociated-press' does the job.
Optional argument PROMPT variable not used."
  (with-current-buffer greader-orig-buffer
    (if (< (buffer-size greader-dissoc-buffer) 100000)
	t
      nil)))

(defun greader-read-dissociated ()
  "Use `dissociated-press to read a text dissociately.
\(Helpful for
mindfullness!)."
  (interactive)
  (setq greader-orig-buffer (current-buffer))
  (setq greader-dissoc-buffer (get-buffer-create "*Dissociation*"))
  (unwind-protect
      (progn
	(fset 'greader-temp-function (symbol-function 'y-or-n-p))
	(fset 'y-or-n-p (symbol-function
			 'greader-response-for-dissociate))
	(let ((arg (random 10)))
	  (while (equal arg 0)
	    (setq arg (random 10)))
	  (dissociated-press arg))
	(switch-to-buffer greader-dissoc-buffer)
	(goto-char (point-min))

	(greader-mode 1)
	(greader-read))
    (fset 'y-or-n-p (symbol-function 'greader-temp-function))))
(defvar greader-continuous-mode)
(defun greader-read (&optional goto-marker)
  "Start reading of current buffer.
if `GOTO-MARKER' is t and if you pass a prefix to this
function, point jumps at the last position you called command `greader-read'."

  (interactive "P")
  (when goto-marker
    (when greader-continuous-mode
      (user-error "`greader-continuous-mode' is enabled, please
  disable it to use the prefix"))
    (greader-jump-to-register))
  (when (called-interactively-p 'any)
    (greader-set-register))

  (when (and greader-tired-mode (= greader-elapsed-time 0))
    (greader--tired-cleanup)
    (setq-local greader-last-point (point)))

  (cond
   ((and greader-timer-mode (not (timerp greader-stop-timer)))
    (greader-setup-timers)))
  (when (region-active-p)
    (cond
     ((and (not greader-region-mode) (not (greader--active-region-p)))
      (greader-region-mode 1))))
  (run-hooks greader-before-get-sentence-hook)
  (let ((chunk (funcall greader-read-chunk-of-text)))
    (if chunk
	(progn
	  (setq chunk
		(greader--call-functions-after-get-of-sentence chunk))
	  ;; This extra verification is necessary because espeak has a bug that,
	  ;; when we pass a string containing a vocal plus only 2 .. it reads
	  ;; garbage.
	  (if (string-suffix-p ".." chunk)
	      (setq chunk (concat chunk ".")))
	  (greader-set-reading-keymap)
	  (setq-local greader-backend-action #'greader-next-action)
	  (greader-read-asynchronous chunk))
      (progn
	(setq-local greader-backend-action #'greader--default-action)
	(greader-set-greader-keymap)
	(unless (greader--call-before-finish-functions)
	  (greader-read-asynchronous ". end"))))))

(defun greader-stop ()
  "Stop reading of document.
If `greader-dict-mode' and/or `greader-dict-filters-mode' are
active, the dictionary of pronunciation rules will be updated after
calling all the hooks."

  (interactive)
  (cond
   ((and (> greader-elapsed-time 0) greader-timer-mode)
    (greader-cancel-elapsed-timer)
    (greader-cancel-stop-timer)
    (if
	(>= greader-elapsed-time
	    (1- (greader-convert-mins-to-secs greader-timer)))
	(greader-reset-elapsed-time))
    (setq-local greader-stop-timer 0)))
  (setq-local greader--tired-pending nil)
  (greader-set-greader-keymap)
  (greader-tts-stop)
  (run-hooks 'greader-after-stop-hook)
  (when (and (featurep 'greader-dict)
             (or greader-dict-mode
                 greader-dict-filters-mode))
    (greader-dict--update)))

(defun greader-debug (arg)
  "Used to get some fast debugging.
Argument ARG is not used."
  (save-current-buffer
    (get-buffer-create greader-debug-buffer)
    (set-buffer greader-debug-buffer)
    (insert arg)))
(defvar greader-sentence-regexp "[.?!]+[[:space:]]"
  "Regexp to indicate the end of a sentence in terms of greader.")
(defvar greader-classic-nav-mode)
(defun greader-forward-sentence ()
  "Move the point to next sentence."
  (let ((result (greader-call-backend 'next-text)))
    (if (not (equal result 'not-implemented))
	result
      (let
	  ((sentence-end
	    (if greader-classic-nav-mode nil greader-sentence-regexp)))
	(forward-sentence)))))

(defun greader-backward-sentence ()
  "Move back by a sentence in terms of greader."
  (let ((result (greader-call-backend 'next-text)))
    (if (not (equal result 'not-implemented))
	result
      (let
	  ((sentence-end
	    (if greader-classic-nav-mode nil greader-sentence-regexp)))
	(backward-sentence)))))

(defun greader-get-sentence ()
  "Get current sentence.
Before returning sentence, this function runs
`greader-before-get-sentence-hook'
If at end of buffer, nil is returned."
  (let ((result (greader-call-backend 'get-text)))
    (if (stringp result)
	result
      (let ((sentence-start (make-marker)))
	(setq sentence-start (point))
	(save-excursion
	  (when (not (eobp))
	    (greader-forward-sentence))
	  (if (> (point) sentence-start)
	      (string-trim (buffer-substring sentence-start (point))
			   "[ \t\n\r]+")
	    nil))))))

(defun greader-sentence-at-point ()
  "Get sentence starting from point."
  (greader-get-sentence))

(defun greader-process-filter (_process string)
  "Process filter.
Optional argument STRING contains the string passed to
`greader-read-asynchronous'."
  (if greader-filter-enabled
      (message string)))
(defvar greader-after-change-language-hook nil
  "The functions in this variable are executed just after new language is set.")

(defun greader-set-language (lang)
  "Set language of tts.
LANG must be in ISO code, for example `en' for English or `fr' for
French.
With a prefix argument, save the selected voice/language as the new
global default (written to `custom-file' via `customize-save-variable')."
  (interactive
   (list
    (let ((result (greader-call-backend 'set-voice nil)))
      (if (equal result 'not-implemented)
	  (read-string "Set language to: ")
	result))))
  (greader-call-backend 'lang lang)
  (when current-prefix-arg
    (greader-call-backend 'save-voice lang))
  (run-hooks 'greader-after-change-language-hook))

(defun greader-set-punctuation (flag)
  "Set punctuation to FLAG."
  (greader-call-backend 'punctuation flag))

(defun greader--get-local-language ()
  "Return the language code from the system's locale."
  (let ((locale (or (getenv "LANG") ; First try with the LANG environment variable
                    (getenv "LC_ALL") ; Then with LC_ALL
                    "en")))
					; Default to "en" if nothing is found
    ;; Extracts the language code from the locale (e.g., "en_US.UTF-8" becomes "en")
    (if (string-match "\\([a-z]+\\)_" locale)
        (match-string 1 locale)
      "en")))
					; Default to "en" if the locale format is unrecognized

(defun greader-get-language ()
  "Return language set in current back-end.
if `current-backend' does not implement `get-language' command, try to
get the language from the environment."
  (let ((lang nil))
    (if (equal (greader-call-backend 'get-language)
	       'not-implemented)
	(setq lang (greader--get-local-language))
      (setq lang (greader-call-backend 'get-language)))
    lang))

(defun greader-get-rate ()
  "Return the numerical value for current back-end rate."
  (let ((result (greader-call-backend 'get-rate)))
    (if (not (equal result 'not-implemented))
	result
      (user-error "Backend feature \"get-rate\" not implemented for
the current backend"))))

(defun greader-toggle-punctuation ()
  "Toggle punctuation locally for current buffer."
  (interactive)
  (greader-tts-stop)
  (greader-call-backend 'punctuation 'toggle)
  (greader-read))

;;;###autoload
(define-minor-mode greader-timer-mode
  "Stop reading automatically after `greader-timer' minutes.
When enabled, a timer is armed each time `greader-read' starts.
Soft-timer behavior (finish current sentence) is controlled by
`greader-soft-timer'."
  :lighter " Tmr"
  (if greader-timer-mode
      (setq-local greader-timer-enabled-interactively t)
    (setq-local greader-timer-enabled-interactively nil)
    (unless (equal greader-elapsed-timer 0)
      (greader-cancel-elapsed-timer))
    (when (timerp greader-stop-timer)
      (greader-cancel-stop-timer)
      (setq-local greader-stop-timer 0))
    (greader-reset-elapsed-time)
    (when greader-tired-mode
      (greader-tired-mode -1))))

(defun greader-set-timer (&optional timer-in-mins)
  "Set timer for reading expressed in minutes.
This command should be used only if you want to set locally a timer
different of that you set via customize, that is considered the default
value for this variable.
Optional argument TIMER-IN-MINS timer in minutes (integer)."
  (interactive (list (read-number "Set timer for: " greader-timer)))
  (unless (or greader-timer-mode greader-auto-tired-mode)
    (greader-timer-mode 1))
  (setq-local greader-timer timer-in-mins))

(defun greader-timer-remaining ()
  "Display the time remaining before the reading timer expires.
The remaining time is shown in the minibuffer as minutes and seconds."
  (interactive)
  (if (and greader-timer-mode (timerp greader-stop-timer))
      (let* ((total (greader-convert-mins-to-secs greader-timer))
             (remaining (max 0 (- total greader-elapsed-time)))
             (mins (/ remaining 60))
             (secs (% remaining 60)))
        (message "Time remaining: %d min %d sec" mins secs))
    (message "No active timer.")))

(defun greader-setup-timers ()
  "Set up timers, that is, call `run-at-time' using settings you have specified."
  (catch 'timer-is-nil
    (cond
     (greader-timer-mode
      (setq-local greader-stop-timer
		  (run-at-time
		   (- (greader-convert-mins-to-secs greader-timer)
		      greader-elapsed-time)
		   nil #'greader-stop-timer-callback))
      (setq-local greader-elapsed-timer
                  (run-at-time 1 1 #'greader-elapsed-time)))
     ((not greader-timer-mode)
      (throw 'timer-is-nil nil))))
  t)

(defun greader-elapsed-time ()
  "Not documented (internal use)."
  (setq-local greader-elapsed-time (1+ greader-elapsed-time)))

(defun greader-convert-mins-to-secs (mins)
  "Convert MINS in seconds."
  (* mins 60))

(defun greader-cancel-stop-timer ()
  "Not documented, internal use."
  (cancel-timer greader-stop-timer))

(defun greader-cancel-elapsed-timer ()
  "Not documented, internal use."
  (cancel-timer greader-elapsed-timer))

(defun greader-reset-elapsed-time ()
  "Not documented, internal use."
  (setq-local greader-elapsed-time 0))

(defun greader-stop-with-timer ()
  "Stop reading of buffer and also reset timer.
If you use this command, next reading will start timer at its current
value.  If you stop normally with `greader-stop', next reading will
continue from the time elapsed before you stopped."
  (interactive)
  (when greader-timer-mode
    (greader-cancel-elapsed-timer)
    (greader-cancel-stop-timer)
    (setq-local greader-stop-timer 0)
    (greader-reset-elapsed-time))
  (greader-stop))

(defun greader-stop-timer-callback ()
  "Function called when timer expires."
  (cond
   ((greader-soft-timer-p)
    (when greader-tired-mode
      (setq-local greader--tired-pending t))
    (setq-local greader-backend-action #'greader--default-action))
   ((not greader-soft-timer)
    (when greader-tired-mode
      (greader-setup-tired-timer))
    (greader-stop))))

(defun greader-soft-timer-p ()
  "Return t if soft-timer is enabled.
With soft timer, greader will stop reading at the end of sentence is
  actually reading.
If it is disabled, greader will stop reading immediately after timer expiration."
  (if greader-soft-timer
      t
    nil))

;;;###autoload
(define-minor-mode greader-tired-mode
  "After the reading timer expires, move point back to where reading started.
Enabling this mode implicitly enables `greader-timer-mode'."
  :lighter " Trd"
  (if greader-tired-mode
      (unless greader-timer-mode
        (greader-timer-mode 1)
        (setq-local greader-timer-enabled-interactively nil))
    (greader--tired-cleanup)
    (unless greader-timer-enabled-interactively
      (greader-timer-mode -1))))

(defvar greader--tired-intercept-map
  (let ((map (make-sparse-keymap)))
    (define-key map [t] #'greader--tired-wakeup)
    map)
  "Keymap used by `greader--tired-intercept-mode'.
Binds every key to `greader--tired-wakeup', swallowing the original
command so that only reading is resumed.")

(define-minor-mode greader--tired-intercept-mode
  "Transient buffer-local mode that intercepts any key to resume greader.
Enabled by `greader-setup-tired-timer' and disabled by `greader--tired-cleanup'."
  :keymap greader--tired-intercept-map)

(defun greader--tired-cleanup ()
  "Cancel the tired idle timer and deactivate the intercept mode.
This is the single cleanup point for all tired-mode paths."
  (when (timerp greader-tired-timer)
    (cancel-timer greader-tired-timer)
    (setq-local greader-tired-timer nil))
  (when greader--tired-intercept-mode
    (greader--tired-intercept-mode -1)))

(defun greader--tired-wakeup ()
  "Resume reading; called by `greader--tired-intercept-mode' on any key press.
The original command is swallowed: only reading resumes."
  (interactive)
  (greader--tired-cleanup)
  (greader-read))

(defun greader-setup-tired-timer ()
  "Arm the tired-mode idle timer and activate the intercept mode."
  (when greader-tired-mode
    (setq-local greader-tired-timer
                (run-with-idle-timer
                 (time-add (or (current-idle-time) 0)
                           (seconds-to-time greader-tired-time))
                 nil #'greader-tired-mode-callback))
    (greader--tired-intercept-mode 1)))

(defun greader-tired-mode-callback ()
  "Move point back to where reading started after the idle timer fires."
  (greader--tired-cleanup)
  (greader-move-to-last-point))

(defun greader-move-to-last-point ()
  "Not documented, internal use."
  (goto-char greader-last-point))

;;;###autoload
(define-minor-mode greader-auto-tired-mode
  "Automatically enable `greader-tired-mode' between
`greader-auto-tired-mode-time' and `greader-auto-tired-time-end'."
  :lighter " ATrd"
  (if greader-auto-tired-mode
      (progn
        (unless greader-tired-mode (greader-tired-mode 1))
        (setq-local greader-auto-tired-timer
                    (run-at-time nil 1 #'greader-auto-tired-callback
                                 (current-buffer))))
    (when greader-tired-mode (greader-tired-mode -1))
    (when (timerp greader-auto-tired-timer)
      (cancel-timer greader-auto-tired-timer))
    (setq-local greader-auto-tired-timer nil)))

(defun greader-convert-time (time)
  "Return an encoded time for the next occurrence of hour TIME today."
  (when (stringp time) (setq time (string-to-number time)))
  (let ((today-at-time (decode-time)))
    (setf (nth 2 today-at-time) time
          (nth 1 today-at-time) 0
          (nth 0 today-at-time) 0)
    (apply #'encode-time today-at-time)))

(defun greader-current-time-in-interval-p (time1 time2)
  "Return t if current time is between TIME1 and TIME2.
Handles midnight-crossing intervals (e.g. 22:00 to 07:00)."
  (let ((now (current-time)))
    (if (time-less-p time1 time2)
        (and (time-less-p time1 now) (time-less-p now time2))
      ;; midnight-crossing: active if now >= time1 OR now < time2
      (or (not (time-less-p now time1))
          (time-less-p now time2)))))

(defun greader-auto-tired-callback (buffer)
  "Not documented, internal use.
BUFFER is the buffer in which `greader-auto-tired-mode' was enabled."
  (when (buffer-live-p buffer)
    (let ((background (not (eq buffer (current-buffer)))))
      (with-current-buffer buffer
        (if (not greader-auto-tired-mode)
            (when (timerp greader-auto-tired-timer)
              (cancel-timer greader-auto-tired-timer)
              (setq-local greader-auto-tired-timer nil))
          (let ((start (greader-convert-time greader-auto-tired-mode-time))
                (end   (greader-convert-time greader-auto-tired-time-end)))
            (when (and (greader-current-time-in-interval-p start end)
                       (not greader-tired-mode))
              (greader-tired-mode 1)
              (when background
                (message "greader-tired-mode enabled in buffer %s"
                         (buffer-name))))
            (when (and (not (greader-current-time-in-interval-p start end))
                       greader-tired-mode)
              (greader-tired-mode -1)
              (when background
                (message "greader-tired-mode disabled in buffer %s"
                         (buffer-name))))))))))

(defun greader-set-rate (n)
  "Set rate in current buffer to tthe specified value in N.
rate is expressed in words per minute.  For maximum value, see `man espeak'."
  (greader-call-backend 'rate n))

(defun greader-inc-rate (&optional n)
  "Increment rate of speech by N units.
If prefix, it will be used to increment by that.  Default is N=10."
  (interactive "P")
  (if (not n)
      (setq n 10))
  (if (stringp (greader-call-backend 'rate))
      (progn
	(greader-tts-stop)
	(greader-set-rate (+ (greader-call-backend 'rate 'value) n))
	(greader-read))
    (beep)))

(defun greader-dec-rate (&optional n)
  "Decrements rate of speech by units specified in N.
If prefix, it will be used to decrement  rate."
  (interactive "P")
  (if (not n)
      (setq n 10))
  (if (stringp (greader-call-backend 'rate))
      (progn
	(greader-tts-stop)
	(greader-set-rate (- (greader-call-backend 'rate 'value) n))
	(greader-read))
    (beep)))

(defun greader-sentence-needs-dehyphenation (str)
  "Return t if there are lines broken by hyphens in STR, nil otherwise."
  (string-match greader-hyphen-regex str))

(defun greader-dehyphenate (sentence)
  "Join lines broken by hyphens in SENTENCE.
It is possible to customize what this function considers to be an
  hyphen, by setting `greader-hyphen-regex'."
  (replace-regexp-in-string greader-hyphen-regex "" sentence))

(defun greader-get-attributes ()
  "Print text properties associated with current char."
  (interactive)
  (print (text-properties-at (point))))

(defcustom greader-compile-command "--compile="
  "Espeak-ng parameter to compile a lang."
  :tag "greader compile command"
  :type 'string)

(defcustom greader-compile-extra-parameters nil
  "Extra parameters to pass to espeak-ng.
In general you should specify an alternative path for espeak voice
  data."
  :tag "greader compile extra parameters"
  :type '(repeat :tag "extra parameter" string))

;;;###autoload
(defcustom greader-compile-dictsource nil
  "Location of espeak dictionary source data.
You must configure this variable in order to use
  `greader-compile-mode'."
  :tag "greader compile source dictionary directory"
  :type '(repeat :tag "directory:" string))
;;;###autoload
(define-minor-mode greader-compile-mode
  "Espeak voice definition and compilation mode.
This global minor mode of greader allows saving of an
espeak-ng dictionary file and subsequent correspondent voice compilation
in one shot.
In some cases, the directory where espeak-ng keeps its data
is not writable by the normal user, in this case, when
saving the file, you will be asked to enter your password
administrator."
  :global t

  (if greader-compile-mode
      (progn
	(unless greader-compile-dictsource
	  (error "Please set or customize `greader-compile-dictsource'
    to define espeak-ng dictionary source location"))
	(add-hook 'after-save-hook #'greader-check-visited-file)
	;; FIXME: AFAIK `define-minor-mode' will emit pretty much
	;; this exact message if we don't.
	(message "greader-compile minor mode enabled"))
    (when (member #'greader-check-visited-file after-save-hook)
      ;; FIXME: AFAIK `define-minor-mode' will emit pretty much
      ;; this exact message if we don't.
      (message "greader-compile mode disabled"))
    ;; Call `remove-hook' even if the `member' test failed:
    ;; it's safer to do so anyway (e.g. the `member' test may
    ;; actually give the wrong answer).
    (remove-hook 'after-save-hook #'greader-check-visited-file)))

(defvar greader-compile-history nil)
(defun greader-compile (&optional lang)
  "Compile espeak voice for a given LANG.
when called interactively, compile the
espeak-ng definitions for a given language.
By default, `greader-compile' infers the language from the first two
letters of the file you are visiting.
If its LANG parameter is `non-nil', the function will ask for
specifying the language to compile, ignoring the current file name
but proposing it as default.
In case the specified language does not seem compatible with
buffer environment, this function will ask for confirmation before
proceed.
Important notice: The parameter is only for an interactive call
since the function uses the minibuffer to get
the language.
If it is not called interactively, pass no arguments to it, the
function is specifically designed to be executed by a hook."

  (interactive "P")

  (if lang
      (setq lang (read-from-minibuffer "Language (2 letters):"
				       nil
				       nil
				       nil
				       nil
				       nil
				       (greader-compile-guess-lang)))
    (setq lang (greader-compile-guess-lang)))

  (unless lang
    (error "Cannot determine language to compile"))

  (let
      (data-is-writable
       (command
	(append '("espeak")
		(list (concat greader-compile-command lang))
		greader-compile-extra-parameters)))

    (with-temp-buffer
      (call-process "espeak" nil t t "--version")
      (goto-char (point-min))
      (search-forward "/")
      (setq data-is-writable (file-writable-p (thing-at-point
					       'filename))))

    (when (not data-is-writable)
      (setq command (append '("sudo") command)))

    (make-process
     :name "greader-espeak"
     :filter #'greader-compile--filter
     :command command)))

(defun greader-compile--filter (&optional process str)
  "Filter PROCESS for sudo based on STR."
  (when (string-match "password" str)
    (process-send-string process (concat (read-passwd str) "\n")))
  (when (string-match "error" str)
    (error "%s" str)))

(defun greader-compile-guess-lang ()
  "Internal use.
This function return t if the file associated with current buffer
  seems to be an espeak dictionary definition file."

  (when (buffer-file-name)
    (let*
	((lang (buffer-file-name))

	 (start (string-match "/[[:alpha:]][[:alpha:]]_" lang))

	 end)
      (if start
	  (progn
	    (setq start (1+ start))
	    (setq end (string-match "_" lang start))
	    (substring lang start end))
	nil))))

(defun greader-check-visited-file ()
  "Internal use.
Hook for `after-save-hook'."
  (let ((dir (file-truename (file-name-as-directory default-directory)))
	(sources (mapcar (lambda (d) (file-truename (file-name-as-directory d)))
			 greader-compile-dictsource))
	(lang (greader-compile-guess-lang)))
    (message "greader-compile: default-directory=%S" dir)
    (message "greader-compile: dictsource=%S" sources)
    (message "greader-compile: guessed lang=%S" lang)
    (if (not (member dir sources))
	(message "greader-compile: skipping (directory not in dictsource)")
      (if (not lang)
	  (message "greader-compile: skipping (cannot guess language from filename)")
	(message "greader-compile: compiling %s..." lang)
	(greader-compile)))))

(defcustom greader-compile-default-source "extra"
  "Dict source file suffix to use when `greader-compile-at-point' is called.
If nil, you can not use `greader-compile-at-point'."
  :tag "greader compile default dictionary source file"
  :type 'string)
(defcustom greader-compile-history-delete-duplicates t
  "If enabled, duplicates in the history will not be added."
  :type 'boolean)
(defvar greader-espeak-language)
(defun greader-compile-at-point (&optional src dst)
  "Add a word to the espeak dictionary definition.
When called interactively and point is on a word, this function asks
for the definition, assuming you want to define current word.
If you want to be asked about the word to define, call this command
with prefix.
When called from a function, you should specify SRC and DST, even if
SRC and DST are declared as optional."
  (interactive "P")
  (unless greader-compile-default-source
    (error
     "You must set or customize `greader-compile-default-source'"))

  (unless src
    (setq src (thing-at-point 'word t))
    (unless src
      (setq src (read-string "Word to add: "))))

  (when (listp src)
    (setq src (read-string "word to add: "))
    (if (equal src "")
	(setq src (thing-at-point 'word t))))
  (unless dst
    (let ((history-delete-duplicates  greader-compile-history-delete-duplicates))
      (setq dst (read-string (concat "Redefine " src " to: ") nil
			     'greader-compile-history))))

  (let ((lang-file
	 (if (string-prefix-p "/" greader-compile-default-source)
	     greader-compile-default-source
	   (concat (car greader-compile-dictsource)
		   (substring greader-espeak-language 0 2) "_"
		   greader-compile-default-source))))
    (with-current-buffer (find-file-noselect lang-file)
      (goto-char (point-max))
      (insert src " " dst "\n")
      (save-buffer)
      (unless greader-compile-mode
	(greader-compile)))))

(defun greader-compile-goto-source ()
  "Visit default dictsource currently used by `greader-compile-at-point'."
  (interactive)
  (if (string-match "/" greader-compile-default-source)
      (find-file greader-compile-default-source)
    (find-file (concat (car greader-compile-dictsource)
		       (substring greader-espeak-language 0 2) "_"
		       greader-compile-default-source))))

(defcustom greader-backward-acoustic-feedback nil
  "If t, when point returns to the end of sentence, plays a beep."
  :tag "greader backward acoustic feedback"
  :type 'boolean)

(defcustom greader-backward-seconds 5
  "Number of seconds to wait before returning at the end of sentence."
  :tag "greader-backward seconds"
  :type 'float)

(defvar greader--marker-backward (make-marker))

(defvar greader--timer-backward nil)

(defcustom greader-classic-nav-mode nil
  "Enable classic navigation while reading."
  :type 'boolean)

(defun greader--forward ()
  "Internal forward sentence."
  (when (and (equal
	      (point) greader--marker-backward)
	     greader-reading-mode)
    (greader-forward-sentence)
    (backward-char 2)
    (when greader-backward-acoustic-feedback
      (beep))))

(defun greader--set-forward-timer ()
  "Set the timer for `greader-backward'."
  (setq greader--timer-backward
	(run-with-idle-timer greader-backward-seconds nil
			     #'greader--forward)))

(defun greader-backward ()
  "Restart reading from start of sentence.
When at start of sentence, this function sets a timer for
`greader--set-forward-timer' seconds, and, if the cursor is yet at
start of sentence, puts the point at the end.
So you can use this command like a player, if you press <left> you
will ear the start of last read sentence, and if you press again
while timer is in effect, you go back by one sentence."
  (interactive)
  (when (bobp)
    (signal 'beginning-of-buffer ()))
  (when greader--timer-backward
    (cancel-timer greader--timer-backward)
    (setq greader--timer-backward nil))
  (greader-tts-stop)
  (greader-backward-sentence)
  (greader-set-register)
  (setq greader--marker-backward (point))
  (greader--set-forward-timer)
  (greader-read))

(defun greader-forward ()
  "Move point to next sentence and start reading from there."
  (interactive)
  (when (eobp)
    (signal 'end-of-buffer nil))
  (greader-tts-stop)
  (greader-forward-sentence)
  (greader-set-register)
  (greader-read))

;; greader-queue-mode
;; This minor mode enables an alternative reading mode, which
;; works with blocks of text instead of the buffer in a linear fashion.

(defvar-local greader-queue nil
  "This is the variable that contains the queue.
each element is formed by a cons, whose form is `start-position
. end-position'.")

(defvar-local greader-queue-current-element nil
  "Represent the current item in the queue (as index).")

;; Questa funzione aggiunge un elemento alla coda.
(defun greader-queue-add-element (&optional start end)
  "Add an item to the queue.
If START and END are nil, check if the region is active.
If the region is not active either, then it throws an error."
  (interactive)
  (unless (and start end)
    (if (region-active-p)
	(progn
	  (setq start (region-beginning) end (region-end))
	  (deactivate-mark))
      (user-error "Nothing to add")))
  (let ((result (greader-queue-region-overlap start end)))
    (if result
	(greader-queue-modify-element result start end)
      (add-to-list 'greader-queue (cons start end) t)))
  (unless greader-queue-current-element
    (setq greader-queue-current-element 0)))

;; This function determines whether the region overlaps with one of the
;; items in the queue.
(defun greader-queue-region-overlap (&optional start end)
  "Return the index of the element that overlaps the region.
If the region does not overlap any of the items in the queue,
then return nil."
  (unless (and start end)
    (if (region-active-p)
	(setq start (region-beginning) end (region-end))
      (user-error "Please specify a region")))
  (if greader-queue
      (let ((result nil) (counter 0))
	(dolist (item greader-queue)
	  (when (or
		 (and (>= start (car item)) (<= start (cdr item)))
		 (and (>= end (car item)) (<= end (cdr item))))
	    (setq result counter))
	  (setq counter (1+ counter)))
	result)
    nil))

;; This function modifies an item in the queue.
(defun greader-queue-modify-element (index start end)
  "Modify the item specified in INDEX with the new START and END.
This function modifies the `greader-queue' variable."
  (let ((result nil) (counter 0))
    (dolist (item greader-queue)
      (if (equal counter index)
	  (progn
	    (push (cons start end) result)
	    (setq counter (1+ counter)))
	(push item result)
	(setq counter (1+ counter))))
    (setq greader-queue (reverse result))))

;;this function resets the queue.
(defun greader-queue-reset-queue ()
  "Reset the queue and relative variables."
  (interactive)
  (setq greader-queue nil)
  (setq greader-queue-current-element nil))

;; This function removes an item from the queue.
(defun greader-queue-remove-element (&optional index)
  "Remove the item in INDEX.
If INDEX is nil, use the `greader-queue-current-element' variable."
  (interactive)
  (unless index
    (setq index greader-queue-current-element))
  (when (>= index (length greader-queue))
    (user-error "Index out of range"))
  (setq greader-queue (seq-remove-at-position greader-queue index)))

;; This function gets the text linked to an element of the
;; queue.
(defun greader-queue-get-element (&optional index)
  "return the text associated with a queue item or nil if INDEX is beyond
the limit.
If INDEX is nil, use `greader-queue-current-element'."
  (unless index
    (setq index greader-queue-current-element))
  (when (equal (length greader-queue) 0)
    (user-error "Queue is emty"))
  (let ((result nil))
    (when (< greader-queue-current-element (length greader-queue))
      (setq result (buffer-substring (car (elt greader-queue index))
				     (cdr (elt
					   greader-queue
					   index)))))
    result))

;; This function returns the next item in the queue. If
;; the current element is the last one, then it returns nil.
(defun greader-queue-get-next-element ()
  "return the next item in the queue.
If the current element is the last one, then return nil."
  (unless greader-queue-current-element
    (setq greader-queue-current-element 0))
  (if (equal (1+ greader-queue-current-element) (length
						 greader-queue))
      nil
    (setq greader-queue-current-element
	  (1+ greader-queue-current-element))
    (greader-queue-get-element)))

;; This function returns the previous item in the queue, if it is
;; the first one, returns it.
(defun greader-queue-get-prev-element ()
  "Return the previous item in the queue.
If the current element is the first, it returns it."
  (unless greader-queue-current-element
    (setq greader-queue-current-element 0))
  (if (> greader-queue-current-element 0)
      (setq greader-queue-current-element (1-
					   greader-queue-current-element)))
  (greader-queue-get-element))

;; This function will act as a sentinel for the tts when invoked
;; by the `greader-queue-read' function.
(defun greader-queue-next-action (&optional _process _string)
  "Sentinel process for greader-queue-mode."
  (setq greader-queue-current-element (1+
				       greader-queue-current-element))
  (greader-queue-read))

;; This function is a reimplementation in salsa queue's
;; reader-read. The idea is to map it right in place of
;; greader-read in the `greader-queue-mode' keymap.
(defun greader-queue-read ()
  "Entry point for `greader-queue-mode'."
  (interactive)
  (let ((text (greader-queue-get-element)))
    (if text
	(progn
	  (setq-local greader-backend-action
		      #'greader-queue-next-action)
	  (greader-read-asynchronous text))
      (setq-local greader-backend-action #'greader--default-action)
      (greader-read-asynchronous "end of queue."))))

;; This function stops reading of queue.
(defun greader-queue-stop ()
  "stop reading of queue."
  (interactive)
  (setq greader-backend-action #'greader--default-action)
  (greader-tts-stop))
;; This function moves the point to the beginning of the previous element
;; in the queue and start reading.
(defun greader-queue-backward ()
  "Move the point to the beginning of the item in the queue and start the
reading.
If we are already at the first element, it makes a ding and does
nothing else."
  (interactive)
  (if (equal greader-queue-current-element 0)
      (ding)
    (greader-tts-stop)
    (setq greader-queue-current-element (1-
					 greader-queue-current-element))
    (greader-queue-read)))

;; This function moves the point to the next item in the queue and
;; reads it.
(defun greader-queue-forward ()
  "Move the point to the next item in the queue and read it.
If it is already the last item in the queue it beeps and does nothing
else."
  (if (equal greader-queue-current-element (- 1 (length
						 greader-queue)))
      (ding)
    (greader-tts-stop)
    (setq greader-queue-current-element (1+
					 greader-queue-current-element))
    (greader-queue-read)))

;; this is the keymap for greader-queue-mode.
(defvar-keymap greader-queue-mode-map
  :doc "greader-queue-mode map."
  "C-r RET" #'greader-queue-add-element
  "C-r SPC" #'greader-queue-read
  "C-r <left>" #'greader-queue-backward
  "C-r <right>" #'greader-queue-forward
  "C-r ." #'greader-queue-stop)
(defvar-local greader-greader-mode-was-active nil
  "This variable becomes t if `greader-mode' is active when
`greader-queue-mode' is enabled.
This is to avoid reactivating `greader-mode' if it wasn't active
before.")

;;;###autoload
(define-minor-mode greader-queue-mode
  "Read buffers as blocks of text.
In this mode, text reading occurs via blocks.  normally greader
reads the text of a buffer sequentially; in queue-mode you add blocks
of text to a queue, so you can choose only certain parts of the
buffer.  As reading progresses, further blocks can be added, or you
can add the blocks and then start reading."
  :lighter " greader-q"
  (cond
   (greader-queue-mode
    (when greader-mode
      (setq greader-greader-mode-was-active t)
      (greader-mode -1)))
   ((not greader-queue-mode)
    (when greader-greader-mode-was-active
      (greader-mode 1)))))

(defcustom greader-enriched-tag "link: "
  "Message to be spoken when clicking elements are encountered.
If the value is a string, that string will be used.
If it is a function, it must return a string."
  :type '(choice (string :tag "String")
                 (function :tag "function")))

(defun greader--get-enriched-tag ()
  "Return the value of `greader-enriched-tag'."
  (pcase greader-enriched-tag
    ((pred functionp)
     (with-no-warnings (funcall #'greader-enriched-tag)))
    ((pred stringp)
     greader-enriched-tag)))

(defun greader-scrap-links (input-string)
  "Modify the INPUT-STRING string to precede each link with `link: '"
  (let ((pos 0)
        (modified nil)
        (result (copy-sequence input-string)))
    ;; Search for the location of the next link.
    (while
	(setq pos (next-single-property-change pos 'mouse-face result))
      ;; Check if the location has the 'mouse-face' property set.
      (when (get-text-property pos 'mouse-face result)
        (setq modified t)
	;; Add 'link:' before the location.
        (setq result (concat (substring result 0 pos)
                             (greader--get-enriched-tag)
                             (substring result pos)))
	;; Update the search position taking into account the "link: " string we just entered.
        (setq pos (+ pos 6))))
    ;; Return the modified string if links were found.
    (if modified result input-string)))

;;;###autoload
(define-minor-mode greader-enriched-mode
  "This mode causes greader to announce clickable objects.
To configure the message with which it must be announced
the element, configure the `greader-enriched-tag' variable."
  :lighter " rich"
  :global t
  (if greader-enriched-mode
      (progn
	(unless greader-mode
	  (greader-mode 1))
	(add-hook 'greader-after-get-sentence-functions
		  #'greader-scrap-links))
    (remove-hook 'greader-after-get-sentence-functions
		 #'greader-scrap-links)))

;;greader-continuous-mode
;; In this mode, greader will try to "guess" the function in the
;; current major mode that allows you to scroll the page
;; next one.
;;To do this, it assumes that, usually, the command to switch to
;; next page or section in a buffer is associated with the space key.
;; However, it will be possible to specify via the variable
;; customizable `greader-continuous-modes' functions associated with
;; particular major modes.
(defcustom greader-continuous-modes '((nov-mode . nov-next-document))
  "Alist mapping major modes to functions for greader-continuous
guessing."
  :type '(alist :key-type (symbol :tag "mode-name") 
                :value-type (function :tag "Scroll function")))

(defcustom greader-continuous-excluded-modes ()
  "Alist mapping major modes to functions for greader-continuous guessing."
  :type '(list (symbol :tag "modes")))

(defcustom greader-continuous-key "SPC"
  "The key or key sequence from which the scroll function is to be derived."
  :type 'string)

(defun greader-continuous-guess-function ()
  "Guess the function for greader-continuous mode.
this guessing is based on GREADER-CONTINUOUS-KEY.
If GREADER-CONTINUOUS-KEY is nil, checks against
`greader-continuous-excluded-modes'
and `greader-continuous-modes' to determine the appropriate function."
  (cond
   ((member major-mode greader-continuous-excluded-modes)
    ;; If the current major mode is excluded, return nil.
    nil)
   ((assoc major-mode greader-continuous-modes)
    ;; If the current major mode is included, return the associated function.
    (cdr (assoc major-mode greader-continuous-modes)))
   ;; If a key sequence is provided, get the corresponding command.
   (greader-continuous-key
    (let ((command (key-binding (kbd greader-continuous-key))))
      ;; Return nil if the command is `self-insert-command',
      ;; otherwise return the command itself.
      (unless (eq command 'self-insert-command)
        command)))
   (t
    ;; If the major mode is not mentioned in any list, return nil.
    nil)))

;; The following is the function that will be added to
;; `greader-before-finish-functions', just in case
;; `greader-continuous-mode' is enabled.
(defun greader-continuous-call-function ()
  "Call the function returned by `greader-continuous-guess-key'.
If the `greader-continuous-guess-key` function returns nil, then
this function will return nil, otherwise it returns t. It also handles
any errors that occur during the execution of the command or
the reading process, returning nil in such cases."
  (condition-case nil
      ;; The condition-case block here is to handle any errors
      ;; that might occur in any part of the following code.
      (let ((command (greader-continuous-guess-function)))
        ;; Check if a valid command is returned.
        (when command
          ;; Calls the function returned by greader-continuous-guess-function.
	  ;; We check that the point is not at the end of the buffer.
	  (when (eobp)
	    (goto-char (- (point-max) 1)))
          (funcall command)
          (greader-read))
        t)
					; Returns t if no error occurs.
    ((debug error) nil)))
					; Returns nil in case of an error.

;; greader-continuous-mode
;; This minor-mode will take care of adding to the hook
;; `greader-before-finish-functions' the function
;; `greader-continuous-call-function'.
;; If minor-mode is deactivated, the function will be removed
;; from the hook.
(define-minor-mode greader-continuous-mode
  "This minor-mode enables autoscrolling in buffers that support it
require.
Examples are `info-mode', `nov-mode', to some extent `man-mode' etc...
When this minor-mode is active, say in `info-mode', it will be
called the `info-scroll-up' function instead of finishing reading."
  :lighter " continuous"
  (if greader-continuous-mode
      (progn
	(greader-study-mode -1)
	(unless (greader-continuous-guess-function)
	  (let ((error-string
		 (concat
		  "I can't determine the function for
scroll in "
		  (symbol-name major-mode) ".\nPlease add
this major mode to the variable `greader-continuous-modes'")))
	    (greader-continuous-mode -1)
	    (user-error "%s" error-string)))
	(add-hook 'greader-before-finish-functions
		  #'greader-continuous-call-function 0 t))
    (remove-hook 'greader-before-finish-functions
		 #'greader-continuous-call-function t)))
;; greader-study-mode
;; This is the complementary mode of "greader-continuous-mode", and
;; is used to repeatedly read the contents of a buffer or part of
;; it.
(defvar-local greader-study-start-position 1
  "The buffer position in which restart of reading will happen.")

;; greader-study-restart is the function that will be added to the hook
;; `greader-before-finish-functions'.
;; The function simply returns to the beginning of the buffer or the
;; active region and runs `greader-read'.
(defun greader-study-restart ()
  "restart reading of buffer or region."
  (if greader-region-mode
      (goto-char (region-beginning))
    (goto-char greader-study-start-position))
  (greader-read) t)

;; greader-study-mode
(define-minor-mode greader-study-mode
  "In study-mode, reading of buffer will restart continuously.
If `greader-region-mode' is enabled, restart will behave accordingly."
  :lighter " study"
  (if greader-study-mode
      (progn
	(greader-continuous-mode -1)
	(add-hook 'greader-before-finish-functions
		  #'greader-study-restart 0 t))
    (remove-hook 'greader-before-finish-functions
		 #'greader-study-restart t)))

;;;###autoload
(defun greader-study-set-position (pos)
  "Set the position in which reading will restart.
When called interactively, use the current position in the buffer.
If `greader-study-mode' is not enabled, enable it first."
  (interactive "d")
  (unless greader-study-mode
    (greader-study-mode 1))
  (cond
   ((not pos)
    (user-error "Position must be a positive integer"))
   ((< pos 1)
    (user-error "position is not valid")))
  (setq greader-study-start-position pos))

;; Estimated reading time calculation.
(defvar-local greader--buffer-words nil
  "Total buffer words.")
(defcustom greader-reading-time-adjustment 10
  "Percentage adjustment to add to the estimated reading time.
This value is added as a percentage to the calculated reading time."
  :type 'integer
  :group 'greader)

(defun greader--estimated-reading-time (&optional start end)
  "Calculate the estimated reading time between START and END, based
on your reading speed in WPM (words per minute).
The selected back-end must support `rate' command.
If START or END is not provided, consider the entire buffer.

The reading time is adjusted by a percentage specified in
`greader-reading-time-adjustment`."
  (if-let* ((wpm (and (numberp (greader-get-rate))
                      (greader-get-rate))))
      (progn
        (setq greader--buffer-words (if greader--buffer-words
                                        greader--buffer-words
                                      (count-words (or start (point-min))
                                                   (or end (point-max)))))
        (let* ((total-minutes (/ (* 1.0 greader--buffer-words) wpm))
               (total-seconds (round (* total-minutes 60)))
               ;; Aggiungi la percentuale configurabile
               (adjusted-seconds (round (* total-seconds
                                           (+ 1.0 (/ greader-reading-time-adjustment 100.0)))))
               (hours (/ adjusted-seconds 3600))
               (minutes (/ (% adjusted-seconds 3600) 60))
               (seconds (% adjusted-seconds 60)))
          (list (propertize (format "%02d:%02d:%02d" hours minutes seconds)
                            'greader-estimated-time t)
                `(,hours ,minutes ,seconds))))
    nil))


(defun greader--estimated-reading-time-remove ()
  "Remove estimated-time banner from the mode line."
  (catch 'banner-found
    (dolist (elt mode-line-misc-info)
      (if (listp elt)
	  (let ((line (cadr elt)))
	    (and
	     (equal (car elt) :propertize)
	     (text-property-any 0 (- (length line) 1)
				'greader-estimated-time t line)
	     (setq-local mode-line-misc-info (delete elt
						     mode-line-misc-info))))
	(throw 'banner-found t))
      nil)))
(declare-function dtk-speak nil)
(defun greader-estimated-time-update ()
  "update of estimated reading time.
new data is stored in the mode-line.
The calculation is made from point to end of the buffer.
If the region is active, use it."
  (interactive)
  (setq greader--buffer-words nil)
  (greader--estimated-reading-time-remove)
  (let ((region-beginning
	 (if (region-active-p) (region-beginning) (point)))
	(region-end
	 (if (region-active-p) (region-end) (point-max))))
    (add-to-list 'mode-line-misc-info (list :propertize (car (greader--estimated-reading-time
							      region-beginning region-end))
					    'greader-estimated-time
					    t))
    (when (and (featurep 'emacspeak) (called-interactively-p 'any))
      (dtk-speak (car (greader--estimated-reading-time)))))
  (force-mode-line-update))

;;;###autoload
(define-minor-mode greader-estimated-time-mode
  "keep mode line updated in respect of remaining reading time.
This mode updates the mode line on certain events, such as when pass
to the next sentence, or when you stop the reading."
  :lighter " "
  (if greader-estimated-time-mode
      (progn
	(add-hook 'greader-before-read-hook
		  #'greader-estimated-time-update)
	(add-hook 'greader-after-stop-hook
		  #'greader-estimated-time-update))
    (remove-hook 'greader-before-read-hook 'greader-estimated-time-update)
    (remove-hook 'greader-after-stop-hook
		 'greader-estimated-time-update)
    (greader--estimated-reading-time-remove))
  (force-mode-line-update))



(defun greader-set-map-prefix (keys)
  "Set `greader-keymap-prefix' to KEYS for the current session."
  (interactive "kSet greader prefix to: ")
  (let ((key-str (key-description keys)))
    (define-key greader-mode-map (kbd greader-keymap-prefix) nil)
    (setq greader-keymap-prefix key-str)
    (define-key greader-mode-map (kbd greader-keymap-prefix) greader-prefix-keymap)
    (message "greader prefix set to %s for the current session." key-str)))

(define-obsolete-function-alias 'greader-toggle-timer
  'greader-timer-mode "0.16")
(define-obsolete-function-alias 'greader-toggle-tired-mode
  'greader-tired-mode "0.16")
(define-obsolete-function-alias 'greader-toggle-auto-tired-mode
  'greader-auto-tired-mode "0.16")

(provide 'greader)
;;; greader.el ends here