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