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