Added NONAMELESSUNION/STRUCT defines.
[wine] / dlls / kernel / editline.c
1 /*
2  * line edition function for Win32 console
3  *
4  * Copyright 2001 Eric Pouech
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <string.h>
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "wincon.h"
29 #include "wine/unicode.h"
30 #include "winnls.h"
31 #include "wine/debug.h"
32 #include "console_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(console);
35
36 struct WCEL_Context;
37
38 typedef struct
39 {
40     WCHAR                       val;            /* vk or unicode char */
41     void                        (*func)(struct WCEL_Context* ctx);
42 } KeyEntry;
43
44 typedef struct
45 {
46     DWORD                       keyState;       /* keyState (from INPUT_RECORD) to match */
47     BOOL                        chkChar;        /* check vk or char */
48     KeyEntry*                   entries;        /* array of entries */
49 } KeyMap;
50
51 typedef struct WCEL_Context {
52     WCHAR*                      line;           /* the line being edited */
53     size_t                      alloc;          /* number of WCHAR in line */
54     unsigned                    len;            /* number of chars in line */
55     unsigned                    ofs;            /* offset for cursor in current line */
56     WCHAR*                      yanked;         /* yanked line */
57     unsigned                    mark;           /* marked point (emacs mode only) */
58     CONSOLE_SCREEN_BUFFER_INFO  csbi;           /* current state (initial cursor, window size, attribute) */
59     HANDLE                      hConIn;
60     HANDLE                      hConOut;
61     unsigned                    done : 1,       /* to 1 when we're done with editing */
62                                 error : 1,      /* to 1 when an error occurred in the editing */
63                                 can_wrap : 1;   /* to 1 when multi-line edition can take place */
64     unsigned                    histSize;
65     unsigned                    histPos;
66     WCHAR*                      histCurr;
67 } WCEL_Context;
68
69 #if 0
70 static void WCEL_Dump(WCEL_Context* ctx, const char* pfx)
71 {
72     MESSAGE("%s: [line=%s[alloc=%u] ofs=%u len=%u start=(%d,%d) mask=%c%c%c]\n"
73             "\t\thist=(size=%u pos=%u curr=%s)\n"
74             "\t\tyanked=%s\n",
75             pfx, debugstr_w(ctx->line), ctx->alloc, ctx->ofs, ctx->len,
76             ctx->csbi.dwCursorPosition.X, ctx->csbi.dwCursorPosition.Y,
77             ctx->done ? 'D' : 'd', ctx->error ? 'E' : 'e', ctx->can_wrap ? 'W' : 'w',
78             ctx->histSize, ctx->histPos, debugstr_w(ctx->histCurr),
79             debugstr_w(ctx->yanked));
80 }
81 #endif
82
83 /* ====================================================================
84  *
85  * Console helper functions
86  *
87  * ====================================================================*/
88
89 static BOOL WCEL_Get(WCEL_Context* ctx, INPUT_RECORD* ir)
90 {
91     DWORD               retv;
92
93     for (;;)
94     {
95         /* data available ? */
96         if (ReadConsoleInputW(ctx->hConIn, ir, 1, &retv) && retv == 1)
97             return TRUE;
98         /* then wait... */
99         switch (WaitForSingleObject(ctx->hConIn, INFINITE))
100         {
101         case WAIT_OBJECT_0:
102             break;
103         default:
104             /* we have checked that hConIn was a console handle (could be sb) */
105             ERR("Shouldn't happen\n");
106             /* fall thru */
107         case WAIT_ABANDONED:
108         case WAIT_TIMEOUT:
109             ctx->error = 1;
110             ERR("hmm bad situation\n");
111             return FALSE;
112         }
113     }
114 }
115
116 static inline void WCEL_Beep(WCEL_Context* ctx)
117 {
118     Beep(400, 300);
119 }
120
121 static inline BOOL WCEL_IsSingleLine(WCEL_Context* ctx, size_t len)
122 {
123     return ctx->csbi.dwCursorPosition.X + ctx->len + len <= ctx->csbi.dwSize.X;
124 }
125
126 static inline COORD WCEL_GetCoord(WCEL_Context* ctx, int ofs)
127 {
128     COORD       c;
129     unsigned    len = ctx->csbi.dwSize.X - ctx->csbi.dwCursorPosition.X;
130
131     c.Y = ctx->csbi.dwCursorPosition.Y;
132     if (ofs >= len)
133     {
134         ofs -= len;
135         c.X = ofs % ctx->csbi.dwSize.X;
136         c.Y += 1 + ofs / ctx->csbi.dwSize.X;
137     }
138     else c.X = ctx->csbi.dwCursorPosition.X + ofs;
139     return c;
140 }
141
142 static inline void WCEL_Update(WCEL_Context* ctx, int beg, int len)
143 {
144     WriteConsoleOutputCharacterW(ctx->hConOut, &ctx->line[beg], len,
145                                  WCEL_GetCoord(ctx, beg), NULL);
146     FillConsoleOutputAttribute(ctx->hConOut, ctx->csbi.wAttributes, len,
147                                WCEL_GetCoord(ctx, beg), NULL);
148 }
149
150 /* ====================================================================
151  *
152  * context manipulation functions
153  *
154  * ====================================================================*/
155
156 static BOOL WCEL_Grow(WCEL_Context* ctx, size_t len)
157 {
158     if (!WCEL_IsSingleLine(ctx, len) && !ctx->can_wrap)
159     {
160         FIXME("Mode doesn't allow to wrap. However, we should allow to overwrite current string\n");
161         return FALSE;
162     }
163
164     if (ctx->len + len >= ctx->alloc)
165     {
166         WCHAR*  newline;
167         size_t  newsize;
168
169         /* round up size to 32 byte-WCHAR boundary */
170         newsize = (ctx->len + len + 1 + 31) & ~31;
171         newline = HeapReAlloc(GetProcessHeap(), 0, ctx->line, sizeof(WCHAR) * newsize);
172         if (!newline) return FALSE;
173         ctx->line = newline;
174         ctx->alloc = newsize;
175     }
176     return TRUE;
177 }
178
179 static void WCEL_DeleteString(WCEL_Context* ctx, int beg, int end)
180 {
181     unsigned    str_len = end - beg;
182     COORD       cbeg = WCEL_GetCoord(ctx, ctx->len - str_len);
183     COORD       cend = WCEL_GetCoord(ctx, ctx->len);
184     CHAR_INFO   ci;
185
186     if (end < ctx->len)
187         memmove(&ctx->line[beg], &ctx->line[end], (ctx->len - end) * sizeof(WCHAR));
188     /* we need to clean from ctx->len - str_len to ctx->len */
189
190     ci.Char.UnicodeChar = ' ';
191     ci.Attributes = ctx->csbi.wAttributes;
192
193     if (cbeg.Y == cend.Y)
194     {
195         /* partial erase of sole line */
196         CONSOLE_FillLineUniform(ctx->hConOut, cbeg.X, cbeg.Y,
197                                 cend.X - cbeg.X, &ci);
198     }
199     else
200     {
201         int         i;
202         /* erase til eol on first line */
203         CONSOLE_FillLineUniform(ctx->hConOut, cbeg.X, cbeg.Y,
204                                 ctx->csbi.dwSize.X - cbeg.X, &ci);
205         /* completly erase all the others (full lines) */
206         for (i = cbeg.Y + 1; i < cend.Y; i++)
207             CONSOLE_FillLineUniform(ctx->hConOut, 0, i, ctx->csbi.dwSize.X, &ci);
208         /* erase from beg of line until last pos on last line */
209         CONSOLE_FillLineUniform(ctx->hConOut, 0, cend.Y, cend.X, &ci);
210     }
211     ctx->len -= str_len;
212     WCEL_Update(ctx, 0, ctx->len);
213     ctx->line[ctx->len] = 0;
214 }
215
216 static void WCEL_InsertString(WCEL_Context* ctx, const WCHAR* str)
217 {
218     size_t      len = lstrlenW(str);
219
220     if (!len || !WCEL_Grow(ctx, len)) return;
221     if (ctx->len > ctx->ofs)
222         memmove(&ctx->line[ctx->ofs + len], &ctx->line[ctx->ofs], (ctx->len - ctx->ofs) * sizeof(WCHAR));
223     memcpy(&ctx->line[ctx->ofs], str, len * sizeof(WCHAR));
224     ctx->len += len;
225     ctx->line[ctx->len] = 0;
226     WCEL_Update(ctx, ctx->ofs, ctx->len - ctx->ofs);
227
228     ctx->ofs += len;
229 }
230
231 static void WCEL_InsertChar(WCEL_Context* ctx, WCHAR c)
232 {
233     WCHAR       buffer[2];
234
235     /* do not insert 0..31 control characters */
236     if (c < ' ' && c != '\t') return;
237
238     buffer[0] = c;
239     buffer[1] = 0;
240     WCEL_InsertString(ctx, buffer);
241 }
242
243 static void WCEL_FreeYank(WCEL_Context* ctx)
244 {
245     if (ctx->yanked)
246     {
247         HeapFree(GetProcessHeap(), 0, ctx->yanked);
248         ctx->yanked = NULL;
249     }
250 }
251
252 static void WCEL_SaveYank(WCEL_Context* ctx, int beg, int end)
253 {
254     int len = end - beg;
255     if (len <= 0) return;
256
257     WCEL_FreeYank(ctx);
258     ctx->yanked = HeapReAlloc(GetProcessHeap(), 0, ctx->yanked, (len + 1) * sizeof(WCHAR));
259     if (!ctx->yanked) return;
260     memcpy(ctx->yanked, &ctx->line[beg], len * sizeof(WCHAR));
261     ctx->yanked[len] = 0;
262 }
263
264 /* FIXME NTDLL doesn't export iswalnum, and I don't want to link in msvcrt when most
265  * of the data lay in unicode lib
266  */
267 static inline BOOL WCEL_iswalnum(WCHAR wc)
268 {
269     return get_char_typeW(wc) & (C1_ALPHA|C1_DIGIT|C1_LOWER|C1_UPPER);
270 }
271
272 static int WCEL_GetLeftWordTransition(WCEL_Context* ctx, int ofs)
273 {
274     ofs--;
275     while (ofs >= 0 && !WCEL_iswalnum(ctx->line[ofs])) ofs--;
276     while (ofs >= 0 && WCEL_iswalnum(ctx->line[ofs])) ofs--;
277     if (ofs >= 0) ofs++;
278     return max(ofs, 0);
279 }
280
281 static int WCEL_GetRightWordTransition(WCEL_Context* ctx, int ofs)
282 {
283     ofs++;
284     while (ofs <= ctx->len && WCEL_iswalnum(ctx->line[ofs])) ofs++;
285     while (ofs <= ctx->len && !WCEL_iswalnum(ctx->line[ofs])) ofs++;
286     return min(ofs, ctx->len);
287 }
288
289 static WCHAR* WCEL_GetHistory(WCEL_Context* ctx, int idx)
290 {
291     WCHAR*      ptr;
292
293     if (idx == ctx->histSize - 1)
294     {
295         ptr = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(ctx->histCurr) + 1) * sizeof(WCHAR));
296         lstrcpyW(ptr, ctx->histCurr);
297     }
298     else
299     {
300         int     len = CONSOLE_GetHistory(idx, NULL, 0);
301
302         if ((ptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
303         {
304             CONSOLE_GetHistory(idx, ptr, len);
305         }
306     }
307     return ptr;
308 }
309
310 static void     WCEL_HistoryInit(WCEL_Context* ctx)
311 {
312     ctx->histPos  = CONSOLE_GetNumHistoryEntries();
313     ctx->histSize = ctx->histPos + 1;
314     ctx->histCurr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WCHAR));
315 }
316
317 static void    WCEL_MoveToHist(WCEL_Context* ctx, int idx)
318 {
319     WCHAR*      data = WCEL_GetHistory(ctx, idx);
320     int         len = lstrlenW(data) + 1;
321
322     /* save current line edition for recall when needed (FIXME seems broken to me) */
323     if (ctx->histPos == ctx->histSize - 1)
324     {
325         if (ctx->histCurr) HeapFree(GetProcessHeap(), 0, ctx->histCurr);
326         ctx->histCurr = HeapAlloc(GetProcessHeap(), 0, (ctx->len + 1) * sizeof(WCHAR));
327         memcpy(ctx->histCurr, ctx->line, (ctx->len + 1) * sizeof(WCHAR));
328     }
329     /* need to clean also the screen if new string is shorter than old one */
330     WCEL_DeleteString(ctx, 0, ctx->len);
331     ctx->ofs = 0;
332     /* insert new string */
333     if (WCEL_Grow(ctx, len))
334     {
335         WCEL_InsertString(ctx, data);
336         HeapFree(GetProcessHeap(), 0, data);
337         ctx->histPos = idx;
338     }
339 }
340
341 static void    WCEL_FindPrevInHist(WCEL_Context* ctx)
342 {
343     int startPos = ctx->histPos;
344     WCHAR*      data;
345     int         len, oldofs;
346
347     if (ctx->histPos && ctx->histPos == ctx->histSize) {
348         startPos--;
349         ctx->histPos--;
350     }
351
352     do {
353        data = WCEL_GetHistory(ctx, ctx->histPos);
354
355        if (ctx->histPos) ctx->histPos--;
356        else ctx->histPos = (ctx->histSize-1);
357
358        len = lstrlenW(data) + 1;
359        if ((len >= ctx->ofs) &&
360            (memcmp(ctx->line, data, ctx->ofs * sizeof(WCHAR)) == 0)) {
361
362            /* need to clean also the screen if new string is shorter than old one */
363            WCEL_DeleteString(ctx, 0, ctx->len);
364
365            if (WCEL_Grow(ctx, len))
366            {
367               oldofs = ctx->ofs;
368               ctx->ofs = 0;
369               WCEL_InsertString(ctx, data);
370               ctx->ofs = oldofs;
371               SetConsoleCursorPosition(ctx->hConOut, WCEL_GetCoord(ctx, ctx->ofs));
372               HeapFree(GetProcessHeap(), 0, data);
373               return;
374            }
375        }
376     } while (ctx->histPos != startPos);
377
378     return;
379 }
380
381 /* ====================================================================
382  *
383  * basic edition functions
384  *
385  * ====================================================================*/
386
387 static void WCEL_Done(WCEL_Context* ctx)
388 {
389     WCHAR       nl = '\n';
390     if (!WCEL_Grow(ctx, 1)) return;
391     ctx->line[ctx->len++] = '\n';
392     ctx->line[ctx->len] = 0;
393     WriteConsoleW(ctx->hConOut, &nl, 1, NULL, NULL);
394     ctx->done = 1;
395 }
396
397 static void WCEL_MoveLeft(WCEL_Context* ctx)
398 {
399     if (ctx->ofs > 0) ctx->ofs--;
400 }
401
402 static void WCEL_MoveRight(WCEL_Context* ctx)
403 {
404     if (ctx->ofs < ctx->len) ctx->ofs++;
405 }
406
407 static void WCEL_MoveToLeftWord(WCEL_Context* ctx)
408 {
409     int new_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs);
410     if (new_ofs != ctx->ofs) ctx->ofs = new_ofs;
411 }
412
413 static void WCEL_MoveToRightWord(WCEL_Context* ctx)
414 {
415     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
416     if (new_ofs != ctx->ofs) ctx->ofs = new_ofs;
417 }
418
419 static void WCEL_MoveToBeg(WCEL_Context* ctx)
420 {
421     ctx->ofs = 0;
422 }
423
424 static void WCEL_MoveToEnd(WCEL_Context* ctx)
425 {
426     ctx->ofs = ctx->len;
427 }
428
429 static void WCEL_SetMark(WCEL_Context* ctx)
430 {
431     ctx->mark = ctx->ofs;
432 }
433
434 static void WCEL_ExchangeMark(WCEL_Context* ctx)
435 {
436     unsigned tmp;
437
438     if (ctx->mark > ctx->len) return;
439     tmp = ctx->ofs;
440     ctx->ofs = ctx->mark;
441     ctx->mark = tmp;
442 }
443
444 static void WCEL_CopyMarkedZone(WCEL_Context* ctx)
445 {
446     unsigned beg, end;
447
448     if (ctx->mark > ctx->len || ctx->mark == ctx->ofs) return;
449     if (ctx->mark > ctx->ofs)
450     {
451         beg = ctx->ofs;         end = ctx->mark;
452     }
453     else
454     {
455         beg = ctx->mark;        end = ctx->ofs;
456     }
457     WCEL_SaveYank(ctx, beg, end);
458 }
459
460 static void WCEL_TransposeChar(WCEL_Context* ctx)
461 {
462     WCHAR       c;
463
464     if (!ctx->ofs || ctx->ofs == ctx->len) return;
465
466     c = ctx->line[ctx->ofs];
467     ctx->line[ctx->ofs] = ctx->line[ctx->ofs - 1];
468     ctx->line[ctx->ofs - 1] = c;
469
470     WCEL_Update(ctx, ctx->ofs - 1, 2);
471     ctx->ofs++;
472 }
473
474 static void WCEL_TransposeWords(WCEL_Context* ctx)
475 {
476     int left_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs),
477         right_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
478     if (left_ofs < ctx->ofs && right_ofs > ctx->ofs)
479     {
480         unsigned len_r = right_ofs - ctx->ofs;
481         unsigned len_l = ctx->ofs - left_ofs;
482
483         char*   tmp = HeapAlloc(GetProcessHeap(), 0, len_r * sizeof(WCHAR));
484         if (!tmp) return;
485
486         memcpy(tmp, &ctx->line[ctx->ofs], len_r * sizeof(WCHAR));
487         memmove(&ctx->line[left_ofs + len_r], &ctx->line[left_ofs], len_l * sizeof(WCHAR));
488         memcpy(&ctx->line[left_ofs], tmp, len_r * sizeof(WCHAR));
489
490         HeapFree(GetProcessHeap(), 0, tmp);
491         WCEL_Update(ctx, left_ofs, len_l + len_r);
492         ctx->ofs = right_ofs;
493     }
494 }
495
496 static void WCEL_LowerCaseWord(WCEL_Context* ctx)
497 {
498     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
499     if (new_ofs != ctx->ofs)
500     {
501         int     i;
502         for (i = ctx->ofs; i <= new_ofs; i++)
503             ctx->line[i] = tolowerW(ctx->line[i]);
504         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
505         ctx->ofs = new_ofs;
506     }
507 }
508
509 static void WCEL_UpperCaseWord(WCEL_Context* ctx)
510 {
511     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
512     if (new_ofs != ctx->ofs)
513     {
514         int     i;
515         for (i = ctx->ofs; i <= new_ofs; i++)
516             ctx->line[i] = toupperW(ctx->line[i]);
517         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
518         ctx->ofs = new_ofs;
519     }
520 }
521
522 static void WCEL_CapitalizeWord(WCEL_Context* ctx)
523 {
524     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
525     if (new_ofs != ctx->ofs)
526     {
527         int     i;
528
529         ctx->line[ctx->ofs] = toupperW(ctx->line[ctx->ofs]);
530         for (i = ctx->ofs + 1; i <= new_ofs; i++)
531             ctx->line[i] = tolowerW(ctx->line[i]);
532         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
533         ctx->ofs = new_ofs;
534     }
535 }
536
537 static void WCEL_Yank(WCEL_Context* ctx)
538 {
539     WCEL_InsertString(ctx, ctx->yanked);
540 }
541
542 static void WCEL_KillToEndOfLine(WCEL_Context* ctx)
543 {
544     WCEL_SaveYank(ctx, ctx->ofs, ctx->len);
545     WCEL_DeleteString(ctx, ctx->ofs, ctx->len);
546 }
547
548 static void WCEL_KillMarkedZone(WCEL_Context* ctx)
549 {
550     unsigned beg, end;
551
552     if (ctx->mark > ctx->len || ctx->mark == ctx->ofs) return;
553     if (ctx->mark > ctx->ofs)
554     {
555         beg = ctx->ofs;         end = ctx->mark;
556     }
557     else
558     {
559         beg = ctx->mark;        end = ctx->ofs;
560     }
561     WCEL_SaveYank(ctx, beg, end);
562     WCEL_DeleteString(ctx, beg, end);
563     ctx->ofs = beg;
564 }
565
566 static void WCEL_DeletePrevChar(WCEL_Context* ctx)
567 {
568     if (ctx->ofs)
569     {
570         WCEL_DeleteString(ctx, ctx->ofs - 1, ctx->ofs);
571         ctx->ofs--;
572     }
573 }
574
575 static void WCEL_DeleteCurrChar(WCEL_Context* ctx)
576 {
577     if (ctx->ofs < ctx->len)
578         WCEL_DeleteString(ctx, ctx->ofs, ctx->ofs + 1);
579 }
580
581 static void WCEL_DeleteLeftWord(WCEL_Context* ctx)
582 {
583     int new_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs);
584     if (new_ofs != ctx->ofs)
585     {
586         WCEL_DeleteString(ctx, new_ofs, ctx->ofs);
587         ctx->ofs = new_ofs;
588     }
589 }
590
591 static void WCEL_DeleteRightWord(WCEL_Context* ctx)
592 {
593     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
594     if (new_ofs != ctx->ofs)
595     {
596         WCEL_DeleteString(ctx, ctx->ofs, new_ofs);
597     }
598 }
599
600 static void WCEL_MoveToPrevHist(WCEL_Context* ctx)
601 {
602     if (ctx->histPos) WCEL_MoveToHist(ctx, ctx->histPos - 1);
603 }
604
605 static void WCEL_MoveToNextHist(WCEL_Context* ctx)
606 {
607     if (ctx->histPos < ctx->histSize - 1) WCEL_MoveToHist(ctx, ctx->histPos + 1);
608 }
609
610 static void WCEL_MoveToFirstHist(WCEL_Context* ctx)
611 {
612     if (ctx->histPos != 0) WCEL_MoveToHist(ctx, 0);
613 }
614
615 static void WCEL_MoveToLastHist(WCEL_Context* ctx)
616 {
617     if (ctx->histPos != ctx->histSize - 1) WCEL_MoveToHist(ctx, ctx->histSize - 1);
618 }
619
620 static void WCEL_Redraw(WCEL_Context* ctx)
621 {
622     COORD       c = WCEL_GetCoord(ctx, ctx->len);
623     CHAR_INFO   ci;
624
625     WCEL_Update(ctx, 0, ctx->len);
626
627     ci.Char.UnicodeChar = ' ';
628     ci.Attributes = ctx->csbi.wAttributes;
629
630     CONSOLE_FillLineUniform(ctx->hConOut, c.X, c.Y, ctx->csbi.dwSize.X - c.X, &ci);
631 }
632
633 static void WCEL_RepeatCount(WCEL_Context* ctx)
634 {
635 #if 0
636 /* FIXME: wait untill all console code is in kernel32 */
637     INPUT_RECORD        ir;
638     unsigned            repeat = 0;
639
640     while (WCEL_Get(ctx, &ir, FALSE))
641     {
642         if (ir.EventType != KEY_EVENT) break;
643         if (ir.Event.KeyEvent.bKeyDown)
644         {
645             if ((ir.Event.KeyEvent.dwControlKeyState & ~(NUMLOCK_ON|SCROLLLOCK_ON|CAPSLOCK_ON)) != 0)
646                 break;
647             if (ir.Event.KeyEvent.uChar.UnicodeChar < '0' ||
648                 ir.Event.KeyEvent.uChar.UnicodeChar > '9')
649                 break;
650             repeat = repeat * 10 + ir.Event.KeyEvent.uChar.UnicodeChar - '0';
651         }
652         WCEL_Get(ctx, &ir, TRUE);
653     }
654     FIXME("=> %u\n", repeat);
655 #endif
656 }
657
658 /* ====================================================================
659  *
660  *              Key Maps
661  *
662  * ====================================================================*/
663
664 #define CTRL(x) ((x) - '@')
665 static KeyEntry StdKeyMap[] =
666 {
667     {/*BACK*/0x08,      WCEL_DeletePrevChar     },
668     {/*RETURN*/0x0d,    WCEL_Done               },
669     {/*DEL*/127,        WCEL_DeleteCurrChar     },
670     {   0,              NULL                    }
671 };
672
673 static KeyEntry Win32ExtraStdKeyMap[] =
674 {
675     {/*VK_F8*/   0x77,  WCEL_FindPrevInHist     },
676     {   0,              NULL                    }
677 };
678
679
680 static  KeyEntry EmacsKeyMapCtrl[] =
681 {
682     {   CTRL('@'),      WCEL_SetMark            },
683     {   CTRL('A'),      WCEL_MoveToBeg          },
684     {   CTRL('B'),      WCEL_MoveLeft           },
685     /* C: done in server */
686     {   CTRL('D'),      WCEL_DeleteCurrChar     },
687     {   CTRL('E'),      WCEL_MoveToEnd          },
688     {   CTRL('F'),      WCEL_MoveRight          },
689     {   CTRL('G'),      WCEL_Beep               },
690     {   CTRL('H'),      WCEL_DeletePrevChar     },
691     /* I: meaningless (or tab ???) */
692     {   CTRL('J'),      WCEL_Done               },
693     {   CTRL('K'),      WCEL_KillToEndOfLine    },
694     {   CTRL('L'),      WCEL_Redraw             },
695     {   CTRL('M'),      WCEL_Done               },
696     {   CTRL('N'),      WCEL_MoveToNextHist     },
697     /* O; insert line... meaningless */
698     {   CTRL('P'),      WCEL_MoveToPrevHist     },
699     /* Q: [NIY] quoting... */
700     /* R: [NIY] search backwards... */
701     /* S: [NIY] search forwards... */
702     {   CTRL('T'),      WCEL_TransposeChar      },
703     {   CTRL('U'),      WCEL_RepeatCount        },
704     /* V: paragraph down... meaningless */
705     {   CTRL('W'),      WCEL_KillMarkedZone     },
706     {   CTRL('X'),      WCEL_ExchangeMark       },
707     {   CTRL('Y'),      WCEL_Yank               },
708     /* Z: meaningless */
709     {   0,              NULL                    }
710 };
711
712 static KeyEntry EmacsKeyMapAlt[] =
713 {
714     {/*DEL*/127,        WCEL_DeleteLeftWord     },
715     {   '<',            WCEL_MoveToFirstHist    },
716     {   '>',            WCEL_MoveToLastHist     },
717     {   '?',            WCEL_Beep               },
718     {   'b',            WCEL_MoveToLeftWord     },
719     {   'c',            WCEL_CapitalizeWord     },
720     {   'd',            WCEL_DeleteRightWord    },
721     {   'f',            WCEL_MoveToRightWord    },
722     {   'l',            WCEL_LowerCaseWord      },
723     {   't',            WCEL_TransposeWords     },
724     {   'u',            WCEL_UpperCaseWord      },
725     {   'w',            WCEL_CopyMarkedZone     },
726     {   0,              NULL                    }
727 };
728
729 static KeyEntry EmacsKeyMapExtended[] =
730 {
731     {/*RETURN*/  0x0d,  WCEL_Done },
732     {/*VK_PRIOR*/0x21,  WCEL_MoveToPrevHist     },
733     {/*VK_NEXT*/ 0x22,  WCEL_MoveToNextHist     },
734     {/*VK_END*/  0x23,  WCEL_MoveToEnd          },
735     {/*VK_HOME*/ 0x24,  WCEL_MoveToBeg          },
736     {/*VK_RIGHT*/0x27,  WCEL_MoveRight          },
737     {/*VK_LEFT*/ 0x25,  WCEL_MoveLeft           },
738     {/*VK_DEL*/  0x2e,  WCEL_DeleteCurrChar     },
739     {   0,              NULL                    }
740 };
741
742 static KeyMap   EmacsKeyMap[] =
743 {
744     {0x00000000, 1, StdKeyMap},
745     {0x00000001, 1, EmacsKeyMapAlt},    /* left  alt  */
746     {0x00000002, 1, EmacsKeyMapAlt},    /* right alt  */
747     {0x00000004, 1, EmacsKeyMapCtrl},   /* left  ctrl */
748     {0x00000008, 1, EmacsKeyMapCtrl},   /* right ctrl */
749     {0x00000100, 0, EmacsKeyMapExtended},
750     {0,          0, 0}
751 };
752
753 static  KeyEntry Win32KeyMapExtended[] =
754 {
755     {/*VK_LEFT*/ 0x25,  WCEL_MoveLeft           },
756     {/*VK_RIGHT*/0x27,  WCEL_MoveRight          },
757     {/*VK_HOME*/ 0x24,  WCEL_MoveToBeg          },
758     {/*VK_END*/  0x23,  WCEL_MoveToEnd          },
759     {/*VK_UP*/   0x26,  WCEL_MoveToPrevHist     },
760     {/*VK_DOWN*/ 0x28,  WCEL_MoveToNextHist     },
761     {/*VK_DEL*/  0x2e,  WCEL_DeleteCurrChar     },
762     {   0,              NULL                    }
763 };
764
765 static  KeyEntry Win32KeyMapCtrlExtended[] =
766 {
767     {/*VK_LEFT*/ 0x25,  WCEL_MoveToLeftWord     },
768     {/*VK_RIGHT*/0x27,  WCEL_MoveToRightWord    },
769     {/*VK_END*/  0x23,  WCEL_KillToEndOfLine    },
770     {   0,              NULL                    }
771 };
772
773 KeyMap  Win32KeyMap[] =
774 {
775     {0x00000000, 1, StdKeyMap},
776     {0x00000000, 0, Win32ExtraStdKeyMap},
777     {0x00000100, 0, Win32KeyMapExtended},
778     {0x00000104, 0, Win32KeyMapCtrlExtended},
779     {0x00000108, 0, Win32KeyMapCtrlExtended},
780     {0,          0, 0}
781 };
782 #undef CTRL
783
784 /* ====================================================================
785  *
786  *              Read line master function
787  *
788  * ====================================================================*/
789
790 WCHAR* CONSOLE_Readline(HANDLE hConsoleIn)
791 {
792     WCEL_Context        ctx;
793     INPUT_RECORD        ir;
794     KeyMap*             km;
795     KeyEntry*           ke;
796     unsigned            ofs;
797     void                (*func)(struct WCEL_Context* ctx);
798     DWORD               ks;
799     int                 use_emacs;
800
801     memset(&ctx, 0, sizeof(ctx));
802     ctx.hConIn = hConsoleIn;
803     WCEL_HistoryInit(&ctx);
804
805     if (!CONSOLE_GetEditionMode(hConsoleIn, &use_emacs))
806         use_emacs = 0;
807
808     if ((ctx.hConOut = CreateFileA("CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, NULL,
809                                     OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE ||
810         !GetConsoleScreenBufferInfo(ctx.hConOut, &ctx.csbi))
811         return NULL;
812     ctx.can_wrap = (GetConsoleMode(ctx.hConOut, &ks) && (ks & ENABLE_WRAP_AT_EOL_OUTPUT)) ? 1 : 0;
813
814     if (!WCEL_Grow(&ctx, 1))
815     {
816         CloseHandle(ctx.hConOut);
817         return NULL;
818     }
819     ctx.line[0] = 0;
820
821 /* EPP     WCEL_Dump(&ctx, "init"); */
822
823     while (!ctx.done && !ctx.error && WCEL_Get(&ctx, &ir))
824     {
825         if (ir.EventType != KEY_EVENT || !ir.Event.KeyEvent.bKeyDown) continue;
826         TRACE("key%s repeatCount=%u, keyCode=%02x scanCode=%02x char=%02x keyState=%08lx\n",
827               ir.Event.KeyEvent.bKeyDown ? "Down" : "Up  ", ir.Event.KeyEvent.wRepeatCount,
828               ir.Event.KeyEvent.wVirtualKeyCode, ir.Event.KeyEvent.wVirtualScanCode,
829               ir.Event.KeyEvent.uChar.UnicodeChar, ir.Event.KeyEvent.dwControlKeyState);
830
831 /* EPP          WCEL_Dump(&ctx, "before func"); */
832         ofs = ctx.ofs;
833         /* mask out some bits which don't interest us */
834         ks = ir.Event.KeyEvent.dwControlKeyState & ~(NUMLOCK_ON|SCROLLLOCK_ON|CAPSLOCK_ON);
835
836         func = NULL;
837         for (km = (use_emacs) ? EmacsKeyMap : Win32KeyMap; km->entries != NULL; km++)
838         {
839             if (km->keyState != ks)
840                 continue;
841             if (km->chkChar)
842             {
843                 for (ke = &km->entries[0]; ke->func != 0; ke++)
844                     if (ke->val == ir.Event.KeyEvent.uChar.UnicodeChar) break;
845             }
846             else
847             {
848                 for (ke = &km->entries[0]; ke->func != 0; ke++)
849                     if (ke->val == ir.Event.KeyEvent.wVirtualKeyCode) break;
850
851             }
852             if (ke->func)
853             {
854                 func = ke->func;
855                 break;
856             }
857         }
858
859         if (func)
860             (func)(&ctx);
861         else if (!(ir.Event.KeyEvent.dwControlKeyState & (ENHANCED_KEY|LEFT_ALT_PRESSED)))
862             WCEL_InsertChar(&ctx, ir.Event.KeyEvent.uChar.UnicodeChar);
863         else TRACE("Dropped event\n");
864
865 /* EPP         WCEL_Dump(&ctx, "after func"); */
866         if (ctx.ofs != ofs)
867             SetConsoleCursorPosition(ctx.hConOut, WCEL_GetCoord(&ctx, ctx.ofs));
868     }
869     if (ctx.error)
870     {
871         HeapFree(GetProcessHeap(), 0, ctx.line);
872         ctx.line = NULL;
873     }
874     WCEL_FreeYank(&ctx);
875     if (ctx.line)
876         CONSOLE_AppendHistory(ctx.line);
877
878     CloseHandle(ctx.hConOut);
879     if (ctx.histCurr) HeapFree(GetProcessHeap(), 0, ctx.histCurr);
880     return ctx.line;
881 }