aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/boxes/boxes.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/boxes/boxes.c')
-rw-r--r--src/boxes/boxes.c2506
1 files changed, 2506 insertions, 0 deletions
diff --git a/src/boxes/boxes.c b/src/boxes/boxes.c
new file mode 100644
index 0000000..fb5367a
--- /dev/null
+++ b/src/boxes/boxes.c
@@ -0,0 +1,2506 @@
1/* boxes.c - Generic editor development sandbox.
2 *
3 * Copyright 2012 David Seikel <won_fang@yahoo.com.au>
4 *
5 * Not in SUSv4. An entirely new invention, thus no web site either.
6 * See -
7 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html
8 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/more.html
9 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html
10 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/vi.html
11 * http://linux.die.net/man/1/less
12
13USE_BOXES(NEWTOY(boxes, "w#h#m(mode):a(stickchars)1", TOYFLAG_USR|TOYFLAG_BIN))
14
15config BOXES
16 bool "boxes"
17 default n
18 help
19 usage: boxes [-m|--mode mode] [-a|--stickchars] [-w width] [-h height]
20
21 Generic text editor and pager.
22
23 Mode selects which editor or text viewr it emulates, the choices are -
24 emacs is a microemacs type editor.
25 joe is a joe / wordstar type editor.
26 less is a less type pager.
27 mcedit (the default) is cooledit / mcedit type editor.
28 more is a more type pager.
29 nano is a nano / pico type editor.
30 vi is a vi type editor.
31
32 Stick chars means to use ASCII for the boxes instead of "graphics" characters.
33*/
34
35#include "toys.h"
36#include "lib/handlekeys.h"
37
38GLOBALS(
39 char *mode;
40 long h, w;
41)
42
43#define TT this.boxes
44
45#define FLAG_a 2
46#define FLAG_m 4
47#define FLAG_h 8
48#define FLAG_w 16
49
50
51/* This is trying to be a generic text editing, text viewing, and terminal
52 * handling system. The current code is a work in progress, and the design
53 * may change. Certainly at this moment it's only partly written. It is
54 * "usable" though, for a very small value of "usable". In the following
55 * I'll use "editors" to refer to the toys using this, though not all will
56 * be editors.
57 *
58 * The things it is targeting are - vi and more (part of the standards, so
59 * part of the toybox TODO), less (also on the toybox TODO), joe and
60 * wordstar (coz Rob said they would be good to include), nano (again Rob
61 * thinks it would be good and I agree), microemacs (to avoid religous
62 * wars), and mcedit (coz that's what I actually use). The ex editor comes
63 * along for the ride coz vi is basically a screen editor wrapper around
64 * the ex line editor. Sed might be supported coz I'll need to do basic
65 * editing functions that are common to the editors, and sed needs the same
66 * editing functions.
67 *
68 * I will also use this for a midnight commander clone as discussed on the
69 * mailing list. This would have things in common with emacs dired, so we
70 * might get that as well. Parts of this code could also be used for a
71 * file chooser, as used by some of the editors we are targeting. Finally,
72 * the terminal handling stuff might be useful for other toys, so should be
73 * generic in it's own right. Oh, screen is listed in the toybox TODO as
74 * "maybe", so I'll poke at that to.
75 *
76 * The basic building blocks are box, content, context, edit line, and
77 * view. A box is an on screen rectanglur area. Content is a file, and
78 * the text that is in that file. A context represents a particular editor
79 * type, it has key mappings and other similar stuff. The edit line is a
80 * single line where editing happens, it's similar to readline. A view is
81 * a view into a content, there can be many, it represents that portion of
82 * the content that is on screen right now.
83 *
84 * I plan on splitting these things up a bit so they can be used
85 * separately. Then I can make actually toybox libraries out of them. For
86 * now it's all one big file for ease of development.
87 *
88 * The screen is split into boxes, by default there are only two, the main
89 * text area and the command line at the bottom. Each box contains a view,
90 * and each view points to a content (file) for it's text. A content can
91 * have many views. Each content has a context (editor). There is only
92 * ever one edit line, it's the line that is being edited at the moment.
93 * The edit line moves within and between boxes (including the command
94 * line) as needed.
95 *
96 * The justification for boxes is that most of the editors we are trying to
97 * emulate include some splitting up of the screen area for various
98 * reasons, and some of them include a split window system as well. So
99 * this boxes concept covers command line, main editing area, split windows,
100 * menus, on screen display of command keys, file selection, and anything
101 * else that might be needed.
102 *
103 * To keep things simple boxes are organised as a binary tree of boxes.
104 * There is a root box, it's a global. Each box can have two sub boxes.
105 * Only the leaf nodes of the box tree are visible on the screen. Each box
106 * with sub boxes is split either horizontally or vertically. Navigating
107 * through the boxes goes depth first.
108 *
109 * A content keeps track of a file and it's text. Each content also has a
110 * context, which is a collection of the things that define a particular
111 * editor. (I might move the context pointer from content to view, makes
112 * more sense I think.)
113 *
114 * A context is the heart of the generic part of the system. Any given
115 * toybox command that uses this system would basically define a context
116 * and pass that to the rest of the system. See the end of this file for a
117 * few examples. A context holds a list of command to C function mappings,
118 * key to command mappings, and a list of modes.
119 *
120 * Most of the editors targetted include a command line where the user
121 * types in editor commands, and each of those editors has different
122 * commands. They would mostly use the same editing C functions though, or
123 * short wrappers around them. The vi context at the end of this file is a
124 * good example, it has a bunch of short C wrappers around some editing
125 * functions, or uses standard C editing functions directly. So a context
126 * has an editor command to C function mapping.
127 *
128 * The editors respond to keystrokes, and those keystrokes invoke editor
129 * commands, often in a modal way. So there are keystroke to editor
130 * command mappings. To cater for editing modes, each context has a list
131 * of modes, and each mode can have key to command mappings, as well as
132 * menu to command mappings, and a list of displayed key/command pairs.
133 * Menu and key/command pair display is not written yet. Most editors have
134 * a system for remapping key to command mappings, that's not supported
135 * yet. Emacs has a heirarchy of key to command mappings, that's not
136 * supported yet. Some twiddling of the current design would be needed for
137 * those.
138 *
139 * The key mappings used can be multiple keystrokes in a sequence, the
140 * system caters for that. Some can be multi byte like function keys, and
141 * even different strings of bytes depending on the terminal type. To
142 * simplify this, there is a table that maps various terminals ideas of
143 * special keys to key names, and the mapping of keys to commands uses
144 * those key names.
145 *
146 * A view represents the on screen visible portion of a content within a
147 * box. To cater for split window style editors, a content can have many
148 * views. It deals with keeping track of what's shown on screen, mapping
149 * the on screen representation of the text to the stored text during input
150 * and output. Each box holds one view.
151 *
152 * The edit line is basically a movable readline. There are editing C
153 * functions for moving it up and down lines within a view, and for
154 * shifting the edit line to some other box. So an editor would map the
155 * cursor keys for "up a line" and "down a line" to these C functions for
156 * example. Actual readline style functionality is just the bottom command
157 * box being a single line view, with the history file loaded into it's
158 * content, and the Enter key mapped to the editor contexts "do this
159 * command" function. Using most of the system with not much special casing.
160 *
161 *
162 * I assume that there wont be a terribly large number of boxes.
163 * Things like minimum box sizes, current maximum screen sizes, and the fact
164 * that they all have to be on the screen mean that this assumption should
165 * be safe. It's likely that most of the time there will be only a few at
166 * most. The point is there is a built in limit, there's only so many non
167 * overlapping boxes with textual contents that you can squeeze onto one
168 * terminal screen at once.
169 *
170 * I assume that there will only be one command line, no matter how many boxes,
171 * and that the command line is for the current box.
172 *
173 * I use a wide screen monitor and small font.
174 * My usual terminal is 104 x 380 characters.
175 * There will be people with bigger monitors and smaller fonts.
176 * So use sixteen bits for storing screen positions and the like.
177 * Eight bits wont cut it.
178 *
179 *
180 * These are the escape sequences we send -
181 * \x1B[m reset attributes and colours
182 * \x1B[1m turn on bold
183 * \x1B[%d;%dH move cursor
184 * Plus some experimentation with turning on mouse reporting that's not
185 * currently used.
186 *
187 *
188 * TODO - disentangle boxes from views.
189 *
190 * TODO - should split this up into editing, UI, and boxes parts,
191 * so the developer can leave out bits they are not using.
192 *
193 * TODO - Show status line instead of command line when it's not being edited.
194 *
195 * TODO - should review it all for UTF8 readiness. Think I can pull that off
196 * by keeping everything on the output side as "screen position", and using
197 * the formatter to sort out the input to output mapping.
198 *
199 * TODO - see if there are any simple shortcuts to avoid recalculating
200 * everything all the time. And to avoid screen redraws.
201 */
202
203/* Robs "It's too big" lament.
204
205> So when you give me code, assume I'm dumber than you. Because in this
206> context, I am. I need bite sized pieces, each of which I can
207> understand in its entirety before moving on to the next.
208
209As I mentioned in my last email to the Aboriginal linux list, I wrote
210the large blob so I could see how the ideas all work to do the generic
211editor stuff and other things. It kinda needs to be that big to do
212anything that is actually useful. So, onto musings about cutting it up
213into bite sized bits...
214
215You mentioned on the Aboriginal Linux list that you wanted a
216"readline", and you listed some features. My reply was that you had
217basically listed the features of my "basic editor". The main
218difference between "readline" and a full screen editor, is that the
219editor is fullscreen, while the "readline" is one line. They both have
220to deal with a list of lines, going up and down through those lines,
221editing the contents of those lines, one line at a time. For persistent
222line history, they both have to save and load those lines to a file.
223Other than that "readline" adds other behaviour, like moving the
224current line to the end when you hit return and presenting that line to
225the caller (here's the command). So just making "readline" wont cut
226out much of the code. In fact, my "readline" is really just a thin
227wrapper around the rest of the code.
228
229Starting from the other end of the size spectrum, I guess "find out
230terminal size" is a small enough bite sized chunk. To actually do
231anything useful with that you would probably start to write stuff I've
232already written though. Would be better off just using the stuff I've
233already written. On the other hand, maybe that would be useful for
234"ls" listings and the like, then we can start with just that bit?
235
236I guess the smallest useful command I have in my huge blob of code
237would be "more". I could even cut it down more. Show a page of text,
238show the next page of text when you hit the space bar, quit when you
239hit "q". Even then, I would estimate it would only cut out a third of
240the code.
241
242On the other hand, there's a bunch of crap in that blob that is for
243future plans, and is not doing anything now.
244
245In the end though, breaking it up into suitable bite sized bits might
246be almost as hard as writing it in the first place. I'll see what I
247can do, when I find some time. I did want to break it up into three
248bits anyway, and there's a TODO to untangle a couple of bits that are
249currently too tightly coupled.
250
251*/
252
253/* Robs contradiction
254
255On Thu, 27 Dec 2012 06:06:53 -0600 Rob Landley <rob@landley.net> wrote:
256
257> On 12/27/2012 12:56:07 AM, David Seikel wrote:
258> > On Thu, 27 Dec 2012 00:37:46 -0600 Rob Landley <rob@landley.net>
259> > wrote:
260> > > Since ls isn't doiing any of that, probing would just be awkward
261> > > so toysh should set COLUMNS to a sane value. The problem is,
262> > > we're not using toysh yet because it's still just a stub...
263> >
264> > I got some or all of that terminal sizing stuff in my editor thingy
265> > already if I remember correctly. I remember you wanted me to cut it
266> > down into tiny bits to start with, so you don't have to digest the
267> > huge lump I sent.
268>
269> Basically what I'd like is a self-contained line reader. More or less
270> a getline variant that can handle cursoring left and right to insert
271> stuff, handle backspace past a wordwrap (which on unix requires
272> knowing the screen width and your current cursor position), and one
273> that lets up/down escape sequences be hooked for less/more screen
274> scrolling, vi line movement, shell command history, and so on.
275
276Which is most of an editor already, so how to break it up into bite
277sized morsels?
278
279> There's sort of three levels here, the first is "parse raw input,
280> assembling escape sequences into cursor-left and similar as
281> necessary". (That's the one I had to redo in busybox vi because they
282> didn't do it right.)
283>
284> The second is "edit a line of text, handling cursoring _within_ the
285> line". That's the better/interactive getline().
286>
287> The third is handling escapes from that line triggering behavior in
288> the larger command (cursor up and cursor down do different things in
289> less, in vi, and in shell command history).
290>
291> The fiddly bit is that terminal_size() sort of has to integrate with
292> all of these. Possibly I need to have width and height be members of
293> struct toy_context. Or have the better_getline() take a pointer to a
294> state structure it can update, containing that info...
295
296*/
297
298
299static char *borderChars[][6] =
300{
301 {"-", "|", "+", "+", "+", "+"}, // "stick" characters.
302 {"\xE2\x94\x80", "\xE2\x94\x82", "\xE2\x94\x8C", "\xE2\x94\x90", "\xE2\x94\x94", "\xE2\x94\x98"}, // UTF-8
303 {"\x71", "\x78", "\x6C", "\x6B", "\x6D", "\x6A"}, // VT100 alternate character set.
304 {"\xC4", "\xB3", "\xDA", "\xBF", "\xC0", "\xD9"} // DOS
305};
306
307static char *borderCharsCurrent[][6] =
308{
309 {"=", "#", "+", "+", "+", "+"}, // "stick" characters.
310 {"\xE2\x95\x90", "\xE2\x95\x91", "\xE2\x95\x94", "\xE2\x95\x97", "\xE2\x95\x9A", "\xE2\x95\x9D"}, // UTF-8
311 {"\x71", "\x78", "\x6C", "\x6B", "\x6D", "\x6A"}, // VT100 alternate character set has none of these. B-(
312 {"\xCD", "\xBA", "\xC9", "\xBB", "\xC8", "\xBC"} // DOS
313};
314
315
316typedef struct _box box;
317typedef struct _view view;
318
319typedef void (*boxFunction) (box *box);
320typedef void (*eventHandler) (view *view);
321
322struct function
323{
324 char *name; // Name for script purposes.
325 char *description; // Human name for the menus.
326 char type;
327 union
328 {
329 eventHandler handler;
330 char *scriptCallback;
331 };
332};
333
334struct keyCommand
335{
336 char *key, *command;
337};
338
339struct item
340{
341 char *text; // What's shown to humans.
342 struct key *key; // Shortcut key while the menu is displayed.
343 // If there happens to be a key bound to the same command, the menu system should find that and show it to.
344 char type;
345 union
346 {
347 char *command;
348 struct item *items; // An array of next level menu items.
349 };
350};
351
352struct borderWidget
353{
354 char *text, *command;
355};
356
357// TODO - a generic "part of text", and what is used to define them.
358// For instance - word, line, paragraph, section.
359// Each context can have a collection of these.
360
361struct mode
362{
363 struct keyCommand *keys; // An array of key to command mappings.
364 struct item *items; // An array of top level menu items.
365 struct item *functionKeys; // An array of single level "menus". Used to show key commands.
366 uint8_t flags; // commandMode.
367};
368
369/*
370Have a common menu up the top.
371 MC has a menu that changes per mode.
372 Nano has no menu.
373Have a common display of certain keys down the bottom.
374 MC is one row of F1 to F10, but changes for edit / view / file browse. But those are contexts here.
375 Nano is 12 random Ctrl keys, possibly in two lines, that changes depending on the editor mode, like editing the prompt line for various reasons, help.
376*/
377struct context // Defines a context for content. Text viewer, editor, file browser for instance.
378{
379 struct function *commands; // The master list, the ones pointed to by the menus etc should be in this list.
380 struct mode *modes; // A possible empty array of modes, indexed by the view.
381 // OR might be better to have these as a linked list, so that things like Emacs can have it's mode keymap hierarcy.
382 eventHandler handler; // TODO - Might be better to put this in the modes. I think vi will need that.
383 // Should set the damage list if it needs a redraw, and flags if border or status line needs updating.
384 // Keyboard / mouse events if the box did not handle them itself.
385 // DrawAll event for when drawing the box for the first time, on reveals for coming out of full screen, or user hit the redraw key.
386 // Scroll event if the content wants to handle that itself.
387 // Timer event for things like top that might want to have this called regularly.
388 boxFunction doneRedraw; // The box is done with it's redraw, so we can free the damage list or whatever now.
389 boxFunction delete;
390 // This can be used as the sub struct for various context types. Like viewer, editor, file browser, top, etc.
391 // Could even be an object hierarchy, like generic editor, which Basic vi inherits from.
392 // Or not, since the commands might be different / more of them.
393};
394
395// TODO - might be better off just having a general purpose "widget" which includes details of where it gets attached.
396// Status lines can have them to.
397struct border
398{
399 struct borderWidget *topLeft, *topMiddle, *topRight;
400 struct borderWidget *bottomLeft, *bottomMiddle, *bottomRight;
401 struct borderWidget *left, *right;
402};
403
404struct line
405{
406 struct line *next, *prev;
407 uint32_t length; // Careful, this is the length of the allocated memory for real lines, but the number of lines in the header node.
408 char *line; // Should be blank for the header.
409};
410
411struct damage
412{
413 struct damage *next; // A list for faster draws?
414 uint16_t X, Y, W, H; // The rectangle to be redrawn.
415 uint16_t offset; // Offest from the left for showing lines.
416 struct line *lines; // Pointer to a list of text lines, or NULL.
417 // Note - likely a pointer into the middle of the line list in a content.
418};
419
420struct content // For various instances of context types.
421 // Editor / text viewer might have several files open, so one of these per file.
422 // MC might have several directories open, one of these per directory. No idea why you might want to do this. lol
423{
424 struct context *context;
425 char *name, *file, *path;
426 struct line lines;
427// file type
428// double linked list of bookmarks, pointer to line, character position, length (or ending position?), type, blob for types to keep context.
429 uint16_t minW, minH, maxW, maxH;
430 uint8_t flags; // readOnly, modified.
431 // This can be used as the sub struct for various content types.
432};
433
434struct _view
435{
436 struct content *content;
437 box *box;
438 struct border *border; // Can be NULL.
439 char *statusLine; // Text of the status line, or NULL if none.
440 int mode; // For those contexts that can be modal. Normally used to index the keys, menus, and key displays.
441 struct damage *damage; // Can be NULL. If not NULL after context->doneRedraw(), box will free it and it's children.
442 // TODO - Gotta be careful of overlapping views.
443 void *data; // The context controls this blob, it's specific to each box.
444 uint32_t offsetX, offsetY; // Offset within the content, coz box handles scrolling, usually.
445 uint16_t X, Y, W, H; // Position and size of the content area within the box. Calculated, but cached coz that might be needed for speed.
446 uint16_t cX, cY; // Cursor position within the content.
447 uint16_t iX, oW; // Cursor position inside the lines input text, in case the formatter makes it different, and output length.
448 char *output; // The current line formatted for output.
449 uint8_t flags; // redrawStatus, redrawBorder;
450
451 // Assumption is that each box has it's own editLine (likely the line being edited), or that there's a box that is just the editLine (emacs minibuffer, and command lines for other proggies).
452 struct line *line; // Pointer to the current line, might be the only line.
453 char *prompt; // Optional prompt for the editLine.
454
455// Display mode / format hook.
456// view specific bookmarks, including highlighted block and it's type.
457// Linked list of selected lines for a filtered view, or processing only those lines.
458// Linked list of pointers to struct keyCommand, for emacs keymaps hierarchy, and anything similar in other editors. Plus some way of dealing with emacs minor mode keymaps.
459};
460
461struct _box
462{
463 box *sub1, *sub2, *parent;
464 view *view; // This boxes view into it's content. For sharing contents, like a split pane editor for instance, there might be more than one box with this content, but a different view.
465 // If it's just a parent box, it wont have this, so just make it a damn pointer, that's the simplest thing. lol
466 // TODO - Are parent boxes getting a view anyway?
467 uint16_t X, Y, W, H; // Position and size of the box itself, not the content. Calculated, but cached coz that might be needed for speed.
468 float split; // Ratio of sub1's part of the split, the sub2 box gets the rest.
469 uint8_t flags; // Various flags.
470};
471
472
473// Sometimes you just can't avoid circular definitions.
474void drawBox(box *box);
475
476
477#define BOX_HSPLIT 1 // Marks if it's a horizontally or vertically split.
478#define BOX_BORDER 2 // Mark if it has a border, often full screen boxes wont.
479
480static int overWriteMode;
481static box *rootBox; // Parent of the rest of the boxes, or the only box. Always a full screen.
482static box *currentBox;
483static view *commandLine;
484static int commandMode;
485
486#define MEM_SIZE 128 // Chunk size for line memory allocation.
487
488// Inserts the line after the given line, or at the end of content if no line.
489struct line *addLine(struct content *content, struct line *line, char *text, uint32_t length)
490{
491 struct line *result = NULL;
492 uint32_t len;
493
494 if (!length)
495 length = strlen(text);
496 // Round length up.
497 len = (((length + 1) / MEM_SIZE) + 1) * MEM_SIZE;
498 result = xzalloc(sizeof(struct line));
499 result->line = xzalloc(len);
500 result->length = len;
501 strncpy(result->line, text, length);
502
503 if (content)
504 {
505 if (!line)
506 line = content->lines.prev;
507
508 result->next = line->next;
509 result->prev = line;
510
511 line->next->prev = result;
512 line->next = result;
513
514 content->lines.length++;
515 }
516 else
517 {
518 result->next = result;
519 result->prev = result;
520 }
521
522 return result;
523}
524
525void freeLine(struct content *content, struct line *line)
526{
527 line->next->prev = line->prev;
528 line->prev->next = line->next;
529 if (content)
530 content->lines.length--;
531 free(line->line);
532 free(line);
533}
534
535void loadFile(struct content *content)
536{
537 int fd = open(content->path, O_RDONLY);
538
539 if (-1 != fd)
540 {
541 char *temp = NULL;
542 long len;
543
544 do
545 {
546 // TODO - get_rawline() is slow, and wont help much with DOS and Mac line endings.
547 temp = get_rawline(fd, &len, '\n');
548 if (temp)
549 {
550 if (temp[len - 1] == '\n')
551 temp[--len] = '\0';
552 addLine(content, NULL, temp, len);
553 }
554 } while (temp);
555 close(fd);
556 }
557}
558
559// TODO - load and save should be able to deal with pipes, and with loading only parts of files, to load more parts later.
560
561void saveFile(struct content *content)
562{
563// TODO - Should do "Save as" as well. Which is just a matter of changing content->path before calling this.
564 int fd;
565
566 fd = open(content->path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
567
568 if (-1 != fd)
569 {
570 struct line *line = content->lines.next;
571
572 while (&(content->lines) != line) // We are at the end if we have wrapped to the beginning.
573 {
574 write(fd, line->line, strlen(line->line));
575 write(fd, "\n", 1);
576 line = line->next;
577 }
578 close(fd);
579 }
580 else
581 {
582 fprintf(stderr, "Can't open file %s\n", content->path);
583 exit(1);
584 }
585}
586
587struct content *addContent(char *name, struct context *context, char *filePath)
588{
589 struct content *result = xzalloc(sizeof(struct content));
590
591 result->lines.next = &(result->lines);
592 result->lines.prev = &(result->lines);
593 result->name = strdup(name);
594 result->context = context;
595
596 if (filePath)
597 {
598 result->path = strdup(filePath);
599 loadFile(result);
600 }
601
602 return result;
603}
604
605// General purpose line moosher. Used for appends, inserts, overwrites, and deletes.
606// TODO - should have the same semantics as mooshStrings, only it deals with whole lines in double linked lists.
607// We need content so we can adjust it's number of lines if needed.
608void mooshLines(struct content *content, struct line *result, struct line *moosh, uint16_t index, uint16_t length, int insert)
609{
610}
611
612// General purpose string moosher. Used for appends, inserts, overwrites, and deletes.
613void mooshStrings(struct line *result, char *moosh, uint16_t index, uint16_t length, int insert)
614{
615 char *c, *pos;
616 int limit = strlen(result->line);
617 int mooshLen = 0, resultLen;
618
619 if (moosh)
620 mooshLen = strlen(moosh);
621
622 /*
623 * moosh == NULL a deletion
624 * length == 0 simple insertion
625 * length < mooshlen delete some, insert moosh
626 * length == mooshlen exact overwrite.
627 * length > mooshlen delete a lot, insert moosh
628 */
629
630 mooshLen -= length;
631 resultLen = limit + mooshLen;
632
633 // If we need more space, allocate more.
634 if (resultLen > result->length)
635 {
636 result->length = resultLen + MEM_SIZE;
637 result->line = xrealloc(result->line, result->length);
638 }
639
640 if (limit <= index) // At end, just add to end.
641 {
642 // TODO - Possibly add spaces to pad out to where index is?
643 // Would be needed for "go beyond end of line" and "column blocks".
644 // Both of those are advanced editing.
645 index = limit;
646 insert = 1;
647 }
648
649 pos = &(result->line[index]);
650
651 if (insert) // Insert / delete before current character, so move it and the rest up / down mooshLen bytes.
652 {
653 if (0 < mooshLen) // Gotta move things up.
654 {
655 c = &(result->line[limit]);
656 while (c >= pos)
657 {
658 *(c + mooshLen) = *c;
659 c--;
660 }
661 }
662 else if (0 > mooshLen) // Gotta move things down.
663 {
664 c = pos;
665 while (*c)
666 {
667 *c = *(c - mooshLen); // A double negative.
668 c++;
669 }
670 }
671 }
672
673 if (moosh)
674 {
675 c = moosh;
676 do
677 {
678 *pos++ = *c++;
679 }
680 while (*c);
681 }
682}
683
684// TODO - Should draw the current border in green, the text as default (or highlight / bright).
685// Then allow one other box to be red bordered (MC / dired destination box).
686// All other boxes with dark gray border, and dim text.
687void drawLine(int y, int start, int end, char *left, char *internal, char *contents, char *right, int current)
688{
689 int size = strlen(internal);
690 int len = (end - start) * size, x = 0;
691 char line[len + 1];
692
693 if ('\0' != left[0]) // Assumes that if one side has a border, then so does the other.
694 len -= 2 * size;
695
696 if (contents)
697 {
698 // strncpy wont add a null at the end if the source is longer, but will pad with nulls if source is shorter.
699 // So it's best to put a safety null in first.
700 line[len] = '\0';
701 strncpy(line, contents, len);
702 // Make sure the following while loop pads out line with the internal character.
703 x = strlen(line);
704 }
705 while (x < len)
706 {
707 strcpy(&line[x], internal);
708 x += size;
709 }
710 line[x++] = '\0';
711 if ('\0' == left[0]) // Assumes that if one side has a border, then so does the other.
712 {
713 if (current)
714 printf("\x1B[1m\x1B[%d;%dH%s\x1B[m", y + 1, start + 1, line);
715 else
716 printf("\x1B[m\x1B[%d;%dH%s", y + 1, start + 1, line);
717 }
718 else
719 {
720 if (current)
721 printf("\x1B[1m\x1B[%d;%dH%s%s%s\x1B[m", y + 1, start + 1, left, line, right);
722 else
723 printf("\x1B[m\x1B[%d;%dH%s%s%s", y + 1, start + 1, left, line, right);
724 }
725}
726
727void formatCheckCursor(view *view, long *cX, long *cY, char *input)
728{
729 int i = 0, o = 0, direction = (*cX) - view->cX;
730
731 // Adjust the cursor if needed, depending on the contents of the line, and the direction of travel.
732 while (input[i])
733 {
734 // When o is equal to the cX position, update the iX position to be where i is.
735 if ('\t' == input[i])
736 {
737 int j = 8 - (i % 8);
738
739 // Check if the cursor is in the middle of the tab.
740 if (((*cX) > o) && ((*cX) < (o + j)))
741 {
742 if (0 <= direction)
743 {
744 *cX = (o + j);
745 view->iX = i + 1;
746 }
747 else
748 {
749 *cX = o;
750 view->iX = i;
751 }
752 }
753 o += j;
754 }
755 else
756 {
757 if ((*cX) == o)
758 view->iX = i;
759 o++;
760 }
761 i++;
762 }
763 // One more check in case the cursor is at the end of the line.
764 if ((*cX) == o)
765 view->iX = i;
766}
767
768// TODO - Should convert control characters to reverse video, and deal with UTF8.
769
770/* FIXME - We get passed a NULL input, apparently when the file length is close to the screen length. -
771> On Thu, 6 Sep 2012 11:56:17 +0800 Roy Tam <roytam@gmail.com> wrote:
772>
773> > 2012/9/6 David Seikel <onefang@gmail.com>:
774> > >> Program received signal SIGSEGV, Segmentation fault.
775> > >> formatLine (view=0x8069168, input=0x0, output=0x806919c)
776> > >> at toys/other/boxes.c:843
777> > >> 843 int len = strlen(input), i = 0, o = 0;
778> > >> (gdb) bt
779> > >> #0 formatLine (view=0x8069168, input=0x0, output=0x806919c)
780> > >> at toys/other/boxes.c:843
781> > >> #1 0x0804f1dd in moveCursorAbsolute (view=0x8069168, cX=0,
782> > >> cY=10, sX=0, sY=0) at toys/other/boxes.c:951
783> > >> #2 0x0804f367 in moveCursorRelative (view=0x8069168, cX=0,
784> > >> cY=10, sX=0, sY=0) at toys/other/boxes.c:1011
785> > >> #3 0x0804f479 in upLine (view=0x8069168, event=0x0) at
786> > >> toys/other/boxes.c:1442 #4 0x0804fb63 in handleKey
787> > >> (view=0x8069168, i=2, keyName=<optimized out>, buffer=0xbffffad8
788> > >> "\033[A") at toys/other/boxes.c:1593 #5 0x0805008d in editLine
789> > >> (view=0x8069168, X=-1, Y=-1, W=-1, H=-1) at
790> > >> toys/other/boxes.c:1785 #6 0x08050288 in boxes_main () at
791> > >> toys/other/boxes.c:2482 #7 0x0804b262 in toy_exec
792> > >> (argv=0xbffffd58) at main.c:104 #8 0x0804b29d in toybox_main ()
793> > >> at main.c:118 #9 0x0804b262 in toy_exec (argv=0xbffffd54) at
794> > >> main.c:104 #10 0x0804b29d in toybox_main () at main.c:118
795> > >> #11 0x0804affa in main (argc=5, argv=0xbffffd54) at main.c:159
796> > >
797> > > No segfault here when I try that, nor with different files. As I
798> > > said, it has bugs. I have seen other cases before when NULL lines
799> > > are passed around near that code. Guess I've not got them all.
800> > > Might help to mention what terminal proggy you are using, it's
801> > > size in characters, toybox version, OS, etc. Something is
802> > > different between you and me.
803> >
804> > Terminal Program: PuTTY
805> > Windows size: 80 * 25 chars
806> > Toybox version: hg head
807> > OS: Linux 3.2 (Debian wheezy)
808> > File: Toybox LICENSE file
809>
810> I'll install PuTTY, try toybox hg head, and play with them later, see
811> if I can reproduce that segfault. I use the last released tarball of
812> toybox, an old Ubuntu, and a bunch of other terminal proggies. I did
813> not know that PuTTY had been ported to Unix.
814>
815> But as I mentioned, not interested in a bug hunt right now. That will
816> be more appropriate when it's less of a "sandbox for testing the
817> ideas" and more of a "good enough to bother using". Always good to
818> have other terminals for testing though.
819
820Seems to be sensitive to the number of lines. On my usual huge
821roxterm, using either toybox 0.4 or hg head, doing this -
822
823./toybox boxes -m less LICENSE -h 25
824
825and just hitting down arrow until you get to the bottom of the page
826segfaults as well. -h means "pretend the terminal is that many lines
827high", there's a similar -w as well. 80x25 in any other terminal did
828the same. For that particular file (17 lines long), any value of -h
829between 19 and 34 will segfault after some moving around. -h 35 makes
830it segfault straight away. Less than 19 or over 35 is fine. Longer
831files don't have that problem, though I suspect it will happen on
832shortish files where the number of lines is about the length of the
833screen.
834
835I guess that somewhere I'm doing maths wrong and getting an out of
836bounds line number when the file length is close to the screen length.
837I'll make note of that, and fix it when I next get time to beat on
838boxes.
839
840Thanks for reporting it Roy.
841*/
842
843int formatLine(view *view, char *input, char **output)
844{
845 int len = strlen(input), i = 0, o = 0;
846
847 *output = xrealloc(*output, len + 1);
848
849 while (input[i])
850 {
851 if ('\t' == input[i])
852 {
853 int j = 8 - (i % 8);
854
855 *output = xrealloc(*output, len + j + 1);
856 for (; j; j--)
857 {
858 (*output)[o++] = ' ';
859 len++;
860 }
861 len--; // Not counting the actual tab character itself.
862 }
863 else
864 (*output)[o++] = input[i];
865 i++;
866 }
867 (*output)[o++] = '\0';
868
869 return len;
870}
871
872void drawContentLine(view *view, int y, int start, int end, char *left, char *internal, char *contents, char *right, int current)
873{
874 char *temp = NULL;
875 int offset = view->offsetX, len;
876
877 if (contents == view->line->line)
878 {
879 view->oW = formatLine(view, contents, &(view->output));
880 temp = view->output;
881 len = view->oW;
882 }
883 else // Only time we are not drawing the current line, and only used for drawing the entire page.
884 len = formatLine(NULL, contents, &(temp));
885
886 if (offset > len)
887 offset = len;
888 drawLine(y, start, end, left, internal, &(temp[offset]), right, current);
889}
890
891void updateLine(view *view)
892{
893 int y, len;
894
895 // Coz things might change out from under us, find the current view. Again.
896 if (commandMode) view = commandLine;
897 else view = currentBox->view;
898
899 // TODO - When doing scripts and such, might want to turn off the line update until finished.
900 // Draw the prompt and the current line.
901 y = view->Y + (view->cY - view->offsetY);
902 len = strlen(view->prompt);
903 drawLine(y, view->X, view->X + view->W, "", " ", view->prompt, "", 0);
904 drawContentLine(view, y, view->X + len, view->X + view->W, "", " ", view->line->line, "", 1);
905 // Move the cursor.
906 printf("\x1B[%d;%dH", y + 1, view->X + len + (view->cX - view->offsetX) + 1);
907 fflush(stdout);
908}
909
910void doCommand(view *view, char *command)
911{
912 if (command)
913 {
914 struct function *functions = view->content->context->commands;
915 int i;
916
917// TODO - Some editors have a shortcut command concept. The smallest unique first part of each command will match, as well as anything longer.
918// A further complication is if we are not implementing some commands that might change what is "shortest unique prefix".
919
920 for (i = 0; functions[i].name; i++)
921 {
922 if (strcmp(functions[i].name, command) == 0)
923 {
924 if (functions[i].handler)
925 {
926 functions[i].handler(view);
927 updateLine(view);
928 }
929 break;
930 }
931 }
932 }
933}
934
935int moveCursorAbsolute(view *view, long cX, long cY, long sX, long sY)
936{
937 struct line *newLine = view->line;
938 long oX = view->offsetX, oY = view->offsetY;
939 long lX = view->oW, lY = view->content->lines.length - 1;
940 long nY = view->cY;
941 uint16_t w = view->W - 1, h = view->H - 1;
942 int moved = 0, updatedY = 0, endOfLine = 0;
943
944 // Check if it's still within the contents.
945 if (0 > cY) // Trying to move before the beginning of the content.
946 cY = 0;
947 else if (lY < cY) // Trying to move beyond end of the content.
948 cY = lY;
949 if (0 > cX) // Trying to move before the beginning of the line.
950 {
951 // See if we can move to the end of the previous line.
952 if (view->line->prev != &(view->content->lines))
953 {
954 cY--;
955 endOfLine = 1;
956 }
957 else
958 cX = 0;
959 }
960 else if (lX < cX) // Trying to move beyond end of line.
961 {
962 // See if we can move to the begining of the next line.
963 if (view->line->next != &(view->content->lines))
964 {
965 cY++;
966 cX = 0;
967 }
968 else
969 cX = lX;
970 }
971
972 // Find the new line.
973 while (nY != cY)
974 {
975 updatedY = 1;
976 if (nY < cY)
977 {
978 newLine = newLine->next;
979 nY++;
980 if (view->content->lines.prev == newLine) // We are at the end if we have wrapped to the beginning.
981 break;
982 }
983 else
984 {
985 newLine = newLine->prev;
986 nY--;
987 if (view->content->lines.next == newLine) // We are at the end if we have wrapped to the beginning.
988 break;
989 }
990 }
991 cY = nY;
992
993 // Check if we have moved past the end of the new line.
994 if (updatedY)
995 {
996 // Format it.
997 view->oW = formatLine(view, newLine->line, &(view->output));
998 if (view->oW < cX)
999 endOfLine = 1;
1000 if (endOfLine)
1001 cX = view->oW;
1002 }
1003
1004 // Let the formatter decide if it wants to adjust things.
1005 // It's up to the formatter to deal with things if it changes cY.
1006 // On the other hand, changing cX is it's job.
1007 formatCheckCursor(view, &cX, &cY, newLine->line);
1008
1009 // Check the scrolling.
1010 lY -= view->H - 1;
1011 oX += sX;
1012 oY += sY;
1013
1014 if (oY > cY) // Trying to move above the box.
1015 oY += cY - oY;
1016 else if ((oY + h) < cY) // Trying to move below the box
1017 oY += cY - (oY + h);
1018 if (oX > cX) // Trying to move to the left of the box.
1019 oX += cX - oX;
1020 else if ((oX + w) <= cX) // Trying to move to the right of the box.
1021 oX += cX - (oX + w);
1022
1023 if (oY < 0)
1024 oY = 0;
1025 if (oY >= lY)
1026 oY = lY;
1027 if (oX < 0)
1028 oX = 0;
1029 // TODO - Should limit oX to less than the longest line, minus box width.
1030 // Gonna be a pain figuring out what the longest line is.
1031 // On the other hand, don't think that will be an actual issue unless "move past end of line" is enabled, and that's an advanced editor thing.
1032 // Though still might want to do that for the longest line on the new page to be.
1033
1034 if ((view->cX != cX) || (view->cY != cY))
1035 moved = 1;
1036
1037 // Actually update stuff, though some have been done already.
1038 view->cX = cX;
1039 view->cY = cY;
1040 view->line = newLine;
1041
1042 // Handle scrolling.
1043 if ((view->offsetX != oX) || (view->offsetY != oY))
1044 {
1045 view->offsetX = oX;
1046 view->offsetY = oY;
1047
1048 if (view->box)
1049 drawBox(view->box);
1050 }
1051
1052 return moved;
1053}
1054
1055int moveCursorRelative(view *view, long cX, long cY, long sX, long sY)
1056{
1057 return moveCursorAbsolute(view, view->cX + cX, view->cY + cY, sX, sY);
1058}
1059
1060void sizeViewToBox(box *box, int X, int Y, int W, int H)
1061{
1062 uint16_t one = 1, two = 2;
1063
1064 if (!(box->flags & BOX_BORDER))
1065 {
1066 one = 0;
1067 two = 0;
1068 }
1069 box->view->X = X;
1070 box->view->Y = Y;
1071 box->view->W = W;
1072 box->view->H = H;
1073 if (0 > X) box->view->X = box->X + one;
1074 if (0 > Y) box->view->Y = box->Y + one;
1075 if (0 > W) box->view->W = box->W - two;
1076 if (0 > H) box->view->H = box->H - two;
1077}
1078
1079view *addView(char *name, struct context *context, char *filePath, uint16_t X, uint16_t Y, uint16_t W, uint16_t H)
1080{
1081 view *result = xzalloc(sizeof(struct _view));
1082
1083 result->X = X;
1084 result->Y = Y;
1085 result->W = W;
1086 result->H = H;
1087
1088 result->content = addContent(name, context, filePath);
1089 result->prompt = xzalloc(1);
1090 // If there was content, format it's first line as usual, otherwise create an empty first line.
1091 if (result->content->lines.next != &(result->content->lines))
1092 {
1093 result->line = result->content->lines.next;
1094 result->oW = formatLine(result, result->line->line, &(result->output));
1095 }
1096 else
1097 {
1098 result->line = addLine(result->content, NULL, "\0", 0);
1099 result->output = xzalloc(1);
1100 }
1101
1102 return result;
1103}
1104
1105box *addBox(char *name, struct context *context, char *filePath, uint16_t X, uint16_t Y, uint16_t W, uint16_t H)
1106{
1107 box *result = xzalloc(sizeof(struct _box));
1108
1109 result->X = X;
1110 result->Y = Y;
1111 result->W = W;
1112 result->H = H;
1113 result->view = addView(name, context, filePath, X, Y, W, H);
1114 result->view->box = result;
1115 sizeViewToBox(result, X, Y, W, H);
1116
1117 return result;
1118}
1119
1120void freeBox(box *box)
1121{
1122 if (box)
1123 {
1124 freeBox(box->sub1);
1125 freeBox(box->sub2);
1126 if (box->view)
1127 {
1128 // In theory the line should not be part of the content if there is no content, so we should free it.
1129 if (!box->view->content)
1130 freeLine(NULL, box->view->line);
1131 free(box->view->prompt);
1132 free(box->view->output);
1133 free(box->view);
1134 }
1135 free(box);
1136 }
1137}
1138
1139void drawBox(box *box)
1140{
1141 // This could be heavily optimized, but let's keep things simple for now.
1142 // Optimized for sending less characters I mean, on slow serial links for instance.
1143
1144 char **bchars = (toys.optflags & FLAG_a) ? borderChars[0] : borderChars[1];
1145 char *left = "\0", *right = "\0";
1146 struct line *lines = NULL;
1147 int y = box->Y, current = (box == currentBox);
1148 uint16_t h = box->Y + box->H;
1149
1150 if (current)
1151 bchars = (toys.optflags & FLAG_a) ? borderCharsCurrent[0] : borderCharsCurrent[1];
1152
1153 // Slow and laborious way to figure out where in the linked list of lines we start from.
1154 // Wont scale well, but is simple.
1155 if (box->view && box->view->content)
1156 {
1157 int i = box->view->offsetY;
1158
1159 lines = &(box->view->content->lines);
1160 while (i--)
1161 {
1162 lines = lines->next;
1163 if (&(box->view->content->lines) == lines) // We are at the end if we have wrapped to the beginning.
1164 break;
1165 }
1166 }
1167
1168 if (box->flags & BOX_BORDER)
1169 {
1170 h--;
1171 left = right = bchars[1];
1172 drawLine(y++, box->X, box->X + box->W, bchars[2], bchars[0], NULL, bchars[3], current);
1173 }
1174
1175 while (y < h)
1176 {
1177 char *line = "";
1178
1179 if (lines)
1180 {
1181 lines = lines->next;
1182 if (&(box->view->content->lines) == lines) // We are at the end if we have wrapped to the beginning.
1183 lines = NULL;
1184 else
1185 line = lines->line;
1186 // Figure out which line is our current line while we are here.
1187 if (box->view->Y + (box->view->cY - box->view->offsetY) == y)
1188 box->view->line = lines;
1189 }
1190 drawContentLine(box->view, y++, box->X, box->X + box->W, left, " ", line, right, current);
1191 }
1192 if (box->flags & BOX_BORDER)
1193 drawLine(y++, box->X, box->X + box->W, bchars[4], bchars[0], NULL, bchars[5], current);
1194 fflush(stdout);
1195}
1196
1197void drawBoxes(box *box)
1198{
1199 if (box->sub1) // If there's one sub box, there's always two.
1200 {
1201 drawBoxes(box->sub1);
1202 drawBoxes(box->sub2);
1203 }
1204 else
1205 drawBox(box);
1206}
1207
1208void calcBoxes(box *box)
1209{
1210 if (box->sub1) // If there's one sub box, there's always two.
1211 {
1212 box->sub1->X = box->X;
1213 box->sub1->Y = box->Y;
1214 box->sub1->W = box->W;
1215 box->sub1->H = box->H;
1216 box->sub2->X = box->X;
1217 box->sub2->Y = box->Y;
1218 box->sub2->W = box->W;
1219 box->sub2->H = box->H;
1220 if (box->flags & BOX_HSPLIT)
1221 {
1222 box->sub1->H *= box->split;
1223 box->sub2->H -= box->sub1->H;
1224 box->sub2->Y += box->sub1->H;
1225 }
1226 else
1227 {
1228 box->sub1->W *= box->split;
1229 box->sub2->W -= box->sub1->W;
1230 box->sub2->X += box->sub1->W;
1231 }
1232 sizeViewToBox(box->sub1, -1, -1, -1, -1);
1233 calcBoxes(box->sub1);
1234 sizeViewToBox(box->sub2, -1, -1, -1, -1);
1235 calcBoxes(box->sub2);
1236 }
1237 // Move the cursor to where it is, to check it's not now outside the box.
1238 moveCursorAbsolute(box->view, box->view->cX, box->view->cY, 0, 0);
1239
1240 // We could call drawBoxes() here, but this is recursive, and so is drawBoxes().
1241 // The combination might be deadly. Drawing the content of a box might be an expensive operation.
1242 // Later we might use a dirty box flag to deal with this, if it's not too much of a complication.
1243}
1244
1245void deleteBox(view *view)
1246{
1247 box *box = view->box;
1248
1249 if (box->parent)
1250 {
1251 struct _box *oldBox = box, *otherBox = box->parent->sub1;
1252
1253 if (otherBox == oldBox)
1254 otherBox = box->parent->sub2;
1255 if (currentBox->parent == box->parent)
1256 currentBox = box->parent;
1257 box = box->parent;
1258 box->X = box->sub1->X;
1259 box->Y = box->sub1->Y;
1260 if (box->flags & BOX_HSPLIT)
1261 box->H = box->sub1->H + box->sub2->H;
1262 else
1263 box->W = box->sub1->W + box->sub2->W;
1264 box->flags &= ~BOX_HSPLIT;
1265 // Move the other sub boxes contents up to this box.
1266 box->sub1 = otherBox->sub1;
1267 box->sub2 = otherBox->sub2;
1268 if (box->sub1)
1269 {
1270 box->sub1->parent = box;
1271 box->sub2->parent = box;
1272 box->flags = otherBox->flags;
1273 if (currentBox == box)
1274 currentBox = box->sub1;
1275 }
1276 else
1277 {
1278 if (!box->parent)
1279 box->flags &= ~BOX_BORDER;
1280 box->split = 1.0;
1281 }
1282 otherBox->sub1 = NULL;
1283 otherBox->sub2 = NULL;
1284 // Safe to free the boxes now that we have all their contents.
1285 freeBox(otherBox);
1286 freeBox(oldBox);
1287 }
1288 // Otherwise it must be a single full screen box. Never delete that one, unless we are quitting.
1289
1290 // Start the recursive recalculation of all the sub boxes.
1291 calcBoxes(box);
1292 drawBoxes(box);
1293}
1294
1295void cloneBox(struct _box *box, struct _box *sub)
1296{
1297 sub->parent = box;
1298 // Only a full screen box has no border.
1299 sub->flags |= BOX_BORDER;
1300 sub->view = xmalloc(sizeof(struct _view));
1301 // TODO - After this is more stable, should check if the memcpy() is simpler than - xzalloc() then copy a few things manually.
1302 // Might even be able to arrange the structure so we can memcpy just part of it, leaving the rest blank.
1303 memcpy(sub->view, box->view, sizeof(struct _view));
1304 sub->view->damage = NULL;
1305 sub->view->data = NULL;
1306 sub->view->output = NULL;
1307 sub->view->box = sub;
1308 if (box->view->prompt)
1309 sub->view->prompt = strdup(box->view->prompt);
1310}
1311
1312void splitBox(box *box, float split)
1313{
1314 uint16_t size;
1315 int otherBox = 0;
1316
1317 // First some sanity checks.
1318 if (0.0 > split)
1319 {
1320 // TODO - put this in the status line, or just silently fail. Also, better message. lol
1321 fprintf(stderr, "User is crazy.\n");
1322 return;
1323 }
1324 else if (1.0 <= split) // User meant to unsplit, and it may already be split.
1325 {
1326 // Actually, this means that the OTHER sub box gets deleted.
1327 if (box->parent)
1328 {
1329 if (box == box->parent->sub1)
1330 deleteBox(box->parent->sub2->view);
1331 else
1332 deleteBox(box->parent->sub1->view);
1333 }
1334 return;
1335 }
1336 else if (0.0 < split) // This is the normal case, so do nothing.
1337 {
1338 }
1339 else // User meant to delete this, zero split.
1340 {
1341 deleteBox(box->view);
1342 return;
1343 }
1344 if (box->flags & BOX_HSPLIT)
1345 size = box->H;
1346 else
1347 size = box->W;
1348 if (6 > size) // Is there room for 2 borders for each sub box and one character of content each?
1349 // TODO - also should check the contents minimum size.
1350 // No need to check the no border case, that's only for full screen.
1351 // People using terminals smaller than 6 characters get what they deserve.
1352 {
1353 // TODO - put this in the status line, or just silently fail.
1354 fprintf(stderr, "Box is too small to split.\n");
1355 return;
1356 }
1357
1358 // Note that a split box is actually three boxes. The parent, which is not drawn, and the two subs, which are.
1359 // Based on the assumption that there wont be lots of boxes, this keeps things simple.
1360 // It's possible that the box has already been split, and this is called just to update the split.
1361 box->split = split;
1362 if (NULL == box->sub1) // If not split already, do so.
1363 {
1364 box->sub1 = xzalloc(sizeof(struct _box));
1365 box->sub2 = xzalloc(sizeof(struct _box));
1366 cloneBox(box, box->sub1);
1367 cloneBox(box, box->sub2);
1368 if (box->flags & BOX_HSPLIT)
1369 {
1370 // Split the boxes in the middle of the content.
1371 box->sub2->view->offsetY += (box->H * box->split) - 2;
1372 // Figure out which sub box the cursor will be in, then update the cursor in the other box.
1373 if (box->sub1->view->cY < box->sub2->view->offsetY)
1374 box->sub2->view->cY = box->sub2->view->offsetY;
1375 else
1376 {
1377 box->sub1->view->cY = box->sub2->view->offsetY - 1;
1378 otherBox = 1;
1379 }
1380 }
1381 else
1382 {
1383 // Split the boxes in the middle of the content.
1384 box->sub2->view->offsetX += (box->W * box->split) - 2;
1385 // Figure out which sub box the cursor will be in, then update the cursor in the other box.
1386 if (box->sub1->view->cX < box->sub2->view->offsetX)
1387 box->sub2->view->cX = box->sub2->view->offsetX;
1388 else
1389 {
1390 box->sub1->view->cX = box->sub2->view->offsetX - 1;
1391 otherBox = 1;
1392 }
1393 }
1394 }
1395
1396 if ((currentBox == box) && (box->sub1))
1397 {
1398 if (otherBox)
1399 currentBox = box->sub2;
1400 else
1401 currentBox = box->sub1;
1402 }
1403
1404 // Start the recursive recalculation of all the sub boxes.
1405 calcBoxes(box);
1406 drawBoxes(box);
1407}
1408
1409// TODO - Might be better to just have a double linked list of boxes, and traverse that instead.
1410// Except that leaves a problem when deleting boxes, could end up with a blank space.
1411void switchBoxes(view *view)
1412{
1413 box *box = view->box;
1414
1415 // The assumption here is that box == currentBox.
1416 struct _box *oldBox = currentBox;
1417 struct _box *thisBox = box;
1418 int backingUp = 0;
1419
1420 // Depth first traversal.
1421 while ((oldBox == currentBox) && (thisBox->parent))
1422 {
1423 if (thisBox == thisBox->parent->sub1)
1424 {
1425 if (backingUp && (thisBox->parent))
1426 currentBox = thisBox->parent->sub2;
1427 else if (thisBox->sub1)
1428 currentBox = thisBox->sub1;
1429 else
1430 currentBox = thisBox->parent->sub2;
1431 }
1432 else if (thisBox == thisBox->parent->sub2)
1433 {
1434 thisBox = thisBox->parent;
1435 backingUp = 1;
1436 }
1437 }
1438
1439 // If we have not found the next box to move to, move back to the beginning.
1440 if (oldBox == currentBox)
1441 currentBox = rootBox;
1442
1443 // If we ended up on a parent box, go to it's first sub.
1444 while (currentBox->sub1)
1445 currentBox = currentBox->sub1;
1446
1447 // Just redraw them all.
1448 drawBoxes(rootBox);
1449}
1450
1451// TODO - It might be better to do away with this bunch of single line functions
1452// and map script commands directly to lower functions.
1453// How to deal with the various argument needs?
1454// Might be where we can re use the toybox argument stuff.
1455
1456void halveBoxHorizontally(view *view)
1457{
1458 view->box->flags |= BOX_HSPLIT;
1459 splitBox(view->box, 0.5);
1460}
1461
1462void halveBoxVertically(view *view)
1463{
1464 view->box->flags &= ~BOX_HSPLIT;
1465 splitBox(view->box, 0.5);
1466}
1467
1468void switchMode(view *view)
1469{
1470 currentBox->view->mode++;
1471 // Assumes that modes will always have a key mapping, which I think is a safe bet.
1472 if (NULL == currentBox->view->content->context->modes[currentBox->view->mode].keys)
1473 currentBox->view->mode = 0;
1474 commandMode = currentBox->view->content->context->modes[currentBox->view->mode].flags & 1;
1475}
1476
1477void leftChar(view *view)
1478{
1479 moveCursorRelative(view, -1, 0, 0, 0);
1480}
1481
1482void rightChar(view *view)
1483{
1484 moveCursorRelative(view, 1, 0, 0, 0);
1485}
1486
1487void upLine(view *view)
1488{
1489 moveCursorRelative(view, 0, -1, 0, 0);
1490}
1491
1492void downLine(view *view)
1493{
1494 moveCursorRelative(view, 0, 1, 0, 0);
1495}
1496
1497void upPage(view *view)
1498{
1499 moveCursorRelative(view, 0, 0 - (view->H - 1), 0, 0 - (view->H - 1));
1500}
1501
1502void downPage(view *view)
1503{
1504 moveCursorRelative(view, 0, view->H - 1, 0, view->H - 1);
1505}
1506
1507void endOfLine(view *view)
1508{
1509 moveCursorAbsolute(view, strlen(view->prompt) + view->oW, view->cY, 0, 0);
1510}
1511
1512void startOfLine(view *view)
1513{
1514 // TODO - add the advanced editing "smart home".
1515 moveCursorAbsolute(view, strlen(view->prompt), view->cY, 0, 0);
1516}
1517
1518void splitLine(view *view)
1519{
1520 // TODO - should move this into mooshLines().
1521 addLine(view->content, view->line, &(view->line->line[view->iX]), 0);
1522 view->line->line[view->iX] = '\0';
1523 moveCursorAbsolute(view, 0, view->cY + 1, 0, 0);
1524 if (view->box)
1525 drawBox(view->box);
1526}
1527
1528void deleteChar(view *view)
1529{
1530 // TODO - should move this into mooshLines().
1531 // If we are at the end of the line, then join this and the next line.
1532 if (view->oW == view->cX)
1533 {
1534 // Only if there IS a next line.
1535 if (&(view->content->lines) != view->line->next)
1536 {
1537 mooshStrings(view->line, view->line->next->line, view->iX, 1, !overWriteMode);
1538 view->line->next->line = NULL;
1539 freeLine(view->content, view->line->next);
1540 // TODO - should check if we are on the last page, then deal with scrolling.
1541 if (view->box)
1542 drawBox(view->box);
1543 }
1544 }
1545 else
1546 mooshStrings(view->line, NULL, view->iX, 1, !overWriteMode);
1547}
1548
1549void backSpaceChar(view *view)
1550{
1551 if (moveCursorRelative(view, -1, 0, 0, 0))
1552 deleteChar(view);
1553}
1554
1555void saveContent(view *view)
1556{
1557 saveFile(view->content);
1558}
1559
1560void executeLine(view *view)
1561{
1562 struct line *result = view->line;
1563
1564 // Don't bother doing much if there's nothing on this line.
1565 if (result->line[0])
1566 {
1567 doCommand(currentBox->view, result->line);
1568 // If we are not at the end of the history contents.
1569 if (&(view->content->lines) != result->next)
1570 {
1571 struct line *line = view->content->lines.prev;
1572
1573 // Remove the line first.
1574 result->next->prev = result->prev;
1575 result->prev->next = result->next;
1576 // Check if the last line is already blank, then remove it.
1577 if ('\0' == line->line[0])
1578 {
1579 freeLine(view->content, line);
1580 line = view->content->lines.prev;
1581 }
1582 // Then add it to the end.
1583 result->next = line->next;
1584 result->prev = line;
1585 line->next->prev = result;
1586 line->next = result;
1587 view->cY = view->content->lines.length - 1;
1588 }
1589 moveCursorAbsolute(view, 0, view->content->lines.length, 0, 0);
1590 // Make sure there is one blank line at the end.
1591 if ('\0' != view->line->line[0])
1592 {
1593 endOfLine(view);
1594 splitLine(view);
1595 }
1596 }
1597
1598 saveFile(view->content);
1599}
1600
1601void quit(view *view)
1602{
1603 handle_keys_quit();
1604}
1605
1606void nop(view *view)
1607{
1608 // 'tis a nop, don't actually do anything.
1609}
1610
1611
1612typedef void (*CSIhandler) (long extra, int *code, int count);
1613
1614struct CSI
1615{
1616 char *code;
1617 CSIhandler func;
1618};
1619
1620static void termSize(long extra, int *params, int count)
1621{
1622 struct _view *view = (struct _view *) extra; // Though we pretty much stomp on this straight away.
1623 int r = params[0], c = params[1];
1624
1625 // The defaults are 1, which get ignored by the heuristic below.
1626 // Check it's not an F3 key variation, coz some of them use the same CSI function code.
1627 // This is a heuristic, we are checking against an unusable terminal size.
1628 // TODO - Double check what the maximum F3 variations can be.
1629 if ((2 == count) && (8 < r) && (8 < c))
1630 {
1631 commandLine->Y = r;
1632 commandLine->W = c;
1633 rootBox->W = c;
1634 rootBox->H = r - 1;
1635 sizeViewToBox(rootBox, -1, -1, -1, -1);
1636 calcBoxes(rootBox);
1637 drawBoxes(rootBox);
1638
1639 // Move the cursor to where it is, to check it's not now outside the terminal window.
1640 moveCursorAbsolute(rootBox->view, rootBox->view->cX, rootBox->view->cY, 0, 0);
1641
1642 // We have no idea which is the current view now.
1643 if (commandMode) view = commandLine;
1644 else view = currentBox->view;
1645 updateLine(view);
1646 }
1647}
1648
1649struct CSI CSIcommands[] =
1650{
1651 {"R", termSize} // Parameters are cursor line and column. Note this may be sent at other times, not just during terminal resize.
1652};
1653
1654
1655// Callback for incoming sequences from the terminal.
1656static int handleEvent(long extra, struct keyevent *event)
1657{
1658 switch (event->type)
1659 {
1660 case HK_CSI :
1661 {
1662 int j;
1663
1664 for (j = 0; j < ARRAY_LEN(CSIcommands); j++)
1665 {
1666 if (strcmp(CSIcommands[j].code, event->sequence) == 0)
1667 {
1668 CSIcommands[j].func(extra, event->params, event->count);
1669 break;
1670 }
1671 }
1672 break;
1673 }
1674
1675 case HK_KEYS :
1676 {
1677 struct _view *view = (struct _view *) extra; // Though we pretty much stomp on this straight away.
1678 struct keyCommand *commands = currentBox->view->content->context->modes[currentBox->view->mode].keys;
1679 int j, l = strlen(event->sequence);
1680
1681 // Coz things might change out from under us, find the current view.
1682 if (commandMode) view = commandLine;
1683 else view = currentBox->view;
1684
1685 // Search for a key sequence bound to a command.
1686 for (j = 0; commands[j].key; j++)
1687 {
1688 if (strncmp(commands[j].key, event->sequence, l) == 0)
1689 {
1690 // If it's a partial match, keep accumulating them.
1691 if (strlen(commands[j].key) != l)
1692 return 0;
1693 else
1694 {
1695 doCommand(view, commands[j].command);
1696 return 1;
1697 }
1698 }
1699 }
1700
1701 // See if it's ordinary keys.
1702 // NOTE - with vi style ordinary keys can be commands,
1703 // but they would be found by the command check above first.
1704 if (!event->isTranslated)
1705 {
1706 // TODO - Should check for tabs to, and insert them.
1707 // Though better off having a function for that?
1708 mooshStrings(view->line, event->sequence, view->iX, 0, !overWriteMode);
1709 view->oW = formatLine(view, view->line->line, &(view->output));
1710 moveCursorRelative(view, strlen(event->sequence), 0, 0, 0);
1711 updateLine(view);
1712 }
1713 break;
1714 }
1715
1716 default : break;
1717 }
1718
1719 // Tell handle_keys to drop it, coz we dealt with it, or it's not one of ours.
1720 return 1;
1721}
1722
1723
1724// The default command to function mappings, with help text. Any editor that does not have it's own commands can use these for keystroke binding and such.
1725// Though most of the editors have their own variation.
1726// TODO - Maybe just use the joe one as default, it uses short names at least.
1727// Though vi is the only one in POSIX, so might be better to treat that one as the "standard" default.
1728// With some commands from others for stuff vi doesn't support.
1729struct function simpleEditCommands[] =
1730{
1731 {"backSpaceChar", "Back space last character.", 0, {backSpaceChar}},
1732 {"deleteBox", "Delete a box.", 0, {deleteBox}},
1733 {"deleteChar", "Delete current character.", 0, {deleteChar}},
1734 {"downLine", "Move cursor down one line.", 0, {downLine}},
1735 {"downPage", "Move cursor down one page.", 0, {downPage}},
1736 {"endOfLine", "Go to end of line.", 0, {endOfLine}},
1737 {"executeLine", "Execute a line as a script.", 0, {executeLine}},
1738 {"leftChar", "Move cursor left one character.", 0, {leftChar}},
1739 {"quit", "Quit the application.", 0, {quit}},
1740 {"rightChar", "Move cursor right one character.", 0, {rightChar}},
1741 {"save", "Save.", 0, {saveContent}},
1742 {"splitH", "Split box in half horizontally.", 0, {halveBoxHorizontally}},
1743 {"splitLine", "Split line at cursor.", 0, {splitLine}},
1744 {"splitV", "Split box in half vertically.", 0, {halveBoxVertically}},
1745 {"startOfLine", "Go to start of line.", 0, {startOfLine}},
1746 {"switchBoxes", "Switch to another box.", 0, {switchBoxes}},
1747 {"switchMode", "Switch between command and box.", 0, {switchMode}},
1748 {"upLine", "Move cursor up one line.", 0, {upLine}},
1749 {"upPage", "Move cursor up one page.", 0, {upPage}},
1750 {NULL, NULL, 0, {NULL}}
1751};
1752
1753// Construct a simple command line.
1754
1755// The key to command mappings.
1756// TODO - Should not move off the ends of the line to the next / previous line.
1757struct keyCommand simpleCommandKeys[] =
1758{
1759 {"BS", "backSpaceChar"},
1760 {"Del", "deleteChar"},
1761 {"Down", "downLine"},
1762 {"End", "endOfLine"},
1763 {"F10", "quit"},
1764 {"Home", "startOfLine"},
1765 {"Left", "leftChar"},
1766 {"Enter", "executeLine"},
1767 {"Return", "executeLine"},
1768 {"Right", "rightChar"},
1769 {"Esc", "switchMode"},
1770 {"Up", "upLine"},
1771 {NULL, NULL}
1772};
1773
1774
1775// Construct a simple emacs editor.
1776
1777// Mostly control keys, some meta keys.
1778// Ctrl-h and Ctrl-x have more keys in the commands. Some of those extra keys are commands by themselves. Up to "Ctrl-x 4 Ctrl-g" which apparently is identical to just Ctrl-g. shrugs
1779// Ctrl-h is backspace / del. Pffft.
1780// Meta key is either Alt-keystroke, Esc keystroke, or an actual Meta-keystroke (do they still exist?).
1781// TODO - Alt and Meta not supported yet, so using Esc.
1782// Windows commands.
1783
1784// readline uses these same commands, and defaults to emacs keystrokes.
1785struct function simpleEmacsCommands[] =
1786{
1787 {"delete-backward-char", "Back space last character.", 0, {backSpaceChar}},
1788 {"delete-window", "Delete a box.", 0, {deleteBox}},
1789 {"delete-char", "Delete current character.", 0, {deleteChar}},
1790 {"next-line", "Move cursor down one line.", 0, {downLine}},
1791 {"scroll-up", "Move cursor down one page.", 0, {downPage}},
1792 {"end-of-line", "Go to end of line.", 0, {endOfLine}},
1793 {"accept-line", "Execute a line as a script.", 0, {executeLine}}, // From readline, which uses emacs commands, coz mg at least does not seem to have this.
1794 {"backward-char", "Move cursor left one character.", 0, {leftChar}},
1795 {"save-buffers-kill-emacs", "Quit the application.", 0, {quit}}, // TODO - Does more than just quit.
1796 {"forward-char", "Move cursor right one character.", 0, {rightChar}},
1797 {"save-buffer", "Save.", 0, {saveContent}},
1798 {"split-window-horizontally", "Split box in half horizontally.", 0, {halveBoxHorizontally}}, // TODO - Making this one up for now, mg does not have it.
1799 {"newline", "Split line at cursor.", 0, {splitLine}},
1800 {"split-window-vertically", "Split box in half vertically.", 0, {halveBoxVertically}},
1801 {"beginning-of-line", "Go to start of line.", 0, {startOfLine}},
1802 {"other-window", "Switch to another box.", 0, {switchBoxes}}, // There is also "previous-window" for going in the other direction, which we don't support yet.
1803 {"execute-extended-command", "Switch between command and box.", 0, {switchMode}}, // Actually a one time invocation of the command line.
1804 {"previous-line", "Move cursor up one line.", 0, {upLine}},
1805 {"scroll-down", "Move cursor up one page.", 0, {upPage}},
1806 {NULL, NULL, 0, {NULL}}
1807};
1808
1809// The key to command mappings.
1810struct keyCommand simpleEmacsKeys[] =
1811{
1812 {"BS", "delete-backward-char"},
1813 {"Del", "delete-backward-char"},
1814 {"^D", "delete-char"},
1815 {"Down", "next-line"},
1816 {"^N", "next-line"},
1817 {"End", "end-of-line"},
1818 {"^E", "end-of-line"},
1819 {"^X^C", "save-buffers-kill-emacs"},
1820 {"^X^S", "save-buffer"},
1821 {"Home", "beginning-of-line"},
1822 {"^A", "beginning-of-line"},
1823 {"Left", "backward-char"},
1824 {"^B", "backward-char"},
1825 {"PgDn", "scroll-up"},
1826 {"^V", "scroll-up"},
1827 {"PgUp", "scroll-down"},
1828 {"Escv", "scroll-down"}, // M-v
1829 {"Enter", "newline"},
1830 {"Return", "newline"},
1831 {"Right", "forward-char"},
1832 {"^F", "forward-char"},
1833 {"Escx", "execute-extended-command"}, // M-x
1834 {"^X2", "split-window-vertically"},
1835 {"^XP", "other-window"},
1836 {"^X0", "delete-window"},
1837 {"Up", "previous-line"},
1838 {"^P", "previous-line"},
1839 {NULL, NULL}
1840};
1841
1842struct keyCommand simpleEmacsCommandKeys[] =
1843{
1844 {"Del", "delete-backwards-char"},
1845 {"^D", "delete-char"},
1846 {"Down", "next-line"},
1847 {"^N", "next-line"},
1848 {"End", "end-of-line"},
1849 {"^E", "end-of-line"},
1850 {"Home", "beginning-of-line"},
1851 {"^A", "beginning-of-line"},
1852 {"Left", "backward-char"},
1853 {"^B", "backward-char"},
1854 {"Right", "forward-char"},
1855 {"^F", "forward-char"},
1856 {"Up", "previous-line"},
1857 {"^P", "previous-line"},
1858 {"Enter", "accept-line"},
1859 {"Return", "accept-line"},
1860 {"Escx", "execute-extended-command"},
1861 {NULL, NULL}
1862};
1863
1864// An array of various modes.
1865struct mode simpleEmacsMode[] =
1866{
1867 {simpleEmacsKeys, NULL, NULL, 0},
1868 {simpleEmacsCommandKeys, NULL, NULL, 1},
1869 {NULL, NULL, NULL}
1870};
1871
1872// Put it all together into a simple editor context.
1873struct context simpleEmacs =
1874{
1875 simpleEmacsCommands,
1876 simpleEmacsMode,
1877 NULL,
1878 NULL,
1879 NULL
1880};
1881
1882
1883// Construct a simple joe / wordstar editor, using joe is the reference, seems to be the popular Unix variant.
1884// Esc x starts up the command line.
1885// Has multi control key combos. Mostly Ctrl-K, Ctrl-[ (Esc), (Ctrl-B, Ctrl-Q in wordstar and delphi), but might be others.
1886// Can't find a single list of command mappings for joe, gotta search all over. sigh
1887// Even the command line keystroke I stumbled on (Esc x) is not documented.
1888// Note that you don't have to let go of the Ctrl key for the second keystroke, but you can.
1889
1890// From http://joe-editor.sourceforge.net/list.html
1891// TODO - Some of these might be wrong. Just going by the inadequate joe docs for now.
1892struct function simpleJoeCommands[] =
1893{
1894 {"backs", "Back space last character.", 0, {backSpaceChar}},
1895 {"abort", "Delete a box.", 0, {deleteBox}}, // TODO - Should do quit if it's the last window.
1896 {"delch", "Delete current character.", 0, {deleteChar}},
1897 {"dnarw", "Move cursor down one line.", 0, {downLine}},
1898 {"pgdn", "Move cursor down one page.", 0, {downPage}},
1899 {"eol", "Go to end of line.", 0, {endOfLine}},
1900 {"ltarw", "Move cursor left one character.", 0, {leftChar}},
1901 {"killjoe", "Quit the application.", 0, {quit}},
1902 {"rtarw", "Move cursor right one character.", 0, {rightChar}},
1903 {"save", "Save.", 0, {saveContent}},
1904 {"splitw", "Split box in half horizontally.", 0, {halveBoxHorizontally}},
1905 {"open", "Split line at cursor.", 0, {splitLine}},
1906 {"bol", "Go to start of line.", 0, {startOfLine}},
1907 {"home", "Go to start of line.", 0, {startOfLine}},
1908 {"nextw", "Switch to another box.", 0, {switchBoxes}}, // This is "next window", there's also "previous window" which we don't support yet.
1909 {"execmd", "Switch between command and box.", 0, {switchMode}}, // Actually I think this just switches to the command mode, not back and forth. Or it might execute the actual command.
1910 {"uparw", "Move cursor up one line.", 0, {upLine}},
1911 {"pgup", "Move cursor up one page.", 0, {upPage}},
1912
1913 // Not an actual joe command.
1914 {"executeLine", "Execute a line as a script.", 0, {executeLine}}, // Perhaps this should be execmd?
1915 {NULL, NULL, 0, {NULL}}
1916};
1917
1918struct keyCommand simpleJoeKeys[] =
1919{
1920 {"BS", "backs"},
1921 {"^D", "delch"},
1922 {"Down", "dnarw"},
1923 {"^N", "dnarw"},
1924 {"^E", "eol"},
1925 {"^C", "killjoe"},
1926 {"^Kd", "save"},
1927 {"^K^D" "save"},
1928 {"^A", "bol"},
1929 {"Left", "ltarw"},
1930 {"^B", "ltarw"},
1931 {"^V", "pgdn"}, // Actually half a page.
1932 {"^U", "pgup"}, // Actually half a page.
1933 {"Enter", "open"},
1934 {"Return", "open"},
1935 {"Right", "rtarw"},
1936 {"^F", "rtarw"},
1937 {"Escx", "execmd"},
1938 {"Esc^X", "execmd"},
1939 {"^Ko", "splitw"},
1940 {"^K^O", "splitw"},
1941 {"^Kn", "nextw"},
1942 {"^K^N", "nextw"},
1943 {"^Kx", "killjoe"}, // TODO - Should ask if it should save if it's been modified. A good generic thing to do anyway.
1944 {"^K^X", "abort"}, // TODO - These two both close a window, and quit if that was the last window.
1945 {"Up", "uparw"},
1946 {"^P", "uparw"},
1947 {NULL, NULL}
1948};
1949
1950struct keyCommand simpleJoeCommandKeys[] =
1951{
1952 {"BS", "backs"},
1953 {"^D", "delch"},
1954 {"Down", "dnarw"},
1955 {"^N", "dnarw"},
1956 {"^E", "eol"},
1957 {"^A", "bol"},
1958 {"Left", "ltarw"},
1959 {"^B", "ltarw"},
1960 {"Right", "rtarw"},
1961 {"^F", "rtarw"},
1962 {"Escx", "execmd"},
1963 {"Esc^X", "execmd"},
1964 {"Up", "uparw"},
1965 {"^P", "uparw"},
1966 {"Enter", "executeLine"},
1967 {"Return", "executeLine"},
1968 {NULL, NULL}
1969};
1970
1971struct mode simpleJoeMode[] =
1972{
1973 {simpleJoeKeys, NULL, NULL, 0},
1974 {simpleJoeCommandKeys, NULL, NULL, 1},
1975 {NULL, NULL, NULL, 0}
1976};
1977
1978struct context simpleJoe =
1979{
1980 simpleJoeCommands,
1981 simpleJoeMode,
1982 NULL,
1983 NULL,
1984 NULL
1985};
1986
1987
1988// Simple more and / or less.
1989// '/' and '?' for search command mode. I think they both have some ex commands with the usual : command mode starter.
1990// No cursor movement, just scrolling.
1991// TODO - Put content into read only mode.
1992// TODO - actually implement read only mode where up and down one line do actual scrolling instead of cursor movement.
1993
1994struct keyCommand simpleLessKeys[] =
1995{
1996 {"Down", "downLine"},
1997 {"j", "downLine"},
1998 {"Enter", "downLine"},
1999 {"Return", "downLine"},
2000 {"End", "endOfLine"},
2001 {"q", "quit"},
2002 {":q", "quit"}, // TODO - A vi ism, should do ex command stuff instead.
2003 {"ZZ", "quit"},
2004 {"PgDn", "downPage"},
2005 {"f", "downPage"},
2006 {" ", "downPage"},
2007 {"^F", "downPage"},
2008 {"Left", "leftChar"},
2009 {"Right", "rightChar"},
2010 {"PgUp", "upPage"},
2011 {"b", "upPage"},
2012 {"^B", "upPage"},
2013 {"Up", "upLine"},
2014 {"k", "upLine"},
2015 {NULL, NULL}
2016};
2017
2018struct mode simpleLessMode[] =
2019{
2020 {simpleLessKeys, NULL, NULL, 0},
2021 {simpleCommandKeys, NULL, NULL, 1},
2022 {NULL, NULL, NULL}
2023};
2024
2025struct context simpleLess =
2026{
2027 simpleEditCommands,
2028 simpleLessMode,
2029 NULL,
2030 NULL,
2031 NULL
2032};
2033
2034struct keyCommand simpleMoreKeys[] =
2035{
2036 {"j", "downLine"},
2037 {"Enter", "downLine"},
2038 {"Return", "downLine"},
2039 {"q", "quit"},
2040 {":q", "quit"}, // See comments for "less".
2041 {"ZZ", "quit"},
2042 {"f", "downPage"},
2043 {" ", "downPage"},
2044 {"^F", "downPage"},
2045 {"b", "upPage"},
2046 {"^B", "upPage"},
2047 {"k", "upLine"},
2048 {NULL, NULL}
2049};
2050
2051struct mode simpleMoreMode[] =
2052{
2053 {simpleMoreKeys, NULL, NULL, 0},
2054 {simpleCommandKeys, NULL, NULL, 1},
2055 {NULL, NULL, NULL}
2056};
2057
2058struct context simpleMore =
2059{
2060 simpleEditCommands,
2061 simpleMoreMode,
2062 NULL,
2063 NULL,
2064 NULL
2065};
2066
2067
2068// Construct a simple mcedit / cool edit editor.
2069
2070struct keyCommand simpleMceditKeys[] =
2071{
2072 {"BS", "backSpaceChar"},
2073 {"Del", "deleteChar"},
2074 {"Down", "downLine"},
2075 {"End", "endOfLine"},
2076 {"F10", "quit"},
2077 {"Esc0", "quit"},
2078 {"F2", "save"},
2079 {"Esc2", "save"},
2080 {"Home", "startOfLine"},
2081 {"Left", "leftChar"},
2082 {"PgDn", "downPage"},
2083 {"PgUp", "upPage"},
2084 {"Enter", "splitLine"},
2085 {"Return", "splitLine"},
2086 {"Right", "rightChar"},
2087 {"Shift F2", "switchMode"}, // MC doesn't have a command mode.
2088 {"Esc:", "switchMode"}, // Sorta vi like, and coz tmux is screwing with the shift function keys somehow.
2089 {"Esc|", "splitV"}, // MC doesn't have a split window concept, so make these up to match tmux more or less.
2090 {"Esc-", "splitH"},
2091 {"Esco", "switchBoxes"},
2092 {"Escx", "deleteBox"},
2093 {"Up", "upLine"},
2094 {NULL, NULL}
2095};
2096
2097struct mode simpleMceditMode[] =
2098{
2099 {simpleMceditKeys, NULL, NULL, 0},
2100 {simpleCommandKeys, NULL, NULL, 1},
2101 {NULL, NULL, NULL}
2102};
2103
2104struct context simpleMcedit =
2105{
2106 simpleEditCommands,
2107 simpleMceditMode,
2108 NULL,
2109 NULL,
2110 NULL
2111};
2112
2113
2114// Simple nano editor.
2115// Has key to function bindings, but no command line mode. Has "enter parameter on this line" mode for some commands.
2116// Control and meta keys, only singles, unlike emacs and joe.
2117// Can have multiple buffers, but no windows. Think I can skip that for simple editor.
2118
2119struct function simpleNanoCommands[] =
2120{
2121 {"backSpaceChar", "Back space last character.", 0, {backSpaceChar}},
2122 {"delete", "Delete current character.", 0, {deleteChar}},
2123 {"down", "Move cursor down one line.", 0, {downLine}},
2124 {"downPage", "Move cursor down one page.", 0, {downPage}},
2125 {"end", "Go to end of line.", 0, {endOfLine}},
2126 {"left", "Move cursor left one character.", 0, {leftChar}},
2127 {"exit", "Quit the application.", 0, {quit}},
2128 {"right", "Move cursor right one character.", 0, {rightChar}},
2129 {"writeout", "Save.", 0, {saveContent}},
2130 {"enter", "Split line at cursor.", 0, {splitLine}},
2131 {"home", "Go to start of line.", 0, {startOfLine}},
2132 {"up", "Move cursor up one line.", 0, {upLine}},
2133 {"upPage", "Move cursor up one page.", 0, {upPage}},
2134 {NULL, NULL, 0, {NULL}}
2135};
2136
2137
2138// Hmm, back space, page up, and page down don't seem to have bindable commands according to the web page, but they are bound to keys anyway.
2139struct keyCommand simpleNanoKeys[] =
2140{
2141// TODO - Delete key is ^H dammit. Find the alternate Esc sequence for Del.
2142// {"^H", "backSpaceChar"}, // ?
2143 {"BS", "backSpaceChar"},
2144 {"^D", "delete"},
2145 {"Del", "delete"},
2146 {"^N", "down"},
2147 {"Down", "down"},
2148 {"^E", "end"},
2149 {"End", "end"},
2150 {"^X", "exit"},
2151 {"F2", "exit"},
2152 {"^O", "writeout"},
2153 {"F3", "writeout"},
2154 {"^A", "home"},
2155 {"Home", "home"},
2156 {"^B", "left"},
2157 {"Left", "left"},
2158 {"^V", "downPage"}, // ?
2159 {"PgDn", "downPage"},
2160 {"^Y", "upPage"}, // ?
2161 {"PgUp", "upPage"},
2162 {"Enter", "enter"}, // TODO - Not sure if this is correct.
2163 {"Return", "enter"}, // TODO - Not sure if this is correct.
2164 {"^F", "right"},
2165 {"Right", "right"},
2166 {"^P", "up"},
2167 {"Up", "up"},
2168 {NULL, NULL}
2169};
2170
2171struct mode simpleNanoMode[] =
2172{
2173 {simpleNanoKeys, NULL, NULL, 0},
2174 {NULL, NULL, NULL}
2175};
2176
2177struct context simpleNano =
2178{
2179 simpleNanoCommands,
2180 simpleNanoMode,
2181 NULL,
2182 NULL,
2183 NULL
2184};
2185
2186
2187// Construct a simple vi editor.
2188// Only vi is not so simple. lol
2189// The "command line" modes are /, ?, :, and !,
2190// / is regex search.
2191// ? is regex search backwards.
2192// : is ex command mode.
2193// ! is replace text with output from shell command mode.
2194// Arrow keys do the right thing in "normal" mode, but not in insert mode.
2195// "i" goes into insert mode, "Esc" (or Ctrl-[ or Ctrl-C) gets you out. So much for "you can do it all touch typing on the home row". Pffft
2196// Ah, the Esc key WAS a lot closer to the home row (where Tab usually is now) on the original keyboard vi was designed for, ADM3A.
2197// Which is also the keyboard with the arrow keys marked on h, j, k, and l keys.
2198// Did I mention that vi is just a horrid historic relic that should have died long ago?
2199// Emacs looks to have the same problem, originally designed for an ancient keyboard that is nothing like what people actually use these days.
2200// "h", "j", "k", "l" move cursor, which is just random keys for dvorak users.
2201// ":" goes into ex command mode.
2202// ":q" deletes current window in vim.
2203// ":qa!" goes into ex mode and does some sort of quit command.
2204// The 'q' is short for quit, the ! is an optional argument to quit. No idea yet what the a is for, all windows?
2205// Del or "x" to delete a character. Del in insert mode.
2206// "X" to backspace. BS or Ctrl-H to backspace in insert mode.
2207// NOTE - Backspace in normal mode just moves left.
2208// Tab or Ctrl-I to insert a tab in insert mode.
2209// Return in normal mode goes to the start of the next line, or splits the line in insert mode.
2210// ":help" opens a window with help text.
2211// Vim window commands.
2212
2213// Vi needs extra variables and functions.
2214static int viTempExMode;
2215
2216void viMode(view *view)
2217{
2218 currentBox->view->mode = 0;
2219 commandMode = 0;
2220 viTempExMode = 0;
2221}
2222
2223void viInsertMode(view *view)
2224{
2225 currentBox->view->mode = 1;
2226 commandMode = 0;
2227}
2228
2229void viExMode(view *view)
2230{
2231 currentBox->view->mode = 2;
2232 commandMode = 1;
2233 // TODO - Should change this based on the event, : or Q.
2234 viTempExMode = 1;
2235 commandLine->prompt = xrealloc(commandLine->prompt, 2);
2236 strcpy(commandLine->prompt, ":");
2237}
2238
2239void viBackSpaceChar(view *view)
2240{
2241 if ((2 == currentBox->view->mode) && (0 == view->cX) && viTempExMode)
2242 viMode(view);
2243 else
2244 backSpaceChar(view);
2245}
2246
2247void viStartOfNextLine(view *view)
2248{
2249 startOfLine(view);
2250 downLine(view);
2251}
2252
2253struct function simpleViCommands[] =
2254{
2255 // These are actual ex commands.
2256 {"insert", "Switch to insert mode.", 0, {viInsertMode}},
2257 {"quit", "Quit the application.", 0, {quit}},
2258 {"visual", "Switch to visual mode.", 0, {viMode}},
2259 {"write", "Save.", 0, {saveContent}},
2260
2261 // These are not ex commands.
2262 {"backSpaceChar", "Back space last character.", 0, {viBackSpaceChar}},
2263 {"deleteBox", "Delete a box.", 0, {deleteBox}},
2264 {"deleteChar", "Delete current character.", 0, {deleteChar}},
2265 {"downLine", "Move cursor down one line.", 0, {downLine}},
2266 {"downPage", "Move cursor down one page.", 0, {downPage}},
2267 {"endOfLine", "Go to end of line.", 0, {endOfLine}},
2268 {"executeLine", "Execute a line as a script.", 0, {executeLine}},
2269 {"exMode", "Switch to ex mode.", 0, {viExMode}},
2270 {"leftChar", "Move cursor left one character.", 0, {leftChar}},
2271 {"rightChar", "Move cursor right one character.", 0, {rightChar}},
2272 {"splitH", "Split box in half horizontally.", 0, {halveBoxHorizontally}},
2273 {"splitLine", "Split line at cursor.", 0, {splitLine}},
2274 {"splitV", "Split box in half vertically.", 0, {halveBoxVertically}},
2275 {"startOfLine", "Go to start of line.", 0, {startOfLine}},
2276 {"startOfNLine", "Go to start of next line.", 0, {viStartOfNextLine}},
2277 {"switchBoxes", "Switch to another box.", 0, {switchBoxes}},
2278 {"upLine", "Move cursor up one line.", 0, {upLine}},
2279 {"upPage", "Move cursor up one page.", 0, {upPage}},
2280 {NULL, NULL, 0, {NULL}}
2281};
2282
2283struct keyCommand simpleViNormalKeys[] =
2284{
2285 {"BS", "leftChar"},
2286 {"X", "backSpaceChar"},
2287 {"Del", "deleteChar"},
2288 {"x", "deleteChar"},
2289 {"Down", "downLine"},
2290 {"j", "downLine"},
2291 {"End", "endOfLine"},
2292 {"Home", "startOfLine"},
2293 {"Left", "leftChar"},
2294 {"h", "leftChar"},
2295 {"PgDn", "downPage"},
2296 {"^F", "downPage"},
2297 {"PgUp", "upPage"},
2298 {"^B", "upPage"},
2299 {"Enter", "startOfNextLine"},
2300 {"Return", "startOfNextLine"},
2301 {"Right", "rightChar"},
2302 {"l", "rightChar"},
2303 {"i", "insert"},
2304 {":", "exMode"}, // This is the temporary ex mode that you can backspace out of. Or any command backs you out.
2305 {"Q", "exMode"}, // This is the ex mode you need to do the "visual" command to get out of.
2306 {"^Wv", "splitV"},
2307 {"^W^V", "splitV"},
2308 {"^Ws", "splitH"},
2309 {"^WS", "splitH"},
2310 {"^W^S", "splitH"},
2311 {"^Ww", "switchBoxes"},
2312 {"^W^W", "switchBoxes"},
2313 {"^Wq", "deleteBox"},
2314 {"^W^Q", "deleteBox"},
2315 {"Up", "upLine"},
2316 {"k", "upLine"},
2317 {NULL, NULL}
2318};
2319
2320struct keyCommand simpleViInsertKeys[] =
2321{
2322 {"BS", "backSpaceChar"},
2323 {"Del", "deleteChar"},
2324 {"Return", "splitLine"},
2325 {"Esc", "visual"},
2326 {"^C", "visual"},
2327 {NULL, NULL}
2328};
2329
2330struct keyCommand simpleExKeys[] =
2331{
2332 {"BS", "backSpaceChar"},
2333 {"Del", "deleteChar"},
2334 {"Down", "downLine"},
2335 {"End", "endOfLine"},
2336 {"Home", "startOfLine"},
2337 {"Left", "leftChar"},
2338 {"Enter", "executeLine"},
2339 {"Return", "executeLine"},
2340 {"Right", "rightChar"},
2341 {"Esc", "visual"},
2342 {"Up", "upLine"},
2343 {NULL, NULL}
2344};
2345
2346struct mode simpleViMode[] =
2347{
2348 {simpleViNormalKeys, NULL, NULL, 0},
2349 {simpleViInsertKeys, NULL, NULL, 0},
2350 {simpleExKeys, NULL, NULL, 1},
2351 {NULL, NULL, NULL}
2352};
2353
2354struct context simpleVi =
2355{
2356 simpleViCommands,
2357 simpleViMode,
2358 NULL,
2359 NULL,
2360 NULL
2361};
2362
2363
2364// TODO - simple sed editor? May be out of scope for "simple", so leave it until later?
2365// Probably entirely useless for "simple".
2366
2367
2368// TODO - have any unrecognised escape key sequence start up a new box (split one) to show the "show keys" content.
2369// That just adds each "Key is X" to the end of the content, and allows scrolling, as well as switching between other boxes.
2370
2371void boxes_main(void)
2372{
2373 struct context *context = &simpleMcedit; // The default is mcedit, coz that's what I use.
2374 struct termios termio, oldtermio;
2375 char *prompt = "Enter a command : ";
2376 unsigned W = 80, H = 24;
2377
2378 // For testing purposes, figure out which context we use. When this gets real, the toybox multiplexer will sort this out for us instead.
2379 if (toys.optflags & FLAG_m)
2380 {
2381 if (strcmp(TT.mode, "emacs") == 0)
2382 context = &simpleEmacs;
2383 else if (strcmp(TT.mode, "joe") == 0)
2384 context = &simpleJoe;
2385 else if (strcmp(TT.mode, "less") == 0)
2386 context = &simpleLess;
2387 else if (strcmp(TT.mode, "mcedit") == 0)
2388 context = &simpleMcedit;
2389 else if (strcmp(TT.mode, "more") == 0)
2390 context = &simpleMore;
2391 else if (strcmp(TT.mode, "nano") == 0)
2392 context = &simpleNano;
2393 else if (strcmp(TT.mode, "vi") == 0)
2394 context = &simpleVi;
2395 }
2396
2397 // TODO - Should do an isatty() here, though not sure about the usefullness of driving this from a script or redirected input, since it's supposed to be a UI for terminals.
2398 // It would STILL need the terminal size for output though. Perhaps just bitch and abort if it's not a tty?
2399 // On the other hand, sed don't need no stinkin' UI. And things like more or less should be usable on the end of a pipe.
2400
2401 // Grab the old terminal settings and save it.
2402 tcgetattr(0, &oldtermio);
2403 tcflush(0, TCIFLUSH);
2404 termio = oldtermio;
2405
2406 // Mould the terminal to our will.
2407 /*
2408 IUCLC (not in POSIX) Map uppercase characters to lowercase on input.
2409 IXON Enable XON/XOFF flow control on output.
2410 IXOFF Enable XON/XOFF flow control on input.
2411 IXANY (not in POSIX.1; XSI) Enable any character to restart output.
2412
2413 ECHO Echo input characters.
2414 ECHOE If ICANON is also set, the ERASE character erases the preceding input character, and WERASE erases the preceding word.
2415 ECHOK If ICANON is also set, the KILL character erases the current line.
2416 ECHONL If ICANON is also set, echo the NL character even if ECHO is not set.
2417 TOSTOP Send the SIGTTOU signal to the process group of a background process which tries to write to its controlling terminal.
2418 ICANON Enable canonical mode. This enables the special characters EOF, EOL, EOL2, ERASE, KILL, LNEXT, REPRINT, STATUS, and WERASE, and buffers by lines.
2419
2420 VTIME Timeout in deciseconds for non-canonical read.
2421 VMIN Minimum number of characters for non-canonical read.
2422
2423 raw mode turning off ICANON, IEXTEN, and ISIG kills most special key processing.
2424 termio.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
2425 termio.c_oflag &= ~OPOST;
2426 termio.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
2427 termio.c_cflag &= ~(CSIZE | PARENB);
2428 termio.c_cflag |= CS8;
2429
2430 IGNBRK ignore BREAK
2431 BRKINT complicated, bet in this context, sends BREAK as '\x00'
2432 PARMRK characters with parity or frame erors are sent as '\x00'
2433 ISTRIP strip 8th byte
2434 INLCR translate LF to CR in input
2435 IGLCR ignore CR
2436 OPOST enable implementation defined output processing
2437 ISIG generate signals on INTR (SIGINT on ^C), QUIT (SIGQUIT on ^\\), SUSP (SIGTSTP on ^Z), DSUSP (SIGTSTP on ^Y)
2438 IEXTEN enable implementation defined input processing, turns on some key -> signal -tuff
2439 CSIZE mask for character sizes, so in this case, we mask them all out
2440 PARENB enable parity
2441 CS8 8 bit characters
2442
2443 VEOF "sends" EOF on ^D, ICANON turns that on.
2444 VSTART restart output on ^Q, IXON turns that on.
2445 VSTATUS display status info and sends SIGINFO (STATUS) on ^T. Not in POSIX, not supported in Linux. ICANON turns that on.
2446 VSTOP stop output on ^S, IXON turns that on.
2447 */
2448 termio.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IUCLC | IXON | IXOFF | IXANY);
2449 termio.c_oflag &= ~OPOST;
2450 termio.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | TOSTOP | ICANON | ISIG | IEXTEN);
2451 termio.c_cflag &= ~(CSIZE | PARENB);
2452 termio.c_cflag |= CS8;
2453 termio.c_cc[VTIME]=0; // deciseconds.
2454 termio.c_cc[VMIN]=1;
2455 tcsetattr(0, TCSANOW, &termio);
2456
2457 terminal_size(&W, &H);
2458 if (toys.optflags & FLAG_w)
2459 W = TT.w;
2460 if (toys.optflags & FLAG_h)
2461 H = TT.h;
2462
2463 // Create the main box. Right now the system needs one for wrapping around while switching. The H - 1 bit is to leave room for our example command line.
2464 rootBox = addBox("root", context, toys.optargs[0], 0, 0, W, H - 1);
2465 currentBox = rootBox;
2466
2467 // Create the command line view, sharing the same context as the root. It will differentiate based on the view mode of the current box.
2468 // Also load the command line history as it's file.
2469 // TODO - different contexts will have different history files, though what to do about ones with no history, and ones with different histories for different modes?
2470 commandLine = addView("command", rootBox->view->content->context, ".boxes.history", 0, H, W, 1);
2471 // Add a prompt to it.
2472 commandLine->prompt = xrealloc(commandLine->prompt, strlen(prompt) + 1);
2473 strcpy(commandLine->prompt, prompt);
2474 // Move to the end of the history.
2475 moveCursorAbsolute(commandLine, 0, commandLine->content->lines.length, 0, 0);
2476
2477 // All the mouse tracking methods suck one way or another. sigh
2478 // http://rtfm.etla.org/xterm/ctlseq.html documents xterm stuff, near the bottom is the mouse stuff.
2479 // http://leonerds-code.blogspot.co.uk/2012/04/wide-mouse-support-in-libvterm.html is helpful.
2480 // Enable mouse (VT200 normal tracking mode, UTF8 encoding). The limit is 2015. Seems to only be in later xterms.
2481// fputs("\x1B[?1005h", stdout);
2482 // Enable mouse (VT340 locator reporting mode). In theory has no limit. Wont actually work though.
2483 // On the other hand, only allows for four buttons, so only half a mouse wheel.
2484 // Responds with "\1B[e;p;r;c;p&w" where e is event type, p is a bitmap of buttons pressed, r and c are the mouse coords in decimal, and p is the "page number".
2485// fputs("\x1B[1;2'z\x1B[1;3'{", stdout);
2486 // Enable mouse (VT200 normal tracking mode). Has a limit of 256 - 32 rows and columns. An xterm exclusive I think, but works in roxterm at least. No wheel reports.
2487 // Responds with "\x1B[Mbxy" where x and y are the mouse coords, and b is bit encoded buttons and modifiers - 0=MB1 pressed, 1=MB2 pressed, 2=MB3 pressed, 3=release, 4=Shift, 8=Meta, 16=Control
2488// fputs("\x1B[?1000h", stdout);
2489// fflush(stdout);
2490
2491 calcBoxes(currentBox);
2492 drawBoxes(currentBox);
2493 // Do the first cursor update.
2494 updateLine(currentBox->view);
2495
2496 // Run the main loop.
2497 handle_keys((long) currentBox->view, handleEvent);
2498
2499 // TODO - Should remember to turn off mouse reporting when we leave.
2500
2501 // Restore the old terminal settings.
2502 tcsetattr(0, TCSANOW, &oldtermio);
2503
2504 puts("");
2505 fflush(stdout);
2506}