Fixed some issues found by winapi_check.
[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 }
147
148 /* ====================================================================
149  *
150  * context manipulation functions
151  *
152  * ====================================================================*/
153
154 static BOOL WCEL_Grow(WCEL_Context* ctx, size_t len)
155 {
156     if (!WCEL_IsSingleLine(ctx, len) && !ctx->can_wrap)
157     {
158         FIXME("Mode doesn't allow to wrap. However, we should allow to overwrite current string\n");
159         return FALSE;
160     }
161
162     if (ctx->len + len >= ctx->alloc)
163     {
164         WCHAR*  newline;
165         size_t  newsize;
166
167         /* round up size to 32 byte-WCHAR boundary */
168         newsize = (ctx->len + len + 1 + 31) & ~31;
169         newline = HeapReAlloc(GetProcessHeap(), 0, ctx->line, sizeof(WCHAR) * newsize);
170         if (!newline) return FALSE;
171         ctx->line = newline;
172         ctx->alloc = newsize;
173     }
174     return TRUE;
175 }
176
177 static void WCEL_DeleteString(WCEL_Context* ctx, int beg, int end)
178 {
179     unsigned    str_len = end - beg;
180     COORD       cbeg = WCEL_GetCoord(ctx, ctx->len - str_len);
181     COORD       cend = WCEL_GetCoord(ctx, ctx->len);
182     CHAR_INFO   ci;
183
184     if (end < ctx->len)
185         memmove(&ctx->line[beg], &ctx->line[end], (ctx->len - end) * sizeof(WCHAR));
186     /* we need to clean from ctx->len - str_len to ctx->len */
187
188     ci.Char.UnicodeChar = ' ';
189     ci.Attributes = ctx->csbi.wAttributes;
190
191     if (cbeg.Y == cend.Y)
192     {
193         /* partial erase of sole line */
194         CONSOLE_FillLineUniform(ctx->hConOut, cbeg.X, cbeg.Y,
195                                 cend.X - cbeg.X, &ci);
196     }
197     else
198     {
199         int         i;
200         /* erase til eol on first line */
201         CONSOLE_FillLineUniform(ctx->hConOut, cbeg.X, cbeg.Y,
202                                 ctx->csbi.dwSize.X - cbeg.X, &ci);
203         /* completly erase all the others (full lines) */
204         for (i = cbeg.Y + 1; i < cend.Y; i++)
205             CONSOLE_FillLineUniform(ctx->hConOut, 0, i, ctx->csbi.dwSize.X, &ci);
206         /* erase from beg of line until last pos on last line */
207         CONSOLE_FillLineUniform(ctx->hConOut, 0, cend.Y, cend.X, &ci);
208     }
209     ctx->len -= str_len;
210     WCEL_Update(ctx, 0, ctx->len);
211     ctx->line[ctx->len] = 0;
212 }
213
214 static void WCEL_InsertString(WCEL_Context* ctx, const WCHAR* str)
215 {
216     size_t      len = lstrlenW(str);
217
218     if (!len || !WCEL_Grow(ctx, len)) return;
219     if (ctx->len > ctx->ofs)
220         memmove(&ctx->line[ctx->ofs + len], &ctx->line[ctx->ofs], (ctx->len - ctx->ofs) * sizeof(WCHAR));
221     memcpy(&ctx->line[ctx->ofs], str, len * sizeof(WCHAR));
222     ctx->len += len;
223     ctx->line[ctx->len] = 0;
224     WCEL_Update(ctx, ctx->ofs, ctx->len - ctx->ofs);
225
226     ctx->ofs += len;
227 }
228
229 static void WCEL_InsertChar(WCEL_Context* ctx, WCHAR c)
230 {
231     WCHAR       buffer[2];
232
233     /* do not insert 0..31 control characters */
234     if (c < ' ' && c != '\t') return;
235
236     buffer[0] = c;
237     buffer[1] = 0;
238     WCEL_InsertString(ctx, buffer);
239 }
240
241 static void WCEL_FreeYank(WCEL_Context* ctx)
242 {
243     if (ctx->yanked)
244     {
245         HeapFree(GetProcessHeap(), 0, ctx->yanked);
246         ctx->yanked = NULL;
247     }
248 }
249
250 static void WCEL_SaveYank(WCEL_Context* ctx, int beg, int end)
251 {
252     int len = end - beg;
253     if (len <= 0) return;
254
255     WCEL_FreeYank(ctx);
256     ctx->yanked = HeapReAlloc(GetProcessHeap(), 0, ctx->yanked, (len + 1) * sizeof(WCHAR));
257     if (!ctx->yanked) return;
258     memcpy(ctx->yanked, &ctx->line[beg], len * sizeof(WCHAR));
259     ctx->yanked[len] = 0;
260 }
261
262 /* FIXME NTDLL doesn't export iswalnum, and I don't want to link in msvcrt when most
263  * of the data lay in unicode lib
264  */
265 static inline BOOL WCEL_iswalnum(WCHAR wc)
266 {
267     return get_char_typeW(wc) & (C1_ALPHA|C1_DIGIT|C1_LOWER|C1_UPPER);
268 }
269
270 static int WCEL_GetLeftWordTransition(WCEL_Context* ctx, int ofs)
271 {
272     ofs--;
273     while (ofs >= 0 && !WCEL_iswalnum(ctx->line[ofs])) ofs--;
274     while (ofs >= 0 && WCEL_iswalnum(ctx->line[ofs])) ofs--;
275     if (ofs >= 0) ofs++;
276     return max(ofs, 0);
277 }
278
279 static int WCEL_GetRightWordTransition(WCEL_Context* ctx, int ofs)
280 {
281     ofs++;
282     while (ofs <= ctx->len && WCEL_iswalnum(ctx->line[ofs])) ofs++;
283     while (ofs <= ctx->len && !WCEL_iswalnum(ctx->line[ofs])) ofs++;
284     return min(ofs, ctx->len);
285 }
286
287 static WCHAR* WCEL_GetHistory(WCEL_Context* ctx, int idx)
288 {
289     WCHAR*      ptr;
290
291     if (idx == ctx->histSize - 1)
292     {
293         ptr = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(ctx->histCurr) + 1) * sizeof(WCHAR));
294         lstrcpyW(ptr, ctx->histCurr);
295     }
296     else
297     {
298         int     len = CONSOLE_GetHistory(idx, NULL, 0);
299
300         if ((ptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
301         {
302             CONSOLE_GetHistory(idx, ptr, len);
303         }
304     }
305     return ptr;
306 }
307
308 static void     WCEL_HistoryInit(WCEL_Context* ctx)
309 {
310     ctx->histPos  = CONSOLE_GetNumHistoryEntries();
311     ctx->histSize = ctx->histPos + 1;
312     ctx->histCurr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WCHAR));
313 }
314
315 static void    WCEL_MoveToHist(WCEL_Context* ctx, int idx)
316 {
317     WCHAR*      data = WCEL_GetHistory(ctx, idx);
318     int         len = lstrlenW(data) + 1;
319
320     /* save current line edition for recall when needed (FIXME seems broken to me) */
321     if (ctx->histPos == ctx->histSize - 1)
322     {
323         if (ctx->histCurr) HeapFree(GetProcessHeap(), 0, ctx->histCurr);
324         ctx->histCurr = HeapAlloc(GetProcessHeap(), 0, (ctx->len + 1) * sizeof(WCHAR));
325         memcpy(ctx->histCurr, ctx->line, (ctx->len + 1) * sizeof(WCHAR));
326     }
327     /* need to clean also the screen if new string is shorter than old one */
328     WCEL_DeleteString(ctx, 0, ctx->len);
329     ctx->ofs = 0;
330     /* insert new string */
331     if (WCEL_Grow(ctx, len))
332     {
333         WCEL_InsertString(ctx, data);
334         HeapFree(GetProcessHeap(), 0, data);
335         ctx->histPos = idx;
336     }
337 }
338
339 static void    WCEL_FindPrevInHist(WCEL_Context* ctx)
340 {
341     int startPos = ctx->histPos;
342     WCHAR*      data;
343     int         len, oldofs;
344
345     if (ctx->histPos && ctx->histPos == ctx->histSize) {
346         startPos--;
347         ctx->histPos--;
348     }
349
350     do {
351        data = WCEL_GetHistory(ctx, ctx->histPos);
352
353        if (ctx->histPos) ctx->histPos--;
354        else ctx->histPos = (ctx->histSize-1);
355
356        len = lstrlenW(data) + 1;
357        if ((len >= ctx->ofs) &&
358            (memcmp(ctx->line, data, ctx->ofs * sizeof(WCHAR)) == 0)) {
359
360            /* need to clean also the screen if new string is shorter than old one */
361            WCEL_DeleteString(ctx, 0, ctx->len);
362
363            if (WCEL_Grow(ctx, len))
364            {
365               oldofs = ctx->ofs;
366               ctx->ofs = 0;
367               WCEL_InsertString(ctx, data);
368               ctx->ofs = oldofs;
369               SetConsoleCursorPosition(ctx->hConOut, WCEL_GetCoord(ctx, ctx->ofs));
370               HeapFree(GetProcessHeap(), 0, data);
371               return;
372            }
373        }
374     } while (ctx->histPos != startPos);
375
376     return;
377 }
378
379 /* ====================================================================
380  *
381  * basic edition functions
382  *
383  * ====================================================================*/
384
385 static void WCEL_Done(WCEL_Context* ctx)
386 {
387     WCHAR       nl = '\n';
388     if (!WCEL_Grow(ctx, 1)) return;
389     ctx->line[ctx->len++] = '\n';
390     ctx->line[ctx->len] = 0;
391     WriteConsoleW(ctx->hConOut, &nl, 1, NULL, NULL);
392     ctx->done = 1;
393 }
394
395 static void WCEL_MoveLeft(WCEL_Context* ctx)
396 {
397     if (ctx->ofs > 0) ctx->ofs--;
398 }
399
400 static void WCEL_MoveRight(WCEL_Context* ctx)
401 {
402     if (ctx->ofs < ctx->len) ctx->ofs++;
403 }
404
405 static void WCEL_MoveToLeftWord(WCEL_Context* ctx)
406 {
407     int new_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs);
408     if (new_ofs != ctx->ofs) ctx->ofs = new_ofs;
409 }
410
411 static void WCEL_MoveToRightWord(WCEL_Context* ctx)
412 {
413     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
414     if (new_ofs != ctx->ofs) ctx->ofs = new_ofs;
415 }
416
417 static void WCEL_MoveToBeg(WCEL_Context* ctx)
418 {
419     ctx->ofs = 0;
420 }
421
422 static void WCEL_MoveToEnd(WCEL_Context* ctx)
423 {
424     ctx->ofs = ctx->len;
425 }
426
427 static void WCEL_SetMark(WCEL_Context* ctx)
428 {
429     ctx->mark = ctx->ofs;
430 }
431
432 static void WCEL_ExchangeMark(WCEL_Context* ctx)
433 {
434     unsigned tmp;
435
436     if (ctx->mark > ctx->len) return;
437     tmp = ctx->ofs;
438     ctx->ofs = ctx->mark;
439     ctx->mark = tmp;
440 }
441
442 static void WCEL_CopyMarkedZone(WCEL_Context* ctx)
443 {
444     unsigned beg, end;
445
446     if (ctx->mark > ctx->len || ctx->mark == ctx->ofs) return;
447     if (ctx->mark > ctx->ofs)
448     {
449         beg = ctx->ofs;         end = ctx->mark;
450     }
451     else
452     {
453         beg = ctx->mark;        end = ctx->ofs;
454     }
455     WCEL_SaveYank(ctx, beg, end);
456 }
457
458 static void WCEL_TransposeChar(WCEL_Context* ctx)
459 {
460     WCHAR       c;
461
462     if (!ctx->ofs || ctx->ofs == ctx->len) return;
463
464     c = ctx->line[ctx->ofs];
465     ctx->line[ctx->ofs] = ctx->line[ctx->ofs - 1];
466     ctx->line[ctx->ofs - 1] = c;
467
468     WCEL_Update(ctx, ctx->ofs - 1, 2);
469     ctx->ofs++;
470 }
471
472 static void WCEL_TransposeWords(WCEL_Context* ctx)
473 {
474     int left_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs),
475         right_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
476     if (left_ofs < ctx->ofs && right_ofs > ctx->ofs)
477     {
478         unsigned len_r = right_ofs - ctx->ofs;
479         unsigned len_l = ctx->ofs - left_ofs;
480
481         char*   tmp = HeapAlloc(GetProcessHeap(), 0, len_r * sizeof(WCHAR));
482         if (!tmp) return;
483
484         memcpy(tmp, &ctx->line[ctx->ofs], len_r * sizeof(WCHAR));
485         memmove(&ctx->line[left_ofs + len_r], &ctx->line[left_ofs], len_l * sizeof(WCHAR));
486         memcpy(&ctx->line[left_ofs], tmp, len_r * sizeof(WCHAR));
487
488         HeapFree(GetProcessHeap(), 0, tmp);
489         WCEL_Update(ctx, left_ofs, len_l + len_r);
490         ctx->ofs = right_ofs;
491     }
492 }
493
494 static void WCEL_LowerCaseWord(WCEL_Context* ctx)
495 {
496     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
497     if (new_ofs != ctx->ofs)
498     {
499         int     i;
500         for (i = ctx->ofs; i <= new_ofs; i++)
501             ctx->line[i] = tolowerW(ctx->line[i]);
502         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
503         ctx->ofs = new_ofs;
504     }
505 }
506
507 static void WCEL_UpperCaseWord(WCEL_Context* ctx)
508 {
509     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
510     if (new_ofs != ctx->ofs)
511     {
512         int     i;
513         for (i = ctx->ofs; i <= new_ofs; i++)
514             ctx->line[i] = toupperW(ctx->line[i]);
515         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
516         ctx->ofs = new_ofs;
517     }
518 }
519
520 static void WCEL_CapitalizeWord(WCEL_Context* ctx)
521 {
522     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
523     if (new_ofs != ctx->ofs)
524     {
525         int     i;
526
527         ctx->line[ctx->ofs] = toupperW(ctx->line[ctx->ofs]);
528         for (i = ctx->ofs + 1; i <= new_ofs; i++)
529             ctx->line[i] = tolowerW(ctx->line[i]);
530         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
531         ctx->ofs = new_ofs;
532     }
533 }
534
535 static void WCEL_Yank(WCEL_Context* ctx)
536 {
537     WCEL_InsertString(ctx, ctx->yanked);
538 }
539
540 static void WCEL_KillToEndOfLine(WCEL_Context* ctx)
541 {
542     WCEL_SaveYank(ctx, ctx->ofs, ctx->len);
543     WCEL_DeleteString(ctx, ctx->ofs, ctx->len);
544 }
545
546 static void WCEL_KillMarkedZone(WCEL_Context* ctx)
547 {
548     unsigned beg, end;
549
550     if (ctx->mark > ctx->len || ctx->mark == ctx->ofs) return;
551     if (ctx->mark > ctx->ofs)
552     {
553         beg = ctx->ofs;         end = ctx->mark;
554     }
555     else
556     {
557         beg = ctx->mark;        end = ctx->ofs;
558     }
559     WCEL_SaveYank(ctx, beg, end);
560     WCEL_DeleteString(ctx, beg, end);
561     ctx->ofs = beg;
562 }
563
564 static void WCEL_DeletePrevChar(WCEL_Context* ctx)
565 {
566     if (ctx->ofs)
567     {
568         WCEL_DeleteString(ctx, ctx->ofs - 1, ctx->ofs);
569         ctx->ofs--;
570     }
571 }
572
573 static void WCEL_DeleteCurrChar(WCEL_Context* ctx)
574 {
575     if (ctx->ofs < ctx->len)
576         WCEL_DeleteString(ctx, ctx->ofs, ctx->ofs + 1);
577 }
578
579 static void WCEL_DeleteLeftWord(WCEL_Context* ctx)
580 {
581     int new_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs);
582     if (new_ofs != ctx->ofs)
583     {
584         WCEL_DeleteString(ctx, new_ofs, ctx->ofs);
585         ctx->ofs = new_ofs;
586     }
587 }
588
589 static void WCEL_DeleteRightWord(WCEL_Context* ctx)
590 {
591     int new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
592     if (new_ofs != ctx->ofs)
593     {
594         WCEL_DeleteString(ctx, ctx->ofs, new_ofs);
595     }
596 }
597
598 static void WCEL_MoveToPrevHist(WCEL_Context* ctx)
599 {
600     if (ctx->histPos) WCEL_MoveToHist(ctx, ctx->histPos - 1);
601 }
602
603 static void WCEL_MoveToNextHist(WCEL_Context* ctx)
604 {
605     if (ctx->histPos < ctx->histSize - 1) WCEL_MoveToHist(ctx, ctx->histPos + 1);
606 }
607
608 static void WCEL_MoveToFirstHist(WCEL_Context* ctx)
609 {
610     if (ctx->histPos != 0) WCEL_MoveToHist(ctx, 0);
611 }
612
613 static void WCEL_MoveToLastHist(WCEL_Context* ctx)
614 {
615     if (ctx->histPos != ctx->histSize - 1) WCEL_MoveToHist(ctx, ctx->histSize - 1);
616 }
617
618 static void WCEL_Redraw(WCEL_Context* ctx)
619 {
620     COORD       c = WCEL_GetCoord(ctx, ctx->len);
621     CHAR_INFO   ci;
622
623     WCEL_Update(ctx, 0, ctx->len);
624
625     ci.Char.UnicodeChar = ' ';
626     ci.Attributes = ctx->csbi.wAttributes;
627
628     CONSOLE_FillLineUniform(ctx->hConOut, c.X, c.Y, ctx->csbi.dwSize.X - c.X, &ci);
629 }
630
631 static void WCEL_RepeatCount(WCEL_Context* ctx)
632 {
633 #if 0
634 /* FIXME: wait untill all console code is in kernel32 */
635     INPUT_RECORD        ir;
636     unsigned            repeat = 0;
637
638     while (WCEL_Get(ctx, &ir, FALSE))
639     {
640         if (ir.EventType != KEY_EVENT) break;
641         if (ir.Event.KeyEvent.bKeyDown)
642         {
643             if ((ir.Event.KeyEvent.dwControlKeyState & ~(NUMLOCK_ON|SCROLLLOCK_ON|CAPSLOCK_ON)) != 0)
644                 break;
645             if (ir.Event.KeyEvent.uChar.UnicodeChar < '0' ||
646                 ir.Event.KeyEvent.uChar.UnicodeChar > '9')
647                 break;
648             repeat = repeat * 10 + ir.Event.KeyEvent.uChar.UnicodeChar - '0';
649         }
650         WCEL_Get(ctx, &ir, TRUE);
651     }
652     FIXME("=> %u\n", repeat);
653 #endif
654 }
655
656 /* ====================================================================
657  *
658  *              Key Maps
659  *
660  * ====================================================================*/
661
662 #define CTRL(x) ((x) - '@')
663 static KeyEntry StdKeyMap[] =
664 {
665     {/*BACK*/0x08,      WCEL_DeletePrevChar     },
666     {/*RETURN*/0x0d,    WCEL_Done               },
667     {/*DEL*/127,        WCEL_DeleteCurrChar     },
668     {   0,              NULL                    }
669 };
670
671 static KeyEntry Win32ExtraStdKeyMap[] =
672 {
673     {/*VK_F8*/   0x77,  WCEL_FindPrevInHist     },
674     {   0,              NULL                    }
675 };
676
677
678 static  KeyEntry EmacsKeyMapCtrl[] =
679 {
680     {   CTRL('@'),      WCEL_SetMark            },
681     {   CTRL('A'),      WCEL_MoveToBeg          },
682     {   CTRL('B'),      WCEL_MoveLeft           },
683     /* C: done in server */
684     {   CTRL('D'),      WCEL_DeleteCurrChar     },
685     {   CTRL('E'),      WCEL_MoveToEnd          },
686     {   CTRL('F'),      WCEL_MoveRight          },
687     {   CTRL('G'),      WCEL_Beep               },
688     {   CTRL('H'),      WCEL_DeletePrevChar     },
689     /* I: meaningless (or tab ???) */
690     {   CTRL('J'),      WCEL_Done               },
691     {   CTRL('K'),      WCEL_KillToEndOfLine    },
692     {   CTRL('L'),      WCEL_Redraw             },
693     {   CTRL('M'),      WCEL_Done               },
694     {   CTRL('N'),      WCEL_MoveToNextHist     },
695     /* O; insert line... meaningless */
696     {   CTRL('P'),      WCEL_MoveToPrevHist     },
697     /* Q: [NIY] quoting... */
698     /* R: [NIY] search backwards... */
699     /* S: [NIY] search forwards... */
700     {   CTRL('T'),      WCEL_TransposeChar      },
701     {   CTRL('U'),      WCEL_RepeatCount        },
702     /* V: paragraph down... meaningless */
703     {   CTRL('W'),      WCEL_KillMarkedZone     },
704     {   CTRL('X'),      WCEL_ExchangeMark       },
705     {   CTRL('Y'),      WCEL_Yank               },
706     /* Z: meaningless */
707     {   0,              NULL                    }
708 };
709
710 static KeyEntry EmacsKeyMapAlt[] =
711 {
712     {/*DEL*/127,        WCEL_DeleteLeftWord     },
713     {   '<',            WCEL_MoveToFirstHist    },
714     {   '>',            WCEL_MoveToLastHist     },
715     {   '?',            WCEL_Beep               },
716     {   'b',            WCEL_MoveToLeftWord     },
717     {   'c',            WCEL_CapitalizeWord     },
718     {   'd',            WCEL_DeleteRightWord    },
719     {   'f',            WCEL_MoveToRightWord    },
720     {   'l',            WCEL_LowerCaseWord      },
721     {   't',            WCEL_TransposeWords     },
722     {   'u',            WCEL_UpperCaseWord      },
723     {   'w',            WCEL_CopyMarkedZone     },
724     {   0,              NULL                    }
725 };
726
727 static KeyEntry EmacsKeyMapExtended[] =
728 {
729     {/*RETURN*/  0x0d,  WCEL_Done },
730     {/*VK_PRIOR*/0x21,  WCEL_MoveToPrevHist     },
731     {/*VK_NEXT*/ 0x22,  WCEL_MoveToNextHist     },
732     {/*VK_END*/  0x23,  WCEL_MoveToEnd          },
733     {/*VK_HOME*/ 0x24,  WCEL_MoveToBeg          },
734     {/*VK_RIGHT*/0x27,  WCEL_MoveRight          },
735     {/*VK_LEFT*/ 0x25,  WCEL_MoveLeft           },
736     {/*VK_DEL*/  0x2e,  WCEL_DeleteCurrChar     },
737     {   0,              NULL                    }
738 };
739
740 static KeyMap   EmacsKeyMap[] =
741 {
742     {0x00000000, 1, StdKeyMap},
743     {0x00000001, 1, EmacsKeyMapAlt},    /* left  alt  */
744     {0x00000002, 1, EmacsKeyMapAlt},    /* right alt  */
745     {0x00000004, 1, EmacsKeyMapCtrl},   /* left  ctrl */
746     {0x00000008, 1, EmacsKeyMapCtrl},   /* right ctrl */
747     {0x00000100, 0, EmacsKeyMapExtended},
748     {0,          0, 0}
749 };
750
751 static  KeyEntry Win32KeyMapExtended[] =
752 {
753     {/*VK_LEFT*/ 0x25,  WCEL_MoveLeft           },
754     {/*VK_RIGHT*/0x27,  WCEL_MoveRight          },
755     {/*VK_HOME*/ 0x24,  WCEL_MoveToBeg          },
756     {/*VK_END*/  0x23,  WCEL_MoveToEnd          },
757     {/*VK_UP*/   0x26,  WCEL_MoveToPrevHist     },
758     {/*VK_DOWN*/ 0x28,  WCEL_MoveToNextHist     },
759     {/*VK_DEL*/  0x2e,  WCEL_DeleteCurrChar     },
760     {   0,              NULL                    }
761 };
762
763 static  KeyEntry Win32KeyMapCtrlExtended[] =
764 {
765     {/*VK_LEFT*/ 0x25,  WCEL_MoveToLeftWord     },
766     {/*VK_RIGHT*/0x27,  WCEL_MoveToRightWord    },
767     {/*VK_END*/  0x23,  WCEL_KillToEndOfLine    },
768     {   0,              NULL                    }
769 };
770
771 KeyMap  Win32KeyMap[] =
772 {
773     {0x00000000, 1, StdKeyMap},
774     {0x00000000, 0, Win32ExtraStdKeyMap},
775     {0x00000100, 0, Win32KeyMapExtended},
776     {0x00000104, 0, Win32KeyMapCtrlExtended},
777     {0x00000108, 0, Win32KeyMapCtrlExtended},
778     {0,          0, 0}
779 };
780 #undef CTRL
781
782 /* ====================================================================
783  *
784  *              Read line master function
785  *
786  * ====================================================================*/
787
788 WCHAR* CONSOLE_Readline(HANDLE hConsoleIn, int use_emacs)
789 {
790     WCEL_Context        ctx;
791     INPUT_RECORD        ir;
792     KeyMap*             km;
793     KeyEntry*           ke;
794     unsigned            ofs;
795     void                (*func)(struct WCEL_Context* ctx);
796     DWORD               ks;
797
798     memset(&ctx, 0, sizeof(ctx));
799     ctx.hConIn = hConsoleIn;
800     WCEL_HistoryInit(&ctx);
801     if ((ctx.hConOut = CreateFileA("CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, NULL,
802                                     OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE ||
803         !GetConsoleScreenBufferInfo(ctx.hConOut, &ctx.csbi))
804         return NULL;
805     ctx.can_wrap = (GetConsoleMode(ctx.hConOut, &ks) && (ks & ENABLE_WRAP_AT_EOL_OUTPUT)) ? 1 : 0;
806
807     if (!WCEL_Grow(&ctx, 1))
808     {
809         CloseHandle(ctx.hConOut);
810         return NULL;
811     }
812     ctx.line[0] = 0;
813
814 /* EPP     WCEL_Dump(&ctx, "init"); */
815
816     while (!ctx.done && !ctx.error && WCEL_Get(&ctx, &ir))
817     {
818         if (ir.EventType != KEY_EVENT || !ir.Event.KeyEvent.bKeyDown) continue;
819         TRACE("key%s repeatCount=%u, keyCode=%02x scanCode=%02x char=%02x keyState=%08lx\n",
820               ir.Event.KeyEvent.bKeyDown ? "Down" : "Up  ", ir.Event.KeyEvent.wRepeatCount,
821               ir.Event.KeyEvent.wVirtualKeyCode, ir.Event.KeyEvent.wVirtualScanCode,
822               ir.Event.KeyEvent.uChar.UnicodeChar, ir.Event.KeyEvent.dwControlKeyState);
823
824 /* EPP          WCEL_Dump(&ctx, "before func"); */
825         ofs = ctx.ofs;
826         /* mask out some bits which don't interest us */
827         ks = ir.Event.KeyEvent.dwControlKeyState & ~(NUMLOCK_ON|SCROLLLOCK_ON|CAPSLOCK_ON);
828
829         func = NULL;
830         for (km = (use_emacs) ? EmacsKeyMap : Win32KeyMap; km->entries != NULL; km++)
831         {
832             if (km->keyState != ks)
833                 continue;
834             if (km->chkChar)
835             {
836                 for (ke = &km->entries[0]; ke->func != 0; ke++)
837                     if (ke->val == ir.Event.KeyEvent.uChar.UnicodeChar) break;
838             }
839             else
840             {
841                 for (ke = &km->entries[0]; ke->func != 0; ke++)
842                     if (ke->val == ir.Event.KeyEvent.wVirtualKeyCode) break;
843
844             }
845             if (ke->func)
846             {
847                 func = ke->func;
848                 break;
849             }
850         }
851
852         if (func)
853             (func)(&ctx);
854         else if (!(ir.Event.KeyEvent.dwControlKeyState & (ENHANCED_KEY|LEFT_ALT_PRESSED)))
855             WCEL_InsertChar(&ctx, ir.Event.KeyEvent.uChar.UnicodeChar);
856         else TRACE("Dropped event\n");
857
858 /* EPP         WCEL_Dump(&ctx, "after func"); */
859         if (ctx.ofs != ofs)
860             SetConsoleCursorPosition(ctx.hConOut, WCEL_GetCoord(&ctx, ctx.ofs));
861     }
862     if (ctx.error)
863     {
864         HeapFree(GetProcessHeap(), 0, ctx.line);
865         ctx.line = NULL;
866     }
867     WCEL_FreeYank(&ctx);
868     if (ctx.line)
869         CONSOLE_AppendHistory(ctx.line);
870
871     CloseHandle(ctx.hConOut);
872     if (ctx.histCurr) HeapFree(GetProcessHeap(), 0, ctx.histCurr);
873     return ctx.line;
874 }