-
Notifications
You must be signed in to change notification settings - Fork 18
/
org_tools.py
121 lines (102 loc) · 2.94 KB
/
org_tools.py
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
from datetime import datetime
import re
from typing import List, Optional
DEFAULT_TEMPLATE = "* %U %:description %:tags\n%:link\n%:initial\n"
def date2org(t: datetime) -> str:
return t.strftime("%Y-%m-%d %a")
def datetime2orgtime(t: datetime) -> str:
return t.strftime("%H:%M")
def datetime2org(t: datetime) -> str:
return date2org(t) + " " + datetime2orgtime(t)
def empty(s) -> bool:
return s is None or len(s.strip()) == 0
def as_org(
url: str,
title: str,
selection: str,
comment: str,
tags: List[str],
org_template: str,
):
"""
Formats captured results according to org template. Supports all sensible (e.g. non-interactive) template expansions from https://orgmode.org/manual/Template-expansion.html#Template-expansion.
Additionally, supports :selection, :comment and :tags expansions.
You can look at `test_templates` for some specific examples.
"""
py_template = re.sub(r'%[:]?([?\w]+)', r'{\1}', org_template)
NOW = datetime.now()
org_date = date2org(NOW)
org_datetime = datetime2org(NOW)
tags_s = '' if len(tags) == 0 else (':' + ':'.join(tags) + ':')
# TODO tabulate selection and comments?
# TODO not sure, maybe add as org quote?
parts = []
if not empty(selection):
parts.extend([
'Selection:',
selection,
])
if not empty(comment):
parts.extend([
'Comment:',
comment
])
initial = '\n'.join(parts)
res = py_template.format(
t=f'<{org_date}>',
u=f'[{org_date}]',
T=f'<{org_datetime}>',
U=f'[{org_datetime}]',
description=title,
link=url,
initial=initial,
i=initial,
tags=tags_s,
selection=selection,
comment=comment,
annotation=f'[[{url}][{title}]]', # https://orgmode.org/manual/capture-protocol.html
**{'?': ''}, # just ignore it
)
return res
# TODO escaping?
# just checks it's not crashing for now
def test_templates():
url = 'https://whatever'
title = 'hello'
selection = """some
selected
text
"""
comment = 'fafewfewf'
tags = ['aba', 'caba']
# https://orgmode.org/guide/Capture-templates.html
org_templates = [
DEFAULT_TEMPLATE,
"* %? [[%:link][%:description]] \nCaptured On: %U",
"* %:annotation",
"* %U %:description :protocol: \n %:link \n%:initial \n\n",
"* %t captured stuff %:tags \n ",
"\n** Selection\n%:selection\n** Comment\n%:comment\n",
"""* TODO [#A] %:link
** Selection
%:selection
** Comment
%:comment
""",
"""* %T %:link %:description
#+BEGIN_QUOTE
%:selection
#+END_QUOTE
""",
]
for org_template in org_templates:
res = as_org(
url,
title,
selection,
comment,
tags,
org_template=org_template
)
print()
print(res)