UNPKG

43.6 kBMarkdownView Raw
1# literate-programming-lib [![Build Status](https://travis-ci.org/jostylr/literate-programming-lib.png)](https://travis-ci.org/jostylr/literate-programming-lib)
2
3Write your code anywhere and in any order with as much explanation as you
4like. literate-programming will weave it all together to produce your project.
5
6This is a modificaiton of and an implementation of
7[Knuth's Literate Programming](http://www-cs-faculty.stanford.edu/~uno/lp.html)
8technique. It is
9perhaps most in line with [noweb](http://tex.loria.fr/litte/ieee.pdf).
10
11It uses markdown as the basic document format with the code to be weaved
12together being markdown code blocks. GitHub flavored code fences can also be used
13to demarcate code blocks. In particular, [commonmark](http://commonmark.org/)
14is the spec that the parsing of the markdown is used. Anything considered code
15by it will be considered code by literate programming.
16
17This processing does not care what language(s) your are programming in. But it
18may skew towards more useful for the web stack.
19
20This is the core library that is used as a module. See
21[-cli](https://github.com/jostylr/literate-programming-cli) for the command
22line client. The [full](https://github.com/jostylr/literate-programming)
23version has a variety of useful standard
24plugins ("batteries included").
25
26## Installation
27
28This requires [node.js](http://nodejs.org) and [npm](https://npmjs.org/) to be
29installed. See [nvm](https://github.com/creationix/nvm) for a recommend
30installation of node; it allows one to toggle between different versions. This
31has been tested on node.js .10, .12, and io.js. It is basic javascript and
32should work pretty much on any javascript engine.
33
34Then issue the command:
35
36 npm install literate-programming-lib
37
38Since this is the library module, typically you use the client version install
39and do not install the lib directly. If you are hacking with modules, then you
40already know that you will want this in the package.json file.
41
42## Using as a module
43
44You can use `Folder = require('literate-programming-lib');` to get
45a constructor that will create what I think of as a folder.
46The folder will handle all the documents and scopes and etc.
47
48To actually use this library (as opposed to the command line client),
49you need to establish how it fetches documents and tell
50it how to save documents. An example is below. If you just want to compile
51some documents, use the command line client and ignore this. Just saying the
52following is not pretty. At least, not yet!
53
54The thing to keep in mind is
55that this library is strutured around events
56using my [event-when](https://github.com/jostylr/event-when) library. The
57variable gcd is the event emitter (dispatcher if you will).
58
59
60 var fs = require('fs');
61 var Folder = require('literate-programming-lib');
62 var folder = new Folder();
63 var gcd = folder.gcd;
64 var colon = folder.colon;
65
66 gcd.on("need document", function (rawname) {
67 var safename = colon.escape(rawname);
68 fs.readfile(rawname, {encoding:'utf8'}, function (err, text) {
69 if (err) {
70 gcd.emit("error:file not found:" + safename);
71 } else {
72 folder.newdoc(safename, text);
73 }
74 });
75 });
76
77 gcd.on("file ready", function(text, evObj) {
78 var filename = evObj.pieces[0];
79 fs.writefile(filename, text);
80 });
81
82 gcd.emit("need document:first.md");
83
84This last line should start the whole chain of compilation with first.md being read in
85and then any of its files being called, etc., and then any files to save will
86get saved.
87
88The reason the lib does not have this natively is that I separated it out
89specifically to avoid requiring file system access. Instead you can use any kind of
90function that provides text, or whatever. It should be fine to also use
91`folder.newdoc` directly on each bit of text as needed; everything will
92patiently wait until the right stuff is ready. I think.
93
94Note that live code can be run from a literate program as well. So be
95careful!
96
97## Example
98
99Let's give a quick example of what a sample text might look like.
100
101 # Welcome
102
103 So you want to make a literate program? Let's have a program that outputs
104 all numbers between 1 to 10.
105
106 Let's save it in file count.js
107
108 [count.js](#Structure "save:")
109
110 ## Structure
111
112 We have some intial setup. Then we will generate the array of numbers. We
113 end with outputting the numbers.
114
115 var numarr = [], start=1, end = 11, step = 1;
116
117 _"Loop"
118
119 _"Output"
120
121 ## Output
122
123 At this point, we have the array of numbers. Now we can join them with a
124 comma and output that to the console.
125
126 console.log("The numbers are: ", numarr.join(", ") );
127
128 ## Loop
129
130 Set the loop up and push the numbers onto it.
131
132 var i;
133 for (i = start; i < end; i += step) {
134 numarr.push(i);
135 }
136
137A full example of a literate program is lp.md in this repository. It compiles
138to this library.
139
140
141## Document syntax
142
143A literate program is a markdown document with some special conventions.
144
145The basic idea is that each header line (regardless of level, either atx # or
146seText underline ) demarcates a full block. Code blocks within a full block
147are the bits that are woven together.
148
149### Code Block
150
151Each code block can contain whatever kind of code, but there is a primary special
152syntax.
153
154`_"Block name"` This tells the compiler to compile the block with "Block
155 name" and then replace the `_"Block name"` with that code.
156
157Note the the allowed quotes are double, single, and backtick. Matching types
158are expected. And yes, it is useful to have three different types.
159
160The full syntax is something of the form
161`_"scope name::block name:minor block name | cmd arg 1, arg 2 | cmd2 |cmd3 ..."`
162where the scope name allows us to refer to other documents (or artificial
163common scopes) and the commands run the output of one to the input of the
164other, also taking in arguments which could they themselves be block
165substitutions.
166
167Note that one can also backslash escape the underscore. To have multiple
168escapes (to allow for multiple compiling), one can use `\#_"` where the number
169gets decremented by one on each compile and, when it is compiled with a 0 there,
170the sub finally gets run.
171
172A block of the form `_":first"` would look for a minor block, i.e., a block
173that has been created by a switch directive. See next section.
174
175### Directive
176
177A directive is a command that interacts with external input/output. Just about
178every literate program has at least one save directive that will save some
179compiled block to a file.
180
181The syntax for the save directive is
182
183 [file.ext](#name-the-heading "save: encoding | pipe commands")
184
185where
186
187* `file.ext` is the name of the file to save to
188* `name-the-heading` is the heading of the block whose compiled version is being saved.
189Spaces in the heading get converted to dashes for id linking purposes. Colons can be used
190to reference other scopes and/or minor blocks. In particular, `#:jack` will
191refernce the `jack` minor in the current heading block where the save
192directive is located.
193* `save:` is there to say this is the directive to save a file
194* `encoding` is any valid encoding of
195 [iconv-lite](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings).
196 This is relevant more in the command line module, but is here as the save
197 directive is here.
198* `pipe commands` optional commands to process the text before saving. See
199 next section.
200
201
202For other directives, what the various parts mean depends, but it is always
203
204 [some](#stuff "dir: whatever")
205
206where the `dir` should be replaced with a directive name. If dir is absent,
207but the colon is there, then this demarcates a minor block start.
208
209### Pipes
210
211One can also use pipes to pipe the compiled text through a command to do
212something to it. For example, `_"Some JS code | jshint"` will take the code
213in block `some JS code` and pipe it into the jshint command which can be a
214thin wrapper for the jshint module and report errors to the console.
215That command would then return the text in an untouched fashion. We can also use
216pipe commands to modify the text.
217
218Commands can be used in block substitutions, minor block directive switches, and
219other directives that are setup to use them such as the save and out directive:
220`[code.js](#some-js-code "save: | jstidy)` will tidy up the code
221before storing it in the file `code.js`.
222
223If you want your own directive to process pipes, see the [save directive](https://github.com/jostylr/literate-programming-lib/blob/master/lp.md#save) in
224lp.md. Pay particular attention to the "process" and "deal with start" minor
225blocks. The functionality of pipe parsing is in the `doc.pipeParsing` command,
226but there events that need to be respected in the setup.
227
228Commands take arguments separated by commas and commands end with pipes or the
229block naming quote. One can also use a named code block as an argument, using
230any of the quote marks (same or different as surroung block name). To
231escape commas, quotes, pipes, underscores, spaces (spaces get trimmed from the
232beginning and ending of an argument), newlines, one can use a backslash, which
233also escapes itself. Note that the commonmark parser will escape all
234backslash-punctuation combinations outside of code blocks. So you may need a
235double backslash in directive command pipings.
236
237You can also use `\n` to puta newline in line or `\u...` where the ... is a
238unicode codepoint per javascript spec implemented by [string.fromcodepoint](https://github.com/mathiasbynens/String.fromCodePoint).
239
240
241### Minor Block
242
243Finally, you can use distinct code blocks within a full block. If you simply
244have multiple code blocks with none of the switching syntax below, then they
245will get concatenated into a single code block.
246
247You can also switch to have what I call minor blocks within a main heading. This is mainly
248used for small bits that are just pushed out of the way for convenience. A
249full heading change is more appropriate for something that merits separate attention.
250
251To create a minor block, one can either use a link of the form `[code name]()` or
252`[code name](#whatever ":|cmd ...")` Note this is a bit of a break from
253earlier versions in which a link on its own line would create a minor block. Now it is
254purely on the form and not on placement.
255
256
257Example: Let's say in heading block `### Loopy` we have `[outer loop]()`
258Then it will create a code block that can be referenced by
259`_"Loopy:outer loop"`.
260
261Note: If the switch syntax is `[](#... ":|...")` then this just transforms
262whatever is point to in href using the pipe commands. That is, it is not a
263switch, but fills in a gap for main blocks not having pipe switch syntax. The
264key is the empty link text.
265
266#### Templating
267
268One use of minor blocks is as a templating mechanism.
269
270 ## Top
271
272 After the first compile, the numbers will be decremented, but the blocks
273 will not be evaluated.
274
275 \1_":first"
276
277 \2_":second"
278
279 \1_":final"
280
281
282 This is now a template. We could use it as
283
284 [happy.txt](# "save:| compile basic, great")
285 [sad.txt](# "save:| compile basic, grumpy")
286
287
288 # Basic
289
290 [first]()
291
292 Greetings and Salutations
293
294 [final]()
295
296 Sincerely,
297 Jack
298
299 # Great
300
301 [second]()
302
303 You are great.
304
305 # Grumpy
306
307 [second]()
308
309 You are grumpy.
310
311This would produce two text files
312
313
314happy.txt:
315
316 Greetings and Salutations
317
318 You are great.
319
320 Sincerely,
321 Jack
322
323sad.txt:
324
325
326 Greetings and Salutations
327
328 You are grumpy.
329
330
331 Sincerely,
332 Jack
333
334
335Note that you need to be careful about feeding in the escaped commands into
336other parsers. For example, I was using Jade to generate HTML structure and
337then using this templating to inject content (using markdown). Well, Jade
338escapes quotes and this was causing troubles. So I used backticks to delimit
339the block name instead of quotes and it worked fine. Be flexible.
340
341
342## Nifty parts of writing literate programming
343
344* You can have your code in any order you wish.
345* You can separate out flow control from the processing. For example,
346
347 if (condition) {
348 _"Truth"
349 } else {
350 _"Beauty"
351 }
352
353 The above lets you write the if/else statement with its logic and put the
354 code in the code blocks `truth` and `beauty`. This can help keep one's
355 code to within a single screenful per notion.
356* You can write code in the currently live document that has no effect, put in
357 ideas in the future, etc.
358* You can "paste" multiple blocks of code using the same block name. This is
359 like DRY, but the code does get repeated for the computer. You can also
360 substitute in various values in the substitution process so that code
361 blocks that are almost the same but with different names can come from the
362 same root structure.
363* You can put distracting data checks/sanitation/transformations into another
364 block and focus on the algorithm without the use of functions (which can be
365 distracting).
366* You can process the blocks in any fashion you want. So for example, to
367 create a JSON object, one could use a simpler setup appropriate for the
368 particular data and then transform it into JSON. It's all good.
369* This brings DSL and grunt power, written in the same place as your code. It
370 is really about coding up an entire project.
371* Getting the length of functions right is difficult. Too short functions,
372 and boilerplate and redirection becomes quite the bother. Too long, and it
373 is hard to understand what all a function is doing. Too long and we lose
374 composability. Too short, the chain of composing them becomes too long.
375 Literate programming can help somewhat in that we can have longer functions
376 and still have it understood. We could also potentially use the litpro
377 blocks again allowing for some composability though that that should be
378 rare. I think the rule of thumb is that if breaking it up seems good from a
379 usability stance, do it. If breaking it up is more about keeping a function
380 to a readable length, use litpro blocks. Another advantage of using litpro
381 blocks is that we get the benefit of small parts when coding, but when
382 debugging, we can see a much larger flow of code all at once in the compiled
383 version.
384
385I also like to use it to compile an entire project from a single file, pulling
386in other literate program files as needed. That is, one can have a
387command-and-control literate program file and a bunch of separate files for
388separate concerns. But note that you need not split the project into any
389pre-defined ways. For example, if designing a web interface, you can organize
390the files by widgets, mixing in HTML, CSS, and JS in a single file whose
391purpose is clear. Then the central file can pull it all in to a single web
392page (or many) as well as save the CSS and JS to their own files as per the
393reommendation, lessing the CSS, tanspiling ES6, linting, and minifying all as
394desired. Or you could just write each output file separate in its own litpro
395document.
396
397It's all good. You decide the order and grouping. The structure of your litpro
398documents is up to you and is **independent** of the needed structures of the
399output.
400
401## Built in directives
402
403There are a variety of directives that come built in.
404
405* **Save** `[filename](#start "save:options|commands")` Save the text from start
406 into file filename. The options can be used in different ways, but in the
407 command client it is an encoding string for saving the file; the default
408 encoding is utf8.
409* **Store** `[name](#start "store:value|...")` If the value is present, then
410 it is sent through the pipes. If there is no
411 value, then the `#start` location is used for the value and that gets piped.
412 The name is used to store the value.
413* **Transform** `[des|name](#start "transform:|...)` or `[des|name](#start ":|...")`.
414 This takes the value that start points to and transforms it using the pipe
415 commands. Note one can store the transformed values by placing the variable
416 name after a pipe in the link text.
417 The description of link text has no role. For the syntax
418 with no transform, it can be link text that starts with a pipe or it can be
419 completely empty. Note that if it is empty, then it does not appear and is
420 completely obscure to the reader.
421* **Load** `[alias](url "load:options")` This loads the file, found at the url
422 (file name probably) and stores it in the alias scope as well as under the
423 url name. We recommend using a short alias and not relying on the filename
424 path since the alias is what will be used repeatedly to reference the blocks
425 in the loaded file. Options are open, but for the command line client it is
426 the encoding string with default utf8. Note there are no pipes since there
427 is no block to act on it.
428* **Define** `[commandName](#start "define: async/sync/raw|cmd")` This allows one
429 to define commands in a lit pro document. Very handy. Order is irrelevant;
430 anything requiring a command will wait for it to be defined. This is
431 convenient, but also a bit more of a bother for debugging. Anyway, the start
432 is where we find the text for the body of the command. The post colon, pre
433 pipe area expects one of three options which is explained below in plugins.
434 The default is sync which if you return the text you want to pass along from
435 the command, then it is all good. Start with that. You can also pipe your
436 command definition through pipe commands before finally installing the
437 function as a live function. Lots of power, lots of headaches :) The
438 signature of a command is `function (input, args, name)` where the input is
439 the text being piped in, the args are the arguments array (all text) of the
440 command, and name is the name to be emitted when done. For async, name is a
441 callback function that should be called when done. For sync, you probably
442 need not worry about a name. The doc that is calling the command is the
443 `this`. This defines the command only for current doc. To do it across docs
444 in the project, define it in the lprc.js. The commandName should be one
445 word.
446* **Subcommand** `[subcommandname](#cmdName "subcommand:")` This defines
447 subcommandname (one word) and attaches it to be active in the cmdName. If no
448 cmdName, then it becomes available to all commands.
449* **Block**s on/off `[off](# "block:")` Stops recording code blocks. This is
450 good when writing a bunch of explanatory code text that you do not want
451 compiled. You can turn it back on with the `[on](# "block:")` directive.
452 Directives and headings are still actively being run and used. These can be
453 nested. Think "block comment" sections. Good for turning off troublesome
454 sections.
455* **Eval** `[des|name](# "eval:)` Whatever block the eval finds itself, it will eval. It
456 will eval it only up to the point where it is placed. This is an immediate
457 action and can be quite useful for interventions. The eval will have access
458 to the doc object which gives one access to just about everything else. This
459 is one of those things that make running a literate progamming insecure. The
460 return value is nonexistent and the program will not usually wait for any async
461 actions to complete. If you put a pipe in the link name text, then the
462 anything after the pipe will become a name that the variable `ret` will be
463 stored in.
464* **Ignore** `[language](# "ignore:")` This ignores the `language` code blocks.
465 For example, by convention, you could use code fence blocks with language js
466 for compiled code and ignore those with javascript. So you can have example
467 code that will not be seen and still get your syntax highlighting and
468 convenience. Note that this only works with code fences, obviously. As soon
469 as this is seen, it will be used and applied there after.
470* **Out** `[outname](#start "save:|commands")` Sends the text from start
471 to the console, using outname as a label.
472* **New scope** `[scope name](# "new scope:")` This creates a new scope (stuff
473 before a double colon). You can use it to store variables in a different
474 scope. Not terribly needed, but it was easy to expose the underlying
475 functionality.
476* **Link Scope** `[alias name](# "link scope:scopename")` This creates an alias for
477 an existing scope. This can be useful if you want to use one name and toggle
478 between them. For example, you could use the alias `v` for `dev` or `deploy`
479 and then have `v::title` be used with just switching what `v` points to
480 depending on needs. A bit of a stretch, I admit.
481* **Log** `[match string](# "log:")` This is a bit digging into the system. You
482 can monitor the events being emitted by using what you want to match for.
483 For example, you could put in a block name (all lower cased) and monitor all
484 events for that. This gets sent to `doc.log` which by default prints to
485 `console.log`. If you use `\:` in the match string, this becomes the triple
486 colon separator that we use for techinical reasons for `block:minor` name syntax.
487 This directive's code gives a bit of insight as to how to get
488 more out of the system.
489* **If** `[...](... "if: flag; directive:...")` If flag holds true (think build
490 flag), then the driective is executed with the arguments as given. A couple
491 of great uses are conditional evaling which allows for a great deal of
492 flexibility and conditional block on/off which may be useful if there is
493 extensive debugging commands involved.
494* **Flag** `[flag name](# "flag:")` This sets the named flag to true. Note
495 there is no way to turn a flag off easily.
496* **Version** `[name](# "version: number ; tagline")` This gives the name and version of
497 the program. Note the semicolon separator.
498 Saves `g::docname`, `g::docversion`, `g::tagline`.
499* **npminfo** `[author name](github/gituser "npminfo: author email; deps: ;
500 dev: " )` This takes in a string for some basic author information and
501 dependencies used. To add on or modify how it handles the deps, dev, etc.,
502 modify the `types` object on `Folder.directives.npminfo`.
503 Saves `g::authorname`, `g::gituser`, `g::authoremail`, `g::npm
504 dependencies`, `g::npm dev dependencies`.
505
506## Built in commands
507
508Note commands need to be one word.
509
510* **Eval** `code, arg1,...` The first argument is the text of the code to
511 eval. In its scope, it will have the incoming text as the `text` variable
512 and the arguments, which could be objects, will be in the `args` array. The
513 code is eval'd (first argument). The code text itself is available in the
514 `code` variable. The variable `text` is what is passed along. This should
515 make for quick hacking on text. The doc variable is also available for
516 inpsecting all sorts of stuff, like the current state of the blocks. If you
517 want to evaluate the incoming text and use the result as text, then the line
518 `text = eval(text)` as the first argument should work.
519* **Async** (async eval) `code1, code2, ...` Same deal as eval, except this
520 code expects a callback function to be called. It is in the variable
521 callback. So you can read a file and have its callback call the callback to
522 send the text along its merry way.
523* **Compile** This compiles a block of text as if it was in the document
524 originally. The compiled text will be the output. The arguments give the
525 names of blocknames that are used if short-hand minor blocks are
526 encountered. This is useful for templating.
527* **Sub** `key1, val1, key2, val2, ...` This replaces `key#` in the text with
528 `val#`. The replacement is sorted based on the length of the key value. This
529 is to help with SUBTITLE being replaced before TITLE, for example, while
530 allowing one to write it in an order that makes reading make sense. A little
531 unorthodox. We'll see if I regret it.
532* **Store** `variable name` This stores the incoming text into the variable
533 name. This is good for stashing something in mid computation. For example,
534 `...|store temp | sub THIS, that | store awe | _"temp"` will stash the
535 incoming text into temp, then substitute out THIS for that, then store that
536 into awe, and finally restore back to the state of temp. Be careful that the
537 variable temp could get overwritten if there are any async operations
538 hanging about. Best to have unique names. See push and pop commands for a
539 better way to do this.
540* **Log** This will output a concatenated string to doc.log (default
541 console.log) with the incoming text and the arguments. This is a good way to
542 see what is going on in the middle of a transformation.
543* **Raw** `start, end` This will look for start in the raw text of the file
544 and end in the file and return everything in between. The start and end are
545 considered stand-alone lines.
546* **Trim** This trims the incoming text, both leading and trailing whitespace.
547 Useful in some tests of mine.
548* **Join** This will concatenate the incoming text and the arguments together
549 using the first argument as the separator. Note one can use `\n` as arg1 and
550 it should give you a newline (use `\\n` if in a directive due to parser
551 escaping backslashes!). No separator can be as easy as `|join ,1,2,...`.
552* **Cat** The arguments are concatenated with the incoming text as is. Useful
553 for single arguments, often with no incoming text.
554* **Push** Simply pushes the current state of the incoming text on the stack
555 for this pipe process.
556* **Pop** Replaces the incoming text with popping out the last unpopped pushed
557 on text.
558* **If** `flag, cmd, arg1, arg2, ....` If the flag is present (think build
559 flag), then the command will execute with the given input text and
560 arguments. Otherwise, the input text is passed on.
561* **When** `name1, name2, ...` This takes in the event names and waits for
562 them to be emitted by done or manually with a
563 `doc.parent.done.gcd.once(name, "done")`. That would probably be used in
564 directives. The idea of this setup is to wait to execute a cli command for
565 when everything is setup. It passes through the incoming text.
566* **Done** `name` This is a command to emit the done event for name. It just
567 passes through the incoming text. The idea is that it would be, say, a
568 filename of something that got saved.
569
570## Built-in Subcommands
571
572With command arguments, one can run commands on arguments to get them in some
573appropriate form or use, including passing in objects or arrays. You can use
574them as `cmd a, subcmd(arg1, arg2, arg3)` would have subcmd acting on the args
575and the result of that would be the argument place
576 The `a` would be passed into cmd as the first
577argument, but anything might get passed into cmd by subcmd's return value. It
578could also store an object into a state for configuration.
579
580There are several built-in subcommands. Note that these are case insensitive.
581
582* `e` or `echo` This expects a quote-delimited string to be passed in and
583 will strip the quotes. This is useful as the appearance of a quote will mask
584 all other mechanics. So `e("a, b and _this")` will produce a literal
585 argument of `a, b, and _this`. Multiple arguments will be stripped and
586 passed on as multipel arguments.
587* `j` or `join` The first entry is the joiner separator and it joins the rest
588 of the arguments. For arrays, they are flattened with the separator as well
589 (just one level -- then it gets messy and wrong, probably).
590* `a` or `arr` or `array` This creates an array of the arguments.
591* `arguments` or `args` Inverse of array. This expects an array and each
592 element becomes a separate argument that the command will see. E.g., `cmd
593 arguments(arr(3, 4))` is equivalent to `cmd 3, 4`. This is useful for
594 constructing the args elsewhere. In particular, `args(obj(_"returns json of
595 an array"))` will result in the array from the subsitution becoming the
596 arguments to pass in.
597* `o` or `obj` or `object` This presumes that a JSON stringed object is ready
598 to be made into an object.
599* `merge` Merge arrays or objects, depending on what is there.
600* `kv` or `key-value` This produces an object based on the assumption that a
601 `key, value` pairing are the arguments. The key should be text. Multiple
602 pairs welcome.
603* `act` This allows one to do `obj, method, args` to apply a method to an
604 object with the slot 2 and above being arguments. For example, one could do
605 `act( arr(3, 4, 5), slice, 2, 3)` to slice the array to `[5]`.
606* `prop` or `property`. This will take the arguments as a property chain to
607 extract the value being pointed to.
608* `json` This will convert an object to JSON representation.
609* `set` The presumption is that an object is passed in whose key:values should
610 be added to the command state. `gSet` does this in a way that other
611 commands in the pipe chain can see it. `set(kv(name, val, ...))` would
612 probably be the typical way.
613* `get` This retrieves the value for the given key argument. `gGet` does the
614 same for the pipe chain. Multiple keys can be given and each associated
615 value will be returned as distinct arguments.
616* `n` or `#` or `number` This converts the argument(s) to numbers, using js
617 Number function. `n(1, 2, 3)` will create three arguments of integers. To
618 get an array, use `arr(n(1, 2, 3)`
619* `eval` will evaluate the argument and use the magic `ret` variable as the
620 value to return. This can also see doc (and doc.cmdName) and args has the
621 arguments post code. Recommend using backticks for quoting the eval; it
622 will check for that automatically (just backticks, can do echo for the
623 others if needed).
624* `log` This logs the argument and passes them along as arguments.
625* `t` or `true`. This returns the true value.
626* `f` or `false`. This returns the false value.
627* `null`. This returns the null value.
628* `doc`. This returns the doc variable. This could be useful in connection to
629 the property method and the log subcommand.
630* `skip`. This returns no arguments.
631
632To build one's own command, you can attach a function whose arguments will be
633the arguments passed in. The `this` is the doc object. The current name (say
634for scope storing) is in doc.cmdName. This will point to within a whole pipe
635chunk. Pop off the last part (delimited by triple colon) to get to the whole
636command scope. The return value will be used as in an argument into the
637command or another subcommand. If it is an array and the flag `args` is set to
638true, then each entry in the array will be expanded into a set of arguments.
639So instead of 1 argument, several could be returned. If nothing is returned,
640then no arguments are passed on and it is as if it wasn't there.
641
642
643## h5 and h6
644
645So this design treats h5 and h6 headings differently. They become subheadings
646of h1-4 headings. So for example, if we have `# top` and then `##### doc` and
647`###### something` then the sections would be recorded as `top, top/doc,
648top/doc/something` and we have a path syntax such as `../` which would yield
649`top/doc` if placed in `top/doc/something`. Ideally, this should work as you
650imagine. See `tests/h5.md` for the test examples.
651
652
653## Plugins
654
655This is a big topic which I will only touch on here. You can define commands
656in the text of a literate program, and we will discuss this a bit here, but
657mostly, both commands and directives get defined in module plugins or the `lprc.js`
658file if need be.
659
660### Defining Commands
661
662The define directive allows one to create commands within a document. This is
663a good place to start getting used to how things work.
664
665A command has the function signature `function (input, args, name)-> void`
666where the input is the incoming text (we are piping along when evaluating
667commands), args are the arguments that are comma separated after the command
668name, and the name is the name of the event that needs to be emitted with the
669outgoing text. The function context is the `doc` example.
670
671A minimal example is
672
673 function ( input, args, name) {
674 this.gcd.emit(name, input);
675 }
676
677We simply emit the name with the incoming text as data. We usually use `doc`
678for the `this` variable. This is the `raw` option in the define directive.
679
680The default is `sync` and is very easy.
681
682 function ( input, args, name) {
683 return input;
684 }
685
686That is, we just return the text we want to return. In general, the name is
687not needed though it may provide context clues.
688
689The third option is an `async` command. For those familiar with node
690conventions, this is easy and natural.
691
692 function (input, args, callback, name) {
693 callback(null, input);
694 }
695
696The callback takes in an error as first argument and, if no error, the text to
697output. One should be able to use this as a function callback to pass into
698other callback async setups in node.
699
700So that's the flow. Obviously, you are free to do what you like with the text
701inside. You can access the document as `this` and from there get to the event
702emitter `gcd` and the parent, `folder`, leading to other docs. The scopes are
703available as well. Synchronous is the easiest, but asynchronous control flow
704is just as good and is needed for reading files, network requests, external
705process executions, etc.
706
707### Plugin convention.
708
709I recommend the following npm module conventions for plugins for
710literate-programming.
711
7121. litpro-... is the name. So all plugins would be namespaced to litpro.
713 Clear, but short.
7142. Set `module.exports = function(Folder, other)` The first argument is the
715 Folder object which construts folders which constructs documents. By
716 accessing Folder, one can add a lot of functionality. This access is
717 granted in the command line client before any `folder` is created.
718
719 The other argument depends on context, but for the command line client it
720 is the parsed in arguments object. It can be useful for a number of
721 purposes, but one should limit its use as it narrows the context of the
722 use.
7233. Define commands and, less, directives. Commands are for transforming text,
724 directives are for doing document flow maipulations. Other hacks on
725 `Folder` should be even less rare than adding directives.
7264. Commands and directives are globally defined.
7275. `Folder.commands[cmd name] = function (input, args, name)...` is how to add a
728 command function. You can use `Folder.sync(cmdname, cmdfun)` and
729 `Folder.async` to install sync and async functions directly in the same
730 fashion as used by the define directive.
7316. `Folder.directives[directive name] = function (args)` is how to install a
732 directive. There are no helper functions for directives. These are more for
733 controlling the flow of the compiling in the large. The arg keys are read
734 off from `[link](href "directive:input")`. Also provided is the current
735 block name which is given by the key `cur`.
7367. If you want to do stuff after folder and its event emitter, gcd, is
737 created, then you can modify Folder.postInit to be a function that does
738 whatever you want on a folder instance. Think of it as a secondary
739 constructor function.
7408. The Folder has a plugins object where one can stash whatever under the
741 plugin's name. This is largely for options and alternatives. The folder and
742 doc object have prototyped objects on this as well which allows one to
743 choose the scope of applicability of objects. But beware that subobjects
744 are not prototyped (unless setup in that way; you may want to implement
745 that by Object.creating what is there, if anything). Think of it as deciding
746 where options should live when creating them.
747
748### Structure of Doc and Folder
749
750To really hack the doc compiling, one should inspect the structure of Folder,
751folder, and doc. The Folder is a constructor and it has a variety of
752properties on it that are global to all folders. But it also has several
753prototype properties that get inherited by the folder instances. Some of those
754get inherited by the docs as well. For each folder, there is also a gcd object
755which is the event emitter, which comes from the, ahem, magnificient event-when
756library (I wrote it with this use in mind). In many ways, hacking on gcd will
757manipulate the flow of the compiling.
758
759I wrote the folder instance to maintain flexibility, but typically (so far at
760least), one folder instance per run is typical. Still, there might be a use
761for it in say have a development and production compile separate but running
762simultaneously?
763
764
765#### Folder
766
767These are the properties of Folder that may be of interest.
768
769* commands. This is an object that is prototyped onto the instance of a
770 folder. Changing this adds commands to all created folder instances.
771* directives. This holds the directives. Otherwise same as commands.
772* reporter. This holds the functions that report out problems. See
773 reporters below. This is not prototyped and is shared across instances.
774* postInit. This does modification of the instance. Default is a noop.
775* sync, async. These install sync and async commands, respectively.
776* defSubCommand. Installs a subcommand.
777* plugins. This is a space to stash stuff for plugins. Use the plugin sans
778 litpr as the key. Then put there whatever is of use. The idea is if you
779 require something like jshint and then want default options, you can put
780 that there. Then in a lprc file, someone can override those options it will
781 be applied across the project.
782
783
784#### folder
785
786Each instance of folder comes with its own instances of:
787
788* docs. Holds all the documents.
789* scopes. Holds all the scopes which are the stuff before the double colon. It
790 includes the blocks from the compiled docs but also any created scopes.
791* reports. This holds all the reports of stuff waiting. As stuff stops
792 waiting, the reports go away. Ideally, this should be empty when all is
793 done.
794* stack. This is for the push and pop of text piping.
795* gcd. This is the event-emitter shared between docs, but not folders. Default
796 actions are added during the instantiation, largely related to the parsing
797 which sets up later. If you want to log what goes on, you may want to look
798 at the event-when docs (makeLog is a good place to start).
799* flags. This holds what flags are present.
800
801and shares via the prototype
802
803* parse. This parses the text of docs using commonmark spec
804* newdoc. This creates a new document. Kind of a constructor, but simply
805 called as a function. it calls the constructor Doc.
806* colon. We replace colons with a unicode triple colon for emitting purposes
807 of block names (event-when uses colon as separators too). This contains the
808 escape (does replacement), restore (undoes it), and v which is the unicode
809 tripe colon. If the v is replaced entirely, everything should hopefully work
810 just fine with a new separator.
811* createScope. Creating a scope.
812* join. What is used to concatenate code blocks under same block heading.
813 Default is "\n"
814* log. What to do with logging. Defaults to console.log.
815* indicator. An internal use to allow escaping of whitespace in command
816 arguments that would otherwisebe trimmed.
817* wrapSync, wrapAsync. These wrap functions up for command sync, async, but do
818 not install them. Not sure why not install them.
819* subnameTransform. A function that deals with shorthand minor substitutions
820 that avoid using the main block heading. This can be overwritten if you want
821 some custom behavior.
822* reportwaits. This is a function that produces the reports of what is still
823 waiting. Very useful for debugging. This returns an array.
824* simpleReport. This reports on the substitutions that did not get resolved.
825 This returns an array. It also includes any commands that were called but
826 not defined. Subcommands throw errors when not defined, but since commands
827 can be defined later, they will not. Hence this mechanism.
828* Doc. This is the constructor for documents.
829
830
831and uses Object.create to kind of share
832
833* commands
834* directives
835* plugins
836
837and direct copying from
838
839* reporters
840
841#### doc
842
843Each file leads to a doc which is stored in the folder. Each doc has a variety
844of stuff going on.
845
846Unique to each instance
847
848* file. The actual path to the file. It is treated as unique and there is a
849 scope dedicated to it. Don't mess with it. It is also how docs are keyed in
850 the folder.docs object.
851* text. The actual text of the file.
852* blockOff. This tracks whether to take in code blocks as usual. See blocks
853 directive. If 0, code blocks are queued up. If greater than 1, code blocks
854 are ignored.
855* levels. This tracks the level of the heading that is currently being used.
856 See h5/h6 description
857* blocks. Each heading gets its own key in the blocks and the raw code blocks
858 are put here.
859* heading, curname. These are part of the block parsing. curname is the full
860 name while heading excludes minor block names.
861* vars. This is where the variables live. As each code block is compiled,
862 its result gets stored here. But one can also add any bit of var name and
863 text to this.
864* parent. This is the folder that contains this doc.
865
866
867Inherited from folder
868
869* commands, modifications affect all
870* directives, modifications affect all
871* scopes, modifications affect all
872* gcd, modifications affect all. Be careful to scope added events to files,
873 etc.
874* plugins, modifications affect all
875* colon, Object.created
876* join, overwriting will only affect doc
877* log, overwriting will only affect doc
878* subnameTransform, overwriting will only affect doc
879* indicator, overwriting will only affect doc
880* wrapSync, wrapAsync, overwriting will only affect doc
881
882Prototyped on Doc. Almost all are internal and are of little to no interest.
883
884* pipeParsing. This parses the pipes. This may be useful if you want to do
885 something like in the save or define directives. Check them out in the
886 source if you want to see how to use it.
887* blockCompiling. This is what the compile command taps into. See how it is
888 done there.
889* getscope. Looks up a scope and does appropriate async waiting for an
890 existing scope if need be.
891* retrieve. retrieves variable.
892* createLinkedScope. Creates a link to a scope and notifies all.
893* indent. This is the default indenting function for subbing in multi-line
894 blocks. The default idea is to indent up to the indent of the line that
895 contains the block sub; further existing indentation in sublines is
896 respected on top of that.
897* getIndent. Figuring out the indent
898* substituteParsing
899* regexs. Some regular expressions that are used in the parsing of the code
900 blocks.
901* backslash. The backslash function applied to command arguments.
902* whitespaceEscape. Handlingwhitespace escaping in conjunction with
903 backslash. Putting the whitespace back.
904* store. stores a variable.
905
906#### Reporting
907
908A key feature of any programming environment is debugging. It is my hope that
909this version has some better debugging information. The key to this is the
910reporting function of what is waiting around.
911
912The way it works is that when an event of the form `waiting for:type:...` is
913emitted with data `[evt, reportname, ...]` then reporters gets a key of the
914event string wthout the `waiting for:`, and when the `evt` is emitted, it is
915removed.
916
917If it is still waiting around when all is done, then it gets reported. The
918reportname is used to look up which reporter is used. Then that reporter takes
919in the remaining arguments and produces a string that will be part of the
920final report that gets printed out.
921
922Some of the waiting is not done by the emitting, but rather by presence in
923.when and .onces.
924
925
926## LICENSE
927
928[MIT-LICENSE](https://github.com/jostylr/literate-programming-lib/blob/master/LICENSE-MIT)