~bzg/worg

ref: dea41fec71017fb96e1ba4e408cf900ed0c8bbf4 worg/org-hacks.org -rw-r--r-- 151.2 KiB
dea41fecRussell Adams Updated expectations for non-subscriber posts to be delayed by moderation. 6 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
#+TITLE:      Org ad hoc code, quick hacks and workarounds
#+AUTHOR:     Worg people
#+OPTIONS:    H:3 num:nil toc:t \n:nil ::t |:t ^:t -:t f:t *:t tex:t d:(HIDE) tags:not-in-toc
#+STARTUP:    align fold nodlcheck hidestars oddeven lognotestate
#+SEQ_TODO:   TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
#+TAGS:       Write(w) Update(u) Fix(f) Check(c)
#+LANGUAGE:   en
#+PRIORITIES: A C B
#+CATEGORY:   worg
#+HTML_LINK_UP:    index.html
#+HTML_LINK_HOME:  https://orgmode.org/worg/

# This file is released by its authors and contributors under the GNU
# Free Documentation license v1.3 or later, code examples are released
# under the GNU General Public License v3 or later.

# This file is the default header for new Org files in Worg.  Feel free
# to tailor it to your needs.

This page is for ad hoc bits of code. Feel free to add quick hacks and
workaround. Go crazy.

* Hacking Org: Working within Org-mode
** Org Agenda

*** Colorize clocking tasks with a block
:PROPERTIES:
:DIR:      /home/stardiviner/Code/Emacs/worg/images/agenda/
:END:

Show Org Agenda tasks with heigh spacing based on clock time with ~org-agenda-log-mode~.

[[file:images/agenda/org-agenda-colorized-blocks.png]]

Here is original author's post https://emacs-china.org/t/org-agenda/8679.

Here is a hook function to use archive this effect:

#+begin_src emacs-lisp
;; work with org-agenda dispatcher [c] "Today Clocked Tasks" to view today's clocked tasks.
(defun org-agenda-log-mode-colorize-block ()
  "Set different line spacing based on clock time duration."
  (save-excursion
    (let* ((colors (cl-case (alist-get 'background-mode (frame-parameters))
		                 ('light
		                  (list "#F6B1C3" "#FFFF9D" "#BEEB9F" "#ADD5F7"))
		                 ('dark
		                  (list "#aa557f" "DarkGreen" "DarkSlateGray" "DarkSlateBlue"))))
           pos
           duration)
      (nconc colors colors)
      (goto-char (point-min))
      (while (setq pos (next-single-property-change (point) 'duration))
        (goto-char pos)
        (when (and (not (equal pos (point-at-eol)))
                   (setq duration (org-get-at-bol 'duration)))
          ;; larger duration bar height
          (let ((line-height (if (< duration 15) 1.0 (+ 0.5 (/ duration 30))))
                (ov (make-overlay (point-at-bol) (1+ (point-at-eol)))))
            (overlay-put ov 'face `(:background ,(car colors) :foreground "black"))
            (setq colors (cdr colors))
            (overlay-put ov 'line-height line-height)
            (overlay-put ov 'line-spacing (1- line-height))))))))

(add-hook 'org-agenda-finalize-hook #'org-agenda-log-mode-colorize-block)
#+end_src

*** Picking up a random task in the global TODO list

Tony day [[http://mid.gmane.org/m2zk19l1me.fsf@gmail.com][shared]] [[https://gist.github.com/4343164][this gist]] to pick up a
random task.

** Building and Managing Org
*** Generating autoloads and Compiling Org without make
    :PROPERTIES:
    :CUSTOM_ID: compiling-org-without-make
    :END:

#+index: Compilation!without make

  Compilation is optional, but you _must_ update the autoloads file
  each time you update org, even when you run org uncompiled!

  Starting with Org 7.9 you'll find functions for creating the
  autoload files and do byte-compilation in =mk/org-fixup.el=.  When
  you execute the commands below, your current directory must be where
  org has been unpacked into, in other words the file =README= should
  be found in your current directory and the directories =lisp= and
  =etc= should be subdirectories of it.  The command =emacs= should be
  found in your =PATH= and start the Emacs version you are using.  To
  make just the autoloads file do:
  : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads
  To make the autoloads file and byte-compile org:
  : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile
  To make the autoloads file and byte-compile all of org again:
  : emacs -batch -Q -L lisp -l ../mk/org-fixup -f org-make-autoloads-compile-force
  If you are not using Git, you'll have to make fake version strings
  first if =org-version.el= is not already available (if it is, you
  could also edit the version strings there).
  : emacs -batch -Q -L lisp -l ../mk/org-fixup \
  : --eval '(let ((org-fake-release "7.9.1")(org-fake-git-version "7.9.1-fake"))\
  : (org-make-autoloads))'
  The above assumes a
  POSIX shell for its quoting.  Windows =CMD.exe= has quite different
  quoting rules and this won't work, so your other option is to start
  Emacs like this
  : emacs -Q -L lisp -l ../mk/org-fixup
  then paste the following into the =*scratch*= buffer
#+BEGIN_SRC emacs-lisp
  (let ((org-fake-release     "7.9.1")
        (org-fake-git-version "7.9.1-fake"))
    (org-make-autoloads))
#+END_SRC
  position the cursor after the closing paren and press =C-j= or =C-x
  C-e= to evaluate the form.  Of course you can replace
  =org-make-autoloads= with =org-make-autoloads-compile= or even
  =org-make-autoloads-compile-force= if you wish with both variants.

  For *older org versions only* (that do not yet have
  =mk/org-fixup.el=), you can use the definitions below.  To use
  this function, adjust the variables =my/org-lisp-directory= and
  =my/org-compile-sources= to suit your needs.  If you have
  byte-compiled org, but want to run org uncompiled again, just remove
  all =*.elc= files in the =lisp/= directory, set
  =my/org-compile-sources= to =nil=.

#+BEGIN_SRC emacs-lisp
  (defvar my/org-lisp-directory "~/.emacs.d/org/lisp/"
    "Directory where your org-mode files live.")

  (defvar my/org-compile-sources t
    "If `nil', never compile org-sources. `my/compile-org' will only create
  the autoloads file `org-loaddefs.el' then. If `t', compile the sources, too.")

  ;; Customize: (must end with a slash!)
  (setq my/org-lisp-directory "~/.emacs.d/org/lisp/")

  ;; Customize:
  (setq  my/org-compile-sources t)

  (defun my/compile-org(&optional directory)
    "Generate autoloads file org-loaddefs.el.  Optionally compile
     all *.el files that come with org-mode."
    (interactive)
    (defun my/compile-org()
      "Generate autoloads file org-loaddefs.el.  Optionally compile
       all *.el files that come with org-mode."
      (interactive)
      (let ((dirlisp (file-name-directory my/org-lisp-directory)))
        (add-to-list 'load-path dirlisp)
        (require 'autoload)
        (let ((generated-autoload-file (concat dirlisp "org-loaddefs.el")))
          ;; create the org-loaddefs file
          (update-directory-autoloads dirlisp)
          (when my/org-compile-sources
            ;; optionally byte-compile
            (byte-recompile-directory dirlisp 0 'force)))))
  #+END_SRC
*** Reload Org

#+index: Initialization!Reload

As of Org version 6.23b (released Sunday Feb 22, 2009) there is a new
function to reload org files.

Normally you want to use the compiled files since they are faster.
If you update your org files you can easily reload them with

: M-x org-reload

If you run into a bug and want to generate a useful backtrace you can
reload the source files instead of the compiled files with

: C-u M-x org-reload

and turn on the "Enter Debugger On Error" option.  Redo the action
that generates the error and cut and paste the resulting backtrace.
To switch back to the compiled version just reload again with

: M-x org-reload

*** Check for possibly problematic old link escapes
:PROPERTIES:
:CUSTOM_ID: check-old-link-escapes
:END:
#+index: Link!Escape
Starting with version 7.5 Org uses [[https://en.wikipedia.org/wiki/Percent-encoding][percent escaping]] more consistently
and with a modified algorithm to determine which characters to escape
and how.

As a side effect this modified behaviour might break existing links if
they contain a sequence of characters that look like a percent escape
(e.g. =[0-9A-Fa-f]{2}=) but are in fact not a percent escape.

The function below can be used to perform a preliminary check for such
links in an Org mode file.  It will run through all links in the file
and issue a warning if it finds a percent escape sequence which is not
in old Org's list of known percent escapes.

#+begin_src emacs-lisp
  (defun dmaus/org-check-percent-escapes ()
    "*Check buffer for possibly problematic old link escapes."
    (interactive)
    (when (eq major-mode 'org-mode)
      (let ((old-escapes '("%20" "%5B" "%5D" "%E0" "%E2" "%E7" "%E8" "%E9"
                           "%EA" "%EE" "%F4" "%F9" "%FB" "%3B" "%3D" "%2B")))
        (unless (boundp 'warning-suppress-types)
          (setq warning-suppress-types nil))
        (widen)
        (show-all)
        (goto-char (point-min))
        (while (re-search-forward org-any-link-re nil t)
          (let ((end (match-end 0)))
            (goto-char (match-beginning 0))
            (while (re-search-forward "%[0-9a-zA-Z]\\{2\\}" end t)
              (let ((escape (match-string-no-properties 0)))
                (unless (member (upcase escape) old-escapes)
                  (warn "Found unknown percent escape sequence %s at buffer %s, position %d"
                        escape
                        (buffer-name)
                        (- (point) 3)))))
            (goto-char end))))))
#+end_src

** Structure Movement and Editing
*** Go back to the previous top-level heading

#+BEGIN_SRC emacs-lisp
(defun org-back-to-top-level-heading ()
  "Go back to the current top level heading."
  (interactive)
  (or (re-search-backward "^\* " nil t)
      (goto-char (point-min))))
#+END_SRC

*** Go to a child of the current heading
    :PROPERTIES:
    :CUSTOM_ID: org-jump-to-child
    :END:
#+index: Navigation!Heading
- [[http://langec.wordpress.com][Christoph Lange]]

=org-jump-to-child= in [[file:code/elisp/org-jump.el::(defun org-jump-to-child][org-jump.el]] (keybinding suggested there: =C-c o c=) interactively prompts for the title of a child node, i.e. sub-heading, of the current heading and jumps to the child node having that title (in case of ambiguity: the /last/ such node).

In the absence of a readily accessible structural representation of the tree outline, this is ipmlemented by walking over all child nodes and collecting their titles and their positions in the file.

*** Go to a heading by its ID (=CUSTOM_ID= property)
    :PROPERTIES:
    :CUSTOM_ID: org-jump-to-id
    :END:
#+index: Navigation!Heading
- [[http://langec.wordpress.com][Christoph Lange]]

=org-jump-to-id= in [[file:code/elisp/org-jump.el::(defun org-jump-to-id][org-jump.el]] (keybinding suggested there: =C-c o j=) interactively prompts for the one of the =CUSTOM_ID= property values in the current document and jumps to the [first] node that has this ID.

This implementation works efficiently in a 5 MB org file with 100 IDs. Together with ido or helm I find it a very user-friendly way of jumping to frequently used headings.

I noticed that =org-babel-ref-goto-headline-id= does something similar, so maybe some code could be shared among the two functions.
*** Show next/prev heading tidily

#+index: Navigation!Heading
- Dan Davison
  These close the current heading and open the next/previous heading.

#+begin_src emacs-lisp
(defun ded/org-show-next-heading-tidily ()
  "Show next entry, keeping other entries closed."
  (if (save-excursion (end-of-line) (outline-invisible-p))
      (progn (org-show-entry) (show-children))
    (outline-next-heading)
    (unless (and (bolp) (org-on-heading-p))
      (org-up-heading-safe)
      (hide-subtree)
      (error "Boundary reached"))
    (org-overview)
    (org-reveal t)
    (org-show-entry)
    (show-children)))

(defun ded/org-show-previous-heading-tidily ()
  "Show previous entry, keeping other entries closed."
  (let ((pos (point)))
    (outline-previous-heading)
    (unless (and (< (point) pos) (bolp) (org-on-heading-p))
      (goto-char pos)
      (hide-subtree)
      (error "Boundary reached"))
    (org-overview)
    (org-reveal t)
    (org-show-entry)
    (show-children)))

(setq org-use-speed-commands t)
(add-to-list 'org-speed-commands-user
             '("n" ded/org-show-next-heading-tidily))
(add-to-list 'org-speed-commands-user
             '("p" ded/org-show-previous-heading-tidily))
#+end_src

*** Promote all items in subtree
#+index: Structure Editing!Promote
- Matt Lundin

This function will promote all items in a subtree. Since I use
subtrees primarily to organize projects, the function is somewhat
unimaginatively called my-org-un-project:

#+begin_src emacs-lisp
(defun my-org-un-project ()
  (interactive)
  (org-map-entries 'org-do-promote "LEVEL>1" 'tree)
  (org-cycle t))
#+end_src

*** Turn a heading into an Org link
    :PROPERTIES:
    :CUSTOM_ID: heading-to-link
    :END:
#+index: Structure Editing!Heading
#+index: Link!Turn a heading into a
From David Maus:

#+begin_src emacs-lisp
  (defun dmj:turn-headline-into-org-mode-link ()
    "Replace word at point by an Org mode link."
    (interactive)
    (when (org-at-heading-p)
      (let ((hl-text (nth 4 (org-heading-components))))
        (unless (or (null hl-text)
                    (org-string-match-p "^[ \t]*:[^:]+:$" hl-text))
          (beginning-of-line)
          (search-forward hl-text (point-at-eol))
          (replace-string
           hl-text
           (format "[[file:%s.org][%s]]"
                   (org-link-escape hl-text)
                   (org-link-escape hl-text '((?\] . "%5D") (?\[ . "%5B"))))
           nil (- (point) (length hl-text)) (point))))))
#+end_src

*** Using M-up and M-down to transpose paragraphs
#+index: Structure Editing!paragraphs

From Paul Sexton: By default, if used within ordinary paragraphs in
org mode, =M-up= and =M-down= transpose *lines* (not sentences).  The
following code makes these keys transpose paragraphs, keeping the
point at the start of the moved paragraph. Behavior in tables and
headings is unaffected. It would be easy to modify this to transpose
sentences.

#+begin_src emacs-lisp
(defun org-transpose-paragraphs (arg)
 (interactive)
 (when (and (not (or (org-at-table-p) (org-on-heading-p) (org-at-item-p)))
            (thing-at-point 'sentence))
   (transpose-paragraphs arg)
   (backward-paragraph)
   (re-search-forward "[[:graph:]]")
   (goto-char (match-beginning 0))
   t))

(add-to-list 'org-metaup-hook
 (lambda () (interactive) (org-transpose-paragraphs -1)))
(add-to-list 'org-metadown-hook
 (lambda () (interactive) (org-transpose-paragraphs 1)))
#+end_src
*** Changelog support for org headers
#+index: Structure Editing!Heading
-- James TD Smith

Put the following in your =.emacs=, and =C-x 4 a= and other functions which
use =add-log-current-defun= like =magit-add-log= will pick up the nearest org
headline as the "current function" if you add a changelog entry from an org
buffer.

#+BEGIN_SRC emacs-lisp
  (defun org-log-current-defun ()
    (save-excursion
      (org-back-to-heading)
      (if (looking-at org-complex-heading-regexp)
          (match-string 4))))

  (add-hook 'org-mode-hook
            (lambda ()
              (make-variable-buffer-local 'add-log-current-defun-function)
              (setq add-log-current-defun-function 'org-log-current-defun)))
#+END_SRC

*** Different org-cycle-level behavior
#+index: Cycling!behavior
-- Ryan Thompson

In recent org versions, when your point (cursor) is at the end of an
empty header line (like after you first created the header), the TAB
key (=org-cycle=) has a special behavior: it cycles the headline through
all possible levels. However, I did not like the way it determined
"all possible levels," so I rewrote the whole function, along with a
couple of supporting functions.

The original function's definition of "all possible levels" was "every
level from 1 to one more than the initial level of the current
headline before you started cycling." My new definition is "every
level from 1 to one more than the previous headline's level." So, if
you have a headline at level 4 and you use ALT+RET to make a new
headline below it, it will cycle between levels 1 and 5, inclusive.

The main advantage of my custom =org-cycle-level= function is that it
is stateless: the next level in the cycle is determined entirely by
the contents of the buffer, and not what command you executed last.
This makes it more predictable, I hope.

#+BEGIN_SRC emacs-lisp
(require 'cl)

(defun org-point-at-end-of-empty-headline ()
  "If point is at the end of an empty headline, return t, else nil."
  (and (looking-at "[ \t]*$")
       (save-excursion
         (beginning-of-line 1)
         (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))))

(defun org-level-increment ()
  "Return the number of stars that will be added or removed at a
time to headlines when structure editing, based on the value of
`org-odd-levels-only'."
  (if org-odd-levels-only 2 1))

(defvar org-previous-line-level-cached nil)

(defun org-recalculate-previous-line-level ()
  "Same as `org-get-previous-line-level', but does not use cached
value. It does *set* the cached value, though."
  (set 'org-previous-line-level-cached
       (let ((current-level (org-current-level))
             (prev-level (when (> (line-number-at-pos) 1)
                           (save-excursion
                             (previous-line)
                             (org-current-level)))))
         (cond ((null current-level) nil) ; Before first headline
               ((null prev-level) 0)      ; At first headline
               (prev-level)))))

(defun org-get-previous-line-level ()
  "Return the outline depth of the last headline before the
current line. Returns 0 for the first headline in the buffer, and
nil if before the first headline."
  ;; This calculation is quite expensive, with all the regex searching
  ;; and stuff. Since org-cycle-level won't change lines, we can reuse
  ;; the last value of this command.
  (or (and (eq last-command 'org-cycle-level)
           org-previous-line-level-cached)
      (org-recalculate-previous-line-level)))

(defun org-cycle-level ()
  (interactive)
  (let ((org-adapt-indentation nil))
    (when (org-point-at-end-of-empty-headline)
      (setq this-command 'org-cycle-level) ;Only needed for caching
      (let ((cur-level (org-current-level))
            (prev-level (org-get-previous-line-level)))
        (cond
         ;; If first headline in file, promote to top-level.
         ((= prev-level 0)
          (loop repeat (/ (- cur-level 1) (org-level-increment))
                do (org-do-promote)))
         ;; If same level as prev, demote one.
         ((= prev-level cur-level)
          (org-do-demote))
         ;; If parent is top-level, promote to top level if not already.
         ((= prev-level 1)
          (loop repeat (/ (- cur-level 1) (org-level-increment))
                do (org-do-promote)))
         ;; If top-level, return to prev-level.
         ((= cur-level 1)
          (loop repeat (/ (- prev-level 1) (org-level-increment))
                do (org-do-demote)))
         ;; If less than prev-level, promote one.
         ((< cur-level prev-level)
          (org-do-promote))
         ;; If deeper than prev-level, promote until higher than
         ;; prev-level.
         ((> cur-level prev-level)
          (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
                do (org-do-promote))))
        t))))
#+END_SRC

*** Count words in an Org buffer
# FIXME: Does not fit too well under Structure. Any idea where to put it?
Paul Sexton [[https://list.orgmode.org/loom.20110220T224023-532@post.gmane.org][posted]] this function to count words in an Org buffer:

#+begin_src emacs-lisp
(defun org-word-count (beg end
                           &optional count-latex-macro-args?
                           count-footnotes?)
  "Report the number of words in the Org mode buffer or selected region.
Ignores:
- comments
- tables
- source code blocks (#+BEGIN_SRC ... #+END_SRC, and inline blocks)
- hyperlinks (but does count words in hyperlink descriptions)
- tags, priorities, and TODO keywords in headers
- sections tagged as 'not for export'.

The text of footnote definitions is ignored, unless the optional argument
COUNT-FOOTNOTES? is non-nil.

If the optional argument COUNT-LATEX-MACRO-ARGS? is non-nil, the word count
includes LaTeX macro arguments (the material between {curly braces}).
Otherwise, and by default, every LaTeX macro counts as 1 word regardless
of its arguments."
  (interactive "r")
  (unless mark-active
    (setf beg (point-min)
	  end (point-max)))
  (let ((wc 0)
	(latex-macro-regexp "\\\\[A-Za-z]+\\(\\[[^]]*\\]\\|\\){\\([^}]*\\)}"))
    (save-excursion
      (goto-char beg)
      (while (< (point) end)
        (cond
         ;; Ignore comments.
         ((or (org-in-commented-line) (org-at-table-p))
          nil)
         ;; Ignore hyperlinks. But if link has a description, count
         ;; the words within the description.
         ((looking-at org-bracket-link-analytic-regexp)
          (when (match-string-no-properties 5)
            (let ((desc (match-string-no-properties 5)))
              (save-match-data
                (incf wc (length (remove "" (org-split-string
                                             desc "\\W")))))))
          (goto-char (match-end 0)))
         ((looking-at org-any-link-re)
          (goto-char (match-end 0)))
         ;; Ignore source code blocks.
         ((org-in-regexps-block-p "^#\\+BEGIN_SRC\\W" "^#\\+END_SRC\\W")
          nil)
         ;; Ignore inline source blocks, counting them as 1 word.
         ((save-excursion
            (backward-char)
            (looking-at org-babel-inline-src-block-regexp))
          (goto-char (match-end 0))
          (setf wc (+ 2 wc)))
         ;; Count latex macros as 1 word, ignoring their arguments.
         ((save-excursion
            (backward-char)
            (looking-at latex-macro-regexp))
          (goto-char (if count-latex-macro-args?
                         (match-beginning 2)
                       (match-end 0)))
          (setf wc (+ 2 wc)))
         ;; Ignore footnotes.
         ((and (not count-footnotes?)
               (or (org-footnote-at-definition-p)
                   (org-footnote-at-reference-p)))
          nil)
         (t
          (let ((contexts (org-context)))
            (cond
             ;; Ignore tags and TODO keywords, etc.
             ((or (assoc :todo-keyword contexts)
                  (assoc :priority contexts)
                  (assoc :keyword contexts)
                  (assoc :checkbox contexts))
              nil)
             ;; Ignore sections marked with tags that are
             ;; excluded from export.
             ((assoc :tags contexts)
              (if (intersection (org-get-tags-at) org-export-exclude-tags
                                :test 'equal)
                  (org-forward-same-level 1)
                nil))
             (t
              (incf wc))))))
        (re-search-forward "\\w+\\W*")))
    (message (format "%d words in %s." wc
                     (if mark-active "region" "buffer")))))
#+end_src

*** Check for misplaced SCHEDULED and DEADLINE cookies
  :PROPERTIES:
  :CUSTOM_ID: check-for-misplaced-timestamps
  :END:

The =SCHEDULED= and =DEADLINE= cookies should be used on the line *right
below* the headline -- like this:

#+begin_src org
,* A headline
  SCHEDULED: <2012-04-09 lun.>
#+end_src

This is what =org-scheduled= and =org-deadline= (and other similar
commands) do.  And the manual explicitely tell people to stick to this
format (see the section "8.3.1 Inserting deadlines or schedules").

If you think you might have subtrees with misplaced =SCHEDULED= and
=DEADLINE= cookies, this command lets you check the current buffer:

#+begin_src emacs-lisp
(defun org-check-misformatted-subtree ()
  "Check misformatted entries in the current buffer."
  (interactive)
  (show-all)
  (org-map-entries
   (lambda ()
     (when (and (move-beginning-of-line 2)
		(not (looking-at org-heading-regexp)))
       (if (or (and (org-get-scheduled-time (point))
		    (not (looking-at (concat "^.*" org-scheduled-regexp))))
	       (and (org-get-deadline-time (point))
		    (not (looking-at (concat "^.*" org-deadline-regexp)))))
	   (when (y-or-n-p "Fix this subtree? ")
	     (message "Call the function again when you're done fixing this subtree.")
	     (recursive-edit))
	 (message "All subtrees checked."))))))
#+end_src

*** Sorting list by checkbox type

#+index: checkbox!sorting

You can use a custom function to sort list by checkbox type.
Here is a function suggested by Carsten:

#+BEGIN_SRC emacs-lisp
(defun org-sort-list-by-checkbox-type ()
  "Sort list items according to Checkbox state."
  (interactive)
  (org-sort-list
   nil ?f
   (lambda ()
     (if (looking-at org-list-full-item-re)
	 (cdr (assoc (match-string 3)
		     '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
       4))))
#+END_SRC

Use the function above directly on the list.  If you want to use an
equivalent function after =C-c ^ f=, use this one instead:

#+BEGIN_SRC emacs-lisp
  (defun org-sort-list-by-checkbox-type-1 ()
    (lambda ()
      (if (looking-at org-list-full-item-re)
          (cdr (assoc (match-string 3)
                      '(("[X]" . 1) ("[-]" . 2) ("[ ]" . 3) (nil . 4))))
        4)))
#+END_SRC

*** Adding Licenses to org files

You can add pretty standard licenses, such as creative commons or gfdl
to org articles using =org-license.el=.

** Org Table
   :PROPERTIES:
   :CUSTOM_ID: Tables
   :END:

*** Align all tables in a file
  :PROPERTIES:
  :CUSTOM_ID: align-tables-in-file
  :END:

Andrew Young provided this function in [[https://list.orgmode.org/502F4EDF.3080800@wilkesley.net][this thread]]:

#+begin_src emacs-lisp
  (defun my-align-all-tables ()
    (interactive)
    (org-table-map-tables 'org-table-align 'quietly))
#+end_src

*** Transpose table
    :PROPERTIES:
    :CUSTOM_ID: transpose-table
    :END:
#+index: Table!Calculation

Since Org 7.8, you can use =org-table-transpose-table-at-point= (which
see.)  There are also other solutions:

- with org-babel and Emacs Lisp: provided by Thomas S. Dye in the mailing
  list, see [[https://list.orgmode.org/4BBCE264.3000407@alumni.ethz.ch][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00239.html][gnu]]

- with org-babel and R: provided by Dan Davison in the mailing list (old
  =#+TBLR:= syntax), see [[https://list.orgmode.org/20081230193550.GA7961@stats.ox.ac.uk][gmane]] or [[http://lists.gnu.org/archive/html/emacs-orgmode/2008-12/msg00454.html][gnu]]

- with field coordinates in formulas (=@#= and =$#=): see [[#field-coordinates-in-formulas-transpose-table][Worg]].

*** Manipulate hours/minutes/seconds in table formulas
#+index: Table!hours-minutes-seconds
Both Bastien and Martin Halder have posted code ([[https://list.orgmode.org/00BD91C6-C610-4CDD-B3E0-E9FECDAA372C@gmail.com][Bastien's code]] and
[[https://list.orgmode.org/00BD91C6-C610-4CDD-B3E0-E9FECDAA372C@gmail.com][Martin's code]]) for interpreting =dd:dd= or =dd:dd:dd= strings (where
"=d=" is any digit) as time values in Org-mode table formula.  These
functions have now been wrapped up into a =with-time= macro which can
be used in table formula to translate table cell values to and from
numerical values for algebraic manipulation.

Here is the code implementing this macro.
#+begin_src emacs-lisp :results silent
  (defun org-time-string-to-seconds (s)
    "Convert a string HH:MM:SS to a number of seconds."
    (cond
     ((and (stringp s)
           (string-match "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
      (let ((hour (string-to-number (match-string 1 s)))
            (min (string-to-number (match-string 2 s)))
            (sec (string-to-number (match-string 3 s))))
        (+ (* hour 3600) (* min 60) sec)))
     ((and (stringp s)
           (string-match "\\([0-9]+\\):\\([0-9]+\\)" s))
      (let ((min (string-to-number (match-string 1 s)))
            (sec (string-to-number (match-string 2 s))))
        (+ (* min 60) sec)))
     ((stringp s) (string-to-number s))
     (t s)))

  (defun org-time-seconds-to-string (secs)
    "Convert a number of seconds to a time string."
    (cond ((>= secs 3600) (format-seconds "%h:%.2m:%.2s" secs))
          ((>= secs 60) (format-seconds "%m:%.2s" secs))
          (t (format-seconds "%s" secs))))

  (defmacro with-time (time-output-p &rest exprs)
    "Evaluate an org-table formula, converting all fields that look
  like time data to integer seconds.  If TIME-OUTPUT-P then return
  the result as a time value."
    (list
     (if time-output-p 'org-time-seconds-to-string 'identity)
     (cons 'progn
           (mapcar
            (lambda (expr)
              `,(cons (car expr)
                      (mapcar
                       (lambda (el)
                         (if (listp el)
                             (list 'with-time nil el)
                           (org-time-string-to-seconds el)))
                       (cdr expr))))
            `,@exprs))))
#+end_src

Which allows the following forms of table manipulation such as adding
and subtracting time values.
: | Date             | Start | Lunch |  Back |   End |  Sum |
: |------------------+-------+-------+-------+-------+------|
: | [2011-03-01 Tue] |  8:00 | 12:00 | 12:30 | 18:15 | 9:45 |
: #+TBLFM: $6='(with-time t (+ (- $5 $4) (- $3 $2)))

and dividing time values by integers
: |  time | miles | minutes/mile |
: |-------+-------+--------------|
: | 34:43 |   2.9 |        11:58 |
: | 32:15 |  2.77 |        11:38 |
: | 33:56 |   3.0 |        11:18 |
: | 52:22 |  4.62 |        11:20 |
: #+TBLFM: $3='(with-time t (/ $1 $2))

*Update*: As of Org version 7.6, you can use the =T= flag (both in Calc and
Elisp formulas) to compute time durations.  For example:

: | Task 1 | Task 2 |   Total |
: |--------+--------+---------|
: |  35:00 |  35:00 | 1:10:00 |
: #+TBLFM: @2$3=$1+$2;T

*** Dates computation
#+index: Table!dates
Xin Shi [[https://list.orgmode.org/5236d6f90907211206y20951c9dtc711cf71afc520e2@mail.gmail.com][asked]] for a way to calculate the duration of
dates stored in an org table.

Nick Dokos [[https://list.orgmode.org/10926.1248205548@alphaville.usa.hp.com][suggested]]:

Try the following:

: | Start Date |   End Date | Duration |
: |------------+------------+----------|
: | 2004.08.07 | 2005.07.08 |      335 |
: #+TBLFM: $3=(date(<$2>)-date(<$1>))

See [[https://list.orgmode.org/17380.1218757692@alphaville.usa.hp.com][this thread]] as well as [[https://list.orgmode.org/48A5BADA.4070507@cs.tu-berlin.de][this post]] (which is really a followup on the
above).  The problem that this last article pointed out was solved in [[https://list.orgmode.org/18981.1220565299@alphaville.usa.hp.com][this
post]] and Chris Randle's original musings are [[https://list.orgmode.org/00be01c8a9f4$a310ca00$6580a8c0@CUBE][here]].

*** Hex computation
#+index: Table!Calculation
As with Times computation, the following code allows Computation with
Hex values in Org-mode tables using the =with-hex= macro.

Here is the code implementing this macro.
#+begin_src emacs-lisp
  (defun org-hex-strip-lead (str)
    (if (and (> (length str) 2) (string= (substring str 0 2) "0x"))
        (substring str 2) str))

  (defun org-hex-to-hex (int)
    (format "0x%x" int))

  (defun org-hex-to-dec (str)
    (cond
     ((and (stringp str)
           (string-match "\\([0-9a-f]+\\)" (setf str (org-hex-strip-lead str))))
      (let ((out 0))
        (mapc
         (lambda (ch)
           (setf out (+ (* out 16)
                        (if (and (>= ch 48) (<= ch 57)) (- ch 48) (- ch 87)))))
         (coerce (match-string 1 str) 'list))
        out))
     ((stringp str) (string-to-number str))
     (t str)))

  (defmacro with-hex (hex-output-p &rest exprs)
    "Evaluate an org-table formula, converting all fields that look
      like hexadecimal to decimal integers.  If HEX-OUTPUT-P then
      return the result as a hex value."
    (list
     (if hex-output-p 'org-hex-to-hex 'identity)
     (cons 'progn
           (mapcar
            (lambda (expr)
              `,(cons (car expr)
                      (mapcar (lambda (el)
                                (if (listp el)
                                    (list 'with-hex nil el)
                                  (org-hex-to-dec el)))
                              (cdr expr))))
            `,@exprs))))
#+end_src

Which allows the following forms of table manipulation such as adding
and subtracting hex values.
| 0x10 | 0x0 | #ERROR | #ERROR |
| 0x20 | 0x1 | #ERROR | #ERROR |
| 0x30 | 0x2 | #ERROR | #ERROR |
| 0xf0 | 0xf | #ERROR | #ERROR |
#+TBLFM: $3='(with-hex 'hex (+ $2 $1))::$4='(with-hex nil (identity $3))

*** Field coordinates in formulas (=@#= and =$#=)
    :PROPERTIES:
    :CUSTOM_ID: field-coordinates-in-formulas
    :END:
#+index: Table!Field Coordinates
-- Michael Brand

Following are some use cases that can be implemented with the “field
coordinates in formulas” described in the corresponding chapter in the
[[https://orgmode.org/manual/References.html#References][Org manual]].

**** Copy a column from a remote table into a column
     :PROPERTIES:
     :CUSTOM_ID: field-coordinates-in-formulas-copy-col-to-col
     :END:

current column =$3= = remote column =$2=:
: #+TBLFM: $3 = remote(FOO, @@#$2)

**** Copy a row from a remote table transposed into a column
     :PROPERTIES:
     :CUSTOM_ID: field-coordinates-in-formulas-copy-row-to-col
     :END:

current column =$1= = transposed remote row =@1=:
: #+TBLFM: $1 = remote(FOO, @$#$@#)

**** Transpose table
     :PROPERTIES:
     :CUSTOM_ID: field-coordinates-in-formulas-transpose-table
     :END:

-- Michael Brand

This is more like a demonstration of using “field coordinates in formulas”
and is bound to be slow for large tables. See the discussion in the mailing
list on
[[https://list.orgmode.org/82e274891002251643k327135aajea270914244abff7@mail.gmail.com][gmane]] or
[[http://lists.gnu.org/archive/html/emacs-orgmode/2010-04/msg00086.html][gnu]].
For more efficient solutions see
[[#transpose-table][Worg]].

To transpose this 4x7 table

: #+TBLNAME: FOO
: | year | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 |
: |------+------+------+------+------+------+------|
: | min  |  401 |  501 |  601 |  701 |  801 |  901 |
: | avg  |  402 |  502 |  602 |  702 |  802 |  902 |
: | max  |  403 |  503 |  603 |  703 |  803 |  903 |

start with a 7x4 table without any horizontal line (to have filled
also the column header) and yet empty:

: |   |   |   |   |
: |   |   |   |   |
: |   |   |   |   |
: |   |   |   |   |
: |   |   |   |   |
: |   |   |   |   |
: |   |   |   |   |

Then add the =TBLFM= line below.  After recalculation this will end up with
the transposed copy:

: | year | min | avg | max |
: | 2004 | 401 | 402 | 403 |
: | 2005 | 501 | 502 | 503 |
: | 2006 | 601 | 602 | 603 |
: | 2007 | 701 | 702 | 703 |
: | 2008 | 801 | 802 | 803 |
: | 2009 | 901 | 902 | 903 |
: #+TBLFM: @<$<..@>$> = remote(FOO, @$#$@#)

The formula simply exchanges row and column numbers by taking
- the absolute remote row number =@$#= from the current column number =$#=
- the absolute remote column number =$@#= from the current row number =@#=

Formulas to be taken over from the remote table will have to be transformed
manually.

**** Dynamic variation of ranges

-- Michael Brand

In this example all columns next to =quote= are calculated from the column
=quote= and show the average change of the time series =quote[year]=
during the period of the preceding =1=, =2=, =3= or =4= years:

: | year | quote |   1 a |   2 a |   3 a |   4 a |
: |------+-------+-------+-------+-------+-------|
: | 2005 |    10 |       |       |       |       |
: | 2006 |    12 | 0.200 |       |       |       |
: | 2007 |    14 | 0.167 | 0.183 |       |       |
: | 2008 |    16 | 0.143 | 0.155 | 0.170 |       |
: | 2009 |    18 | 0.125 | 0.134 | 0.145 | 0.158 |
: #+TBLFM: @I$3..@>$>=if(@# >= $#, ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1, string("")) +.0; f-3

The important part of the formula without the field blanking is:

: ($2 / subscr(@-I$2..@+I$2, @# + 1 - $#)) ^ (1 / ($# - 2)) - 1

which is the Emacs Calc implementation of the equation

/AvgChange(i, a) = (quote[i] / quote[i - a]) ^ (1 / a) - 1/

where /i/ is the current time and /a/ is the length of the preceding period.

*** Rearrange one or more field within the same row or column
    :PROPERTIES:
    :CUSTOM_ID: field-same-row-or-column
    :END:
#+index: Table!Editing

-- Michael Brand

**** Rearrange the column sequence in one row only
     :PROPERTIES:
     :CUSTOM_ID: column-sequence-in-row
     :END:
#+index: Table!Editing

The functions below can be used to change the column sequence in one
row only, without affecting the other rows above and below like with
=M-<left>= or =M-<right>= (=org-table-move-column=).  See also the
docstring of the functions for more explanations.  The original table
that serves as the starting point for the examples:

: | a | b | c  | d  |
: | e | 9 | 10 | 11 |
: | f | g | h  | i  |

***** Move current field in row
****** Left

1) place point at "10" in original table
2) =M-x f-org-table-move-field-in-row-left=
3) point is at moved "10"

: | a | b  | c | d  |
: | e | 10 | 9 | 11 |
: | f | g  | h | i  |

****** Right

1) place point at "9" in original table
2) =M-x f-org-table-move-field-in-row-right=
3) point is at moved "9"

: | a | b  | c | d  |
: | e | 10 | 9 | 11 |
: | f | g  | h | i  |

***** Rotate rest of row (range from current field to end of row)
****** Left

1) place point at @2$2 in original table
2) =M-x f-org-table-rotate-rest-of-row-left=
3) point is still at @2$2

: | a | b  | c  | d |
: | e | 10 | 11 | 9 |
: | f | g  | h  | i |

****** Right

1) place point at @2$2 in original table
2) =M-x f-org-table-rotate-rest-of-row-right=
3) point is still at @2$2

: | a | b  | c | d  |
: | e | 11 | 9 | 10 |
: | f | g  | h | i  |

***** Open field in row (table size grows)

This is just for completeness, interactively the same as typing =|
S-TAB=.

1) place point at @2$2 in original table
2) =M-x f-org-table-open-field-in-row-grow=
3) point is still at @2$2

: | a | b | c | d  |    |
: | e |   | 9 | 10 | 11 |
: | f | g | h | i  |    |

**** Rearrange the row sequence in one column only
     :PROPERTIES:
     :CUSTOM_ID: row-sequence-in-column
     :END:
#+index: Table!Editing

The functions below can be used to change the column sequence in one
column only, without affecting the other columns left and right like
with =M-<up>= or =M-<down>= (=org-table-move-row=).  See also the
docstring of the functions for more explanations.  The original table
that serves as the starting point for the examples:

: | a |  b | c |
: |---+----+---|
: | d |  9 | e |
: | f | 10 | g |
: |---+----+---|
: | h | 11 | i |

***** Move current field in column
****** Up

1) place point at "10" in original table
2) =M-x f-org-table-move-field-in-column-up=
3) point is at moved "10"

: | a |  b | c |
: |---+----+---|
: | d | 10 | e |
: | f |  9 | g |
: |---+----+---|
: | h | 11 | i |

****** Down

1) place point at "9" in original table
2) =M-x f-org-table-move-field-in-column-down=
3) point is at moved "9"

: | a |  b | c |
: |---+----+---|
: | d | 10 | e |
: | f |  9 | g |
: |---+----+---|
: | h | 11 | i |

***** Rotate rest of column (range from current field to end of column)
****** Up

1) place point at @2$2 in original table
2) =M-x f-org-table-rotate-rest-of-column-up=
3) point is still at @2$2

: | a |  b | c |
: |---+----+---|
: | d | 10 | e |
: | f | 11 | g |
: |---+----+---|
: | h |  9 | i |

****** Down

1) place point at @2$2 in original table
2) =M-x f-org-table-rotate-rest-of-column-down=
3) point is still at @2$2

: | a |  b | c |
: |---+----+---|
: | d | 11 | e |
: | f |  9 | g |
: |---+----+---|
: | h | 10 | i |

***** Open field in column (table size grows)

1) place point at @2$2 in original table
2) =M-x f-org-table-open-field-in-column-grow=
3) point is still at @2$2

: | a |  b | c |
: |---+----+---|
: | d |    | e |
: | f |  9 | g |
: |---+----+---|
: | h | 10 | i |
: |   | 11 |   |

**** Key bindings for some of the functions

I have this in an Org buffer to change temporarily to the desired
behavior with =C-c C-c= on one of the three code snippets:

: - move in row:
:   #+begin_src emacs-lisp :results silent
:     (org-defkey org-mode-map [(meta left)]
:                 'f-org-table-move-field-in-row-left)
:     (org-defkey org-mode-map [(meta right)]
:                 'f-org-table-move-field-in-row-right)
:     (org-defkey org-mode-map [(left)]  'org-table-previous-field)
:     (org-defkey org-mode-map [(right)] 'org-table-next-field)
:   #+end_src
:
: - rotate in row:
:   #+begin_src emacs-lisp :results silent
:     (org-defkey org-mode-map [(meta left)]
:                 'f-org-table-rotate-rest-of-row-left)
:     (org-defkey org-mode-map [(meta right)]
:                 'f-org-table-rotate-rest-of-row-right)
:     (org-defkey org-mode-map [(left)]  'org-table-previous-field)
:     (org-defkey org-mode-map [(right)] 'org-table-next-field)
:   #+end_src
:
: - back to original:
:   #+begin_src emacs-lisp :results silent
:     (org-defkey org-mode-map [(meta left)]  'org-metaleft)
:     (org-defkey org-mode-map [(meta right)] 'org-metaright)
:     (org-defkey org-mode-map [(left)]  'backward-char)
:     (org-defkey org-mode-map [(right)] 'forward-char)
:   #+end_src

**** Implementation

The functions

: f-org-table-move-field-in-column-up
: f-org-table-move-field-in-column-down
: f-org-table-rotate-rest-of-column-up
: f-org-table-rotate-rest-of-column-down

are not yet implemented.  They could be done similar to
=f-org-table-open-field-in-column-grow=.  A workaround without keeping
horizontal separator lines is to interactively or programmatically
simply:

1) Transpose the table, see
   [[#transpose-table][Org hacks]].
2) Use =f-org-table-*-column-in-row-*=, see
   [[https://orgmode.org/worg/org-hacks.html#column-sequence-in-row][previous
   section]].
3) Transpose the table.

The other functions:

#+BEGIN_SRC emacs-lisp
  (defun f-org-table-move-field-in-row-left ()
    "Move current field in row to the left."
    (interactive)
    (f-org-table-move-field-in-row 'left))
  (defun f-org-table-move-field-in-row-right ()
    "Move current field in row to the right."
    (interactive)
    (f-org-table-move-field-in-row nil))

  (defun f-org-table-move-field-in-row (&optional left)
    "Move current field in row to the right.
  With arg LEFT, move to the left.  For repeated invocation the
  point follows the moved field.  Does not fix formulas."
    ;; Derived from `org-table-move-column'
    (interactive "P")
    (if (not (org-at-table-p))
        (error "Not at a table"))
    (org-table-find-dataline)
    (org-table-check-inside-data-field)
    (let* ((col (org-table-current-column))
           (col1 (if left (1- col) col))
           ;; Current cursor position
           (colpos (if left (1- col) (1+ col))))
      (if (and left (= col 1))
          (error "Cannot move column further left"))
      (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
          (error "Cannot move column further right"))
      (org-table-goto-column col1 t)
      (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
           (replace-match "|\\2|\\1|"))
      (org-table-goto-column colpos)
      (org-table-align)))

  (defun f-org-table-rotate-rest-of-row-left ()
    "Rotate rest of row to the left."
    (interactive)
    (f-org-table-rotate-rest-of-row 'left))
  (defun f-org-table-rotate-rest-of-row-right ()
    "Rotate rest of row to the right."
    (interactive)
    (f-org-table-rotate-rest-of-row nil))

  (defun f-org-table-rotate-rest-of-row (&optional left)
    "Rotate rest of row to the right.
  With arg LEFT, rotate to the left.  For both directions the
  boundaries of the rotation range are the current field and the
  field at the end of the row.  For repeated invocation the point
  stays on the original current field.  Does not fix formulas."
    ;; Derived from `org-table-move-column'
    (interactive "P")
    (if (not (org-at-table-p))
        (error "Not at a table"))
    (org-table-find-dataline)
    (org-table-check-inside-data-field)
    (let ((col (org-table-current-column)))
      (org-table-goto-column col t)
      (and (looking-at (if left
                           "|\\([^|\n]+\\)|\\([^\n]+\\)|$"
                         "|\\([^\n]+\\)|\\([^|\n]+\\)|$"))
           (replace-match "|\\2|\\1|"))
      (org-table-goto-column col)
      (org-table-align)))

  (defun f-org-table-open-field-in-row-grow ()
    "Open field in row, move fields to the right by growing table."
    (interactive)
    (insert "|")
    (backward-char)
    (org-table-align))

  (defun f-org-table-open-field-in-column-grow ()
    "Open field in column, move all fields downwards by growing table."
    (interactive)
    (let ((col (org-table-current-column))
          (p   (point)))
      ;; Cut all fields downwards in same column
      (goto-char (org-table-end))
      (forward-line -1)
      (while (org-at-table-hline-p) (forward-line -1))
      (org-table-goto-column col)
      (org-table-cut-region p (point))
      ;; Paste at one field below
      (goto-char p)
      (forward-line)
      (org-table-goto-column col)
      (org-table-paste-rectangle)
      (goto-char p)
      (org-table-align)))
#+END_SRC

**** Reasons why this is not put into the Org core

I consider this as only a hack for several reasons:

- Generalization: The existing function =org-table-move-column= could
  be enhanced with additional optional parameters to incorporate these
  functionalities and could be used as the only function for better
  maintainability.  Now it's only a copy/paste hack of several similar
  functions with simple modifications.
- Bindings: Should be convenient for repetition like =M-<right>=.
  What should be bound where, what has to be left unbound?
- Does not fix formulas.  Could be resolved for field formulas but
  most probably not for column or range formulas and this can lead to
  confusion.  AFAIK all table manipulations found in Org core fix
  formulas.
- Completeness: Not all variations and combinations are covered yet
  - move, rotate with range to end, rotate with range to begin, rotate
    all
  - left-right, up-down

** Capture and Remember
*** Customize the size of the frame for remember
#+index: Remember!frame
#+index: Customization!remember
(Note: this hack is likely out of date due to the development of
=org-capture=.)

# FIXME: gmane link?
On emacs-orgmode, Ryan C. Thompson suggested this:

#+begin_quote
I am using org-remember set to open a new frame when used,
and the default frame size is much too large. To fix this, I have
designed some advice and a custom variable to implement custom
parameters for the remember frame:
#+end_quote

#+begin_src emacs-lisp
(defcustom remember-frame-alist nil
  "Additional frame parameters for dedicated remember frame."
  :type 'alist
  :group 'remember)

(defadvice remember (around remember-frame-parameters activate)
  "Set some frame parameters for the remember frame."
  (let ((default-frame-alist (append remember-frame-alist
                                     default-frame-alist)))
    ad-do-it))
#+end_src

Setting remember-frame-alist to =((width . 80) (height . 15)))= give a
reasonable size for the frame.
*** [[https://github.com/PhilHudson/org-capture-vars.el][User-defined capture template variables with prompt and completion list]]
*** [[https://github.com/alphapapa/unpackaged.el#ensure-blank-lines-between-headings-and-before-contents][Ensure blank lines between headings and before contents]]
** Handling Links
*** [[#heading-to-link][Turn a heading into an org link]]
*** Quickaccess to the link part of hyperlinks
#+index: Link!Referent
Christian Moe [[https://list.orgmode.org/4E0307D5.8080105@christianmoe.com][asked]], if there is a simpler way to copy the link part
of an org hyperling other than to use `C-c C-l C-a C-k C-g',
which is indeed kind of cumbersome.

The thread offered [[https://list.orgmode.org/871uy9ghdw.fsf@gnu.org][two ways]]:

Using a [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macros.html][keyboard macro]]:
#+begin_src emacs-lisp
(fset 'getlink
      (lambda (&optional arg)
        "Keyboard macro."
        (interactive "p")
        (kmacro-exec-ring-item (quote ("\C-c\C-l\C-a\C-k\C-g" 0 "%d")) arg)))
#+end_src

or a function:
#+begin_src emacs-lisp
(defun my-org-extract-link ()
  "Extract the link location at point and put it on the killring."
  (interactive)
  (when (org-in-regexp org-bracket-link-regexp 1)
    (kill-new (org-link-unescape (org-match-string-no-properties 1)))))
#+end_src

They put the link destination on the killring and can be easily bound to a key.

*** Insert link with HTML title as default description
When using `org-insert-link' (`C-c C-l') it might be useful to extract contents
from HTML <title> tag and use it as a default link description. Here is a way to
accomplish this:

#+begin_src emacs-lisp
(require 'mm-url) ; to include mm-url-decode-entities-string

(defun my-org-insert-link ()
  "Insert org link where default description is set to html title."
  (interactive)
  (let* ((url (read-string "URL: "))
         (title (get-html-title-from-url url)))
    (org-insert-link nil url title)))

(defun get-html-title-from-url (url)
  "Return content in <title> tag."
  (let (x1 x2 (download-buffer (url-retrieve-synchronously url)))
    (save-excursion
      (set-buffer download-buffer)
      (beginning-of-buffer)
      (setq x1 (search-forward "<title>"))
      (search-forward "</title>")
      (setq x2 (search-backward "<"))
      (mm-url-decode-entities-string (buffer-substring-no-properties x1 x2)))))
#+end_src

Then just use `M-x my-org-insert-link' instead of `org-insert-link'.

** Archiving Content in Org-Mode
  :PROPERTIES:
  :CUSTOM_ID: archiving
  :END:

*** Preserve top level headings when archiving to a file
#+index: Archiving!Preserve top level headings
- Matt Lundin

To preserve (somewhat) the integrity of your archive structure while
archiving lower level items to a file, you can use the following
defadvice:

#+begin_src emacs-lisp
(defadvice org-archive-subtree (around my-org-archive-subtree activate)
  (let ((org-archive-location
         (if (save-excursion (org-back-to-heading)
                             (> (org-outline-level) 1))
             (concat (car (split-string org-archive-location "::"))
                     "::* "
                     (car (org-get-outline-path)))
           org-archive-location)))
    ad-do-it))
#+end_src

Thus, if you have an outline structure such as...

#+begin_src org
,* Heading
,** Subheading
,*** Subsubheading
#+end_src

...archiving "Subsubheading" to a new file will set the location in
the new file to the top level heading:

#+begin_src org
,* Heading
,** Subsubheading
#+end_src

While this hack obviously destroys the outline hierarchy somewhat, it
at least preserves the logic of level one groupings.

A slightly more complex version of this hack will not only keep the
archive organized by top-level headings, but will also preserve the
tags found on those headings:

#+begin_src emacs-lisp
  (defun my-org-inherited-no-file-tags ()
    (let ((tags (org-entry-get nil "ALLTAGS" 'selective))
          (ltags (org-entry-get nil "TAGS")))
      (mapc (lambda (tag)
              (setq tags
                    (replace-regexp-in-string (concat tag ":") "" tags)))
            (append org-file-tags (when ltags (split-string ltags ":" t))))
      (if (string= ":" tags) nil tags)))

  (defadvice org-archive-subtree (around my-org-archive-subtree-low-level activate)
    (let ((tags (my-org-inherited-no-file-tags))
          (org-archive-location
           (if (save-excursion (org-back-to-heading)
                               (> (org-outline-level) 1))
               (concat (car (split-string org-archive-location "::"))
                       "::* "
                       (car (org-get-outline-path)))
             org-archive-location)))
      ad-do-it
      (with-current-buffer (find-file-noselect (org-extract-archive-file))
        (save-excursion
          (while (org-up-heading-safe))
          (org-set-tags-to tags)))))
#+end_src

*** Archive in a date tree
#+index: Archiving!date tree
Posted to Org-mode mailing list by Osamu Okano [2010-04-21 Wed].

(Make sure org-datetree.el is loaded for this to work.)

#+begin_src emacs-lisp
;; (setq org-archive-location "%s_archive::date-tree")
(defadvice org-archive-subtree
  (around org-archive-subtree-to-data-tree activate)
  "org-archive-subtree to date-tree"
  (if
      (string= "date-tree"
               (org-extract-archive-heading
                (org-get-local-archive-location)))
      (let* ((dct (decode-time (org-current-time)))
             (y (nth 5 dct))
             (m (nth 4 dct))
             (d (nth 3 dct))
             (this-buffer (current-buffer))
             (location (org-get-local-archive-location))
             (afile (org-extract-archive-file location))
             (org-archive-location
              (format "%s::*** %04d-%02d-%02d %s" afile y m d
                      (format-time-string "%A" (encode-time 0 0 0 d m y)))))
        (message "afile=%s" afile)
        (unless afile
          (error "Invalid `org-archive-location'"))
        (save-excursion
          (switch-to-buffer (find-file-noselect afile))
          (org-datetree-find-year-create y)
          (org-datetree-find-month-create y m)
          (org-datetree-find-day-create y m d)
          (widen)
          (switch-to-buffer this-buffer))
        ad-do-it)
    ad-do-it))
#+end_src

*** Add inherited tags to archived entries
#+index: Archiving!Add inherited tags
To make =org-archive-subtree= keep inherited tags, Osamu OKANO suggests to
advise the function like this:

#+begin_example
(defadvice org-archive-subtree
  (before add-inherited-tags-before-org-archive-subtree activate)
    "add inherited tags before org-archive-subtree"
    (org-set-tags-to (org-get-tags-at)))
#+end_example

** Using and Managing Org-Metadata
*** Remove redundant tags of headlines
  :PROPERTIES:
  :CUSTOM_ID: remove-redundant-tags
  :END:
#+index: Tag!Remove redundant
-- David Maus

A small function that processes all headlines in current buffer and
removes tags that are local to a headline and inherited by a parent
headline or the #+FILETAGS: statement.

#+BEGIN_SRC emacs-lisp
  (defun dmj/org-remove-redundant-tags ()
    "Remove redundant tags of headlines in current buffer.

  A tag is considered redundant if it is local to a headline and
  inherited by a parent headline."
    (interactive)
    (when (eq major-mode 'org-mode)
      (save-excursion
        (org-map-entries
         (lambda ()
           (let ((alltags (split-string (or (org-entry-get (point) "ALLTAGS") "") ":"))
                 local inherited tag)
             (dolist (tag alltags)
               (if (get-text-property 0 'inherited tag)
                   (push tag inherited) (push tag local)))
             (dolist (tag local)
               (if (member tag inherited) (org-toggle-tag tag 'off)))))
         t nil))))
#+END_SRC

*** Remove empty property drawers
  :PROPERTIES:
  :CUSTOM_ID: remove-empty-property-drawers
  :END:
#+index: Drawer!Empty
David Maus proposed this:

#+begin_src emacs-lisp
(defun dmj:org:remove-empty-propert-drawers ()
  "*Remove all empty property drawers in current file."
  (interactive)
  (unless (eq major-mode 'org-mode)
    (error "You need to turn on Org mode for this function."))
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward ":PROPERTIES:" nil t)
      (save-excursion
	(org-remove-empty-drawer-at "PROPERTIES" (match-beginning 0))))))
#+end_src

*** Group task list by a property
#+index: Agenda!Group task list
This advice allows you to group a task list in Org-Mode.  To use it,
set the variable =org-agenda-group-by-property= to the name of a
property in the option list for a TODO or TAGS search.  The resulting
agenda view will group tasks by that property prior to searching.

#+begin_src emacs-lisp
(defvar org-agenda-group-by-property nil
  "Set this in org-mode agenda views to group tasks by property")

(defun org-group-bucket-items (prop items)
  (let ((buckets ()))
    (dolist (item items)
      (let* ((marker (get-text-property 0 'org-marker item))
             (pvalue (org-entry-get marker prop t))
             (cell (assoc pvalue buckets)))
        (if cell
            (setcdr cell (cons item (cdr cell)))
          (setq buckets (cons (cons pvalue (list item))
                              buckets)))))
    (setq buckets (mapcar (lambda (bucket)
                            (cons (car bucket)
                                  (reverse (cdr bucket))))
                          buckets))
    (sort buckets (lambda (i1 i2)
                    (string< (car i1) (car i2))))))

(defadvice org-finalize-agenda-entries (around org-group-agenda-finalize
                                               (list &optional nosort))
  "Prepare bucketed agenda entry lists"
  (if org-agenda-group-by-property
      ;; bucketed, handle appropriately
      (let ((text ""))
        (dolist (bucket (org-group-bucket-items
                         org-agenda-group-by-property
                         list))
          (let ((header (concat "Property "
                                org-agenda-group-by-property
                                " is "
                                (or (car bucket) "<nil>") ":\n")))
            (add-text-properties 0 (1- (length header))
                                 (list 'face 'org-agenda-structure)
                                 header)
            (setq text
                  (concat text header
                          ;; recursively process
                          (let ((org-agenda-group-by-property nil))
                            (org-finalize-agenda-entries
                             (cdr bucket) nosort))
                          "\n\n"))))
        (setq ad-return-value text))
    ad-do-it))
(ad-activate 'org-finalize-agenda-entries)
#+end_src
*** A way to tag a task so that when clocking-out user is prompted to take a note.
#+index: Tag!Clock
#+index: Clock!Tag
    Thanks to Richard Riley (see [[https://list.orgmode.org/vuoc49jfwp.fsf@news.eternal-september.org][this post on the mailing list]]).

A small hook run when clocking out of a task that prompts for a note
when the tag "=clockout_note=" is found in a headline. It uses the tag
("=clockout_note=") so inheritance can also be used...

#+begin_src emacs-lisp
  (defun rgr/check-for-clock-out-note()
        (interactive)
        (save-excursion
          (org-back-to-heading)
          (let ((tags (org-get-tags)))
            (and tags (message "tags: %s " tags)
                 (when (member "clocknote" tags)
                   (org-add-note))))))

  (add-hook 'org-clock-out-hook 'rgr/check-for-clock-out-note)
#+end_src
*** Dynamically adjust tag position
#+index: Tag!position
Here is a bit of code that allows you to have the tags always
right-adjusted in the buffer.

This is useful when you have bigger window than default window-size
and you dislike the aesthetics of having the tag in the middle of the
line.

This hack solves the problem of adjusting it whenever you change the
window size.
Before saving it will revert the file to having the tag position be
left-adjusted so that if you track your files with version control,
you won't run into artificial diffs just because the window-size
changed.

*IMPORTANT*: This is probably slow on very big files.

#+begin_src emacs-lisp
(setq ba/org-adjust-tags-column t)

(defun ba/org-adjust-tags-column-reset-tags ()
  "In org-mode buffers it will reset tag position according to
`org-tags-column'."
  (when (and
         (not (string= (buffer-name) "*Remember*"))
         (eql major-mode 'org-mode))
    (let ((b-m-p (buffer-modified-p)))
      (condition-case nil
          (save-excursion
            (goto-char (point-min))
            (command-execute 'outline-next-visible-heading)
            ;; disable (message) that org-set-tags generates
            (flet ((message (&rest ignored) nil))
              (org-set-tags 1 t))
            (set-buffer-modified-p b-m-p))
        (error nil)))))

(defun ba/org-adjust-tags-column-now ()
  "Right-adjust `org-tags-column' value, then reset tag position."
  (set (make-local-variable 'org-tags-column)
       (- (- (window-width) (length org-ellipsis))))
  (ba/org-adjust-tags-column-reset-tags))

(defun ba/org-adjust-tags-column-maybe ()
  "If `ba/org-adjust-tags-column' is set to non-nil, adjust tags."
  (when ba/org-adjust-tags-column
    (ba/org-adjust-tags-column-now)))

(defun ba/org-adjust-tags-column-before-save ()
  "Tags need to be left-adjusted when saving."
  (when ba/org-adjust-tags-column
     (setq org-tags-column 1)
     (ba/org-adjust-tags-column-reset-tags)))

(defun ba/org-adjust-tags-column-after-save ()
  "Revert left-adjusted tag position done by before-save hook."
  (ba/org-adjust-tags-column-maybe)
  (set-buffer-modified-p nil))

; automatically align tags on right-hand side
(add-hook 'window-configuration-change-hook
          'ba/org-adjust-tags-column-maybe)
(add-hook 'before-save-hook 'ba/org-adjust-tags-column-before-save)
(add-hook 'after-save-hook 'ba/org-adjust-tags-column-after-save)
(add-hook 'org-agenda-mode-hook (lambda ()
                                  (setq org-agenda-tags-column (- (window-width)))))

; between invoking org-refile and displaying the prompt (which
; triggers window-configuration-change-hook) tags might adjust,
; which invalidates the org-refile cache
(defadvice org-refile (around org-refile-disable-adjust-tags)
  "Disable dynamically adjusting tags"
  (let ((ba/org-adjust-tags-column nil))
    ad-do-it))
(ad-activate 'org-refile)
#+end_src
*** Use an "attach" link type to open files without worrying about their location
#+index: Link!Attach
-- Darlan Cavalcante Moreira

In the setup part in my org-files I put:

#+begin_src org
,#+LINK: attach elisp:(org-open-file (org-attach-expand "%s"))
#+end_src

Now I can use the "attach" link type, but org will ask me if I want to
allow executing the elisp code.  To avoid this you can even set
org-confirm-elisp-link-function to nil (I don't like this because it allows
any elisp code in links) or you can set org-confirm-elisp-link-not-regexp
appropriately.

In my case I use

: (setq org-confirm-elisp-link-not-regexp "org-open-file")

This works very well.

** Org Agenda and Task Management
*** Make it easier to set org-agenda-files from multiple directories
#+index: Agenda!Files
- Matt Lundin

#+begin_src emacs-lisp
(defun my-org-list-files (dirs ext)
  "Function to create list of org files in multiple subdirectories.
This can be called to generate a list of files for
org-agenda-files or org-refile-targets.

DIRS is a list of directories.

EXT is a list of the extensions of files to be included."
  (let ((dirs (if (listp dirs)
                  dirs
                (list dirs)))
        (ext (if (listp ext)
                 ext
               (list ext)))
        files)
    (mapc
     (lambda (x)
       (mapc
        (lambda (y)
          (setq files
                (append files
                        (file-expand-wildcards
                         (concat (file-name-as-directory x) "*" y)))))
        ext))
     dirs)
    (mapc
     (lambda (x)
       (when (or (string-match "/.#" x)
                 (string-match "#$" x))
         (setq files (delete x files))))
     files)
    files))

(defvar my-org-agenda-directories '("~/org/")
  "List of directories containing org files.")
(defvar my-org-agenda-extensions '(".org")
  "List of extensions of agenda files")

(setq my-org-agenda-directories '("~/org/" "~/work/"))
(setq my-org-agenda-extensions '(".org" ".ref"))

(defun my-org-set-agenda-files ()
  (interactive)
  (setq org-agenda-files (my-org-list-files
                          my-org-agenda-directories
                          my-org-agenda-extensions)))

(my-org-set-agenda-files)
#+end_src

The code above will set your "default" agenda files to all files
ending in ".org" and ".ref" in the directories "~/org/" and "~/work/".
You can change these values by setting the variables
my-org-agenda-extensions and my-org-agenda-directories. The function
my-org-agenda-files-by-filetag uses these two variables to determine
which files to search for filetags (i.e., the larger set from which
the subset will be drawn).

You can also easily use my-org-list-files to "mix and match"
directories and extensions to generate different lists of agenda
files.

*** Restrict org-agenda-files by filetag
  :PROPERTIES:
  :CUSTOM_ID: set-agenda-files-by-filetag
  :END:
#+index: Agenda!Files
- Matt Lundin

It is often helpful to limit yourself to a subset of your agenda
files. For instance, at work, you might want to see only files related
to work (e.g., bugs, clientA, projectxyz, etc.). The FAQ has helpful
information on filtering tasks using [[file:org-faq.org::#limit-agenda-with-tag-filtering][filetags]] and [[file:org-faq.org::#limit-agenda-with-category-match][custom agendacommands]]. These solutions, however, require reapplying a filter each
time you call the agenda or writing several new custom agenda commands
for each context. Another solution is to use directories for different
types of tasks and to change your agenda files with a function that
sets org-agenda-files to the appropriate directory. But this relies on
hard and static boundaries between files.

The following functions allow for a more dynamic approach to selecting
a subset of files based on filetags:

#+begin_src emacs-lisp
(defun my-org-agenda-restrict-files-by-filetag (&optional tag)
  "Restrict org agenda files only to those containing filetag."
  (interactive)
  (let* ((tagslist (my-org-get-all-filetags))
         (ftag (or tag
                   (completing-read "Tag: "
                                    (mapcar 'car tagslist)))))
    (org-agenda-remove-restriction-lock 'noupdate)
    (put 'org-agenda-files 'org-restrict (cdr (assoc ftag tagslist)))
    (setq org-agenda-overriding-restriction 'files)))

(defun my-org-get-all-filetags ()
  "Get list of filetags from all default org-files."
  (let ((files org-agenda-files)
        tagslist x)
    (save-window-excursion
      (while (setq x (pop files))
        (set-buffer (find-file-noselect x))
        (mapc
         (lambda (y)
           (let ((tagfiles (assoc y tagslist)))
             (if tagfiles
                 (setcdr tagfiles (cons x (cdr tagfiles)))
               (add-to-list 'tagslist (list y x)))))
         (my-org-get-filetags)))
      tagslist)))

(defun my-org-get-filetags ()
  "Get list of filetags for current buffer"
  (let ((ftags org-file-tags)
        x)
    (mapcar
     (lambda (x)
       (org-no-properties x))
     ftags)))
#+end_src

Calling my-org-agenda-restrict-files-by-filetag results in a prompt
with all filetags in your "normal" agenda files. When you select a
tag, org-agenda-files will be restricted to only those files
containing the filetag. To release the restriction, type C-c C-x >
(org-agenda-remove-restriction-lock).

*** Highlight the agenda line under cursor
#+index: Agenda!Highlight
This is useful to make sure what task you are operating on.

#+BEGIN_SRC emacs-lisp
(add-hook 'org-agenda-mode-hook (lambda () (hl-line-mode 1)))
#+END_SRC

Under XEmacs:

#+BEGIN_SRC emacs-lisp
;; hl-line seems to be only for emacs
(require 'highline)
(add-hook 'org-agenda-mode-hook (lambda () (highline-mode 1)))

;; highline-mode does not work straightaway in tty mode.
;; I use a black background
(custom-set-faces
  '(highline-face ((((type tty) (class color))
                    (:background "white" :foreground "black")))))
#+END_SRC

*** Split frame horizontally for agenda
#+index: Agenda!frame
If you would like to split the frame into two side-by-side windows when
displaying the agenda, try this hack from Jan Rehders, which uses the
`toggle-window-split' from

http://www.emacswiki.org/cgi-bin/wiki/ToggleWindowSplit

#+BEGIN_SRC emacs-lisp
;; Patch org-mode to use vertical splitting
(defadvice org-prepare-agenda (after org-fix-split)
  (toggle-window-split))
(ad-activate 'org-prepare-agenda)
#+END_SRC

*** Automatically add an appointment when clocking in a task
#+index: Clock!Automatically add an appointment when clocking in a task
#+index: Appointment!Automatically add an appointment when clocking in a task
#+BEGIN_SRC emacs-lisp
;; Make sure you have a sensible value for `appt-message-warning-time'
(defvar bzg-org-clock-in-appt-delay 100
  "Number of minutes for setting an appointment by clocking-in")
#+END_SRC

This function let's you add an appointment for the current entry.
This can be useful when you need a reminder.

#+BEGIN_SRC emacs-lisp
(defun bzg-org-clock-in-add-appt (&optional n)
  "Add an appointment for the Org entry at point in N minutes."
  (interactive)
  (save-excursion
    (org-back-to-heading t)
    (looking-at org-complex-heading-regexp)
    (let* ((msg (match-string-no-properties 4))
	   (ct-time (decode-time))
	   (appt-min (+ (cadr ct-time)
			(or n bzg-org-clock-in-appt-delay)))
	   (appt-time ; define the time for the appointment
	    (progn (setf (cadr ct-time) appt-min) ct-time)))
      (appt-add (format-time-string
		 "%H:%M" (apply 'encode-time appt-time)) msg)
      (if (interactive-p) (message "New appointment for %s" msg)))))
#+END_SRC

You can advise =org-clock-in= so that =C-c C-x C-i= will automatically
add an appointment:

#+BEGIN_SRC emacs-lisp
(defadvice org-clock-in (after org-clock-in-add-appt activate)
  "Add an appointment when clocking a task in."
  (bzg-org-clock-in-add-appt))
#+END_SRC

You may also want to delete the associated appointment when clocking
out.  This function does this:

#+BEGIN_SRC emacs-lisp
(defun bzg-org-clock-out-delete-appt nil
  "When clocking out, delete any associated appointment."
  (interactive)
  (save-excursion
    (org-back-to-heading t)
    (looking-at org-complex-heading-regexp)
    (let* ((msg (match-string-no-properties 4)))
      (setq appt-time-msg-list
	    (delete nil
		    (mapcar
		     (lambda (appt)
		       (if (not (string-match (regexp-quote msg)
					      (cadr appt))) appt))
		     appt-time-msg-list)))
      (appt-check))))
#+END_SRC

And here is the advice for =org-clock-out= (=C-c C-x C-o=)

#+BEGIN_SRC emacs-lisp
(defadvice org-clock-out (before org-clock-out-delete-appt activate)
  "Delete an appointment when clocking a task out."
  (bzg-org-clock-out-delete-appt))
#+END_SRC

*IMPORTANT*: You can add appointment by clocking in in both an
=org-mode= and an =org-agenda-mode= buffer.  But clocking out from
agenda buffer with the advice above will bring an error.

*** Using external programs for appointments reminders
#+index: Appointment!reminders
Read this rich [[http://comments.gmane.org/gmane.emacs.orgmode/46641][thread]] from the org-mode list.

*** Remove from agenda time grid lines that are in an appointment
#+index: Agenda!time grid
#+index: Appointment!Remove from agenda time grid lines
The agenda shows lines for the time grid.  Some people think that
these lines are a distraction when there are appointments at those
times.  You can get rid of the lines which coincide exactly with the
beginning of an appointment.  Michael Ekstrand has written a piece of
advice that also removes lines that are somewhere inside an
appointment:

#+begin_src emacs-lisp
(defun org-time-to-minutes (time)
  "Convert an HHMM time to minutes"
  (+ (* (/ time 100) 60) (% time 100)))

(defun org-time-from-minutes (minutes)
  "Convert a number of minutes to an HHMM time"
  (+ (* (/ minutes 60) 100) (% minutes 60)))

(defadvice org-agenda-add-time-grid-maybe (around mde-org-agenda-grid-tweakify
                                                  (list ndays todayp))
  (if (member 'remove-match (car org-agenda-time-grid))
      (flet ((extract-window
              (line)
              (let ((start (get-text-property 1 'time-of-day line))
                    (dur (get-text-property 1 'duration line)))
                (cond
                 ((and start dur)
                  (cons start
                        (org-time-from-minutes
                         (+ dur (org-time-to-minutes start)))))
                 (start start)
                 (t nil)))))
        (let* ((windows (delq nil (mapcar 'extract-window list)))
               (org-agenda-time-grid
                (list (car org-agenda-time-grid)
                      (cadr org-agenda-time-grid)
                      (remove-if
                       (lambda (time)
                         (find-if (lambda (w)
                                    (if (numberp w)
                                        (equal w time)
                                      (and (>= time (car w))
                                           (< time (cdr w)))))
                                  windows))
                       (caddr org-agenda-time-grid)))))
          ad-do-it))
    ad-do-it))
(ad-activate 'org-agenda-add-time-grid-maybe)
#+end_src
*** Disable version control for Org mode agenda files
#+index: Agenda!Files
-- David Maus

Even if you use Git to track your agenda files you might not need
vc-mode to be enabled for these files.

#+begin_src emacs-lisp
(add-hook 'find-file-hook 'dmj/disable-vc-for-agenda-files-hook)
(defun dmj/disable-vc-for-agenda-files-hook ()
  "Disable vc-mode for Org agenda files."
  (if (and (fboundp 'org-agenda-file-p)
           (org-agenda-file-p (buffer-file-name)))
      (remove-hook 'find-file-hook 'vc-find-file-hook)
    (add-hook 'find-file-hook 'vc-find-file-hook)))
#+end_src

*** Easy customization of TODO colors
#+index: Customization!Todo keywords
#+index: Todo keywords!Customization

-- Ryan C. Thompson

Here is some code I came up with some code to make it easier to
customize the colors of various TODO keywords. As long as you just
want a different color and nothing else, you can customize the
variable org-todo-keyword-faces and use just a string color (i.e. a
string of the color name) as the face, and then org-get-todo-face
will convert the color to a face, inheriting everything else from
the standard org-todo face.

To demonstrate, I currently have org-todo-keyword-faces set to

#+BEGIN_SRC emacs-lisp
(("IN PROGRESS" . "dark orange")
 ("WAITING" . "red4")
 ("CANCELED" . "saddle brown"))
#+END_SRC

  Here's the code, in a form you can put in your =.emacs=

#+BEGIN_SRC emacs-lisp
(eval-after-load 'org-faces
 '(progn
    (defcustom org-todo-keyword-faces nil
      "Faces for specific TODO keywords.
This is a list of cons cells, with TODO keywords in the car and
faces in the cdr.  The face can be a symbol, a color, or a
property list of attributes, like (:foreground \"blue\" :weight
bold :underline t)."
      :group 'org-faces
      :group 'org-todo
      :type '(repeat
              (cons
               (string :tag "Keyword")
               (choice color (sexp :tag "Face")))))))

(eval-after-load 'org
 '(progn
    (defun org-get-todo-face-from-color (color)
      "Returns a specification for a face that inherits from org-todo
 face and has the given color as foreground. Returns nil if
 color is nil."
      (when color
        `(:inherit org-warning :foreground ,color)))

    (defun org-get-todo-face (kwd)
      "Get the right face for a TODO keyword KWD.
If KWD is a number, get the corresponding match group."
      (if (numberp kwd) (setq kwd (match-string kwd)))
      (or (let ((face (cdr (assoc kwd org-todo-keyword-faces))))
            (if (stringp face)
                (org-get-todo-face-from-color face)
              face))
          (and (member kwd org-done-keywords) 'org-done)
          'org-todo))))
#+END_SRC

*** Add an effort estimate on the fly when clocking in
#+index: Effort estimate!Add when clocking in
#+index: Clock!Effort estimate
You can use =org-clock-in-prepare-hook= to add an effort estimate.
This way you can easily have a "tea-timer" for your tasks when they
don't already have an effort estimate.

#+begin_src emacs-lisp
(add-hook 'org-clock-in-prepare-hook
	  'my-org-mode-ask-effort)

(defun my-org-mode-ask-effort ()
  "Ask for an effort estimate when clocking in."
  (unless (org-entry-get (point) "Effort")
    (let ((effort
	   (completing-read
	    "Effort: "
	    (org-entry-get-multivalued-property (point) "Effort"))))
      (unless (equal effort "")
	(org-set-property "Effort" effort)))))
#+end_src

Or you can use a default effort for such a timer:

#+begin_src emacs-lisp
(add-hook 'org-clock-in-prepare-hook
	  'my-org-mode-add-default-effort)

(defvar org-clock-default-effort "1:00")

(defun my-org-mode-add-default-effort ()
  "Add a default effort estimation."
  (unless (org-entry-get (point) "Effort")
    (org-set-property "Effort" org-clock-default-effort)))
#+end_src

*** Use idle timer for automatic agenda views
#+index: Agenda view!Refresh
From John Wiegley's mailing list post (March 18, 2010):

#+begin_quote
I have the following snippet in my .emacs file, which I find very
useful. Basically what it does is that if I don't touch my Emacs for 5
minutes, it displays the current agenda. This keeps my tasks "always
in mind" whenever I come back to Emacs after doing something else,
whereas before I had a tendency to forget that it was there.
#+end_quote

  - [[http://mid.gmane.org/55590EA7-C744-44E5-909F-755F0BBE452D@gmail.com][John Wiegley: Displaying your Org agenda after idle time]]

#+begin_src emacs-lisp
(defun jump-to-org-agenda ()
  (interactive)
  (let ((buf (get-buffer "*Org Agenda*"))
        wind)
    (if buf
        (if (setq wind (get-buffer-window buf))
            (select-window wind)
          (if (called-interactively-p)
              (progn
                (select-window (display-buffer buf t t))
                (org-fit-window-to-buffer)
                ;; (org-agenda-redo)
                )
            (with-selected-window (display-buffer buf)
              (org-fit-window-to-buffer)
              ;; (org-agenda-redo)
              )))
      (call-interactively 'org-agenda-list)))
  ;;(let ((buf (get-buffer "*Calendar*")))
  ;;  (unless (get-buffer-window buf)
  ;;    (org-agenda-goto-calendar)))
  )

(run-with-idle-timer 300 t 'jump-to-org-agenda)
#+end_src

#+results:
: [nil 0 300 0 t jump-to-org-agenda nil idle]

*** Refresh the agenda view regularly
#+index: Agenda view!Refresh
Hack sent by Kiwon Um:

#+begin_src emacs-lisp
(defun kiwon/org-agenda-redo-in-other-window ()
  "Call org-agenda-redo function even in the non-agenda buffer."
  (interactive)
  (let ((agenda-window (get-buffer-window org-agenda-buffer-name t)))
    (when agenda-window
      (with-selected-window agenda-window (org-agenda-redo)))))
(run-at-time nil 300 'kiwon/org-agenda-redo-in-other-window)
#+end_src

*** Reschedule agenda items to today with a single command
#+index: Agenda!Reschedule
This was suggested by Carsten in reply to David Abrahams:

#+begin_example emacs-lisp
(defun org-agenda-reschedule-to-today ()
  (interactive)
  (flet ((org-read-date (&rest rest) (current-time)))
    (call-interactively 'org-agenda-schedule)))
#+end_example

*** Mark subtree DONE along with all subheadings
#+index: Subtree!subheadings
Bernt Hansen [[https://list.orgmode.org/87aac7dnr6.fsf@norang.ca][suggested]] this command:

#+begin_src emacs-lisp
(defun bh/mark-subtree-done ()
  (interactive)
  (org-mark-subtree)
  (let ((limit (point)))
    (save-excursion
      (exchange-point-and-mark)
      (while (> (point) limit)
	(org-todo "DONE")
	(outline-previous-visible-heading 1))
      (org-todo "DONE"))))
#+end_src

Then M-x bh/mark-subtree-done.

*** Mark heading done when all checkboxes are checked.
    :PROPERTIES:
    :CUSTOM_ID: mark-done-when-all-checkboxes-checked
    :END:

#+index: Checkbox

An item consists of a list with checkboxes.  When all of the
checkboxes are checked, the item should be considered complete and its
TODO state should be automatically changed to DONE. The code below
does that. This version is slightly enhanced over the one in the
mailing list (see
https://list.orgmode.org/87r5718ytv.fsf@sputnik.localhost to
reset the state back to TODO if a checkbox is unchecked.

Note that the code requires that a checkbox statistics cookie (the [/]
or [%] thingie in the headline - see the [[https://orgmode.org/manual/Checkboxes.html#Checkboxes][Checkboxes]] section in the
manual) be present in order for it to work. Note also that it is too
dumb to figure out whether the item has a TODO state in the first
place: if there is a statistics cookie, a TODO/DONE state will be
added willy-nilly any time that the statistics cookie is changed.

#+begin_src emacs-lisp
  ;; see https://list.orgmode.org/87r5718ytv.fsf@sputnik.localhost
  (eval-after-load 'org-list
    '(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))

  (defun ndk/checkbox-list-complete ()
    (save-excursion
      (org-back-to-heading t)
      (let ((beg (point)) end)
        (end-of-line)
        (setq end (point))
        (goto-char beg)
        (if (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" end t)
              (if (match-end 1)
                  (if (equal (match-string 1) "100%")
                      ;; all done - do the state change
                      (org-todo 'done)
                    (org-todo 'todo))
                (if (and (> (match-end 2) (match-beginning 2))
                         (equal (match-string 2) (match-string 3)))
                    (org-todo 'done)
                  (org-todo 'todo)))))))
#+end_src

*** Links to custom agenda views
    :PROPERTIES:
    :CUSTOM_ID: links-to-agenda-views
    :END:
#+index: Agenda view!Links to
This hack was [[http://lists.gnu.org/archive/html/emacs-orgmode/2012-08/msg00986.html][posted to the mailing list]] by Nathan Neff.

If you have custom agenda commands defined to some key, say w, then
the following will serve as a link to the custom agenda buffer.
: [[elisp:(org-agenda nil "w")][Show Waiting Tasks]]

Clicking on it will prompt if you want to execute the elisp code.  If
you would rather not have the prompt or would want to respond with a
single letter, ~y~ or ~n~, take a look at the docstrings of the
variables =org-confirm-elisp-link-function= and
=org-confirm-elisp-link-not-regexp=.  Please take special note of the
security risk associated with completely disabling the prompting
before you proceed.

** Exporting org files
*** Ignoring headlines during export
    :PROPERTIES:
    :CUSTOM_ID: ignoreheadline
    :END:
#+index: Export!ignore headlines
Sometimes users want to ignore the headline text during export like in
the Beamer exporter (=ox-beamer=).  In the [[https://orgmode.org/manual/Beamer-export.html#Beamer-export][Beamer exporter]] one can use
the tag =ignoreheading= to disable the export of a certain headline,
whilst still retaining the content of the headline.  We can imitate
this feature in other export backends.  Note that this is not a
particularly easy problem, as the Org exporter creates a static
representation of section numbers, table of contents etc.

Consider the following document:
#+BEGIN_SRC org
  ,* head 1                    :noexport:
  ,* head 2                    :ignoreheading:
  ,* head 3
  ,* =head 4=                  :ignoreheading:

#+END_SRC
We want to remove heading 2 and 4.

There are different strategies to accomplish this:
1. The best option is to remove headings tagged with =ignoreheading=
   before export starts.  This can be accomplished with the hook
   =org-export-before-parsing-hook= that runs before the buffer has
   been parsed.  In the example above, however, =head 2= would not be
   exported as it becomes part of =head 1= which is not exporter.  To
   overcome this move perhaps =head 1= can be moved to the end of the
   buffer.  An example of a hook that removes headings is before
   parsing is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01459.html][here]].  Note, this solution is compatible with
   /all/ export formats!
2. The problem is simple when exporting to LaTeX, as the LaTeX
   compiler determines numbers.  We can thus use
   =org-export-filter-headline-functions= to remove the offending
   headlines.  One regexp-based solution that looks for the word
   =ignoreheading= is available on [[https://stackoverflow.com/questions/10295177/is-there-an-equivalent-of-org-modes-b-ignoreheading-for-non-beamer-documents][StackOverflow]] for both the legacy
   exporter Org v7 exporter and the current Org v8 exporter.  Note,
   however, that this filter will only work with LaTeX (numbering and
   the table of content may break in other exporters).  In the example
   above, this filer will work flawlessly in LaTeX, it will not work
   at all in HTML and it will fail to update section numbers, TOC and
   leave some auxiliary lines behind when exporting to plain text.
3. Another solution that tries to recover the Org element
   representation is available [[https://lists.gnu.org/archive/html/emacs-orgmode/2014-03/msg01480.html][here]].  In the example above this filter
   will not remove =head 4= exporting to any backend, since verbatim
   strings do not retain the Org element representation.  It will
   remove the extra heading line when exporting to plain text, but
   will also fail to update section numbers.  It should be fairly
   simple to also make it work with HTML.

*NOTE: another way to accomplish this behavior is to use the [[https://git.savannah.gnu.org/cgit/emacs/org-mode.git/tree/contrib/lisp/ox-extra.el][=ox-extra.el=]] package:*
To use this, add the following to your =.elisp= file:

#+begin_src emacs-lisp
    (add-to-list 'load-path "path/to/contrib/lisp")
    (require 'ox-extra)
    (ox-extras-activate '(ignore-headlines))
#+end_src

After this is added, then any headlines having an =:ignore:= tag will
be omitted from the export, but their contents will be included in the
export.

*** Export Org to Org and handle includes.
#+index: Export!handle includes
N.B: this does not apply to the "new" export engine (>= 8.0) - the function
=org-export-handle-include-files-recurse= is only available in earlier versions.
There is probably a way to do the same thing in the "new" exporter but nobody
has stepped up to the plate yet.

Nick Dokos came up with this useful function:

#+begin_src emacs-lisp
(defun org-to-org-handle-includes ()
  "Copy the contents of the current buffer to OUTFILE,
recursively processing #+INCLUDEs."
  (let* ((s (buffer-string))
	 (fname (buffer-file-name))
	 (ofname (format "%s.I.org" (file-name-sans-extension fname))))
    (setq result
	  (with-temp-buffer
	    (insert s)
	    (org-export-handle-include-files-recurse)
	    (buffer-string)))
    (find-file ofname)
    (delete-region (point-min) (point-max))
    (insert result)
    (save-buffer)))
#+end_src

*** Specifying LaTeX commands to floating environments
    :PROPERTIES:
    :CUSTOM_ID: latex-command-for-floats
    :END:

#+index: Export!LaTeX
The keyword ~placement~ can be used to specify placement options to
floating environments (like =\begin{figure}= and =\begin{table}=}) in
LaTeX export. Org passes along everything passed in options as long as
there are no spaces. One can take advantage of this to pass other
LaTeX commands and have their scope limited to the floating
environment.

For example one can set the fontsize of a table different from the
default normal size by putting something like =\footnotesize= right
after the placement options. During LaTeX export using the
~#+ATTR_LaTeX:~ line below:

#+begin_src org
,#+ATTR_LaTeX: placement=[<options>]\footnotesize
#+end_src

exports the associated floating environment as shown in the following
block.

#+begin_src latex
\begin{table}[<options>]\footnotesize
...
\end{table}
#+end_src

It should be noted that this hack does not work for beamer export of
tables since the =table= environment is not used. As an ugly
workaround, one can use the following:

#+begin_src org
,#+LATEX: {\footnotesize
,#+ATTR_LaTeX: align=rr
| some | table |
|------+-------|
| ..   | ..    |
,#+LATEX: }
#+end_src

*** Styling code sections with CSS

#+index: HTML!Styling code sections with CSS

Code sections (marked with =#+begin_src= and =#+end_src=) are exported
to HTML using =<pre>= tags, and assigned CSS classes by their content
type.  For example, Perl content will have an opening tag like
=<pre class="src src-perl">=.  You can use those classes to add styling
to the output, such as here where a small language tag is added at the
top of each kind of code box:

#+begin_src lisp
(setq org-export-html-style
 "<style type=\"text/css\">
    <!--/*--><![CDATA[/*><!--*/
      .src             { background-color: #F5FFF5; position: relative; overflow: visible; }
      .src:before      { position: absolute; top: -15px; background: #ffffff; padding: 1px; border: 1px solid #000000; font-size: small; }
      .src-sh:before   { content: 'sh'; }
      .src-bash:before { content: 'sh'; }
      .src-R:before    { content: 'R'; }
      .src-perl:before { content: 'Perl'; }
      .src-sql:before  { content: 'SQL'; }
      .example         { background-color: #FFF5F5; }
    /*]]>*/-->
 </style>")
#+end_src

Additionally, we use color to distinguish code output (the =.example=
class) from input (all the =.src-*= classes).

*** Where can I find nice themes for HTML export?

You can find great looking HTML themes (CSS + JS) at
https://github.com/fniessen/org-html-themes, currently:

- Bigblow, and

  [[file:images/org-html-themes/bigblow.png]]

- ReadTheOrg, a clone of Read The Docs.

  [[file:images/org-html-themes/readtheorg.png]]

See https://www.youtube.com/watch?v=DnSGSiXYuOk for a demo of the Org
HTML theme Bigblow.

*** Including external text fragments

#+index: Export!including external text fragments

I recently had to document some source code but could not modify the
source files themselves. Here is a setup that lets you refer to
fragments of external files, such that the fragments are inserted as
source blocks in the current file during evaluation of the ~call~
lines (thus during export as well).

#+BEGIN_SRC org
  ,* Setup                                                            :noexport:
  ,#+name: fetchsrc
  ,#+BEGIN_SRC emacs-lisp :results raw :var f="foo" :var s="Definition" :var e="\\. *$" :var b=()
    (defvar coqfiles nil)

    (defun fetchlines (file-path search-string &optional end before)
      "Searches for the SEARCH-STRING in FILE-PATH and returns the matching line.
    If the optional argument END is provided as a number, then this
    number of lines is printed.  If END is a string, then it is a
    regular expression indicating the end of the expression to print.
    If END is omitted, then 10 lines are printed.  If BEFORE is set,
    then one fewer line is printed (this is useful when END is a
    string matching the first line that should not be printed)."
      (with-temp-buffer
        (insert-file-contents file-path nil nil nil t)
        (goto-char (point-min))
        (let ((result
               (if (search-forward search-string nil t)
                   (buffer-substring
                    (line-beginning-position)
                    (if end
                        (cond
                         ((integerp end)
                          (line-end-position (if before (- end 1) end)))
                         ((stringp end)
                          (let ((point (re-search-forward end nil t)))
                            (if before (line-end-position 0) point)))
                         (t (line-end-position 10)))
                      (line-end-position 10))))))
          (or result ""))))

    (fetchlines (concat coqfiles f ".v") s e b)
  ,#+END_SRC

  ,#+name: wrap-coq
  ,#+BEGIN_SRC emacs-lisp :var text="" :results raw
  (concat "#+BEGIN_SRC coq\n" text "\n#+END_SRC")
  ,#+END_SRC
#+END_SRC

This is specialized for Coq files (hence the ~coq~ language in the
~wrap-coq~ function, the ~.v~ extension in the ~fetch~ function, and
the default value for ~end~ matching the syntax ending definitions in
Coq). To use it, you need to:
- set the ~coqfiles~ variable to where your source files reside;
- call the function using lines of the form
  #+BEGIN_SRC org
    ,#+call: fetchsrc(f="JsSyntax", s="Inductive expr :=", e="^ *$", b=1) :results drawer :post wrap-coq(text=*this*)
  #+END_SRC
  In this example, we look inside the file ~JsSyntax.v~ in ~coqfiles~,
  search for a line matching ~Inductive expr :=~, and include the
  fragment until the first line consisting only of white space,
  excluded (as ~b=1~).

I use drawers to store the results to avoid a bug leading to
duplication during export when the code has already been evaluated in
the buffer (see [[https://list.orgmode.org/m2k3fkbxec.fsf@polytechnique.org][this thread]] for a description of the problem). This
has been fixed in recent versions of org-mode, so alternative
approaches are possible.

** Babel

*** How do I preview LaTeX fragments when in a LaTeX source block?

When editing =LaTeX= source blocks, you may want to preview LaTeX fragments
just like in an Org-mode buffer.  You can do this by using the usual
keybinding =C-c C-x C-l= after loading this snipped:

#+BEGIN_SRC emacs-lisp
(define-key org-src-mode-map "\C-c\C-x\C-l" 'org-edit-preview-latex-fragment)

(defun org-edit-preview-latex-fragment ()
  "Write latex fragment from source to parent buffer and preview it."
  (interactive)
  (org-src-in-org-buffer (org-preview-latex-fragment)))
#+END_SRC

Thanks to Sebastian Hofer for sharing this.

* Hacking Org: Working with Org-mode and other Emacs Packages
** How to ediff folded Org files
A rather often quip among Org users is when looking at chages with
ediff.  Ediff tends to fold the Org buffers when comparing.  This can
be very inconvenient when trying to determine what changed.  A recent
discussion on the mailing list led to a [[https://list.orgmode.org/87wqo5fnxc.dlv@debian.org][neat solution]] from Ratish
Punnoose.

** org-remember-anything

#+index: Remember!Anything

[[http://www.emacswiki.org/cgi-bin/wiki/Anything][Anything]] users may find the snippet below interesting:

#+BEGIN_SRC emacs-lisp
(defvar org-remember-anything
  '((name . "Org Remember")
    (candidates . (lambda () (mapcar 'car org-remember-templates)))
    (action . (lambda (name)
                (let* ((orig-template org-remember-templates)
                       (org-remember-templates
                        (list (assoc name orig-template))))
                  (call-interactively 'org-remember))))))
#+END_SRC

You can add it to your 'anything-sources' variable and open remember directly
from anything. I imagine this would be more interesting for people with many
remember templates, so that you are out of keys to assign those to.

** Org-mode and saveplace.el

Fix a problem with =saveplace.el= putting you back in a folded position:

#+begin_src emacs-lisp
(add-hook 'org-mode-hook
          (lambda ()
	    (when (outline-invisible-p)
	      (save-excursion
		(outline-previous-visible-heading 1)
		(org-show-subtree)))))
#+end_src

** Using ido-mode for org-refile (and archiving via refile)

First set up ido-mode, for example using:

#+begin_src emacs-lisp
; use ido mode for completion
(setq ido-everywhere t)
(setq ido-enable-flex-matching t)
(setq ido-max-directory-size 100000)
(ido-mode (quote both))
#+end_src

Now to enable it in org-mode, use the following:
#+begin_src emacs-lisp
(setq org-completion-use-ido t)
(setq org-refile-use-outline-path nil)
(setq org-refile-allow-creating-parent-nodes 'confirm)
#+end_src
The last line enables the creation of nodes on the fly.

If you refile into files that are not in your agenda file list, you can add them as target like this (replace file1\_done, etc with your files):
#+begin_src emacs-lisp
(setq org-refile-targets '((org-agenda-files :maxlevel . 5) (("~/org/file1_done" "~/org/file2_done") :maxlevel . 5) ))
#+end_src

For refiling it is often not useful to include targets that have a DONE state. It's easy to remove them by using the verify-refile-target hook.
#+begin_src emacs-lisp
; Exclude DONE state tasks from refile targets; taken from http://doc.norang.ca/org-mode.html
; added check to only include headlines, e.g. line must have at least one child
(defun my/verify-refile-target ()
  "Exclude todo keywords with a DONE state from refile targets"
  (or (not (member (nth 2 (org-heading-components)) org-done-keywords)))
      (save-excursion (org-goto-first-child))
  )
(setq org-refile-target-verify-function 'my/verify-refile-target)
#+end_src
Now when looking for a refile target, you can use the full power of ido to find them. Ctrl-R can be used to switch between different options that ido offers.

** Using ido-completing-read to find attachments

#+index: Attachment!ido completion

-- Matt Lundin.

Org-attach is great for quickly linking files to a project. But if you
use org-attach extensively you might find yourself wanting to browse
all the files you've attached to org headlines. This is not easy to do
manually, since the directories containing the files are not human
readable (i.e., they are based on automatically generated ids). Here's
some code to browse those files using ido (obviously, you need to be
using ido):

#+begin_src emacs-lisp
(load-library "find-lisp")

;; Adapted from http://www.emacswiki.org/emacs/RecentFiles

(defun my-ido-find-org-attach ()
  "Find files in org-attachment directory"
  (interactive)
  (let* ((enable-recursive-minibuffers t)
         (files (find-lisp-find-files org-attach-directory "."))
         (file-assoc-list
          (mapcar (lambda (x)
                    (cons (file-name-nondirectory x)
                          x))
                  files))
         (filename-list
          (remove-duplicates (mapcar #'car file-assoc-list)
                             :test #'string=))
         (filename (ido-completing-read "Org attachments: " filename-list nil t))
         (longname (cdr (assoc filename file-assoc-list))))
    (ido-set-current-directory
     (if (file-directory-p longname)
         longname
       (file-name-directory longname)))
    (setq ido-exit 'refresh
          ido-text-init ido-text
          ido-rotate-temp t)
    (exit-minibuffer)))

(add-hook 'ido-setup-hook 'ido-my-keys)

(defun ido-my-keys ()
  "Add my keybindings for ido."
  (define-key ido-completion-map (kbd "C-;") 'my-ido-find-org-attach))
#+end_src

To browse your org attachments using ido fuzzy matching and/or the
completion buffer, invoke ido-find-file as usual (=C-x C-f=) and then
press =C-;=.

** Link to Gnus messages by Message-Id
#+index: Link!Gnus message by Message-Id
In a [[https://list.orgmode.org/871vy3tg9x.fsf@wolfram.com][recent thread]] on the Org-Mode mailing list, there was some
discussion about linking to Gnus messages without encoding the folder
name in the link.  The following code hooks in to the store-link
function in Gnus to capture links by Message-Id when in nnml folders,
and then provides a link type "mid" which can open this link.  The
=mde-org-gnus-open-message-link= function uses the
=mde-mid-resolve-methods= variable to determine what Gnus backends to
scan.  It will go through them, in order, asking each to locate the
message and opening it from the first one that reports success.

It has only been tested with a single nnml backend, so there may be
bugs lurking here and there.

The logic for finding the message was adapted from [[http://www.emacswiki.org/cgi-bin/wiki/FindMailByMessageId][an Emacs Wiki
article]].

#+begin_src emacs-lisp
;; Support for saving Gnus messages by Message-ID
(defun mde-org-gnus-save-by-mid ()
  (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
    (when (eq major-mode 'gnus-article-mode)
      (gnus-article-show-summary))
    (let* ((group gnus-newsgroup-name)
           (method (gnus-find-method-for-group group)))
      (when (eq 'nnml (car method))
        (let* ((article (gnus-summary-article-number))
               (header (gnus-summary-article-header article))
               (from (mail-header-from header))
               (message-id
                (save-match-data
                  (let ((mid (mail-header-id header)))
                    (if (string-match "<\\(.*\\)>" mid)
                        (match-string 1 mid)
                      (error "Malformed message ID header %s" mid)))))
               (date (mail-header-date header))
               (subject (gnus-summary-subject-string)))
          (org-store-link-props :type "mid" :from from :subject subject
                                :message-id message-id :group group
                                :link (org-make-link "mid:" message-id))
          (apply 'org-store-link-props
                 :description (org-email-link-description)
                 org-store-link-plist)
          t)))))

(defvar mde-mid-resolve-methods '()
  "List of methods to try when resolving message ID's.  For Gnus,
it is a cons of 'gnus and the select (type and name).")
(setq mde-mid-resolve-methods
      '((gnus nnml "")))

(defvar mde-org-gnus-open-level 1
  "Level at which Gnus is started when opening a link")
(defun mde-org-gnus-open-message-link (msgid)
  "Open a message link with Gnus"
  (require 'gnus)
  (require 'org-table)
  (catch 'method-found
    (message "[MID linker] Resolving %s" msgid)
    (dolist (method mde-mid-resolve-methods)
      (cond
       ((and (eq (car method) 'gnus)
             (eq (cadr method) 'nnml))
        (funcall (cdr (assq 'gnus org-link-frame-setup))
                 mde-org-gnus-open-level)
        (when gnus-other-frame-object
          (select-frame gnus-other-frame-object))
        (let* ((msg-info (nnml-find-group-number
                          (concat "<" msgid ">")
                          (cdr method)))
               (group (and msg-info (car msg-info)))
               (message (and msg-info (cdr msg-info)))
               (qname (and group
                           (if (gnus-methods-equal-p
                                (cdr method)
                                gnus-select-method)
                               group
                             (gnus-group-full-name group (cdr method))))))
          (when msg-info
            (gnus-summary-read-group qname nil t)
            (gnus-summary-goto-article message nil t))
          (throw 'method-found t)))
       (t (error "Unknown link type"))))))

(eval-after-load 'org-gnus
  '(progn
     (add-to-list 'org-store-link-functions 'mde-org-gnus-save-by-mid)
     (org-add-link-type "mid" 'mde-org-gnus-open-message-link)))
#+end_src

** Store link to a message when sending in Gnus
#+index: Link!Store link to a message when sending in Gnus
Ulf Stegemann came up with this solution (see his [[http://www.mail-archive.com/emacs-orgmode@gnu.org/msg33278.html][original message]]):

#+begin_src emacs-lisp
(defun ulf-message-send-and-org-gnus-store-link (&optional arg)
  "Send message with `message-send-and-exit' and store org link to message copy.
If multiple groups appear in the Gcc header, the link refers to
the copy in the last group."
  (interactive "P")
    (save-excursion
      (save-restriction
	(message-narrow-to-headers)
	(let ((gcc (car (last
			 (message-unquote-tokens
			  (message-tokenize-header
			   (mail-fetch-field "gcc" nil t) " ,")))))
	      (buf (current-buffer))
	      (message-kill-buffer-on-exit nil)
	      id to from subject desc link newsgroup xarchive)
        (message-send-and-exit arg)
        (or
         ;; gcc group found ...
         (and gcc
              (save-current-buffer
                (progn (set-buffer buf)
                       (setq id (org-remove-angle-brackets
                                 (mail-fetch-field "Message-ID")))
                       (setq to (mail-fetch-field "To"))
                       (setq from (mail-fetch-field "From"))
                       (setq subject (mail-fetch-field "Subject"))))
              (org-store-link-props :type "gnus" :from from :subject subject
                                    :message-id id :group gcc :to to)
              (setq desc (org-email-link-description))
              (setq link (org-gnus-article-link
                          gcc newsgroup id xarchive))
              (setq org-stored-links
                    (cons (list link desc) org-stored-links)))
         ;; no gcc group found ...
         (message "Can not create Org link: No Gcc header found."))))))

(define-key message-mode-map [(control c) (control meta c)]
  'ulf-message-send-and-org-gnus-store-link)
#+end_src

** Link to visit a file and run occur
#+index: Link!Visit a file and run occur
Add the following bit of code to your startup (after loading org),
and you can then use links like =occur:my-file.txt#regex= to open a
file and run occur with the regex on it.

#+BEGIN_SRC emacs-lisp
  (defun org-occur-open (uri)
    "Visit the file specified by URI, and run `occur' on the fragment
    \(anything after the first '#') in the uri."
    (let ((list (split-string uri "#")))
      (org-open-file (car list) t)
      (occur (mapconcat 'identity (cdr list) "#"))))
  (org-add-link-type "occur" 'org-occur-open)
#+END_SRC
** Send html messages and attachments with Wanderlust
  -- David Maus

/Note/: The module [[file:org-contrib/org-mime.org][Org-mime]] in Org's contrib directory provides
similar functionality for both Wanderlust and Gnus.  The hack below is
still somewhat different: It allows you to toggle sending of html
messages within Wanderlust transparently.  I.e. html markup of the
message body is created right before sending starts.

*** Send HTML message

Putting the code below in your .emacs adds following four functions:

- dmj/wl-send-html-message

  Function that does the job: Convert everything between "--text
  follows this line--" and first mime entity (read: attachment) or
  end of buffer into html markup using `org-export-region-as-html'
  and replaces original body with a multipart MIME entity with the
  plain text version of body and the html markup version.  Thus a
  recipient that prefers html messages can see the html markup,
  recipients that prefer or depend on plain text can see the plain
  text.

  Cannot be called interactively: It is hooked into SEMI's
  `mime-edit-translate-hook' if message should be HTML message.

- dmj/wl-send-html-message-draft-init

  Cannot be called interactively: It is hooked into WL's
  `wl-mail-setup-hook' and provides a buffer local variable to
  toggle.

- dmj/wl-send-html-message-draft-maybe

  Cannot be called interactively: It is hooked into WL's
  `wl-draft-send-hook' and hooks `dmj/wl-send-html-message' into
  `mime-edit-translate-hook' depending on whether HTML message is
  toggled on or off

- dmj/wl-send-html-message-toggle

  Toggles sending of HTML message.  If toggled on, the letters
  "HTML" appear in the mode line.

  Call it interactively!  Or bind it to a key in `wl-draft-mode'.

If you have to send HTML messages regularly you can set a global
variable `dmj/wl-send-html-message-toggled-p' to the string "HTML" to
toggle on sending HTML message by default.

The image [[http://s11.directupload.net/file/u/15851/48ru5wl3.png][here]] shows an example of how the HTML message looks like in
Google's web front end.  As you can see you have the whole markup of
Org at your service: *bold*, /italics/, tables, lists...

So even if you feel uncomfortable with sending HTML messages at least
you send HTML that looks quite good.

#+begin_src emacs-lisp
(defun dmj/wl-send-html-message ()
  "Send message as html message.
Convert body of message to html using
  `org-export-region-as-html'."
  (require 'org)
  (save-excursion
    (let (beg end html text)
      (goto-char (point-min))
      (re-search-forward "^--text follows this line--$")
      ;; move to beginning of next line
      (beginning-of-line 2)
      (setq beg (point))
      (if (not (re-search-forward "^--\\[\\[" nil t))
          (setq end (point-max))
        ;; line up
        (end-of-line 0)
        (setq end (point)))
      ;; grab body
      (setq text (buffer-substring-no-properties beg end))
      ;; convert to html
      (with-temp-buffer
        (org-mode)
        (insert text)
        ;; handle signature
        (when (re-search-backward "^-- \n" nil t)
          ;; preserve link breaks in signature
          (insert "\n#+BEGIN_VERSE\n")
          (goto-char (point-max))
          (insert "\n#+END_VERSE\n")
          ;; grab html
          (setq html (org-export-region-as-html
                      (point-min) (point-max) t 'string))))
      (delete-region beg end)
      (insert
       (concat
        "--" "<<alternative>>-{\n"
        "--" "[[text/plain]]\n" text
        "--" "[[text/html]]\n"  html
        "--" "}-<<alternative>>\n")))))

(defun dmj/wl-send-html-message-toggle ()
  "Toggle sending of html message."
  (interactive)
  (setq dmj/wl-send-html-message-toggled-p
        (if dmj/wl-send-html-message-toggled-p
            nil "HTML"))
  (message "Sending html message toggled %s"
           (if dmj/wl-send-html-message-toggled-p
               "on" "off")))

(defun dmj/wl-send-html-message-draft-init ()
  "Create buffer local settings for maybe sending html message."
  (unless (boundp 'dmj/wl-send-html-message-toggled-p)
    (setq dmj/wl-send-html-message-toggled-p nil))
  (make-variable-buffer-local 'dmj/wl-send-html-message-toggled-p)
  (add-to-list 'global-mode-string
               '(:eval (if (eq major-mode 'wl-draft-mode)
                           dmj/wl-send-html-message-toggled-p))))

(defun dmj/wl-send-html-message-maybe ()
  "Maybe send this message as html message.

If buffer local variable `dmj/wl-send-html-message-toggled-p' is
non-nil, add `dmj/wl-send-html-message' to
`mime-edit-translate-hook'."
  (if dmj/wl-send-html-message-toggled-p
      (add-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)
    (remove-hook 'mime-edit-translate-hook 'dmj/wl-send-html-message)))

(add-hook 'wl-draft-reedit-hook 'dmj/wl-send-html-message-draft-init)
(add-hook 'wl-mail-setup-hook 'dmj/wl-send-html-message-draft-init)
(add-hook 'wl-draft-send-hook 'dmj/wl-send-html-message-maybe)
#+end_src

*** Attach HTML of region or subtree

Instead of sending a complete HTML message you might only send parts
of an Org file as HTML for the poor souls who are plagued with
non-proportional fonts in their mail program that messes up pretty
ASCII tables.

This short function does the trick: It exports region or subtree to
HTML, prefixes it with a MIME entity delimiter and pushes to killring
and clipboard.  If a region is active, it uses the region, the
complete subtree otherwise.

#+begin_src emacs-lisp
(defun dmj/org-export-region-as-html-attachment (beg end arg)
  "Export region between BEG and END as html attachment.
If BEG and END are not set, use current subtree.  Region or
subtree is exported to html without header and footer, prefixed
with a mime entity string and pushed to clipboard and killring.
When called with prefix, mime entity is not marked as
attachment."
  (interactive "r\nP")
  (save-excursion
    (let* ((beg (if (region-active-p) (region-beginning)
                  (progn
                    (org-back-to-heading)
                    (point))))
           (end (if (region-active-p) (region-end)
                  (progn
                    (org-end-of-subtree)
                    (point))))
           (html (concat "--[[text/html"
                         (if arg "" "\nContent-Disposition: attachment")
                         "]]\n"
                         (org-export-region-as-html beg end t 'string))))
      (when (fboundp 'x-set-selection)
        (ignore-errors (x-set-selection 'PRIMARY html))
        (ignore-errors (x-set-selection 'CLIPBOARD html)))
      (message "html export done, pushed to kill ring and clipboard"))))
#+end_src

*** Adopting for Gnus

The whole magic lies in the special strings that mark a HTML
attachment.  So you might just have to find out what these special
strings are in message-mode and modify the functions accordingly.
** Add sunrise/sunset times to the agenda.
#+index: Agenda!Diary s-expressions
  -- Nick Dokos

The diary package provides the function =diary-sunrise-sunset= which can be used
in a diary s-expression in some agenda file like this:

#+begin_src org
%%(diary-sunrise-sunset)
#+end_src

Seb Vauban asked if it is possible to put sunrise and sunset in
separate lines. Here is a hack to do that. It adds two functions (they
have to be available before the agenda is shown, so I add them early
in my org-config file which is sourced from .emacs, but you'll have to
suit yourself here) that just parse the output of
diary-sunrise-sunset, instead of doing the right thing which would be
to take advantage of the data structures that diary/solar.el provides.
In short, a hack - so perfectly suited for inclusion here :-)

The functions (and latitude/longitude settings which you have to modify for
your location) are as follows:

#+begin_src emacs-lisp
(setq calendar-latitude 48.2)
(setq calendar-longitude 16.4)
(setq calendar-location-name "Vienna, Austria")

(autoload 'solar-sunrise-sunset "solar.el")
(autoload 'solar-time-string "solar.el")
(defun diary-sunrise ()
  "Local time of sunrise as a diary entry.
The diary entry can contain `%s' which will be replaced with
`calendar-location-name'."
  (let ((l (solar-sunrise-sunset date)))
    (when (car l)
      (concat
       (if (string= entry "")
           "Sunrise"
         (format entry (eval calendar-location-name))) " "
         (solar-time-string (caar l) nil)))))

(defun diary-sunset ()
  "Local time of sunset as a diary entry.
The diary entry can contain `%s' which will be replaced with
`calendar-location-name'."
  (let ((l (solar-sunrise-sunset date)))
    (when (cadr l)
      (concat
       (if (string= entry "")
           "Sunset"
         (format entry (eval calendar-location-name))) " "
         (solar-time-string (caadr l) nil)))))
#+end_src

You also need to add a couple of diary s-expressions in one of your agenda
files:

#+begin_src org
%%(diary-sunrise)Sunrise in %s
%%(diary-sunset)
#+end_src

This will show sunrise with the location and sunset without it.

The thread on the mailing list that started this can be found [[https://list.orgmode.org/87oc5rlwc4.wl%lists@700c.org][here]].
In comparison to the version posted on the mailing list, this one
gets rid of the timezone information and can show the location.
** Add lunar phases to the agenda.
#+index: Agenda!Diary s-expressions
   -- Rüdiger

Emacs comes with =lunar.el= to display the lunar phases (=M-x lunar-phases=).
This can be used to display lunar phases in the agenda display with the
following function:

#+begin_src emacs-lisp
(require 'cl-lib)

(org-no-warnings (defvar date))
(defun org-lunar-phases ()
  "Show lunar phase in Agenda buffer."
  (require 'lunar)
  (let* ((phase-list (lunar-phase-list (nth 0 date) (nth 2 date)))
         (phase (cl-find-if (lambda (phase) (equal (car phase) date))
                            phase-list)))
    (when phase
      (setq ret (concat (lunar-phase-name (nth 2 phase)) " "
                        (substring (nth 1 phase) 0 5))))))
#+end_src

Add the following line to an agenda file:

#+begin_src org
,* Lunar phase
,#+CATEGORY: Lunar
%%(org-lunar-phases)
#+end_src

This should display an entry on new moon, first/last quarter moon, and on full
moon.  You can customize the entries by customizing =lunar-phase-names=.

E.g., to add Unicode symbols:

#+begin_src emacs-lisp
(setq lunar-phase-names
      '("● New Moon" ; Unicode symbol: 🌑 Use full circle as fallback
        "☽ First Quarter Moon"
        "○ Full Moon" ; Unicode symbol: 🌕 Use empty circle as fallback
        "☾ Last Quarter Moon"))
#+end_src

Unicode 6 even provides symbols for the Moon with nice faces.  But those
symbols are currently barely supported in fonts.
See [[https://en.wikipedia.org/wiki/Astronomical_symbols#Moon][Astronomical symbols on Wikipedia]].

** Export BBDB contacts to org-contacts.el
#+index: Address Book!BBDB to org-contacts
Try this tool by Wes Hardaker:

http://www.hardakers.net/code/bbdb-to-org-contacts/

** Calculating date differences - how to write a simple elisp function
#+index: Timestamp!date calculations
#+index: Elisp!technique

Alexander Wingård asked how to calculate the number of days between a
time stamp in his org file and today (see
https://list.orgmode.org/064758C1-8D27-4647-A3C2-AB35FB8C6215@gmail.com  Although the
resulting answer is probably not of general interest, the method might
be useful to a budding Elisp programmer.

Alexander started from an already existing org function,
=org-evaluate-time-range=.  When this function is called in the context
of a time range (two time stamps separated by "=--="), it calculates the
number of days between the two dates and outputs the result in Emacs's
echo area. What he wanted was a similar function that, when called from
the context of a single time stamp, would calculate the number of days
between the date in the time stamp and today. The result should go to
the same place: Emacs's echo area.

The solution presented in the mail thread is as follows:

#+begin_src emacs-lisp
(defun aw/org-evaluate-time-range (&optional to-buffer)
  (interactive)
  (if (org-at-date-range-p t)
      (org-evaluate-time-range to-buffer)
    ;; otherwise, make a time range in a temp buffer and run o-e-t-r there
    (let ((headline (buffer-substring (point-at-bol) (point-at-eol))))
      (with-temp-buffer
	(insert headline)
	(goto-char (point-at-bol))
	(re-search-forward org-ts-regexp (point-at-eol) t)
	(if (not (org-at-timestamp-p t))
	    (error "No timestamp here"))
	(goto-char (match-beginning 0))
	(org-insert-time-stamp (current-time) nil nil)
	(insert "--")
	(org-evaluate-time-range to-buffer)))))
#+end_src

The function assumes that point is on some line with some time stamp
(or a date range) in it. Note that =org-evaluate-time-range= does not care
whether the first date is earlier than the second: it will always output
the number of days between the earlier date and the later date.

As stated before, the function itself is of limited interest (although
it satisfied Alexander's need).The *method* used might be of wider
interest however, so here is a short explanation.

The idea is that we want =org-evaluate-time-range= to do all the
heavy lifting, but that function requires that it be in a date-range
context. So the function first checks whether it's in a date range
context already: if so, it calls =org-evaluate-time-range= directly
to do the work. The trick now is to arrange things so we can call this
same function in the case where we do *not* have a date range
context. In that case, we manufacture one: we create a temporary
buffer, copy the line with the purported time stamp to the temp
buffer, find the time stamp (signal an error if no time stamp is
found) and insert a new time stamp with the current time before the
existing time stamp, followed by "=--=": voilà, we now have a time range
on which we can apply our old friend =org-evaluate-time-range= to
produce the answer. Because of the above-mentioned property
of =org-evaluate-time-range=, it does not matter if the existing
time stamp is earlier or later than the current time: the correct
number of days is output.

Note that at the end of the call to =with-temp-buffer=, the temporary
buffer goes away.  It was just used as a scratch pad for the function
to do some figuring.

The idea of using a temp buffer as a scratch pad has wide
applicability in Emacs programming. The rest of the work is knowing
enough about facilities provided by Emacs (e.g. regexp searching) and
by Org (e.g. checking for time stamps and generating a time stamp) so
that you don't reinvent the wheel, and impedance-matching between the
various pieces.

** ibuffer and org files

Neil Smithline posted this snippet to let you browse org files with
=ibuffer=:

#+BEGIN_SRC emacs-lisp
(require 'ibuffer)

(defun org-ibuffer ()
  "Open an `ibuffer' window showing only `org-mode' buffers."
  (interactive)
  (ibuffer nil "*Org Buffers*" '((used-mode . org-mode))))
#+END_SRC

** Enable org-mode links in other modes

Sean O'Halpin wrote a minor mode for this, please check it [[https://github.com/seanohalpin/org-link-minor-mode][here]].

See the relevant discussion [[https://list.orgmode.org/CAOXM+eX-xkGu4B8c=9RLQ+959Sn050wtqSHO2fqhFQX4X5c53A@mail.gmail.com][here]].

** poporg.el: edit comments in org-mode

[[https://github.com/QBobWatson/poporg/blob/master/poporg.el][poporg.el]] is a library by François Pinard which lets you edit comments
and strings from your code using a separate org-mode buffer.

** Convert a .csv file to an Org-mode table

Nicolas Richard has a [[https://list.orgmode.org/87a9rpy1x2.fsf@yahoo.fr][nice recipe]] using the pcsv library ([[http://marmalade-repo.org/packages/pcsv][available]] from
the Marmelade ELPA repository):

#+BEGIN_SRC emacs-lisp
(defun yf/lisp-table-to-org-table (table &optional function)
  "Convert a lisp table to `org-mode' syntax, applying FUNCTION to each of its elements.
The elements should not have any more newlines in them after
applying FUNCTION ; the default converts them to spaces. Return
value is a string containg the unaligned `org-mode' table."
  (unless (functionp function)
    (setq function (lambda (x) (replace-regexp-in-string "\n" " " x))))
  (mapconcat (lambda (x)                ; x is a line.
               (concat "| " (mapconcat function x " | ") " |"))
             table "\n"))

(defun yf/csv-to-table (beg end)
"Convert a csv file to an `org-mode' table."
  (interactive "r")
  (require 'pcsv)
  (insert (yf/lisp-table-to-org-table (pcsv-parse-region beg end)))
  (delete-region beg end)
  (org-table-align))
#+END_SRC

** Don't let visual-line-mode shadow org special commands

=M-x visual-line-mode RET= will use ~beginning-of-visual-line~,
~end-of-visual-line~, and ~kill-visual-line~ instead of
~org-beginning-of-line~, ~org-end-of-line~, and ~org-kill-line~, while 
those might be preferred in an Org buffer.

To avoid this, you can use this hack:

#+begin_src emacs-lisp
(add-hook 'visual-line-mode-hook
          (lambda () (when (derived-mode-p 'org-mode)
                       (local-set-key (kbd "C-a") #'org-beginning-of-line)
                       (local-set-key (kbd "C-e") #'org-end-of-line)
                       (local-set-key (kbd "C-k") #'org-kill-line))))
#+end_src

See [[https://list.orgmode.org/87zh7jfyal.fsf@gmail.com/][this discussion]].

** foldout.el

~foldout.el~, which is part of Emacs, is a nice little companion for
~outline-mode~.  With ~foldout.el~ one can narrow to a subtree and
later unnarrow.  ~foldout.el~ is useful for Org mode out of the box.

There is one annoyance though (at least for me):
~foldout-zoom-subtree~ opens the drawers.

This can be fixed e.g. by using the following slightly modified
version of ~foldout-zoom-subtree~ which uses function ~org-show-entry~
instead of ~outline-show-entry~.

#+begin_src emacs-lisp
(defun foldout-zoom-org-subtree (&optional exposure)
  "Same as `foldout-zoom-subtree' with often nicer zoom in Org mode."
  (interactive "P")
  (cl-letf
      (((symbol-function #'outline-show-entry) (lambda () (org-show-entry))))
    (foldout-zoom-subtree exposure)))
#+end_src
** Integrate Org Capture with YASnippet and Yankpad

Org Capture allows you to quickly store a note. You can mix the Org
Capture template system with those of [[https://github.com/joaotavora/yasnippet][YASnippet]] and [[https://github.com/Kungsgeten/yankpad][Yankpad]].

Check out the repository for how to do it: https://github.com/ag91/ya-org-capture.

A screencast that show the hack in action is [[https://github.com/ag91/ya-org-capture/blob/master/ya-org-capture-screehcast.gif][here]]. And a blog post
describing this in more detail is [[https://ag91.github.io/blog/2020/07/28/how-to-integrate-yasnippet-and-yankpad-with-org-capture/][here]].

** Slack messages as TODOs in your Org Agenda

Too many Slack messages reach you? Keep track of them in your Org
Agenda! With this hack you can mix the power of the [[https://github.com/yuya373/emacs-slack][Emacs Slack]] client
and the order of Org mode.

Try this by running the code at:
https://github.com/ag91/emacs-slack-org-mode-example

Also a blog post that describes in detail how this works is [[https://ag91.github.io/blog/2020/08/14/slack-messages-in-your-org-agenda/][here]].

* Hacking Org: Working with Org-mode and External Programs
** Use Org-mode with Screen [Andrew Hyatt]
#+index: Link!to screen session
"The general idea is that you start a task in which all the work will
take place in a shell.  This usually is not a leaf-task for me, but
usually the parent of a leaf task.  From a task in your org-file, M-x
ash-org-screen will prompt for the name of a session.  Give it a name,
and it will insert a link.  Open the link at any time to go the screen
session containing your work!"

https://list.orgmode.org/c8389b600801271541h4c68e70du589547ea5e8bd52f@mail.gmail.com

#+BEGIN_SRC emacs-lisp
(require 'term)

(defun ash-org-goto-screen (name)
  "Open the screen with the specified name in the window"
  (interactive "MScreen name: ")
  (let ((screen-buffer-name (ash-org-screen-buffer-name name)))
    (if (member screen-buffer-name
                (mapcar 'buffer-name (buffer-list)))
        (switch-to-buffer screen-buffer-name)
      (switch-to-buffer (ash-org-screen-helper name "-dr")))))

(defun ash-org-screen-buffer-name (name)
  "Returns the buffer name corresponding to the screen name given."
  (concat "*screen " name "*"))

(defun ash-org-screen-helper (name arg)
  ;; Pick the name of the new buffer.
  (let ((term-ansi-buffer-name
	 (generate-new-buffer-name
	  (ash-org-screen-buffer-name name))))
    (setq term-ansi-buffer-name
          (term-ansi-make-term
	   term-ansi-buffer-name "/usr/bin/screen" nil arg name))
    (set-buffer term-ansi-buffer-name)
    (term-mode)
    (term-char-mode)
    (term-set-escape-char ?\C-x)
    term-ansi-buffer-name))

(defun ash-org-screen (name)
  "Start a screen session with name"
  (interactive "MScreen name: ")
  (save-excursion
    (ash-org-screen-helper name "-S"))
  (insert-string (concat "[[screen:" name "]]")))

;; And don't forget to add ("screen" . "elisp:(ash-org-goto-screen
;; \"%s\")") to org-link-abbrev-alist.
#+END_SRC

** Org Agenda + Appt + Zenity
    :PROPERTIES:
    :CUSTOM_ID: org-agenda-appt-zenity
    :END:

#+index: Appointment!reminders
#+index: Appt!Zenity
#+BEGIN_EXPORT HTML
<a name="agenda-appt-zenity"></a>
#+END_EXPORT
Russell Adams posted this setup [[https://list.orgmode.org/20080302101346.GB18852@odin.demosthenes.org][on the list]].  It makes sure your agenda
appointments are known by Emacs, and it displays warnings in a [[http://live.gnome.org/Zenity][zenity]]
popup window.

#+BEGIN_SRC emacs-lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; For org appointment reminders

;; Get appointments for today
(defun my-org-agenda-to-appt ()
  (interactive)
  (setq appt-time-msg-list nil)
  (let ((org-deadline-warning-days 0))    ;; will be automatic in org 5.23
        (org-agenda-to-appt)))

;; Run once, activate and schedule refresh
(my-org-agenda-to-appt)
(appt-activate t)
(run-at-time "24:01" nil 'my-org-agenda-to-appt)

; 5 minute warnings
(setq appt-message-warning-time 15)
(setq appt-display-interval 5)

; Update appt each time agenda opened.
(add-hook 'org-finalize-agenda-hook 'my-org-agenda-to-appt)

; Setup zenify, we tell appt to use window, and replace default function
(setq appt-display-format 'window)
(setq appt-disp-window-function (function my-appt-disp-window))

(defun my-appt-disp-window (min-to-app new-time msg)
  (save-window-excursion (shell-command (concat
    "/usr/bin/zenity --info --title='Appointment' --text='"
    msg "' &") nil nil)))
#+END_SRC

** Org and appointment notifications on Mac OS 10.8

Sarah Bagby [[http://mid.gmane.org/EA76104A-9ACD-4141-8D33-2E4D810D9B5A@geol.ucsb.edu][posted some code]] on how to get appointments notifications on
Mac OS 10.8 with [[https://github.com/alloy/terminal-notifier][terminal-notifier]].

** Org-Mode + gnome-osd
#+index: Appointment!reminders
#+index: Appt!gnome-osd
Richard Riley uses gnome-osd in interaction with Org-Mode to display
appointments.  You can look at the code on the [[http://www.emacswiki.org/emacs-en/OrgMode-OSD][emacswiki]].

** txt2org convert text data to org-mode tables
From Eric Schulte

I often find it useful to generate Org-mode tables on the command line
from tab-separated data.  The following awk script makes this easy to
do.  Text data is read from STDIN on a pipe and any command line
arguments are interpreted as rows at which to insert hlines.

Here are two usage examples.
1. running the following
   : $ cat <<EOF|~/src/config/bin/txt2org
   : one 1
   : two 2
   : three 3
   : twenty 20
   : EOF
   results in
   : |    one |  1 |
   : |    two |  2 |
   : |  three |  3 |
   : | twenty | 20 |

2. and the following (notice the command line argument)
   : $ cat <<EOF|~/src/config/bin/txt2org 1
   : strings numbers
   : one 1
   : two 2
   : three 3
   : twenty 20
   : EOF
   results in
   : | strings | numbers |
   : |---------+---------|
   : |     one |       1 |
   : |     two |       2 |
   : |   three |       3 |
   : |  twenty |      20 |

Here is the script itself
#+begin_src awk
  #!/usr/bin/gawk -f
  #
  # Read tab separated data from STDIN and output an Org-mode table.
  #
  # Optional command line arguments specify row numbers at which to
  # insert hlines.
  #
  BEGIN {
      for(i=1; i<ARGC; i++){
          hlines[ARGV[i]+1]=1; ARGV[i] = "-"; } }

  {
      if(NF > max_nf){ max_nf = NF; };
      for(f=1; f<=NF; f++){
          if(length($f) > lengths[f]){ lengths[f] = length($f); };
          row[NR][f]=$f; } }

  END {
      hline_str="|"
      for(f=1; f<=max_nf; f++){
          for(i=0; i<(lengths[f] + 2); i++){ hline_str=hline_str "-"; }
          if( f != max_nf){ hline_str=hline_str "+"; }
          else            { hline_str=hline_str "|"; } }

      for(r=1; r<=NR; r++){ # rows
          if(hlines[r] == 1){ print hline_str; }
          printf "|";
          for(f=1; f<=max_nf; f++){ # columns
              cell=row[r][f]; padding=""
              for(i=0; i<(lengths[f] - length(cell)); i++){ padding=padding " "; }
              # for now just print everything right-aligned
              # if(cell ~ /[0-9.]/){ printf " %s%s |", cell, padding; }
              # else{                printf " %s%s |", padding, cell; }
              printf " %s%s |", padding, cell; }
          printf "\n"; }

      if(hlines[NR+1]){ print hline_str; } }
#+end_src

** remind2org
#+index: Agenda!Views
#+index: Agenda!and Remind (external program)
From Detlef Steuer

https://list.orgmode.org/20080112175502.0fb06b66@linux.site

#+BEGIN_QUOTE
Remind (http://www.roaringpenguin.com/products/remind) is a very powerful
command line calendaring program. Its features supersede the possibilities
of orgmode in the area of date specifying, so that I want to use it
combined with orgmode.

Using the script below I'm able use remind and incorporate its output in my
agenda views.  The default of using 13 months look ahead is easily
changed. It just happens I sometimes like to look a year into the
future. :-)
#+END_QUOTE

** Useful webjumps for conkeror
#+index: Shortcuts!conkeror
If you are using the [[http://conkeror.org][conkeror browser]], maybe you want to put this into
your =~/.conkerorrc= file:

#+begin_example
define_webjump("orglist", "http://search.gmane.org/?query=%s&group=gmane.emacs.orgmode");
define_webjump("worg", "http://www.google.com/cse?cx=002987994228320350715%3Az4glpcrritm&ie=UTF-8&q=%s&sa=Search&siteurl=orgmode.org%2Fworg%2F");
#+end_example

It creates two [[http://conkeror.org/Webjumps][webjumps]] for easily searching the Worg website and the
Org-mode mailing list.

** Use MathJax for HTML export without requiring JavaScript
#+index: Export!MathJax
As of 2010-08-14, MathJax is the default method used to export math to HTML.

If you like the results but do not want JavaScript in the exported pages,
check out [[http://www.jboecker.de/2010/08/15/staticmathjax.html][Static MathJax]], a XULRunner application which generates a static
HTML file from the exported version. It can also embed all referenced fonts
within the HTML file itself, so there are no dependencies to external files.

The download archive contains an elisp file which integrates it into the Org
export process (configurable per file with a "#+StaticMathJax:" line).

Read README.org and the comments in org-static-mathjax.el for usage instructions.

** Use checkboxes and progress cookies in HTML generated from Org
#+index: Export!HTML!Checkboxes
If you want to have dynamically-updated progress cookies for lists
with checkboxes in an HTML document exported from Org, [[https://lists.gnu.org/archive/html/emacs-orgmode/2020-06/msg00323.html][this mailing
list thread]] contains a (partial) Javascript solution.

Note that the Javascript depends on the default HTML structure
generated by Org at the time (the maint branch somewhere between 9.3
and 9.4), so the code won't work without modification if you customize
HTML output or if Org's default HTML export changes.

** Search Org files using lgrep
#+index: search!lgrep
Matt Lundin suggests this:

#+begin_src emacs-lisp
  (defun my-org-grep (search &optional context)
    "Search for word in org files.

Prefix argument determines number of lines."
    (interactive "sSearch for: \nP")
    (let ((grep-find-ignored-files '("#*" ".#*"))
	  (grep-template (concat "grep <X> -i -nH "
				 (when context
				   (concat "-C" (number-to-string context)))
				 " -e <R> <F>")))
      (lgrep search "*org*" "/home/matt/org/")))

  (global-set-key (kbd "<f8>") 'my-org-grep)
#+end_src

** Automatic screenshot insertion
#+index: Link!screenshot
Suggested by Russell Adams

#+begin_src emacs-lisp
  (defun my-org-screenshot ()
    "Take a screenshot into a time stamped unique-named file in the
  same directory as the org-buffer and insert a link to this file."
    (interactive)
    (setq filename
          (concat
           (make-temp-name
            (concat (buffer-file-name)
                    "_"
                    (format-time-string "%Y%m%d_%H%M%S_")) ) ".png"))
    (call-process "import" nil nil nil filename)
    (insert (concat "[[" filename "]]"))
    (org-display-inline-images))
#+end_src

** Capture invitations/appointments from MS Exchange emails
#+index: Appointment!MS Exchange
Dirk-Jan C.Binnema [[https://list.orgmode.org/20100718104515.4C21039C72A@djcbsoftware.nl][provided]] code to do this.  Please check
[[file:code/elisp/org-exchange-capture.el][org-exchange-capture.el]]

** Audio/video file playback within org mode
#+index: Link!audio/video
Paul Sexton provided code that makes =file:= links to audio or video files
(MP3, WAV, OGG, AVI, MPG, et cetera) play those files using the [[https://github.com/dbrock/bongo][Bongo]] Emacs
media player library. The user can pause, skip forward and backward in the
track, and so on from without leaving Emacs. Links can also contain a time
after a double colon -- when this is present, playback will begin at that
position in the track.

See the file [[file:code/elisp/org-player.el][org-player.el]]

** Under X11 Keep a window with the current agenda items at all time
#+index: Agenda!dedicated window
I struggle to keep (in emacs) a window with the agenda at all times.
For a long time I have wanted a sticky window that keeps this
information, and then use my window manager to place it and remove its
decorations (I can also force its placement in the stack: top always,
for example).

I wrote a small program in qt that simply monitors an HTML file and
displays it. Nothing more. It does the work for me, and maybe somebody
else will find it useful. It relies on exporting the agenda as HTML
every time the org file is saved, and then this little program
displays the html file. The window manager is responsible of removing
decorations, making it sticky, and placing it in same place always.

Here is a screenshot (see window to the bottom right). The decorations
are removed by the window manager:

http://turingmachine.org/hacking/org-mode/orgdisplay.png

Here is the code. As I said, very, very simple, but maybe somebody will
find if useful.

http://turingmachine.org/hacking/org-mode/

--daniel german

** Script (thru procmail) to output emails to an Org file
#+index: Conversion!email to org file
Tycho Garen sent [[http://comments.gmane.org/gmane.emacs.orgmode/44773][this]]:

: I've [...] created some procmail and shell glue that takes emails and
: inserts them into an org-file so that I can capture stuff on the go using
: the email program.

Everything is documented [[http://tychoish.com/code/org-mail/][here]].

** Save File With Different Format for Headings (fileconversion)
   :PROPERTIES:
   :CUSTOM_ID: fileconversion
   :END:
#+index: Conversion!fileconversion

Using hooks and on the fly
- When writing a buffer to the file: Replace the leading stars from
  headings with a file char.
- When reading a file into the buffer: Replace the file chars with
  leading stars for headings.

To change the file format just add or remove the keyword in the
~#+STARTUP:~ line in the Org buffer and save.

Now you can also change to Fundamental mode to see how the file looks
like on the level of the file, can go back to Org mode, reenter Org
mode or change to any other major mode and the conversion gets done
whenever necessary.

*** Headings Without Leading Stars (hidestarsfile and nbspstarsfile)
    :PROPERTIES:
    :CUSTOM_ID: hidestarsfile
    :END:
#+index: Conversion!fileconversion hidestarsfile

This is like "a cleaner outline view":
https://orgmode.org/manual/Clean-view.html

Example of the *file content* first with leading stars as usual and
below without leading stars through ~#+STARTUP: odd hidestars
hidestarsfile~:

#+BEGIN_SRC org
  ,#+STARTUP: odd hidestars
  [...]
  ***** TODO section
  ******* subsection
  ********* subsubsec
            - bla bla
  ***** section
        - bla bla
  ******* subsection
#+END_SRC

#+BEGIN_SRC org
  ,#+STARTUP: odd hidestars hidestarsfile
  [...]
      * TODO section
        * subsection
          * subsubsec
            - bla bla
      * section
        - bla bla
        * subsection
#+END_SRC

The latter is convenient for better human readability when an Org file,
additionally to Emacs, is read with a file viewer or, for smaller edits,
with an editor not capable of the Org file format.

~hidestarsfile~ is a hack and can not become part of the Org core:
- An Org file with ~hidestarsfile~ can not contain list items with a
  star as bullet due to the syntax conflict at read time. Mark
  E. Shoulson suggested to use the non-breaking space which is now
  implemented in fileconversion as ~nbspstarsfile~ as an alternative
  for ~hidestarsfile~. Although I don't recommend it because an editor
  like typically e. g. Emacs may render the non-breaking space
  differently from the space ~0x20~.
- An Org file with ~hidestarsfile~ can almost not be edited with an
  Org mode without added functionality of hidestarsfile as long as the
  file is not converted back.

*** Headings in Markdown Format (markdownstarsfile)
    :PROPERTIES:
    :CUSTOM_ID: markdownstarsfile
    :END:
#+index: Conversion!fileconversion markdownstarsfile

Together with ~oddeven~ you can use ~markdownstarsfile~ to be readable
or even basically editable with Markdown (does not make much sense
with ~odd~, see ~org-convert-to-odd-levels~ and
~org-convert-to-oddeven-levels~ for how to convert).

Example of the *file content*:

#+BEGIN_SRC org
  ,#+STARTUP: oddeven markdownstarsfile
  # section level 1
    1. first item of numbered list (same format in Org and Markdown)
  ## section level 2
     - first item of unordered list (same format in Org and Markdown)
  ### section level 3
      + first item of unordered list (same format in Org and Markdown)
  #### section level 4
       * first item of unordered list (same format in Org and Markdown)
       * avoid this item type to be compatible with Org hidestarsfile
#+END_SRC

An Org file with ~markdownstarsfile~ can not contain code comment
lines prefixed with ~#~, even not when within source blocks.

*** emacs-lisp code
    :PROPERTIES:
    :CUSTOM_ID: fileconversion-code
    :END:
#+index: Conversion!fileconversion emacs-lisp code

#+BEGIN_SRC emacs-lisp
  ;; - fileconversion version 0.10
  ;; - DISCLAIMER: Make a backup of your Org files before trying
  ;;   `f-org-fileconv-*'. It is recommended to use a version control
  ;;   system like git and to review and commit the changes in the Org
  ;;   files regularly.
  ;; - Supported "#+STARTUP:" formats: "hidestarsfile",
  ;;   "nbspstarsfile", "markdownstarsfile".

  ;; Design summary: fileconversion is a round robin of two states linked by
  ;; two actions:
  ;; - State `v-org-fileconv-level-org-p' is nil: The level is "file"
  ;;   (encoded).
  ;; - Action `f-org-fileconv-decode': Replace file char with "*".
  ;; - State `v-org-fileconv-level-org-p' is non-nil: The level is "Org"
  ;;   (decoded).
  ;; - Action `f-org-fileconv-encode': Replace "*" with file char.
  ;;
  ;; Naming convention of prefix:
  ;; - f-[...]: "my function", instead of the unspecific prefix `my-*'.
  ;; - v-[...]: "my variable", instead of the unspecific prefix `my-*'.

  (defvar v-org-fileconv-level-org-p nil
    "Whether level of buffer is Org or only file.
  nil: level is file (encoded), non-nil: level is Org (decoded).")
  (make-variable-buffer-local 'v-org-fileconv-level-org-p)
  ;; Survive a change of major mode that does `kill-all-local-variables', e.
  ;; g. when reentering Org mode through "C-c C-c" on a #+STARTUP: line.
  (put 'v-org-fileconv-level-org-p 'permanent-local t)

  ;; * Callback `f-org-fileconv-org-mode-beg' before `org-mode'
  (defadvice org-mode (before org-mode-advice-before-fileconv)
    (f-org-fileconv-org-mode-beg))
  (ad-activate 'org-mode)
  (defun f-org-fileconv-org-mode-beg ()
    ;; - Reason to test `buffer-file-name': Only when converting really
    ;;   from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
    ;;   file.
    ;; - No `message' to not wipe a possible "File mode specification error:".
    ;; - `f-org-fileconv-decode' in org-mode-hook would be too late for
    ;;   performance reasons, see
    ;;   http://lists.gnu.org/archive/html/emacs-orgmode/2013-11/msg00920.html
    (when (buffer-file-name) (f-org-fileconv-decode)))

  ;; * Callback `f-org-fileconv-org-mode-end' after `org-mode'
  (add-hook 'org-mode-hook 'f-org-fileconv-org-mode-end
            nil   ; _Prepend_ to hook to have it first.
            nil)  ; Hook addition global.
  (defun f-org-fileconv-org-mode-end ()
    ;; - Reason to test `buffer-file-name': only when converting really
    ;;   from/to an Org _file_, not e. g. for a temp Org buffer unrelated to a
    ;;   file.
    ;; - No `message' to not wipe a possible "File mode specification error:".
    (when (buffer-file-name)
      ;; - Adding this to `change-major-mode-hook' or "defadvice before" of
      ;;   org-mode would be too early and already trigger during find-file.
      ;; - Argument 4: t to limit hook addition to buffer locally, this way
      ;;   and as required the hook addition will disappear when the major
      ;;   mode of the buffer changes.
      (add-hook 'change-major-mode-hook 'f-org-fileconv-encode nil t)
      (add-hook 'before-save-hook       'f-org-fileconv-encode nil t)
      (add-hook 'after-save-hook        'f-org-fileconv-decode nil t)))

  (defun f-org-fileconv-re ()
    "Check whether there is a #+STARTUP: line for fileconversion.
  If found then return the expressions required for the conversion."
    (save-excursion
      (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
      (let (re-list (count 0))
        (while (re-search-forward "^[ \t]*#\\+STARTUP:" nil t)
          ;; #+STARTUP: hidestarsfile
          (when (string-match-p "\\bhidestarsfile\\b" (thing-at-point 'line))
            ;; Exclude e. g.:
            ;; - Line starting with star for bold emphasis.
            ;; - Line of stars to underline section title in loosely quoted
            ;;   ASCII style (star at end of line).
            (setq re-list '("\\(\\* \\)"  ; common-re
                            ?\ ))         ; file-char
            (setq count (1+ count)))
          ;; #+STARTUP: nbspstarsfile
          (when (string-match-p "\\bnbspstarsfile\\b" (thing-at-point 'line))
            (setq re-list '("\\(\\* \\)"  ; common-re
                            ?\xa0))       ; file-char non-breaking space
            (setq count (1+ count)))
          ;; #+STARTUP: markdownstarsfile
          (when (string-match-p "\\bmarkdownstarsfile\\b"
                                (thing-at-point 'line))
            ;; Exclude e. g. "#STARTUP:".
            (setq re-list '("\\( \\)"  ; common-re
                            ?#))       ; file-char
            (setq count (1+ count))))
        (when (> count 1) (error "More than one fileconversion found."))
        re-list)))

  (defun f-org-fileconv-decode ()
    "In headings replace file char with '*'."
    (let ((re-list (f-org-fileconv-re)))
      (when (and re-list (not v-org-fileconv-level-org-p))
        ;; No `save-excursion' to be able to keep point in case of error.
        (let* ((common-re (nth 0 re-list))
               (file-char (nth 1 re-list))
               (file-re   (concat "^" (string file-char) "+" common-re))
               (org-re    (concat "^\\*+" common-re))
               len
               (p         (point)))
          (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
          ;; Syntax check.
          (when (re-search-forward org-re nil t)
            (goto-char (match-beginning 0))
            (org-reveal)
            (error "Org fileconversion decode: Syntax conflict at point."))
          (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
          ;; Substitution.
          (with-silent-modifications
            (while (re-search-forward file-re nil t)
              (goto-char (match-beginning 0))
              ;; Faster than a lisp call of insert and delete on each single
              ;; char.
              (setq len (- (match-beginning 1) (match-beginning 0)))
              (insert-char ?* len)
              (delete-char len)))
          (goto-char p))))

          ;; Notes for ediff when only one file has fileconversion:
          ;; - The changes to the buffer with fileconversion until here are
          ;;   not regarded by `ediff-files' because the first call to diff is
          ;;   made with the bare files directly. Only `ediff-update-diffs'
          ;;   and `ediff-buffers' write the decoded buffers to temp files and
          ;;   then call diff with them.
          ;; - Workarounds (choose one):
          ;;   - After ediff-files first do a "!" (ediff-update-diffs) in the
          ;;     "*Ediff Control Panel*".
          ;;   - Instead of using `ediff-files' first open the files and then
          ;;     run `ediff-buffers' (better for e. g. a script that takes two
          ;;     files as arguments and uses "emacs --eval").

    ;; The level is Org most of all when no fileconversion is in effect.
    (setq v-org-fileconv-level-org-p t))

  (defun f-org-fileconv-encode ()
    "In headings replace '*' with file char."
    (let ((re-list (f-org-fileconv-re)))
      (when (and re-list v-org-fileconv-level-org-p)
        ;; No `save-excursion' to be able to keep point in case of error.
        (let* ((common-re (nth 0 re-list))
               (file-char (nth 1 re-list))
               (file-re   (concat "^" (string file-char) "+" common-re))
               (org-re    (concat "^\\*+" common-re))
               len
               (p         (point)))
          (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
          ;; Syntax check.
          (when (re-search-forward file-re nil t)
            (goto-char (match-beginning 0))
            (org-reveal)
            (error "Org fileconversion encode: Syntax conflict at point."))
          (goto-char (point-min))  ; `beginning-of-buffer' is not allowed.
          ;; Substitution.
          (with-silent-modifications
            (while (re-search-forward org-re nil t)
              (goto-char (match-beginning 0))
              ;; Faster than a lisp call of insert and delete on each single
              ;; char.
              (setq len (- (match-beginning 1) (match-beginning 0)))
              (insert-char file-char len)
              (delete-char len)))
          (goto-char p)
          (setq v-org-fileconv-level-org-p nil))))
    nil)  ; For the hook.
#+END_SRC

Michael Brand

** Meaningful diff for org files in a git repository
#+index: git!diff org files
Since most diff utilities are primarily meant for source code, it is
difficult to read diffs of text files like ~.org~ files easily. If you
version your org directory with a SCM like git you will know what I
mean. However for git, there is a way around. You can use
=gitattributes= to define a custom diff driver for org files. Then a
regular expression can be used to configure how the diff driver
recognises a "function".

Put the following in your =<org_dir>/.gitattributes=.
: *.org	diff=org
Then put the following lines in =<org_dir>/.git/config=
: [diff "org"]
: 	xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"

This will let you see diffs for org files with each hunk identified by
the unmodified headline closest to the changes. After the
configuration a diff should look something like the example below.

#+begin_example
diff --git a/org-hacks.org b/org-hacks.org
index a0672ea..92a08f7 100644
--- a/org-hacks.org
+++ b/org-hacks.org
@@ -2495,6 +2495,22 @@ ** Script (thru procmail) to output emails to an Org file

 Everything is documented [[http://tychoish.com/code/org-mail/][here]].

+** Meaningful diff for org files in a git repository
+
+Since most diff utilities are primarily meant for source code, it is
+difficult to read diffs of text files like ~.org~ files easily. If you
+version your org directory with a SCM like git you will know what I
+mean. However for git, there is a way around. You can use
+=gitattributes= to define a custom diff driver for org files. Then a
+regular expression can be used to configure how the diff driver
+recognises a "function".
+
+Put the following in your =<org_dir>/.gitattributes=.
+: *.org	diff=org
+Then put the following lines in =<org_dir>/.git/config=
+: [diff "org"]
+: 	xfuncname = "^(\\*+ [a-zA-Z0-9]+.+)$"
+
 * Musings

 ** Cooking?  Brewing?
#+end_example

** Opening devonthink links

John Wiegley wrote [[https://github.com/jwiegley/dot-emacs/blob/master/lisp/org-devonthink.el][org-devonthink.el]], which lets you handle devonthink
links from org-mode.

** Memacs - Org-mode collecting meta-data from the disk and cloud

Karl Voit designed Memacs ([[https://en.wikipedia.org/wiki/Memex][Memex]] and Emacs) which is a collection of
modules that are able to get meta-data from different kind of
sources. Memacs then generates output files containing meta-data in
Org-mode format. Those files a most likely integrated as ~*.org_archive~
files in your agenda.

This way, you can get a pretty decent overview of your (digital) life:
- file name timestamps ([[https://en.wikipedia.org/wiki/Iso_date][ISO 8601]]; like "2013-10-11 Product Demonstration.odp")
- emails (IMAP, POP, Maildir, mbox)
- RSS feeds (blog updates, ... *lots* of possibilities there!)
- version system commits (SVN, git)
- calendar (iCal, CSV)
- text messages from your phone (Android)
- phone calls (Android)
- photographs (EXIF)
- bank accounts ([[http://easybank.at][easybank]])
- usenet postings (slrn, mbox, ...)
- XML (a sub-set of easy-to-parse XML files can be parsed with minimal
  effort)

General idea: you set up the module(s) you would like to use once and
they are running in the background. As long as the data source does
not change, you should not have to worry about the module again.

It is hard to explain the vast amount of (small) benefits you get once
you have set up your Memacs modules.

There is [[http://arxiv.org/abs/1304.1332][a whitepaper which describes Memacs]] and its implications.

Memacs is [[https://github.com/novoid/Memacs][hosted on github]] and is written in Python.

You can use Memacs to write your own Memacs module: an example module
demonstrates how to write modules with very low effort. Please
consider a pull request on github so that other people can use your
module as well!

[[https://github.com/novoid/twitter-json_to_orgmode][Twitter JSON to Org-mode]] generates Memacs-like output files for
[[https://blog.twitter.com/2012/your-twitter-archive][Twitter export archives]] (JSON) but is independent of Memacs.

** Displaying Vega and Vega lite graphs with org

See [[https://github.com/vladkotu/vladkotu.github.io/blob/source/blog/org-clj-plot/clj-plot.org#vega-vega-lite-wrappers][this example]].

** Emacs as an Org capture server

#+begin_quote
The general idea is to run an Emacs server as a daemon which clients
can quickly connect to via a bash script. The client executes
org-capture and the frame closes upon finalizing or aborting the
capture.
#+end_quote

See No Wayman's [[https://list.orgmode.org/87a6xz3lnd.fsf@gmail.com/][message on the list]] and [[https://gist.github.com/progfolio/af627354f87542879de3ddc30a31adc1][this gist]] for details.

* Musings

** Cooking?  Brewing?
#+index: beer!brewing
#+index: cooking!conversions
See [[https://list.orgmode.org/87livkco7y.wl%egh@e6h.org][this message]] from Erik Hetzner:

It currently does metric/english conversion, and a few other tricks.
Basically I just use calc’s units code.  I think scaling recipes, or
turning percentages into weights would be pretty easy.

  https://gitorious.org/org-cook/org-cook

There is also, for those interested:

  https://gitorious.org/org-brew/org-brew

for brewing beer. This is again, mostly just calc functions, including
hydrometer correction, abv calculation, priming sugar for a given CO_2
volume, etc. More integration with org-mode should be possible: for
instance it would be nice to be able to use a lookup table (of ingredients)
to calculate target original gravity, IBUs, etc.