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