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