UNPKG

1.39 kBJavaScriptView Raw
1var cardinal = require('cardinal')
2 , rewrite = require('./rewrite')
3 , config = require('../config/current')
4 , utl = require('./utl');
5
6/**
7 * Tries to grab a complete JavaScript snippet from the history.
8 *
9 * @name completeAppend
10 * @function
11 * @param history {Array[{String}]} last entered lines in reverse order (i.e., last entered line is at index 0)
12 * @return {Object} the smallest portion of the history that was parsable or just the last line if none was found as { raw, highlighted }
13 */
14module.exports = function completeAppend(history) {
15 var highlighted
16 , code = ''
17 , rewritten
18 , l = history.length
19 , start = 0
20 , format = utl.shallowClone(config.feed.format);
21
22 if (l === 0) return null;
23
24 // skip commands, i.e. '.append'
25 while (/^[ ]*\.\w+[ ]*$/.test(history[start])) {
26 start++;
27 if (start == l) return null;
28 }
29
30 format.compact = false;
31 for (var i = start; i < l; i++) {
32 try {
33 code = '\n' + history[i] + code;
34
35 rewritten = '\n' + rewrite(code, format);
36 highlighted = cardinal.highlight(rewritten);
37 // no blow up means code was parsable, so we are done
38 return { raw: rewritten, highlighted: highlighted };
39 } catch (e) {/* keep trying */ }
40 }
41
42 code = '\n' + history[start] + '\n';
43 // we got here because no parsable portion was found
44 return { raw: code, highlighted: code };
45};