├── .dir-locals.el
├── .gitattributes
├── .gitignore
├── LICENSE
├── Makefile
├── README.org
├── example.org
├── makem.sh
├── notes.org
├── org-make-toc.el
└── test
├── data.org
└── test.org
/.dir-locals.el:
--------------------------------------------------------------------------------
1 | ;;; Directory Local Variables
2 | ;;; For more information see (info "(emacs) Directory Variables")
3 |
4 | ((magit-status-mode
5 | (magit-todos-exclude-globs "Makefile" "makem.sh")))
6 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | makem.sh linguist-vendored
2 | Makefile linguist-vendored
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.elc
2 | /.sandbox/
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | # * makem.sh/Makefile --- Script to aid building and testing Emacs Lisp packages
2 |
3 | # This Makefile is from the makem.sh repo: .
4 |
5 | # * Arguments
6 |
7 | # For consistency, we use only var=val options, not hyphen-prefixed options.
8 |
9 | # NOTE: I don't like duplicating the arguments here and in makem.sh,
10 | # but I haven't been able to find a way to pass arguments which
11 | # conflict with Make's own arguments through Make to the script.
12 | # Using -- doesn't seem to do it.
13 |
14 | ifdef install-deps
15 | INSTALL_DEPS = "--install-deps"
16 | endif
17 | ifdef install-linters
18 | INSTALL_LINTERS = "--install-linters"
19 | endif
20 |
21 | ifdef sandbox
22 | ifeq ($(sandbox), t)
23 | SANDBOX = --sandbox
24 | else
25 | SANDBOX = --sandbox=$(sandbox)
26 | endif
27 | endif
28 |
29 | ifdef debug
30 | DEBUG = "--debug"
31 | endif
32 |
33 | # ** Verbosity
34 |
35 | # Since the "-v" in "make -v" gets intercepted by Make itself, we have
36 | # to use a variable.
37 |
38 | verbose = $(v)
39 |
40 | ifneq (,$(findstring vv,$(verbose)))
41 | VERBOSE = "-vv"
42 | else ifneq (,$(findstring v,$(verbose)))
43 | VERBOSE = "-v"
44 | endif
45 |
46 | # * Rules
47 |
48 | # TODO: Handle cases in which "test" or "tests" are called and a
49 | # directory by that name exists, which can confuse Make.
50 |
51 | %:
52 | @./makem.sh $(DEBUG) $(VERBOSE) $(SANDBOX) $(INSTALL_DEPS) $(INSTALL_LINTERS) $(@)
53 |
54 | .DEFAULT: init
55 | init:
56 | @./makem.sh $(DEBUG) $(VERBOSE) $(SANDBOX) $(INSTALL_DEPS) $(INSTALL_LINTERS)
57 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | #+PROPERTY: LOGGING nil
2 |
3 | * org-make-toc
4 | :PROPERTIES:
5 | :TOC: ignore
6 | :END:
7 |
8 | [[https://melpa.org/#/org-make-toc][file:https://melpa.org/packages/org-make-toc-badge.svg]] [[https://stable.melpa.org/#/org-make-toc][file:https://stable.melpa.org/packages/org-make-toc-badge.svg]]
9 |
10 | This package makes it easy to have one or more customizable tables of contents in Org files. They can be updated manually, or automatically when the file is saved. Links to headings are created compatible with GitHub's Org renderer.
11 |
12 | * Contents :noexport:
13 | :PROPERTIES:
14 | :TOC: :include siblings :depth 0 :ignore this
15 | :END:
16 | :CONTENTS:
17 | - [[#installation][Installation]]
18 | - [[#usage][Usage]]
19 | - [[#changelog][Changelog]]
20 | :END:
21 |
22 | * Installation
23 |
24 | ** MELPA
25 |
26 | If you installed from MELPA, you're done.
27 |
28 | ** Manual
29 |
30 | Install these required packages:
31 |
32 | + =dash=
33 | + =s=
34 |
35 | Then put this file in your load-path, and put this in your init file:
36 |
37 | #+BEGIN_SRC elisp
38 | (require 'org-make-toc)
39 | #+END_SRC
40 |
41 | * Usage
42 |
43 | A document may have any number of tables of contents (TOCs), each of which may list entries in a highly configurable way.
44 |
45 | To make a basic TOC, follow these steps:
46 |
47 | 1. Choose a heading to contain a TOC and move the point to it.
48 | 2. Run command =org-make-toc-insert=, which inserts a =:CONTENTS:= drawer and sets TOC properties. Set the =include= property to =all=.
49 | 3. Run the command =org-make-toc= to update all TOCs in the document.
50 |
51 | Use command =org-make-toc-set= to change TOC properties for the entry at point with completion.
52 |
53 | ** Example
54 |
55 | Here's a simple document containing a simple TOC:
56 |
57 | #+BEGIN_SRC org
58 | ,* Heading
59 | :PROPERTIES:
60 | :TOC: :include all
61 | :END:
62 |
63 | This text appears before the TOC.
64 |
65 | :CONTENTS:
66 | - [[#heading][Heading]]
67 | - [[#subheading][Subheading]]
68 | :END:
69 |
70 | This text appears after it.
71 |
72 | ,** Subheading
73 | #+END_SRC
74 |
75 | ** Advanced
76 |
77 | The =:TOC:= property is a property list which may set these keys and values.
78 |
79 | These keys accept one setting, like =:include all=:
80 |
81 | + =:include= Which headings to include in the TOC.
82 | - =all= Include all headings in the document.
83 | - =descendants= Include the TOC's descendant headings.
84 | - =siblings= Include the TOC's sibling headings.
85 | + =:depth= A number >= 0 indicating a depth relative to this heading. Descendant headings at or above this relative depth are included in TOCs that include this heading.
86 |
87 | These keys accept either one setting or a list of settings, like =:force depth= or =:force (depth ignore)=:
88 |
89 | + =:force= Heading-local settings to override when generating the TOC at this heading.
90 | - =depth= Override =:depth= settings.
91 | - =ignore= Override =:ignore= settings.
92 | + =:ignore= Which headings, relative to this heading, to exclude from TOCs.
93 | - =descendants= Exclude descendants of this heading.
94 | - =siblings= Exclude siblings of this heading.
95 | - =this= Exclude this heading (not its siblings or descendants).
96 | + =:local= Heading-local settings to ignore when generating TOCs at higher levels.
97 | - =depth= Ignore =:depth= settings.
98 |
99 | See [[https://github.com/alphapapa/org-make-toc/blob/master/example.org][example.org]] for a comprehensive example of the features described above.
100 |
101 | ** Automatically update on save
102 |
103 | To automatically update a file's TOC when the file is saved, use the command =add-file-local-variable= to add =org-make-toc= to the Org file's =before-save-hook=.
104 |
105 | Or, you may activate it in all Org buffers like this:
106 |
107 | #+BEGIN_SRC elisp
108 | (add-hook 'org-mode-hook #'org-make-toc-mode)
109 | #+END_SRC
110 |
111 | ** Making links work in both Emacs/Org and on GitHub
112 |
113 | Because of the way GitHub renders Org documents and links, it's not possible to make links which work in both Org itself and the GitHub-rendered HTML unless headings have ~CUSTOM_ID~ properties. If the option ~org-make-toc-insert-custom-ids~ is enabled, this package will automatically add them as needed.
114 |
115 | * Changelog
116 | :PROPERTIES:
117 | :TOC: :depth 0
118 | :END:
119 |
120 | ** 0.6
121 |
122 | *Compatibility*
123 | + Org 9.3 or later is now required.
124 |
125 | *Additions*
126 |
127 | + Option ~org-make-toc-insert-custom-ids~ automatically adds ~CUSTOM_ID~ properties to headings so links can work on both GitHub-rendered Org files and in Emacs. (Thanks to [[https://github.com/noctuid][Fox Kiester]].)
128 |
129 | *Fixes*
130 |
131 | + Tolerate whitespace before drawer opening/closing lines. ([[https://github.com/alphapapa/org-make-toc/pull/15][#15]], [[https://github.com/alphapapa/org-make-toc/issues/17][#17]]. Thanks to [[https://github.com/progfolio][Nicholas Vollmer]].)
132 | + Link-type function called with position as argument. (Fixes occasional bugs with heading IDs.)
133 | + Mode ~org-make-toc-mode~ now adds to the ~before-save-hook~ in the local buffer rather than globally. ([[https://github.com/alphapapa/org-make-toc/pull/24][#24]]. Thanks to [[https://github.com/akirak][Akira Komamura]].)
134 |
135 | ** 0.5
136 |
137 | This version is a major rewrite that requires reconfiguring existing TOCs. Please see the usage instructions anew. Users who don't want to convert to 0.5-style TOCs may continue using version 0.4.
138 |
139 | *Changes*
140 | + TOCs are now contained in =:CONTENTS:= drawers, which allows them to co-exist with entry content and be placed flexibly.
141 | + The =:TOC:= property, which contains all TOC settings, is now formatted like a Lisp property list, and the settings have been redesigned to be clearer, more concise, more flexible, and more powerful.
142 |
143 | ** 0.4
144 |
145 | *Additions*
146 | + Omit invisible characters from link titles (e.g. Org markup characters like ~=~ and =~=).
147 | + Option ~org-make-toc-link-type-fn~ allows choosing GitHub-compatible or regular Org-style links.
148 | + Command =org-make-toc-at-point=, which updates the TOC at the current entry.
149 | + Optionally place TOC in a =:CONTENTS:= drawer which co-exists with entry content.
150 |
151 | *Changes*
152 | + Changed no-TOC-node-found error to a message, so e.g. when =org-make-toc-mode= is active in a buffer without a TOC, saving will not signal an error.
153 |
154 | *Fixes*
155 | + Remove excess indentation from TOC while preserving list structure.
156 | + Don't insert a blank line when TOC is empty.
157 | + Autoload minor mode. (Thanks to [[https://github.com/akirak][Akira Komamura]].)
158 | + Filename prefix order in links. (Thanks to [[https://github.com/dakra][Daniel Kraus]].)
159 |
160 | ** 0.3.1
161 |
162 | *Fixes*
163 | + Use =cadr= instead of =second=.
164 |
165 | ** 0.3
166 |
167 | *Additions*
168 | + Option ~org-make-toc-filename-prefix~ to add the filename before the anchor in links. This allows a ToC to refer to entries in another file by manually copying a ToC from one file into another. See [[https://github.com/alphapapa/org-make-toc/pull/2][issue 2]]. Thanks to [[https://github.com/dakra][Daniel Kraus]].
169 |
170 | *Changes*
171 | + Minor refactoring.
172 |
173 | ** 0.2
174 |
175 | *Additions*
176 | + Multiple tables of contents are now supported in a single document.
177 | + Entries' =TOC= property can now also be set to the values =all=, =children=, and =siblings=, which allow tables of contents to be created for only parts of a document.
178 | - =all= includes all entries in a document, including other tables of contents, except ignored entries.
179 | - =children= includes only child entries, except ignored entries.
180 | - =siblings= includes only sibling entries, except ignored entries.
181 | + The command =org-make-toc-mode= toggles =org-make-toc= on the =before-save-hook= in the current buffer. This may be added to the global =org-mode-hook= to activate it in every Org buffer.
182 | + The =examples.org= file shows an example of all of the options used together in a complex, book-like document.
183 |
184 | ** 0.1
185 |
186 | Initial release.
187 |
188 | * Credits
189 | :PROPERTIES:
190 | :TOC: :ignore this
191 | :END:
192 |
193 | This package was inspired by Sergei Nosov's [[https://github.com/snosov1/toc-org][toc-org]] package.
194 |
195 | * Development
196 | :PROPERTIES:
197 | :TOC: :ignore this
198 | :END:
199 |
200 | Bug reports, feature requests, suggestions — /oh my/!
201 |
202 | * License
203 | :PROPERTIES:
204 | :TOC: :ignore this
205 | :END:
206 |
207 | GPLv3
208 |
209 | # Local Variables:
210 | # eval: (require 'org-make-toc)
211 | # before-save-hook: org-make-toc
212 | # org-export-with-properties: ()
213 | # org-export-with-title: t
214 | # End:
215 |
216 |
--------------------------------------------------------------------------------
/example.org:
--------------------------------------------------------------------------------
1 |
2 |
3 | * Document top-level heading
4 |
5 | This is an example of a complex document. To see the Org syntax, view the [[https://raw.githubusercontent.com/alphapapa/org-make-toc/master/example.org][raw version]] of this file.
6 |
7 | ** Main ToC: Itself excluded
8 | :PROPERTIES:
9 | :TOC: :include all :ignore this
10 | :END:
11 |
12 | This heading itself is excluded from its TOC.
13 |
14 | :CONTENTS:
15 | - [[#document-top-level-heading][Document top-level heading]]
16 | - [[#chapter-1-inline-toc][Chapter 1: Inline TOC]]
17 | - [[#section-1a][Section 1a]]
18 | - [[#subsection-1a1][Subsection 1a1]]
19 | - [[#subsection-1b1-included-despite-its-excluded-parent][Subsection 1b1: Included, despite its excluded parent]]
20 | - [[#chapter-2-toc-as-sibling][Chapter 2: TOC as sibling]]
21 | - [[#chapter-2-toc][Chapter 2 TOC]]
22 | - [[#section-2a][Section 2a]]
23 | - [[#subsection-2a1][Subsection 2a1]]
24 | - [[#section-2b-child-is-excluded][Section 2b: Child is excluded]]
25 | - [[#chapter-3-toc-as-parent][Chapter 3: TOC as parent]]
26 | - [[#chapter-3-toc][Chapter 3 TOC]]
27 | - [[#section-3a][Section 3a]]
28 | - [[#subsection-3a1][Subsection 3a1]]
29 | - [[#section-3b][Section 3b]]
30 | - [[#subsection-3b1][Subsection 3b1]]
31 | - [[#chapter-4-limited-depth][Chapter 4: Limited depth]]
32 | - [[#section-4a][Section 4a]]
33 | - [[#section-4b][Section 4b]]
34 | - [[#chapter-5-local-settings][Chapter 5: Local settings]]
35 | - [[#section-5a][Section 5a]]
36 | - [[#section-5a1][Section 5a1]]
37 | - [[#section-5a2][Section 5a2]]
38 | - [[#section-5b][Section 5b]]
39 | - [[#section-5b1][Section 5b1]]
40 | - [[#section-5c][Section 5c]]
41 | - [[#section-5c1][Section 5c1]]
42 | - [[#section-5c1a][Section 5c1a]]
43 | - [[#section-5c1b][Section 5c1b]]
44 | - [[#appendices][Appendices]]
45 | - [[#appendix-a-comprehensive-toc][Appendix A: Comprehensive TOC]]
46 | - [[#appendix-b][Appendix B]]
47 | - [[#appendix-c][Appendix C]]
48 | :END:
49 |
50 | ** Chapter 1: Inline TOC
51 | :PROPERTIES:
52 | :TOC: :include descendants
53 | :END:
54 |
55 | This chapter includes its TOC inline, with text before...
56 |
57 | :CONTENTS:
58 | - [[#section-1a][Section 1a]]
59 | - [[#subsection-1a1][Subsection 1a1]]
60 | - [[#subsection-1b1-included-despite-its-excluded-parent][Subsection 1b1: Included, despite its excluded parent]]
61 | :END:
62 |
63 | ...and after it.
64 |
65 | *** Section 1a
66 |
67 | This section is included in the chapter's TOC.
68 |
69 | **** Subsection 1a1
70 |
71 | This subsection is also included.
72 |
73 | *** Section 1b: Excluded, but child included
74 | :PROPERTIES:
75 | :TOC: :ignore this
76 | :END:
77 |
78 | This section is not included in the chapter's TOC, but its subsection is (you probably wouldn't want to do this, but you could).
79 |
80 | **** Subsection 1b1: Included, despite its excluded parent
81 |
82 | This subsection is included in the chapter's TOC even though its parent is excluded.
83 |
84 | ** Chapter 2: TOC as sibling
85 |
86 | This chapter has its TOC as a sibling of its sections.
87 |
88 | *** Chapter 2 TOC
89 | :PROPERTIES:
90 | :TOC: :include siblings
91 | :END:
92 | :CONTENTS:
93 | - [[#section-2a][Section 2a]]
94 | - [[#subsection-2a1][Subsection 2a1]]
95 | - [[#section-2b-child-is-excluded][Section 2b: Child is excluded]]
96 | :END:
97 |
98 | *** Section 2a
99 |
100 | This section is included.
101 |
102 | **** Subsection 2a1
103 |
104 | This subsection is included.
105 |
106 | *** Section 2b: Child is excluded
107 | :PROPERTIES:
108 | :TOC: :depth 0
109 | :END:
110 |
111 | This section is included in the TOC.
112 |
113 | **** Subsection 2b1: The excluded child
114 |
115 | But its subsection is not.
116 |
117 | ** Chapter 3: TOC as parent
118 |
119 | This chapter has its TOC as a parent of the chapter sections.
120 |
121 | *** Chapter 3 TOC
122 | :PROPERTIES:
123 | :TOC: :include descendants
124 | :END:
125 | :CONTENTS:
126 | - [[#section-3a][Section 3a]]
127 | - [[#subsection-3a1][Subsection 3a1]]
128 | - [[#section-3b][Section 3b]]
129 | - [[#subsection-3b1][Subsection 3b1]]
130 | :END:
131 |
132 | **** Section 3a
133 |
134 | This section is included.
135 |
136 | ***** Subsection 3a1
137 |
138 | This subsection is included.
139 |
140 | **** Section 3b
141 |
142 | This section is included.
143 |
144 | ***** Subsection 3b1
145 |
146 | This subsection is included.
147 |
148 | ** Chapter 4: Limited depth
149 | :PROPERTIES:
150 | :TOC: :include descendants :depth 1
151 | :END:
152 |
153 | This chapter's TOC uses =:depth 1= to exclude subsections.
154 |
155 | :CONTENTS:
156 | - [[#section-4a][Section 4a]]
157 | - [[#section-4b][Section 4b]]
158 | :END:
159 |
160 | *** Section 4a
161 |
162 | This section is included in the chapter's TOC.
163 |
164 | **** Subsection 4a1
165 |
166 | This subsection is excluded.
167 |
168 | *** Section 4b
169 |
170 | This section is included in the chapter's TOC.
171 |
172 | **** Subsection 4b1
173 |
174 | This subsection is excluded.
175 |
176 | ** Chapter 5: Local settings
177 | :PROPERTIES:
178 | :TOC: :include descendants :depth 2
179 | :END:
180 |
181 | This chapter's TOC includes descendants only two levels deep by default. However, Section 5b sets =:depth 3= (relative to itself) in order to include deeper descendants in its own section TOC. Normally this depth setting would propagate up to the Chapter 5 TOC and cause, e.g. Section 5b1a to be included in the Chapter 5 TOC. However, Section 5b also sets =:local depth=, which prevents its depth setting from propagating up the tree, so the sections 5b1a and 5b1b are excluded from the Chapter 5 TOC.
182 |
183 | One could also set =:force depth= in the chapter 5 TOC to accomplish the same thing. However, doing so would force the depth setting for /all/ subtrees in its TOC. Instead, by using =:local depth= on Section 5b, we allow Section 5c to set =:depth 3=, which /is/ allowed to propagate up to the chapter 5 TOC. So notice that, although Sections 5b and 5c are structurally identical, the way they are shown in the Chapter 5 TOC differs, because Section 5b sets =:local depth= while Section 5c does not.
184 |
185 | If this seems complicated, perhaps it is, but it's optional power that's available when needed.
186 |
187 | :CONTENTS:
188 | - [[#section-5a][Section 5a]]
189 | - [[#section-5a1][Section 5a1]]
190 | - [[#section-5a2][Section 5a2]]
191 | - [[#section-5b][Section 5b]]
192 | - [[#section-5b1][Section 5b1]]
193 | - [[#section-5c][Section 5c]]
194 | - [[#section-5c1][Section 5c1]]
195 | - [[#section-5c1a][Section 5c1a]]
196 | - [[#section-5c1b][Section 5c1b]]
197 | :END:
198 |
199 | *** Section 5a
200 |
201 | This section is included in the Chapter 5 TOC.
202 |
203 | **** Section 5a1
204 |
205 | This section is included in the Chapter 5 TOC.
206 |
207 | **** Section 5a2
208 |
209 | This section is included in the Chapter 5 TOC.
210 |
211 | *** Section 5b
212 | :PROPERTIES:
213 | :TOC: :include descendants :depth 3 :local depth
214 | :END:
215 | :CONTENTS:
216 | - [[#section-5b1][Section 5b1]]
217 | - [[#section-5b1a][Section 5b1a]]
218 | - [[#section-5b1b][Section 5b1b]]
219 | :END:
220 |
221 | **** Section 5b1
222 |
223 | This section is included in the Chapter 5 TOC.
224 |
225 | ***** Section 5b1a
226 |
227 | This section is *not* included in the Chapter 5 TOC.
228 |
229 | ***** Section 5b1b
230 |
231 | This section is *not* included in the Chapter 5 TOC.
232 |
233 | *** Section 5c
234 | :PROPERTIES:
235 | :TOC: :include descendants :depth 3
236 | :END:
237 | :CONTENTS:
238 | - [[#section-5c1][Section 5c1]]
239 | - [[#section-5c1a][Section 5c1a]]
240 | - [[#section-5c1b][Section 5c1b]]
241 | :END:
242 |
243 | **** Section 5c1
244 |
245 | This section is included in the Chapter 5 TOC.
246 |
247 | ***** Section 5c1a
248 |
249 | This section is included in the Chapter 5 TOC.
250 |
251 | ***** Section 5c1b
252 |
253 | This section is included in the Chapter 5 TOC.
254 |
255 | ** Appendices
256 | :PROPERTIES:
257 | :TOC: :include descendants :depth 1
258 | :END:
259 |
260 | The appendices have a local TOC, and one of them is a comprehensive TOC of the entire document (unlike the main TOC at the top of the document, which is abridged).
261 |
262 | :CONTENTS:
263 | - [[#appendix-a-comprehensive-toc][Appendix A: Comprehensive TOC]]
264 | - [[#appendix-b][Appendix B]]
265 | - [[#appendix-c][Appendix C]]
266 | :END:
267 |
268 | *** Appendix A: Comprehensive TOC
269 | :PROPERTIES:
270 | :TOC: :include all :force (depth ignore)
271 | :END:
272 |
273 | This comprehensive TOC uses =:include all :force (depth ignore)= to force all headings to be included, regardless of their local settings.
274 |
275 | :CONTENTS:
276 | - [[#document-top-level-heading][Document top-level heading]]
277 | - [[#main-toc-itself-excluded][Main ToC: Itself excluded]]
278 | - [[#chapter-1-inline-toc][Chapter 1: Inline TOC]]
279 | - [[#section-1a][Section 1a]]
280 | - [[#subsection-1a1][Subsection 1a1]]
281 | - [[#section-1b-excluded-but-child-included][Section 1b: Excluded, but child included]]
282 | - [[#subsection-1b1-included-despite-its-excluded-parent][Subsection 1b1: Included, despite its excluded parent]]
283 | - [[#chapter-2-toc-as-sibling][Chapter 2: TOC as sibling]]
284 | - [[#chapter-2-toc][Chapter 2 TOC]]
285 | - [[#section-2a][Section 2a]]
286 | - [[#subsection-2a1][Subsection 2a1]]
287 | - [[#section-2b-child-is-excluded][Section 2b: Child is excluded]]
288 | - [[#subsection-2b1-the-excluded-child][Subsection 2b1: The excluded child]]
289 | - [[#chapter-3-toc-as-parent][Chapter 3: TOC as parent]]
290 | - [[#chapter-3-toc][Chapter 3 TOC]]
291 | - [[#section-3a][Section 3a]]
292 | - [[#subsection-3a1][Subsection 3a1]]
293 | - [[#section-3b][Section 3b]]
294 | - [[#subsection-3b1][Subsection 3b1]]
295 | - [[#chapter-4-limited-depth][Chapter 4: Limited depth]]
296 | - [[#section-4a][Section 4a]]
297 | - [[#subsection-4a1][Subsection 4a1]]
298 | - [[#section-4b][Section 4b]]
299 | - [[#subsection-4b1][Subsection 4b1]]
300 | - [[#chapter-5-local-settings][Chapter 5: Local settings]]
301 | - [[#section-5a][Section 5a]]
302 | - [[#section-5a1][Section 5a1]]
303 | - [[#section-5a2][Section 5a2]]
304 | - [[#section-5b][Section 5b]]
305 | - [[#section-5b1][Section 5b1]]
306 | - [[#section-5b1a][Section 5b1a]]
307 | - [[#section-5b1b][Section 5b1b]]
308 | - [[#section-5c][Section 5c]]
309 | - [[#section-5c1][Section 5c1]]
310 | - [[#section-5c1a][Section 5c1a]]
311 | - [[#section-5c1b][Section 5c1b]]
312 | - [[#appendices][Appendices]]
313 | - [[#appendix-a-comprehensive-toc][Appendix A: Comprehensive TOC]]
314 | - [[#appendix-b][Appendix B]]
315 | - [[#appendix-c][Appendix C]]
316 | - [[#footer-excluded][Footer: Excluded]]
317 | :END:
318 |
319 | *** Appendix B
320 |
321 | Possibly vestigial.
322 |
323 | *** Appendix C
324 |
325 | Definitely vestigial.
326 |
327 | ** Footer: Excluded
328 | :PROPERTIES:
329 | :TOC: :ignore this
330 | :END:
331 |
332 | # Local Variables:
333 | # before-save-hook: org-make-toc
334 | # End:
335 |
--------------------------------------------------------------------------------
/makem.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # * makem.sh --- Script to aid building and testing Emacs Lisp packages
4 |
5 | # URL: https://github.com/alphapapa/makem.sh
6 | # Version: 0.7-pre
7 |
8 | # * Commentary:
9 |
10 | # makem.sh is a script that helps to build, lint, and test Emacs Lisp
11 | # packages. It aims to make linting and testing as simple as possible
12 | # without requiring per-package configuration.
13 |
14 | # It works similarly to a Makefile in that "rules" are called to
15 | # perform actions such as byte-compiling, linting, testing, etc.
16 |
17 | # Source and test files are discovered automatically from the
18 | # project's Git repo, and package dependencies within them are parsed
19 | # automatically.
20 |
21 | # Output is simple: by default, there is no output unless errors
22 | # occur. With increasing verbosity levels, more detail gives positive
23 | # feedback. Output is colored by default to make reading easy.
24 |
25 | # The script can run Emacs with the developer's local Emacs
26 | # configuration, or with a clean, "sandbox" configuration that can be
27 | # optionally removed afterward. This is especially helpful when
28 | # upstream dependencies may have released new versions that differ
29 | # from those installed in the developer's personal configuration.
30 |
31 | # * License:
32 |
33 | # This program is free software; you can redistribute it and/or modify
34 | # it under the terms of the GNU General Public License as published by
35 | # the Free Software Foundation, either version 3 of the License, or
36 | # (at your option) any later version.
37 |
38 | # This program is distributed in the hope that it will be useful,
39 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
40 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 | # GNU General Public License for more details.
42 |
43 | # You should have received a copy of the GNU General Public License
44 | # along with this program. If not, see .
45 |
46 | # * Functions
47 |
48 | function usage {
49 | cat <$file <$file <$file <"$file" <$file <"$file" <$file <&1)
338 |
339 | # Set output file.
340 | output_file=$(mktemp) || die "Unable to make output file."
341 | paths_temp+=("$output_file")
342 |
343 | # Run Emacs.
344 | debug "run_emacs: ${emacs_command[@]} $@ &>\"$output_file\""
345 | "${emacs_command[@]}" "$@" &>"$output_file"
346 |
347 | # Check exit code and output.
348 | exit=$?
349 | [[ $exit != 0 ]] \
350 | && debug "Emacs exited non-zero: $exit"
351 |
352 | [[ $verbose -gt 1 || $exit != 0 ]] \
353 | && cat $output_file
354 |
355 | return $exit
356 | }
357 |
358 | # ** Compilation
359 |
360 | function batch-byte-compile {
361 | debug "batch-byte-compile: ERROR-ON-WARN:$compile_error_on_warn"
362 |
363 | [[ $compile_error_on_warn ]] && local error_on_warn=(--eval "(setq byte-compile-error-on-warn t)")
364 |
365 | run_emacs \
366 | --load "$(elisp-byte-compile-file)" \
367 | "${error_on_warn[@]}" \
368 | --eval "(unless (makem-batch-byte-compile) (kill-emacs 1))" \
369 | "$@"
370 | }
371 |
372 | function byte-compile-file {
373 | debug "byte-compile: ERROR-ON-WARN:$compile_error_on_warn"
374 | local file="$1"
375 |
376 | [[ $compile_error_on_warn ]] && local error_on_warn=(--eval "(setq byte-compile-error-on-warn t)")
377 |
378 | # FIXME: Why is the line starting with "&& verbose 3" not indented properly? Emacs insists on indenting it back a level.
379 | run_emacs \
380 | --load "$(elisp-byte-compile-file)" \
381 | "${error_on_warn[@]}" \
382 | --eval "(pcase-let ((\`(,num-errors ,num-warnings) (makem-byte-compile-file \"$file\"))) (when (or (and byte-compile-error-on-warn (not (zerop num-warnings))) (not (zerop num-errors))) (kill-emacs 1)))" \
383 | && verbose 3 "Compiling $file finished without errors." \
384 | || { verbose 3 "Compiling file failed: $file"; return 1; }
385 | }
386 |
387 | # ** Files
388 |
389 | function submodules {
390 | # Echo a list of submodules's paths relative to the repo root.
391 | # TODO: Parse with bash regexp instead of cut.
392 | git submodule status | awk '{print $2}'
393 | }
394 |
395 | function project-root {
396 | # Echo the root of the project (or superproject, if running from
397 | # within a submodule).
398 | root_dir=$(git rev-parse --show-superproject-working-tree)
399 | [[ $root_dir ]] || root_dir=$(git rev-parse --show-toplevel)
400 | [[ $root_dir ]] || error "Can't find repo root."
401 |
402 | echo "$root_dir"
403 | }
404 |
405 | function files-project {
406 | # Return a list of files in project; or with $1, files in it
407 | # matching that pattern. Excludes submodules.
408 | [[ $1 ]] && pattern="/$1" || pattern="."
409 |
410 | local excludes
411 | for submodule in $(submodules)
412 | do
413 | excludes+=(":!:$submodule")
414 | done
415 |
416 | git ls-files -- "$pattern" "${excludes[@]}"
417 | }
418 |
419 | function dirs-project {
420 | # Echo list of directories to be used in load path.
421 | files-project-feature | dirnames
422 | files-project-test | dirnames
423 | }
424 |
425 | function files-project-elisp {
426 | # Echo list of Elisp files in project.
427 | files-project 2>/dev/null \
428 | | egrep "\.el$" \
429 | | filter-files-exclude-default \
430 | | filter-files-exclude-args
431 | }
432 |
433 | function files-project-feature {
434 | # Echo list of Elisp files that are not tests and provide a feature.
435 | files-project-elisp \
436 | | grep -E -v "$test_files_regexp" \
437 | | filter-files-feature
438 | }
439 |
440 | function files-project-test {
441 | # Echo list of Elisp test files.
442 | files-project-elisp | grep -E "$test_files_regexp"
443 | }
444 |
445 | function dirnames {
446 | # Echo directory names for files on STDIN.
447 | while read file
448 | do
449 | dirname "$file"
450 | done
451 | }
452 |
453 | function filter-files-exclude-default {
454 | # Filter out paths (STDIN) which should be excluded by default.
455 | grep -E -v "(/\.cask/|-autoloads.el|.dir-locals)"
456 | }
457 |
458 | function filter-files-exclude-args {
459 | # Filter out paths (STDIN) which are excluded with --exclude.
460 | if [[ ${files_exclude[@]} ]]
461 | then
462 | (
463 | # We use a subshell to set IFS temporarily so we can send
464 | # the list of files to grep -F. This is ugly but more
465 | # correct than replacing spaces with line breaks. Note
466 | # that, for some reason, using IFS="\n" or IFS='\n' doesn't
467 | # work, and a literal line break seems to be required.
468 | IFS="
469 | "
470 | grep -Fv "${files_exclude[*]}"
471 | )
472 | else
473 | cat
474 | fi
475 | }
476 |
477 | function filter-files-feature {
478 | # Read paths on STDIN and echo ones that (provide 'a-feature).
479 | while read path
480 | do
481 | grep -E "^\\(provide '" "$path" &>/dev/null \
482 | && echo "$path"
483 | done
484 | }
485 |
486 | function args-load-files {
487 | # For file in $@, echo "--load $file".
488 | for file in "$@"
489 | do
490 | sans_extension=${file%%.el}
491 | printf -- '--load %q ' "$sans_extension"
492 | done
493 | }
494 |
495 | function args-load-path {
496 | # Echo load-path arguments.
497 | for path in $(dirs-project | sort -u)
498 | do
499 | printf -- '-L %q ' "$path"
500 | done
501 | }
502 |
503 | function test-files-p {
504 | # Return 0 if $files_project_test is non-empty.
505 | [[ "${files_project_test[@]}" ]]
506 | }
507 |
508 | function buttercup-tests-p {
509 | # Return 0 if Buttercup tests are found.
510 | test-files-p || die "No tests found."
511 | debug "Checking for Buttercup tests..."
512 |
513 | grep "(require 'buttercup)" "${files_project_test[@]}" &>/dev/null
514 | }
515 |
516 | function ert-tests-p {
517 | # Return 0 if ERT tests are found.
518 | test-files-p || die "No tests found."
519 | debug "Checking for ERT tests..."
520 |
521 | # We check for this rather than "(require 'ert)", because ERT may
522 | # already be loaded in Emacs and might not be loaded with
523 | # "require" in a test file.
524 | grep "(ert-deftest" "${files_project_test[@]}" &>/dev/null
525 | }
526 |
527 | function package-main-file {
528 | # Echo the package's main file.
529 | file_pkg=$(files-project "*-pkg.el" 2>/dev/null)
530 |
531 | if [[ $file_pkg ]]
532 | then
533 | # Use *-pkg.el file if it exists.
534 | echo "$file_pkg"
535 | else
536 | # Use shortest filename (a sloppy heuristic that will do for now).
537 | for file in "${files_project_feature[@]}"
538 | do
539 | echo ${#file} "$file"
540 | done \
541 | | sort -h \
542 | | head -n1 \
543 | | sed -r 's/^[[:digit:]]+ //'
544 | fi
545 | }
546 |
547 | function dependencies {
548 | # Echo list of package dependencies.
549 |
550 | # Search package headers. Use -a so grep won't think that an Elisp file containing
551 | # control characters (rare, but sometimes necessary) is binary and refuse to search it.
552 | grep -E -a -i '^;; Package-Requires: ' $(files-project-feature) $(files-project-test) \
553 | | grep -E -o '\([^([:space:]][^)]*\)' \
554 | | grep -E -o '^[^[:space:])]+' \
555 | | sed -r 's/\(//g' \
556 | | grep -E -v '^emacs$' # Ignore Emacs version requirement.
557 |
558 | # Search Cask file.
559 | if [[ -r Cask ]]
560 | then
561 | grep -E '\(depends-on "[^"]+"' Cask \
562 | | sed -r -e 's/\(depends-on "([^"]+)".*/\1/g'
563 | fi
564 |
565 | # Search -pkg.el file.
566 | if [[ $(files-project "*-pkg.el" 2>/dev/null) ]]
567 | then
568 | sed -nr 's/.*\(([-[:alnum:]]+)[[:blank:]]+"[.[:digit:]]+"\).*/\1/p' $(files-project- -- -pkg.el 2>/dev/null)
569 | fi
570 | }
571 |
572 | # ** Sandbox
573 |
574 | function sandbox {
575 | verbose 2 "Initializing sandbox..."
576 |
577 | # *** Sandbox arguments
578 |
579 | # MAYBE: Optionally use branch-specific sandbox?
580 |
581 | # Check or make user-emacs-directory.
582 | if [[ $sandbox_dir ]]
583 | then
584 | # Directory given as argument: ensure it exists.
585 | if ! [[ -d $sandbox_dir ]]
586 | then
587 | debug "Making sandbox directory: $sandbox_dir"
588 | mkdir -p "$sandbox_dir" || die "Unable to make sandbox dir."
589 | fi
590 |
591 | # Add Emacs version-specific subdirectory, creating if necessary.
592 | sandbox_dir="$sandbox_dir/$(emacs-version)"
593 | if ! [[ -d $sandbox_dir ]]
594 | then
595 | mkdir "$sandbox_dir" || die "Unable to make sandbox subdir: $sandbox_dir"
596 | fi
597 | else
598 | # Not given: make temp directory, and delete it on exit.
599 | local sandbox_dir=$(mktemp -d) || die "Unable to make sandbox dir."
600 | paths_temp+=("$sandbox_dir")
601 | fi
602 |
603 | # Make argument to load init file if it exists.
604 | init_file="$sandbox_dir/init.el"
605 |
606 | # Set sandbox args. This is a global variable used by the run_emacs function.
607 | args_sandbox=(
608 | --title "makem.sh: $(basename $(pwd)) (sandbox: $sandbox_dir)"
609 | --eval "(setq user-emacs-directory (file-truename \"$sandbox_dir\"))"
610 | --load package
611 | --eval "(setq package-user-dir (expand-file-name \"elpa\" user-emacs-directory))"
612 | --eval "(setq user-init-file (file-truename \"$init_file\"))"
613 | )
614 |
615 | # Add package-install arguments for dependencies.
616 | if [[ $install_deps ]]
617 | then
618 | local deps=($(dependencies))
619 | debug "Installing dependencies: ${deps[@]}"
620 |
621 | for package in "${deps[@]}"
622 | do
623 | args_sandbox_package_install+=(--eval "(package-install '$package)")
624 | done
625 | fi
626 |
627 | # Add package-install arguments for linters.
628 | if [[ $install_linters ]]
629 | then
630 | debug "Installing linters: package-lint relint"
631 |
632 | args_sandbox_package_install+=(
633 | --eval "(package-install 'elsa)"
634 | --eval "(package-install 'package-lint)"
635 | --eval "(package-install 'relint)")
636 | fi
637 |
638 | # *** Install packages into sandbox
639 |
640 | if [[ ${args_sandbox_package_install[@]} ]]
641 | then
642 | # Initialize the sandbox (installs packages once rather than for every rule).
643 | verbose 1 "Installing packages into sandbox..."
644 |
645 | run_emacs \
646 | --eval "(package-refresh-contents)" \
647 | "${args_sandbox_package_install[@]}" \
648 | && success "Packages installed." \
649 | || die "Unable to initialize sandbox."
650 | fi
651 |
652 | verbose 2 "Sandbox initialized."
653 | }
654 |
655 | # ** Utility
656 |
657 | function cleanup {
658 | # Remove temporary paths (${paths_temp[@]}).
659 |
660 | for path in "${paths_temp[@]}"
661 | do
662 | if [[ $debug ]]
663 | then
664 | debug "Debugging enabled: not deleting temporary path: $path"
665 | elif [[ -r $path ]]
666 | then
667 | rm -rf "$path"
668 | else
669 | debug "Temporary path doesn't exist, not deleting: $path"
670 | fi
671 | done
672 | }
673 |
674 | function echo-unset-p {
675 | # Echo 0 if $1 is set, otherwise 1. IOW, this returns the exit
676 | # code of [[ $1 ]] as STDOUT.
677 | [[ $1 ]]
678 | echo $?
679 | }
680 |
681 | function ensure-package-available {
682 | # If package $1 is available, return 0. Otherwise, return 1, and
683 | # if $2 is set, give error otherwise verbose. Outputting messages
684 | # here avoids repetition in callers.
685 | local package=$1
686 | local direct_p=$2
687 |
688 | if ! run_emacs --load $package &>/dev/null
689 | then
690 | if [[ $direct_p ]]
691 | then
692 | error "$package not available."
693 | else
694 | verbose 2 "$package not available."
695 | fi
696 | return 1
697 | fi
698 | }
699 |
700 | function ensure-tests-available {
701 | # If tests of type $1 (like "ERT") are available, return 0. Otherwise, if
702 | # $2 is set, give an error and return 1; otherwise give verbose message. $1
703 | # should have a corresponding predicate command, like ert-tests-p for ERT.
704 | local test_name=$1
705 | local test_command="${test_name,,}-tests-p" # Converts name to lowercase.
706 | local direct_p=$2
707 |
708 | if ! $test_command
709 | then
710 | if [[ $direct_p ]]
711 | then
712 | error "$test_name tests not found."
713 | else
714 | verbose 2 "$test_name tests not found."
715 | fi
716 | return 1
717 | fi
718 | }
719 |
720 | function echo_color {
721 | # This allows bold, italic, etc. without needing a function for
722 | # each variation.
723 | local color_code="COLOR_$1"
724 | shift
725 |
726 | if [[ $color ]]
727 | then
728 | echo -e "${!color_code}${@}${COLOR_off}"
729 | else
730 | echo "$@"
731 | fi
732 | }
733 | function debug {
734 | if [[ $debug ]]
735 | then
736 | function debug {
737 | echo_color yellow "DEBUG ($(ts)): $@" >&2
738 | }
739 | debug "$@"
740 | else
741 | function debug {
742 | true
743 | }
744 | fi
745 | }
746 | function error {
747 | echo_color red "ERROR ($(ts)): $@" >&2
748 | ((errors++))
749 | return 1
750 | }
751 | function die {
752 | [[ $@ ]] && error "$@"
753 | exit $errors
754 | }
755 | function log {
756 | echo "LOG ($(ts)): $@" >&2
757 | }
758 | function log_color {
759 | local color_name=$1
760 | shift
761 | echo_color $color_name "LOG ($(ts)): $@" >&2
762 | }
763 | function success {
764 | if [[ $verbose -ge 2 ]]
765 | then
766 | log_color green "$@" >&2
767 | fi
768 | }
769 | function verbose {
770 | # $1 is the verbosity level, rest are echoed when appropriate.
771 | if [[ $verbose -ge $1 ]]
772 | then
773 | [[ $1 -eq 1 ]] && local color_name=blue
774 | [[ $1 -eq 2 ]] && local color_name=cyan
775 | [[ $1 -ge 3 ]] && local color_name=white
776 |
777 | shift
778 | log_color $color_name "$@" >&2
779 | fi
780 | }
781 |
782 | function ts {
783 | date "+%Y-%m-%d %H:%M:%S"
784 | }
785 |
786 | function emacs-version {
787 | # Echo Emacs version number.
788 |
789 | # Don't use run_emacs function, which does more than we need.
790 | "${emacs_command[@]}" -Q --batch --eval "(princ emacs-version)" \
791 | || die "Unable to get Emacs version."
792 | }
793 |
794 | function rule-p {
795 | # Return 0 if $1 is a rule.
796 | [[ $1 =~ ^(lint-?|tests?)$ ]] \
797 | || [[ $1 =~ ^(batch|interactive)$ ]] \
798 | || [[ $(type -t "$2" 2>/dev/null) =~ function ]]
799 | }
800 |
801 | # * Rules
802 |
803 | # These functions are intended to be called as rules, like a Makefile.
804 | # Some rules test $1 to determine whether the rule is being called
805 | # directly or from a meta-rule; if directly, an error is given if the
806 | # rule can't be run, otherwise it's skipped.
807 |
808 | function all {
809 | verbose 1 "Running all rules..."
810 |
811 | lint
812 | tests
813 | }
814 |
815 | function compile-batch {
816 | [[ $compile ]] || return 0
817 | unset compile # Only compile once.
818 |
819 | verbose 1 "Compiling..."
820 | verbose 2 "Batch-compiling files..."
821 | debug "Byte-compile files: ${files_project_byte_compile[@]}"
822 |
823 | batch-byte-compile "${files_project_byte_compile[@]}"
824 | }
825 |
826 | function compile-each {
827 | [[ $compile ]] || return 0
828 | unset compile # Only compile once.
829 |
830 | verbose 1 "Compiling..."
831 | debug "Byte-compile files: ${files_project_byte_compile[@]}"
832 |
833 | local compile_errors
834 | for file in "${files_project_byte_compile[@]}"
835 | do
836 | verbose 2 "Compiling file: $file..."
837 | byte-compile-file "$file" \
838 | || compile_errors=t
839 | done
840 |
841 | [[ ! $compile_errors ]]
842 | }
843 |
844 | function compile {
845 | if [[ $compile = batch ]]
846 | then
847 | compile-batch "$@"
848 | else
849 | compile-each "$@"
850 | fi
851 | local status=$?
852 |
853 | if [[ $compile_error_on_warn ]]
854 | then
855 | # Linting: just return status code, because lint rule will print messages.
856 | [[ $status = 0 ]]
857 | else
858 | # Not linting: print messages here.
859 | [[ $status = 0 ]] \
860 | && success "Compiling finished without errors." \
861 | || error "Compiling failed."
862 | fi
863 | }
864 |
865 | function batch {
866 | # Run Emacs in batch mode with ${args_batch_interactive[@]} and
867 | # with project source and test files loaded.
868 | verbose 1 "Executing Emacs with arguments: ${args_batch_interactive[@]}"
869 |
870 | run_emacs \
871 | $(args-load-files "${files_project_feature[@]}" "${files_project_test[@]}") \
872 | "${args_batch_interactive[@]}"
873 | }
874 |
875 | function interactive {
876 | # Run Emacs interactively. Most useful with --sandbox and --install-deps.
877 | local load_file_args=$(args-load-files "${files_project_feature[@]}" "${files_project_test[@]}")
878 | verbose 1 "Running Emacs interactively..."
879 | verbose 2 "Loading files: ${load_file_args//--load /}"
880 |
881 | [[ $compile ]] && compile
882 |
883 | unset arg_batch
884 | run_emacs \
885 | $load_file_args \
886 | --eval "(load user-init-file)" \
887 | "${args_batch_interactive[@]}"
888 | arg_batch="--batch"
889 | }
890 |
891 | function lint {
892 | verbose 1 "Linting..."
893 |
894 | lint-checkdoc
895 | lint-compile
896 | lint-declare
897 | # NOTE: Elint doesn't seem very useful at the moment. See comment
898 | # in lint-elint function.
899 | # lint-elint
900 | lint-indent
901 | lint-package
902 | lint-regexps
903 | }
904 |
905 | function lint-checkdoc {
906 | verbose 1 "Linting checkdoc..."
907 |
908 | local checkdoc_file="$(elisp-checkdoc-file)"
909 | paths_temp+=("$checkdoc_file")
910 |
911 | run_emacs \
912 | --load="$checkdoc_file" \
913 | "${files_project_feature[@]}" \
914 | && success "Linting checkdoc finished without errors." \
915 | || error "Linting checkdoc failed."
916 | }
917 |
918 | function lint-compile {
919 | verbose 1 "Linting compilation..."
920 |
921 | compile_error_on_warn=true
922 | compile "${files_project_byte_compile[@]}" \
923 | && success "Linting compilation finished without errors." \
924 | || error "Linting compilation failed."
925 | unset compile_error_on_warn
926 | }
927 |
928 | function lint-declare {
929 | verbose 1 "Linting declarations..."
930 |
931 | local check_declare_file="$(elisp-check-declare-file)"
932 | paths_temp+=("$check_declare_file")
933 |
934 | run_emacs \
935 | --load "$check_declare_file" \
936 | -f makem-check-declare-files-and-exit \
937 | "${files_project_feature[@]}" \
938 | && success "Linting declarations finished without errors." \
939 | || error "Linting declarations failed."
940 | }
941 |
942 | function lint-elsa {
943 | verbose 1 "Linting with Elsa..."
944 |
945 | # MAYBE: Install Elsa here rather than in sandbox init, to avoid installing
946 | # it when not needed. However, we should be careful to be clear about when
947 | # packages are installed, because installing them does execute code.
948 | run_emacs \
949 | --load elsa \
950 | -f elsa-run-files-and-exit \
951 | "${files_project_feature[@]}" \
952 | && success "Linting with Elsa finished without errors." \
953 | || error "Linting with Elsa failed."
954 | }
955 |
956 | function lint-elint {
957 | # NOTE: Elint gives a lot of spurious warnings, apparently because it doesn't load files
958 | # that are `require'd, so its output isn't very useful. But in case it's improved in
959 | # the future, and since this wrapper code already works, we might as well leave it in.
960 | verbose 1 "Linting with Elint..."
961 |
962 | local errors=0
963 | for file in "${files_project_feature[@]}"
964 | do
965 | verbose 2 "Linting with Elint: $file..."
966 | run_emacs \
967 | --load "$(elisp-elint-file)" \
968 | --eval "(makem-elint-file \"$file\")" \
969 | && verbose 3 "Linting with Elint found no errors." \
970 | || { error "Linting with Elint failed: $file"; ((errors++)) ; }
971 | done
972 |
973 | [[ $errors = 0 ]] \
974 | && success "Linting with Elint finished without errors." \
975 | || error "Linting with Elint failed."
976 | }
977 |
978 | function lint-indent {
979 | verbose 1 "Linting indentation..."
980 |
981 | # We load project source files as well, because they may contain
982 | # macros with (declare (indent)) rules which must be loaded to set
983 | # indentation.
984 |
985 | run_emacs \
986 | --load "$(elisp-lint-indent-file)" \
987 | $(args-load-files "${files_project_feature[@]}" "${files_project_test[@]}") \
988 | --funcall makem-lint-indent-batch-and-exit \
989 | "${files_project_feature[@]}" "${files_project_test[@]}" \
990 | && success "Linting indentation finished without errors." \
991 | || error "Linting indentation failed."
992 | }
993 |
994 | function lint-package {
995 | ensure-package-available package-lint $1 || return $(echo-unset-p $1)
996 |
997 | verbose 1 "Linting package..."
998 |
999 | run_emacs \
1000 | --load package-lint \
1001 | --eval "(setq package-lint-main-file \"$(package-main-file)\")" \
1002 | --funcall package-lint-batch-and-exit \
1003 | "${files_project_feature[@]}" \
1004 | && success "Linting package finished without errors." \
1005 | || error "Linting package failed."
1006 | }
1007 |
1008 | function lint-regexps {
1009 | ensure-package-available relint $1 || return $(echo-unset-p $1)
1010 |
1011 | verbose 1 "Linting regexps..."
1012 |
1013 | run_emacs \
1014 | --load relint \
1015 | --funcall relint-batch \
1016 | "${files_project_source[@]}" \
1017 | && success "Linting regexps finished without errors." \
1018 | || error "Linting regexps failed."
1019 | }
1020 |
1021 | function tests {
1022 | verbose 1 "Running all tests..."
1023 |
1024 | test-ert
1025 | test-buttercup
1026 | }
1027 |
1028 | function test-ert-interactive {
1029 | verbose 1 "Running ERT tests interactively..."
1030 |
1031 | unset arg_batch
1032 | run_emacs \
1033 | $(args-load-files "${files_project_test[@]}") \
1034 | --eval "(ert-run-tests-interactively t)"
1035 | arg_batch="--batch"
1036 | }
1037 |
1038 | function test-buttercup {
1039 | ensure-tests-available Buttercup $1 || return $(echo-unset-p $1)
1040 | compile || die
1041 |
1042 | verbose 1 "Running Buttercup tests..."
1043 |
1044 | local buttercup_file="$(elisp-buttercup-file)"
1045 | paths_temp+=("$buttercup_file")
1046 |
1047 | run_emacs \
1048 | $(args-load-files "${files_project_test[@]}") \
1049 | --load "$buttercup_file" \
1050 | --eval "(progn (setq backtrace-on-error-noninteractive nil) (buttercup-run))" \
1051 | && success "Buttercup tests finished without errors." \
1052 | || error "Buttercup tests failed."
1053 | }
1054 |
1055 | function test-ert {
1056 | ensure-tests-available ERT $1 || return $(echo-unset-p $1)
1057 | compile || die
1058 |
1059 | verbose 1 "Running ERT tests..."
1060 | debug "Test files: ${files_project_test[@]}"
1061 |
1062 | run_emacs \
1063 | $(args-load-files "${files_project_test[@]}") \
1064 | -f ert-run-tests-batch-and-exit \
1065 | && success "ERT tests finished without errors." \
1066 | || error "ERT tests failed."
1067 | }
1068 |
1069 | # * Defaults
1070 |
1071 | test_files_regexp='^((tests?|t)/)|-tests?.el$|^test-'
1072 |
1073 | emacs_command=("emacs")
1074 | errors=0
1075 | verbose=0
1076 | compile=true
1077 | arg_batch="--batch"
1078 | compile=each
1079 |
1080 | # MAYBE: Disable color if not outputting to a terminal. (OTOH, the
1081 | # colorized output is helpful in CI logs, and I don't know if,
1082 | # e.g. GitHub Actions logging pretends to be a terminal.)
1083 | color=true
1084 |
1085 | # TODO: Using the current directory (i.e. a package's repo root directory) in
1086 | # load-path can cause weird errors in case of--you guessed it--stale .ELC files,
1087 | # the zombie problem that just won't die. It's incredible how many different ways
1088 | # this problem presents itself. In this latest example, an old .ELC file, for a
1089 | # .EL file that had since been renamed, was present on my local system, which meant
1090 | # that an example .EL file that hadn't been updated was able to "require" that .ELC
1091 | # file's feature without error. But on another system (in this case, trying to
1092 | # setup CI using GitHub Actions), the old .ELC was not present, so the example .EL
1093 | # file was not able to load the feature, which caused a byte-compilation error.
1094 |
1095 | # In this case, I will prevent such example files from being compiled. But in
1096 | # general, this can cause weird problems that are tedious to debug. I guess
1097 | # the best way to fix it would be to actually install the repo's code as a
1098 | # package into the sandbox, but doing that would require additional tooling,
1099 | # pulling in something like Quelpa or package-build--and if the default recipe
1100 | # weren't being used, the actual recipe would have to be fetched off MELPA or
1101 | # something, which seems like getting too smart for our own good.
1102 |
1103 | # TODO: Emit a warning if .ELC files that don't match any .EL files are detected.
1104 |
1105 | # ** Colors
1106 |
1107 | COLOR_off='\e[0m'
1108 | COLOR_black='\e[0;30m'
1109 | COLOR_red='\e[0;31m'
1110 | COLOR_green='\e[0;32m'
1111 | COLOR_yellow='\e[0;33m'
1112 | COLOR_blue='\e[0;34m'
1113 | COLOR_purple='\e[0;35m'
1114 | COLOR_cyan='\e[0;36m'
1115 | COLOR_white='\e[0;37m'
1116 |
1117 | # ** Package system args
1118 |
1119 | args_package_archives=(
1120 | --eval "(add-to-list 'package-archives '(\"gnu\" . \"https://elpa.gnu.org/packages/\") t)"
1121 | --eval "(add-to-list 'package-archives '(\"melpa\" . \"https://melpa.org/packages/\") t)"
1122 | )
1123 |
1124 | args_org_package_archives=(
1125 | --eval "(add-to-list 'package-archives '(\"org\" . \"https://orgmode.org/elpa/\") t)"
1126 | )
1127 |
1128 | args_package_init=(
1129 | --eval "(package-initialize)"
1130 | )
1131 |
1132 | elisp_org_package_archive="(add-to-list 'package-archives '(\"org\" . \"https://orgmode.org/elpa/\") t)"
1133 |
1134 | # * Args
1135 |
1136 | args=$(getopt -n "$0" \
1137 | -o dhce:E:i:s::vf:CO \
1138 | -l compile-batch,exclude:,emacs:,install-deps,install-linters,debug,debug-load-path,help,install:,verbose,file:,no-color,no-compile,no-org-repo,sandbox:: \
1139 | -- "$@") \
1140 | || { usage; exit 1; }
1141 | eval set -- "$args"
1142 |
1143 | while true
1144 | do
1145 | case "$1" in
1146 | --install-deps)
1147 | install_deps=true
1148 | ;;
1149 | --install-linters)
1150 | install_linters=true
1151 | ;;
1152 | -d|--debug)
1153 | debug=true
1154 | verbose=2
1155 | args_debug=(--eval "(setq init-file-debug t)"
1156 | --eval "(setq debug-on-error t)")
1157 | ;;
1158 | --debug-load-path)
1159 | debug_load_path=true
1160 | ;;
1161 | -h|--help)
1162 | usage
1163 | exit
1164 | ;;
1165 | -c|--compile-batch)
1166 | debug "Compiling files in batch mode"
1167 | compile=batch
1168 | ;;
1169 | -E|--emacs)
1170 | shift
1171 | emacs_command=($1)
1172 | ;;
1173 | -i|--install)
1174 | shift
1175 | args_sandbox_package_install+=(--eval "(package-install '$1)")
1176 | ;;
1177 | -s|--sandbox)
1178 | sandbox=true
1179 | shift
1180 | sandbox_dir="$1"
1181 |
1182 | if ! [[ $sandbox_dir ]]
1183 | then
1184 | debug "No sandbox dir: installing dependencies."
1185 | install_deps=true
1186 | else
1187 | debug "Sandbox dir: $1"
1188 | fi
1189 | ;;
1190 | -v|--verbose)
1191 | ((verbose++))
1192 | ;;
1193 | -e|--exclude)
1194 | shift
1195 | debug "Excluding file: $1"
1196 | files_exclude+=("$1")
1197 | ;;
1198 | -f|--file)
1199 | shift
1200 | args_files+=("$1")
1201 | ;;
1202 | -O|--no-org-repo)
1203 | unset elisp_org_package_archive
1204 | ;;
1205 | --no-color)
1206 | unset color
1207 | ;;
1208 | -C|--no-compile)
1209 | unset compile
1210 | ;;
1211 | --)
1212 | # Remaining args (required; do not remove)
1213 | shift
1214 | rest=("$@")
1215 | break
1216 | ;;
1217 | esac
1218 |
1219 | shift
1220 | done
1221 |
1222 | debug "ARGS: $args"
1223 | debug "Remaining args: ${rest[@]}"
1224 |
1225 | # Set package elisp (which depends on --no-org-repo arg).
1226 | package_initialize_file="$(elisp-package-initialize-file)"
1227 | paths_temp+=("$package_initialize_file")
1228 |
1229 | # * Main
1230 |
1231 | trap cleanup EXIT INT TERM
1232 |
1233 | # Change to project root directory first.
1234 | cd "$(project-root)"
1235 |
1236 | # Discover project files.
1237 | files_project_feature=($(files-project-feature))
1238 | files_project_test=($(files-project-test))
1239 | files_project_byte_compile=("${files_project_feature[@]}" "${files_project_test[@]}")
1240 |
1241 | if [[ ${args_files[@]} ]]
1242 | then
1243 | # Add specified files.
1244 | files_project_feature+=("${args_files[@]}")
1245 | files_project_byte_compile+=("${args_files[@]}")
1246 | fi
1247 |
1248 | debug "EXCLUDING FILES: ${files_exclude[@]}"
1249 | debug "FEATURE FILES: ${files_project_feature[@]}"
1250 | debug "TEST FILES: ${files_project_test[@]}"
1251 | debug "BYTE-COMPILE FILES: ${files_project_byte_compile[@]}"
1252 | debug "PACKAGE-MAIN-FILE: $(package-main-file)"
1253 |
1254 | if ! [[ ${files_project_feature[@]} ]]
1255 | then
1256 | error "No files specified and not in a git repo."
1257 | exit 1
1258 | fi
1259 |
1260 | # Set load path.
1261 | args_load_paths=($(args-load-path))
1262 | debug "LOAD PATH ARGS: ${args_load_paths[@]}"
1263 |
1264 | # If rules include linters and sandbox-dir is unspecified, install
1265 | # linters automatically.
1266 | if [[ $sandbox && ! $sandbox_dir ]] && [[ "${rest[@]}" =~ lint ]]
1267 | then
1268 | debug "Installing linters automatically."
1269 | install_linters=true
1270 | fi
1271 |
1272 | # Initialize sandbox.
1273 | [[ $sandbox ]] && sandbox
1274 |
1275 | # Run rules.
1276 | for rule in "${rest[@]}"
1277 | do
1278 | if [[ $batch || $interactive ]]
1279 | then
1280 | debug "Adding batch/interactive argument: $rule"
1281 | args_batch_interactive+=("$rule")
1282 |
1283 | elif [[ $rule = batch ]]
1284 | then
1285 | # Remaining arguments are passed to Emacs.
1286 | batch=true
1287 | elif [[ $rule = interactive ]]
1288 | then
1289 | # Remaining arguments are passed to Emacs.
1290 | interactive=true
1291 |
1292 | elif type -t "$rule" 2>/dev/null | grep function &>/dev/null
1293 | then
1294 | # Pass called-directly as $1 to indicate that the rule is
1295 | # being called directly rather than from a meta-rule.
1296 | $rule called-directly
1297 | elif [[ $rule = test ]]
1298 | then
1299 | # Allow the "tests" rule to be called as "test". Since "test"
1300 | # is a shell builtin, this workaround is required.
1301 | tests
1302 | else
1303 | error "Invalid rule: $rule"
1304 | fi
1305 | done
1306 |
1307 | # Batch/interactive rules.
1308 | [[ $batch ]] && batch
1309 | [[ $interactive ]] && interactive
1310 |
1311 | if [[ $errors -gt 0 ]]
1312 | then
1313 | log_color red "Finished with $errors errors."
1314 | else
1315 | success "Finished without errors."
1316 | fi
1317 |
1318 | exit $errors
1319 |
--------------------------------------------------------------------------------
/notes.org:
--------------------------------------------------------------------------------
1 | #+PROPERTY: logging nil
2 | #+TODO: TODO UNDERWAY | DONE CANCELED
3 | #+TYP_TODO: MAYBE | CANCELED
4 | #+TYP_TODO: TEMPLATE
5 |
6 | * Plans
7 |
8 | ** DONE 0.5
9 |
10 | *** DONE Release 0.5
11 |
12 | + [X] Check comment TODOs (using =magit-todos=).
13 | + [X] Check issues.
14 | + [X] Check plans (in this file).
15 | + [X] Check linters.
16 | + [X] Check tests.
17 | + [X] Update version numbers in file headers.
18 | - [X] org-make-toc.el
19 | + [X] Update changelog in =README.org=.
20 | + [X] Tag and sign new version (using Magit's =t r=).
21 | + [X] Push =master=.
22 | + [X] Push tags.
23 | + [X] Post-release changes:
24 | - [X] Bump version numbers to n+1-pre:
25 | + [X] org-make-toc.el
26 | + [X] README.org
27 |
28 | * Notes
29 |
30 | ** DONE Get document tree
31 | CLOSED: [2017-08-01 Tue 22:41]
32 | :PROPERTIES:
33 | :TESTING: testing
34 | :toc: ignore
35 | :END:
36 | :LOGBOOK:
37 | - State "DONE" from "TODO" [2017-08-01 Tue 22:41]
38 | :END:
39 |
40 | There are different ways to get a tree of the document structure.
41 |
42 | + =org-imenu-get-tree= returns one that should be useful.
43 | + =org-element-parse-buffer= is more semantic and is probably better for my uses. It looks like it returns metadata, while =org-imenu-get-tree= is bare-bones, just what =imenu= needs.
44 |
45 | Yeah, looks like =org-element-parse-buffer= is the way to go.
46 |
47 | *** =org-element-parse-buffer=
48 |
49 | #+BEGIN_SRC elisp :results code
50 | (org-element-parse-buffer 'headline)
51 | #+END_SRC
52 |
53 | #+RESULTS:
54 | #+BEGIN_SRC elisp
55 | (org-data nil
56 | (headline
57 | (:raw-value "Notes" :begin 1 :end 2266 :pre-blank 0 :contents-begin 9 :contents-end 2266 :level 1 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 1 :title "Notes" :parent #0)
58 | (headline
59 | (:raw-value "Build document tree" :begin 9 :end 2266 :pre-blank 0 :contents-begin 37 :contents-end 2266 :level 2 :priority nil :tags nil :todo-keyword
60 | #("TODO" 0 4
61 | (fontified t line-prefix
62 | #("*" 0 1
63 | (face org-hide))
64 | wrap-prefix
65 | #("*** " 0 1
66 | (face org-indent)
67 | 1 4
68 | (face org-indent))
69 | org-todo-head "TODO" face org-todo))
70 | :todo-type todo :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 9 :TESTING "testing" :title "Build document tree" :parent #1)
71 | (headline
72 | (:raw-value "=org-element-parse-buffer=" :begin 390 :end 2266 :pre-blank 1 :contents-begin 422 :contents-end 2266 :level 3 :priority nil :tags nil :todo-keyword nil :todo-type nil :post-blank 0 :footnote-section-p nil :archivedp nil :commentedp nil :post-affiliated 390 :title "=org-element-parse-buffer=" :parent #2)))))
73 | #+END_SRC
74 |
75 | The structure of this appears to be like:
76 |
77 | + 'headline
78 | - List of properties
79 | - List for child heading
80 | + 'headline
81 | + List of properties
82 |
83 | ** DONE Walk tree
84 | CLOSED: [2017-08-02 Wed 01:08]
85 | :LOGBOOK:
86 | - State "DONE" from "UNDERWAY" [2017-08-02 Wed 01:08]
87 | - State "UNDERWAY" from "DONE" [2017-08-02 Wed 00:08]
88 | :END:
89 |
90 | *** cl-loop
91 | :PROPERTIES:
92 | :ID: b75e4923-0a34-4f3f-830c-f5157397add1
93 | :END:
94 |
95 | This works, but it helped me figure out how to use =org-element-map=, so I guess I'll use that.
96 |
97 | #+BEGIN_SRC elisp :results verbatim
98 | (defun org-walk-tree (tree element-pred)
99 | (cl-loop for element in tree
100 | when (eql 'headline (car element))
101 | when (funcall element-pred element)
102 | collect (list 'headline
103 | :name (org-element-property :title element)
104 | :children (org-walk-tree (cddr element) element-pred))))
105 |
106 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/notes.org")
107 | (let ((tree (cddr (org-element-parse-buffer 'headline))))
108 | (org-walk-tree tree (lambda (element)
109 | (not (string= (org-element-property :TOC element)
110 | "ignore"))))))
111 | #+END_SRC
112 |
113 | #+RESULTS:
114 | : ((headline :name "Notes" :children ((headline :name "Filter tree" :children ((headline :name "Remove ignored headings" :children ((headline :name "org-element-map" :children nil) (headline :name "Other loop" :children nil))) (headline :name "Remove too-deep headings" :children nil) (headline :name "Remove higher headings" :children nil))) (headline :name "Transform tree to org list" :children nil) (headline :name "Find TOC element" :children nil) (headline :name "Replace TOC contents with list" :children nil))))
115 |
116 | *** org-element-map
117 | :PROPERTIES:
118 | :ID: fbe83744-e0e9-4d44-8abc-e48809c96478
119 | :END:
120 |
121 | #+BEGIN_SRC elisp :results verbatim
122 | (defun org-walk-tree (tree element-pred)
123 | (cl-loop for element in tree
124 | when (eql 'headline (car element))
125 | when (funcall element-pred element)
126 | collect (list 'headline
127 | :name (org-element-property :title element)
128 | :children (org-walk-tree (cdddr element) element-pred))))
129 |
130 | (defun argh (element)
131 | (unless (string= (org-element-property :TOC element)
132 | "ignore")
133 | (list 'headline
134 | :name (org-element-property :title element)
135 | :children (org-element-map (cddr element) '(headline)
136 | #'argh nil nil '(headline)))))
137 |
138 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/notes.org")
139 | (let ((tree (cddr (org-element-parse-buffer 'headline))))
140 | (org-element-map tree '(headline) #'argh nil nil '(headline))))
141 |
142 | #+END_SRC
143 |
144 | #+RESULTS:
145 | : ((headline :name "Notes" :children ((headline :name "Filter tree" :children ((headline :name "Use treepy to walk the tree" :children nil) (headline :name "Remove ignored headings" :children ((headline :name "cl-loop" :children nil) (headline :name "org-element-map" :children nil))) (headline :name "Remove too-deep headings" :children nil) (headline :name "Remove higher headings" :children nil))) (headline :name "Transform tree to org list" :children nil) (headline :name "Find TOC element" :children nil) (headline :name "Replace TOC contents with list" :children nil))))
146 |
147 | ** DONE Add =:local= to examples.org
148 |
149 | ** TODO Filter tree
150 |
151 | *** DONE Remove higher headings
152 | CLOSED: [2017-08-02 Wed 03:42]
153 | :LOGBOOK:
154 | - State "DONE" from "TODO" [2017-08-02 Wed 03:42]
155 | :END:
156 |
157 | **** DONE Get TOC level
158 | CLOSED: [2017-08-02 Wed 02:06]
159 | :PROPERTIES:
160 | :ID: b2f133c6-7d1e-4eb9-986a-cfb5aecb3905
161 | :END:
162 | :LOGBOOK:
163 | - State "DONE" from [2017-08-02 Wed 02:06]
164 | :END:
165 |
166 | Ugly, but it works. I guess the rather non-standard structure of the element tree makes this necessary. I tried to get =treepy= working with zippers, and I almost did...
167 |
168 | #+BEGIN_SRC elisp
169 | (defun org-make-toc--first-in-tree (tree element-pred)
170 | (cl-loop for element in tree
171 | for type = (car element)
172 | if (eq 'headline type)
173 | for result = (funcall element-pred element)
174 | if result
175 | return result
176 | else
177 | for children = (cddr element)
178 | when children
179 | for result = (org-make-toc--first-in-tree children element-pred)
180 | when result
181 | return result))
182 | #+END_SRC
183 |
184 | #+BEGIN_SRC elisp
185 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/test/data.org")
186 | (let* ((tree (cddr (org-element-parse-buffer 'headline)))
187 | (tree (org-make-toc--remove-ignored-entries tree))
188 | (toc-level (org-make-toc--first-in-tree tree
189 | #'org-make-toc--is-toc-entry
190 | #'org-make-toc--element-level)))
191 | toc-level))
192 | #+END_SRC
193 |
194 | #+RESULTS:
195 | : 2
196 |
197 | **** DONE Remove higher ones
198 | CLOSED: [2017-08-02 Wed 03:41]
199 | :LOGBOOK:
200 | - State "DONE" from "TODO" [2017-08-02 Wed 03:41]
201 | :END:
202 |
203 | #+BEGIN_SRC elisp :results list
204 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/test/data.org")
205 | (let* ((tree (cddr (org-element-parse-buffer 'headline)))
206 | (tree (org-make-toc--remove-ignored-entries tree)))
207 | (org-make-toc--remove-higher-level-than-toc tree)))
208 | #+END_SRC
209 |
210 |
211 | *** MAYBE Remove too-deep headings
212 | :LOGBOOK:
213 | - State "MAYBE" from "TODO" [2017-08-02 Wed 01:08]
214 | :END:
215 |
216 | *** CANCELED Use treepy to walk the tree
217 | CLOSED: [2017-08-02 Wed 00:07]
218 | :LOGBOOK:
219 | - State "CANCELED" from "TODO" [2017-08-02 Wed 00:07]
220 | :END:
221 |
222 | I guess I'm just not smart enough to use treepy, because all I could get out of its walking functions were errors. Or maybe it's just not suitable for the kind of structure =org-element-map= returns. I don't know.
223 |
224 | #+BEGIN_SRC elisp
225 | (require 'treepy)
226 |
227 | (treepy-walk #'identity (cddr (org-element-parse-buffer 'headline)))
228 | #+END_SRC
229 |
230 | *** DONE Remove ignored headings
231 | CLOSED: [2017-08-02 Wed 00:57]
232 | :LOGBOOK:
233 | - State "DONE" from "TODO" [2017-08-02 Wed 00:57]
234 | :END:
235 |
236 | #+BEGIN_SRC elisp
237 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/test/data.org")
238 | (let ((tree (cddr (org-element-parse-buffer 'headline))))
239 | (org-make-toc--remove-ignored-entries tree)))
240 | #+END_SRC
241 |
242 | #+RESULTS:
243 | | headline | A | ((headline Contents ((headline Hmm nil))) (headline A1 nil) (headline A2 nil) (headline A3 nil)) |
244 | | headline | B | ((headline B1 nil) (headline B2 nil) (headline B3 nil)) |
245 | | headline | Ignore-Children | |
246 | | headline | C | ((headline C1 nil) (headline C2 nil) (headline C3 nil)) |
247 | | headline | Invalid | nil |
248 |
249 | ** TODO Use =org-list-to-org= from Org 9.1
250 | :PROPERTIES:
251 | :ID: bafab4a8-6084-40ff-ae0e-5b601b5c034e
252 | :END:
253 |
254 | Should be a nicer way to turn the ToC into the list string.
255 |
256 | ** TODO Check out [[https://github.com/Fuco1/orgpath][orgpath]]
257 |
258 | This looks really cool, although he seems to have abandoned it. I cloned a local copy to src/misc/org. Studying his functions that build a tree should be very helpful.
259 |
260 | ** UNDERWAY Transform tree to org list
261 | :LOGBOOK:
262 | - State "UNDERWAY" from "TODO" [2017-08-02 Wed 04:16]
263 | :END:
264 |
265 | With each element being a link to the real heading. Need to support both GitHub links and Org links.
266 |
267 | *** DONE GitHub-style
268 | CLOSED: [2017-08-02 Wed 04:16]
269 | :LOGBOOK:
270 | - State "DONE" from "TODO" [2017-08-02 Wed 04:16]
271 | :END:
272 |
273 | #+BEGIN_SRC elisp :results org
274 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/test/data.org")
275 | (let* ((tree (cddr (org-element-parse-buffer 'headline)))
276 | (tree (org-make-toc--remove-ignored-entries tree))
277 | (tree (org-make-toc--remove-higher-level-than-toc tree)))
278 | (org-make-toc--tree-to-list tree)))
279 | #+END_SRC
280 |
281 | #+RESULTS:
282 | #+BEGIN_SRC org
283 | - [[Hmm][#hmm]]
284 | - [[A1][#a1]]
285 | - [[A2][#a2]]
286 | - [[A3][#a3]]
287 | - [[B1][#b1]]
288 | - [[B2][#b2]]
289 | - [[B3][#b3]]
290 | - [[C1][#c1]]
291 | - [[C2][#c2]]
292 | - [[C3][#c3]]
293 | #+END_SRC
294 |
295 | ** TODO Replace TOC contents with list
296 |
297 | #+BEGIN_SRC elisp
298 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/test/data.org")
299 | (-when-let* ((tree (cddr (org-element-parse-buffer 'headline)))
300 | (tree (org-make-toc--remove-ignored-entries tree))
301 | (tree (org-make-toc--remove-higher-level-than-toc tree))
302 | (list (org-make-toc--tree-to-list tree))
303 | (pos (org-find-property "TOC" "this")))
304 | (org-make-toc--replace-entry-contents pos list)))
305 |
306 | #+END_SRC
307 |
308 | #+RESULTS:
309 | #+begin_example
310 | - [[#hmm][Hmm]]
311 | - [[#oho][Oho]]
312 | - [[#a1][A1]]
313 | - [[#a2][A2]]
314 | - [[#a3][A3]]
315 | - [[#b1][B1]]
316 | - [[#b2][B2]]
317 | - [[#b3][B3]]
318 | - [[#c1][C1]]
319 | - [[#c2][C2]]
320 | - [[#c3][C3]]
321 | #+end_example
322 |
323 | ** Treepy
324 |
325 | #+BEGIN_SRC elisp
326 | (require 'treepy)
327 |
328 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/test/data.org")
329 | (let* ((tree (cddr (org-element-parse-buffer 'headline)))
330 | (zipper (treepy-zipper #'treepy-branch-p
331 | #'treepy-children
332 | #'treepy-make-node
333 | tree)))
334 | (treepy-children zipper)))
335 |
336 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/test/data.org")
337 | (let* ((tree (cddr (org-element-parse-buffer 'headline)))
338 | (zipper (treepy-zipper (lambda (loc) (eql 'headline (car loc)))
339 | (lambda (loc) (cddr loc))
340 | (lambda (loc) (list 'headline (cdr loc) (cddr loc)))
341 | tree)))
342 | zipper))
343 | #+END_SRC
344 |
345 | * Checklists
346 |
347 | ** TEMPLATE Release
348 |
349 | + [ ] Check comment TODOs (using =magit-todos=).
350 | + [ ] Check issues.
351 | + [ ] Check plans (in this file).
352 | + [ ] Check linters.
353 | + [ ] Check tests.
354 | + [ ] Update version numbers in file headers.
355 | - [ ] org-make-toc.el
356 | + [ ] Update changelog in =README.org=.
357 | + [ ] Tag and sign new version (using Magit's =t r=).
358 | + [ ] Push =master=.
359 | + [ ] Push tags.
360 | + [ ] Post-release changes:
361 | - [ ] Bump version numbers to n+1-pre:
362 | + [ ] org-make-toc.el
363 | + [ ] README.org
364 |
--------------------------------------------------------------------------------
/org-make-toc.el:
--------------------------------------------------------------------------------
1 | ;;; org-make-toc.el --- Automatic tables of contents for Org files -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2020 Adam Porter
4 |
5 | ;; Author: Adam Porter
6 | ;; URL: http://github.com/alphapapa/org-make-toc
7 | ;; Version: 0.6
8 | ;; Package-Requires: ((emacs "26.1") (dash "2.12") (s "1.10.0") (org "9.3") (compat "29.1"))
9 | ;; Keywords: Org, convenience
10 |
11 | ;;; Commentary:
12 |
13 | ;; This package makes it easy to have one or more customizable tables of contents in Org files.
14 | ;; They can be updated manually, or automatically when the file is saved. Links to headings are
15 | ;; created compatible with GitHub's Org renderer.
16 |
17 | ;;;; Installation
18 |
19 | ;; Install the packages `dash' and `s'. Then put this file in your `load-path', and put this in
20 | ;; your init file:
21 |
22 | ;; (require 'org-make-toc)
23 |
24 | ;;;; Usage
25 |
26 | ;; A document may have any number of tables of contents (TOCs), each of
27 | ;; which may list entries in a highly configurable way. To make a basic
28 | ;; TOC, follow these steps:
29 | ;;
30 | ;; 1. Choose a heading to contain a TOC and go to it.
31 | ;; 2. Press `C-c C-x p' (`org-set-property'), add a `TOC' property, and
32 | ;; set its value to `:include all'.
33 | ;; 3. Run command `org-make-toc-insert' to insert the `:CONTENTS:' drawer,
34 | ;; which will contain the TOC entries.
35 | ;; 4. Run the command `org-make-toc' to update all TOCs in the document,
36 | ;; or `org-make-toc-at-point' to update the TOC for the entry at point.
37 | ;;
38 | ;;
39 | ;; Example
40 | ;; ═══════
41 | ;;
42 | ;; Here's a simple document containing a simple TOC:
43 | ;;
44 | ;; ┌────
45 | ;; │ * Heading
46 | ;; │ :PROPERTIES:
47 | ;; │ :TOC: :include all
48 | ;; │ :END:
49 | ;; │
50 | ;; │ This text appears before the TOC.
51 | ;; │
52 | ;; │ :CONTENTS:
53 | ;; │ - [[#heading][Heading]]
54 | ;; │ - [[#subheading][Subheading]]
55 | ;; │ :END:
56 | ;; │
57 | ;; │ This text appears after it.
58 | ;; │
59 | ;; │ ** Subheading
60 | ;; └────
61 | ;;
62 | ;;
63 | ;; Advanced
64 | ;; ════════
65 | ;;
66 | ;; The `:TOC:' property is a property list which may set these keys and
67 | ;; values.
68 | ;;
69 | ;; These keys accept one setting, like `:include all':
70 | ;;
71 | ;; ⁃ `:include' Which headings to include in the TOC.
72 | ;; • `all' Include all headings in the document.
73 | ;; • `descendants' Include the TOC's descendant headings.
74 | ;; • `siblings' Include the TOC's sibling headings.
75 | ;; ⁃ `:depth' A number >= 0 indicating a depth relative to this heading.
76 | ;; Descendant headings at or above this relative depth are included in
77 | ;; TOCs that include this heading.
78 | ;;
79 | ;; These keys accept either one setting or a list of settings, like
80 | ;; `:force depth' or `:force (depth ignore)':
81 | ;;
82 | ;; ⁃ `:force' Heading-local settings to override when generating the TOC
83 | ;; at this heading.
84 | ;; • `depth' Override `:depth' settings.
85 | ;; • `ignore' Override `:ignore' settings.
86 | ;; ⁃ `:ignore' Which headings, relative to this heading, to exclude from
87 | ;; TOCs.
88 | ;; • `descendants' Exclude descendants of this heading.
89 | ;; • `siblings' Exclude siblings of this heading.
90 | ;; • `this' Exclude this heading (not its siblings or descendants).
91 | ;; ⁃ `:local' Heading-local settings to ignore when generating TOCs at
92 | ;; higher levels.
93 | ;; • `depth' Ignore `:depth' settings.
94 | ;;
95 | ;; See [example.org] for a comprehensive example of the features
96 | ;; described above.
97 | ;;
98 | ;;
99 | ;; [example.org]
100 | ;; https://github.com/alphapapa/org-make-toc/blob/master/example.org
101 | ;;
102 | ;;
103 | ;; Automatically update on save
104 | ;; ════════════════════════════
105 | ;;
106 | ;; To automatically update a file's TOC when the file is saved, use the
107 | ;; command `add-file-local-variable' to add `org-make-toc' to the Org
108 | ;; file's `before-save-hook'.
109 | ;;
110 | ;; Or, you may activate it in all Org buffers like this:
111 | ;;
112 | ;; ┌────
113 | ;; │ (add-hook 'org-mode-hook #'org-make-toc-mode)
114 | ;; └────
115 |
116 | ;;; License:
117 |
118 | ;; This program is free software; you can redistribute it and/or modify
119 | ;; it under the terms of the GNU General Public License as published by
120 | ;; the Free Software Foundation, either version 3 of the License, or
121 | ;; (at your option) any later version.
122 |
123 | ;; This program is distributed in the hope that it will be useful,
124 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
125 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
126 | ;; GNU General Public License for more details.
127 |
128 | ;; You should have received a copy of the GNU General Public License
129 | ;; along with this program. If not, see .
130 |
131 | ;;; Code:
132 |
133 | (require 'cl-lib)
134 | (require 'compat)
135 | (require 'org)
136 | (require 'rx)
137 | (require 'seq)
138 | (require 'subr-x)
139 |
140 | (require 'dash)
141 | (require 's)
142 |
143 | ;;;; Variables
144 |
145 | (defgroup org-make-toc nil
146 | "Settings for `org-make-toc'."
147 | :group 'org
148 | :link '(url-link "http://github.com/alphapapa/org-make-toc"))
149 |
150 | (defcustom org-make-toc-filename-prefix nil
151 | "Prefix links with filename before anchor tag."
152 | :type 'boolean
153 | :safe #'booleanp)
154 |
155 | (defcustom org-make-toc-link-type-fn #'org-make-toc--link-entry-github
156 | "Type of links to make.
157 | `org-element' entries are passed to this function, which returns
158 | an Org link as a string, the target of which should be compatible
159 | with the destination of the published file."
160 | :type '(choice (const :tag "GitHub-compatible" org-make-toc--link-entry-github)
161 | (const :tag "Org-compatible" org-make-toc--link-entry-org)
162 | (function :tag "Custom function")))
163 |
164 | (defcustom org-make-toc-insert-custom-ids nil
165 | "Add \"CUSTOM_ID\" properties to headings when using GitHub-compatible links.
166 | When non-nil and using the default `org-make-toc-link-type-fn' to
167 | generate GitHub-compatible links, automatically insert a
168 | \"CUSTOM_ID\" property for each entry. This will allow links to
169 | also work in `org-mode' in Emacs."
170 | :type 'boolean)
171 |
172 | (defcustom org-make-toc-exclude-tags '("noexport")
173 | "Entries with any of these tags are excluded from TOCs."
174 | :type '(repeat string))
175 |
176 | (defconst org-make-toc-contents-drawer-start-regexp
177 | (rx bol (0+ blank) ":CONTENTS:" (0+ blank) eol)
178 | "Regular expression for the beginning of a :CONTENTS: drawer.")
179 |
180 | (defvar-local org-make-toc-disambiguations nil
181 | "Used to disambiguate custom IDs.")
182 | (defvar-local org-make-toc-ids nil
183 | "Maps custom IDs to buffer positions.")
184 |
185 | ;;;; Commands
186 |
187 | ;;;###autoload
188 | (defun org-make-toc ()
189 | "Make or update table of contents in current buffer."
190 | (interactive)
191 | (let ((org-make-toc-disambiguations (make-hash-table :test #'equal))
192 | (org-make-toc-ids (make-hash-table :test #'equal)))
193 | (save-excursion
194 | (goto-char (point-min))
195 | (cl-loop with made-toc
196 | for pos = (org-make-toc--next-toc-position)
197 | while pos
198 | do (progn
199 | (goto-char pos)
200 | (when (org-make-toc--update-toc-at-point)
201 | (setq made-toc t)))
202 | finally do (unless made-toc
203 | (message "org-make-toc: No TOC node found."))))))
204 |
205 | ;;;###autoload
206 | (defun org-make-toc-at-point ()
207 | "Make or update table of contents at current entry."
208 | (interactive)
209 | (let ((org-make-toc-disambiguations (make-hash-table :test #'equal))
210 | (org-make-toc-ids (make-hash-table :test #'equal)))
211 | (unless (org-make-toc--update-toc-at-point)
212 | (user-error "No TOC node found"))))
213 |
214 | ;;;###autoload
215 | (defun org-make-toc-insert ()
216 | "Insert \":CONTENTS:\" drawer at point."
217 | (interactive)
218 | (call-interactively #'org-make-toc-set)
219 | (org-insert-drawer nil "CONTENTS"))
220 |
221 | ;;;###autoload
222 | (defun org-make-toc-set (properties)
223 | "Set TOC PROPERTIES of entry at point."
224 | (interactive (list (org-make-toc--complete-toc-properties)))
225 | (org-set-property "TOC" properties))
226 |
227 | ;;;; Functions
228 |
229 | (defun org-make-toc--complete-toc-properties ()
230 | "Return TOC properties string read with completion."
231 | (cl-labels ((property (property)
232 | (--> (org-entry-get (point) "TOC")
233 | (concat "(" it ")") (read it)
234 | (plist-get it property)
235 | (if it
236 | (prin1-to-string it)
237 | "")))
238 | (read-number (prompt &optional initial-input)
239 | ;; The default `read-number' only accepts a number, and
240 | ;; we need to allow the user to input nothing. But
241 | ;; using `read-string' with `string-to-number' returns
242 | ;; 0 for the empty string, so we use this instead.
243 | (let ((input (read-string prompt initial-input)))
244 | (pcase input
245 | ((rx bos (1+ digit) eos)
246 | (string-to-number input))
247 | ((rx bos (0+ blank) eos) "")
248 | (_ (read-number prompt initial-input)))))
249 | (completing-read-description
250 | (prompt collection &optional predicate require-match
251 | initial-input hist def inherit-input-method)
252 | (let ((choice (completing-read prompt collection predicate require-match
253 | initial-input hist def inherit-input-method)))
254 | (alist-get choice collection nil nil #'equal)))
255 | ;; TODO: Version of `completing-read-multiple' that works like that. Sigh.
256 | )
257 | (let ((props
258 | (list :include (completing-read-description
259 | "Include entries: "
260 | '(("None" . nil) ("All" . all) ("Descendants" . descendants)
261 | ("Siblings" . siblings))
262 | nil t (property :include))
263 | :depth (read-number "Depth (number): " (property :depth))
264 | :force (completing-read-multiple "Force (one or more): "
265 | '(("nothing" . nil) ("depth" . depth)
266 | ("ignore" . ignore))
267 | nil t (property :force))
268 | :ignore (completing-read-multiple "Ignore entries (one or more): "
269 | '(("nothing" . nil) ("descendants" . descendants)
270 | ("siblings" . siblings) ("this" . this))
271 | nil t (property :ignore))
272 | :local (completing-read-multiple "Tree-local settings (one or more): "
273 | '(("nothing" . nil) ("depth" . depth))
274 | nil t (property :force)))))
275 | (when (cl-loop for property in '(:include :depth :force :ignore :local)
276 | thereis (pcase (plist-get props property)
277 | ((or "" "nil" (\` nil)) nil)
278 | (_ t)))
279 | ;; Only return a string if at least one property is set.
280 | (substring (format "%s" (cl-loop for (property value) on props by #'cddr
281 | unless (member value '("" "nil" nil))
282 | append (list property value)))
283 | 1 -1)))))
284 |
285 | (defun org-make-toc--next-toc-position ()
286 | "Return position of next TOC, or nil."
287 | (save-excursion
288 | (when (and (re-search-forward org-make-toc-contents-drawer-start-regexp nil t)
289 | (save-excursion
290 | (beginning-of-line)
291 | (looking-at-p org-drawer-regexp)))
292 | (point))))
293 |
294 | (defun org-make-toc--update-toc-at-point ()
295 | "Make or update table of contents at current entry."
296 | (when-let* ((toc-string (org-make-toc--toc-at-point)))
297 | (org-make-toc--replace-entry-contents toc-string)
298 | t))
299 |
300 | (defun org-make-toc--toc-at-point ()
301 | "Return TOC tree for entry at point."
302 | (cl-labels ((descendants (&key depth force)
303 | (when (and (or (null depth) (> depth 0))
304 | (children-p))
305 | (save-excursion
306 | (save-restriction
307 | (org-narrow-to-subtree)
308 | (outline-next-heading)
309 | (cl-loop collect (cons (entry :force force)
310 | (unless (entry-match :ignore 'descendants)
311 | (descendants :depth (or (unless (or (arg-has force 'depth)
312 | (entry-match :local 'depth))
313 | (entry-property :depth))
314 | (when depth
315 | (1- depth)))
316 | :force force)))
317 | while (next-sibling))))))
318 | (siblings (&key depth force)
319 | (save-excursion
320 | (save-restriction
321 | (when (org-up-heading-safe)
322 | (org-narrow-to-subtree)
323 | (outline-next-heading)
324 | (outline-next-heading))
325 | (cl-loop collect (cons (entry :force force)
326 | (unless (entry-match :ignore 'descendants)
327 | (descendants :depth (or (unless (or (arg-has force 'depth)
328 | (entry-match :local 'depth))
329 | (entry-property :depth))
330 | (when depth
331 | (1- depth)))
332 | :force force)))
333 | while (next-sibling)))))
334 | (children-p ()
335 | (let ((level (org-current-level)))
336 | (save-excursion
337 | (when (outline-next-heading)
338 | (> (org-current-level) level)))))
339 | (next-sibling ()
340 | (let ((pos (point)))
341 | (org-forward-heading-same-level 1 'invisible-ok)
342 | (/= pos (point))))
343 | (arg-has (var val)
344 | (or (equal var val)
345 | (and (listp var)
346 | (member val var))))
347 | (entry (&key force)
348 | (unless (or (and (not (arg-has force 'ignore))
349 | (entry-match :ignore 'this))
350 | ;; TODO: Add configurable predicate list to exclude entries.
351 | (seq-intersection org-make-toc-exclude-tags (org-get-tags))
352 | ;; NOTE: The "COMMENT" keyword is not returned as the to-do keyword
353 | ;; by `org-heading-components', so it can't be tested as a keyword.
354 | (string-match-p (rx bos "COMMENT" (or blank eos))
355 | (nth 4 (org-heading-components))))
356 | (funcall org-make-toc-link-type-fn (point))))
357 | (entry-match (property value)
358 | (when-let* ((found-value (entry-property property)))
359 | (or (equal value found-value)
360 | (and (listp found-value) (member value found-value)))))
361 | (entry-property (property)
362 | (plist-get (read (concat "(" (org-entry-get (point) "TOC") ")"))
363 | property)))
364 | (save-excursion
365 | (save-restriction
366 | (-let* (((&plist :include :depth :force force)
367 | (read (concat "(" (org-entry-get (point) "TOC") ")")))
368 | (tree (pcase include
369 | ;; Set bounds.
370 | ('all (org-with-wide-buffer
371 | (goto-char (point-min))
372 | (when (org-before-first-heading-p)
373 | (outline-next-heading))
374 | (siblings :depth (or (unless (arg-has force 'depth)
375 | (entry-property :depth))
376 | (when depth
377 | (1- depth)))
378 | :force force)))
379 | ('descendants (descendants :depth depth :force force))
380 | ('siblings (siblings :depth depth :force force)))))
381 | (org-make-toc--tree-to-list tree))))))
382 |
383 | (defun org-make-toc--tree-to-list (tree)
384 | "Return list string for TOC TREE."
385 | (cl-labels ((tree (tree depth)
386 | (when (> (length tree) 0)
387 | (when-let* ((entries (->> (append (when (car tree)
388 | (list (concat (s-repeat depth " ")
389 | "- " (car tree))))
390 | (--map (tree it (1+ depth))
391 | (cdr tree)))
392 | -non-nil -flatten)))
393 | (s-join "\n" entries)))))
394 | (->> tree
395 | (--map (tree it 0))
396 | -flatten (s-join "\n"))))
397 |
398 | (defun org-make-toc--disambiguate (string)
399 | "Return STRING having been disambiguated.
400 | Uses hash table `org-make-toc-disambiguations'."
401 | (if (not (gethash string org-make-toc-disambiguations))
402 | (progn
403 | (setf (gethash string org-make-toc-disambiguations) t)
404 | string)
405 | (cl-loop for i from 0 to 1000
406 | do (when (= 1000 i)
407 | (error "Tried to disambiguate %s 1000 times" string))
408 | for new-string = (format "%s-%s" string i)
409 | if (not (gethash new-string org-make-toc-disambiguations))
410 | do (puthash new-string t org-make-toc-disambiguations)
411 | and return new-string)))
412 |
413 | (defun org-make-toc--link-entry-github (pos)
414 | "Return text for entry at POS converted to GitHub style link."
415 | (-when-let* ((title (org-link-display-format (org-entry-get pos "ITEM")))
416 | (target (--> title
417 | org-link-display-format
418 | (downcase it)
419 | (replace-regexp-in-string " " "-" it)
420 | (replace-regexp-in-string "[^[:alnum:]_-]" "" it)))
421 | (filename (if org-make-toc-filename-prefix
422 | (file-name-nondirectory (buffer-file-name))
423 | "")))
424 | (when org-make-toc-insert-custom-ids
425 | (setf target (or (gethash pos org-make-toc-ids)
426 | (setf (gethash pos org-make-toc-ids)
427 | (org-make-toc--disambiguate target))))
428 | (org-set-property "CUSTOM_ID" target))
429 | (org-link-make-string (concat filename "#" target)
430 | (org-make-toc--visible-text title))))
431 |
432 | (defun org-make-toc--link-entry-org (pos)
433 | "Return text for entry at POS converted to regular Org link."
434 | ;; FIXME: There must be a built-in function to do this, although it might be in `org-export'.
435 | (-when-let* ((title (org-link-display-format (org-entry-get pos "ITEM")))
436 | (filename (if org-make-toc-filename-prefix
437 | (concat "file:" (file-name-nondirectory (buffer-file-name)) "::")
438 | "")))
439 | (org-link-make-string (concat filename title)
440 | (org-make-toc--visible-text title))))
441 |
442 | (defun org-make-toc--replace-entry-contents (contents)
443 | "Replace the contents of TOC in entry at point with CONTENTS.
444 | Replaces contents of :CONTENTS: drawer."
445 | (save-excursion
446 | (org-back-to-heading 'invisible-ok)
447 | (let* ((end (org-entry-end-position))
448 | contents-beg contents-end)
449 | (when (and (re-search-forward org-make-toc-contents-drawer-start-regexp end t)
450 | (save-excursion
451 | (beginning-of-line)
452 | (looking-at-p org-drawer-regexp)))
453 | ;; Set the end first, then search back and skip any ":TOC:" property line in the drawer.
454 | (setf contents-end (save-excursion
455 | (when (re-search-forward (rx bol (0+ blank) ":END:" (0+ blank) eol) end)
456 | (match-beginning 0)))
457 | contents-beg (progn
458 | (when (save-excursion
459 | (forward-line 1)
460 | (looking-at-p (rx bol ":TOC:" (0+ blank) (group (1+ nonl)))))
461 | (forward-line 1))
462 | (pos-eol))
463 | contents (concat "\n" (string-trim contents) "\n")
464 | (buffer-substring contents-beg contents-end) contents)))))
465 |
466 | (defun org-make-toc--visible-text (string)
467 | "Return only visible text in STRING after fontifying it like in Org-mode.
468 |
469 | `org-fontify-like-in-org-mode' is a very, very slow function
470 | because it creates a new temporary buffer and runs `org-mode' for
471 | every string it fontifies. This function reuses a single
472 | invisible buffer and only runs `org-mode' when the buffer is
473 | created."
474 | ;; MAYBE: Use `org-sort-remove-invisible' instead? Not sure if it does exactly the same thing.
475 | (let ((buffer (get-buffer " *org-make-toc-fontification*")))
476 | (unless buffer
477 | (setq buffer (get-buffer-create " *org-make-toc-fontification*"))
478 | (with-current-buffer buffer
479 | (buffer-disable-undo)
480 | (org-mode)
481 | (setq-local org-hide-emphasis-markers t)))
482 | (with-current-buffer buffer
483 | (insert string)
484 | (font-lock-ensure)
485 | ;; This is more complicated than I would like, but the `org-find-invisible' and
486 | ;; `org-find-visible' functions don't seem to be appropriate to this task, so this works.
487 | (prog1
488 | (cl-flet ((visible-p () (not (get-char-property (point) 'invisible)))
489 | (invisible-p () (get-char-property (point) 'invisible))
490 | (forward-until (until)
491 | (cl-loop until (or (eobp) (funcall until))
492 | for pos = (next-single-property-change (point) 'invisible nil (point-max))
493 | while pos
494 | do (goto-char pos))
495 | (point))
496 | (backward-until (until)
497 | (cl-loop until (or (eobp) (funcall until))
498 | for pos = (previous-single-property-change (point) 'invisible nil (point-max))
499 | while pos
500 | do (goto-char pos))
501 | (point)))
502 | (goto-char (point-min))
503 | (unless (visible-p)
504 | (forward-until #'visible-p))
505 | (setq string (cl-loop concat (buffer-substring (point) (forward-until #'invisible-p))
506 | until (eobp)
507 | do (forward-until #'visible-p))))
508 | (erase-buffer)))))
509 |
510 | ;;;; Mode
511 |
512 | ;;;###autoload
513 | (define-minor-mode org-make-toc-mode
514 | "Add `org-make-toc' to the `before-save-hook' in the current Org buffer.
515 | With prefix argument ARG, turn on if positive, otherwise off."
516 | :init-value nil
517 | (unless (derived-mode-p 'org-mode)
518 | (user-error "Not an Org buffer"))
519 | (if org-make-toc-mode
520 | (add-hook 'before-save-hook #'org-make-toc nil t)
521 | (remove-hook 'before-save-hook #'org-make-toc t))
522 | (message (format "org-make-toc-mode %s."
523 | (if org-make-toc-mode
524 | "enabled"
525 | "disabled"))))
526 |
527 | ;;;; Footer
528 |
529 | (provide 'org-make-toc)
530 |
531 | ;;; org-make-toc.el ends here
532 |
--------------------------------------------------------------------------------
/test/data.org:
--------------------------------------------------------------------------------
1 | * A
2 | ** Contents
3 | :PROPERTIES:
4 | :toc: this
5 | :END:
6 | - [[#hmm][Hmm]]
7 | - [[#oho][Oho]]
8 | - [[#a1][A1]]
9 | - [[#a2][A2]]
10 | - [[#a3][A3]]
11 | - [[#b1][B1]]
12 | - [[#b2][B2]]
13 | - [[#b3][B3]]
14 | - [[#c1][C1]]
15 | - [[#c2][C2]]
16 | - [[#c3][C3]]
17 | *** Hmm
18 | *** Oho
19 | ** A1
20 | ** A2
21 | ** A3
22 | * B
23 |
24 | ** B1
25 |
26 | ** B2
27 |
28 | ** B3
29 |
30 | * Ignore
31 | :PROPERTIES:
32 | :toc: ignore
33 | :END:
34 |
35 | ** Ignore1
36 |
37 | ** Ignore2
38 |
39 | ** Ignore3
40 | * Ignore-Children
41 | :PROPERTIES:
42 | :toc: ignore-children
43 | :END:
44 |
45 | ** Ignore-Children1
46 |
47 | ** Ignore-Children2
48 |
49 | ** Ignore-Children3
50 | * C
51 |
52 | ** C1
53 |
54 | ** C2
55 |
56 | ** C3
57 | * Invalid
58 | :PROPERTIES:
59 | :toc:
60 | :END:
61 | * Depth
62 | :PROPERTIES:
63 | :TOC: 1
64 | :END:
65 | ** D1
66 | *** D2
67 | **** D3
68 |
--------------------------------------------------------------------------------
/test/test.org:
--------------------------------------------------------------------------------
1 | * Tests
2 |
3 | ** Pcase
4 |
5 | #+BEGIN_SRC elisp
6 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/test/data.org")
7 | (let ((tree (cddr (org-element-parse-buffer 'headline))))
8 | (org-walk-tree-pcase tree)))
9 | #+END_SRC
10 |
11 | #+RESULTS:
12 | | headline | Contents | nil |
13 | | headline | A | ((headline A2 nil) (headline A3 nil)) |
14 | | headline | B | ((headline B2 nil) (headline B3 nil)) |
15 | | headline | Ignore-Children | |
16 | | headline | C | ((headline C2 nil) (headline C3 nil)) |
17 | | headline | Invalid | nil |
18 |
19 | ** Depth
20 |
21 | #+BEGIN_SRC elisp
22 | (with-current-buffer (find-buffer-visiting "~/src/org-make-toc/test/data.org")
23 | (let ((tree (cddr (org-element-parse-buffer 'headline))))
24 | (org-make-toc--remove-ignored-entries tree)))
25 | #+END_SRC
26 |
27 | #+RESULTS:
28 | | headline | (:title A) | ((headline (:title nil) ((headline (:title Hmm) nil) (headline (:title Oho) nil))) (headline (:title A1) nil) (headline (:title A2) nil) (headline (:title A3) nil)) |
29 | | headline | (:title B) | ((headline (:title B1) nil) (headline (:title B2) nil) (headline (:title B3) nil)) |
30 | | headline | (:title Ignore-Children) | |
31 | | headline | (:title C) | ((headline (:title C1) nil) (headline (:title C2) nil) (headline (:title C3) nil)) |
32 | | headline | (:title Invalid) | nil |
33 | | headline | (:title nil) | ((headline (:title nil) nil)) |
34 |
--------------------------------------------------------------------------------