Calling ValidateRect or ValidateRgn on a windows also validates the
[wine] / dlls / user / edit.c
1 /*
2  *      Edit control
3  *
4  *      Copyright  David W. Metcalfe, 1994
5  *      Copyright  William Magro, 1995, 1996
6  *      Copyright  Frans van Dorsselaer, 1996, 1997
7  *
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  * NOTES
24  *
25  * This code was audited for completeness against the documented features
26  * of Comctl32.dll version 6.0 on Oct. 8, 2004, by Dimitrie O. Paun.
27  * 
28  * Unless otherwise noted, we believe this code to be complete, as per
29  * the specification mentioned above.
30  * If you discover missing features, or bugs, please note them below.
31  *
32  * TODO:
33  *   - EDITBALLOONTIP structure
34  *   - EM_GETCUEBANNER/Edit_GetCueBannerText
35  *   - EM_HIDEBALLOONTIP/Edit_HideBalloonTip
36  *   - EM_SETCUEBANNER/Edit_SetCueBannerText
37  *   - EM_SHOWBALLOONTIP/Edit_ShowBalloonTip
38  *   - EM_GETIMESTATUS, EM_SETIMESTATUS
39  *   - EN_ALIGN_LTR_EC
40  *   - EN_ALIGN_RTL_EC
41  *   - ES_OEMCONVERT
42  *   -!ES_AUTOVSCROLL (every multi line control *is* auto vscroll)
43  *   -!ES_AUTOHSCROLL (every single line control *is* auto hscroll)
44  *   
45  * When there is no autoscrolling, the control should first check whether
46  * the new text would fit.  If not, an EN_MAXTEXT should be sent.
47  * However, currently this would require the actual change to be made,
48  * then call EDIT_BuildLineDefs() and then find out that the new text doesn't
49  * fit.  After all this, things should be put back in the state before the
50  * changes. Note that for multi line controls !ES_AUTOHSCROLL works : wordwrap.
51  *
52  */
53
54 #include "config.h"
55
56 #include <stdarg.h>
57 #include <string.h>
58 #include <stdlib.h>
59
60 #include "windef.h"
61 #include "winbase.h"
62 #include "winnt.h"
63 #include "wownt32.h"
64 #include "win.h"
65 #include "wine/winbase16.h"
66 #include "wine/winuser16.h"
67 #include "wine/unicode.h"
68 #include "controls.h"
69 #include "local.h"
70 #include "message.h"
71 #include "user_private.h"
72 #include "wine/debug.h"
73
74 WINE_DEFAULT_DEBUG_CHANNEL(edit);
75 WINE_DECLARE_DEBUG_CHANNEL(combo);
76 WINE_DECLARE_DEBUG_CHANNEL(relay);
77
78 #define BUFLIMIT_MULTI          65534   /* maximum buffer size (not including '\0')
79                                            FIXME: BTW, new specs say 65535 (do you dare ???) */
80 #define BUFLIMIT_SINGLE         32766   /* maximum buffer size (not including '\0') */
81 #define GROWLENGTH              32      /* buffers granularity in bytes: must be power of 2 */
82 #define ROUND_TO_GROW(size)     (((size) + (GROWLENGTH - 1)) & ~(GROWLENGTH - 1))
83 #define HSCROLL_FRACTION        3       /* scroll window by 1/3 width */
84
85 /*
86  *      extra flags for EDITSTATE.flags field
87  */
88 #define EF_MODIFIED             0x0001  /* text has been modified */
89 #define EF_FOCUSED              0x0002  /* we have input focus */
90 #define EF_UPDATE               0x0004  /* notify parent of changed state */
91 #define EF_VSCROLL_TRACK        0x0008  /* don't SetScrollPos() since we are tracking the thumb */
92 #define EF_HSCROLL_TRACK        0x0010  /* don't SetScrollPos() since we are tracking the thumb */
93 #define EF_AFTER_WRAP           0x0080  /* the caret is displayed after the last character of a
94                                            wrapped line, instead of in front of the next character */
95 #define EF_USE_SOFTBRK          0x0100  /* Enable soft breaks in text. */
96
97 typedef enum
98 {
99         END_0 = 0,                      /* line ends with terminating '\0' character */
100         END_WRAP,                       /* line is wrapped */
101         END_HARD,                       /* line ends with a hard return '\r\n' */
102         END_SOFT,                       /* line ends with a soft return '\r\r\n' */
103         END_RICH                        /* line ends with a single '\n' */
104 } LINE_END;
105
106 typedef struct tagLINEDEF {
107         INT length;                     /* bruto length of a line in bytes */
108         INT net_length;                 /* netto length of a line in visible characters */
109         LINE_END ending;
110         INT width;                      /* width of the line in pixels */
111         INT index;                      /* line index into the buffer */
112         struct tagLINEDEF *next;
113 } LINEDEF;
114
115 typedef struct
116 {
117         BOOL is_unicode;                /* how the control was created */
118         LPWSTR text;                    /* the actual contents of the control */
119         UINT buffer_size;               /* the size of the buffer in characters */
120         UINT buffer_limit;              /* the maximum size to which the buffer may grow in characters */
121         HFONT font;                     /* NULL means standard system font */
122         INT x_offset;                   /* scroll offset        for multi lines this is in pixels
123                                                                 for single lines it's in characters */
124         INT line_height;                /* height of a screen line in pixels */
125         INT char_width;                 /* average character width in pixels */
126         DWORD style;                    /* sane version of wnd->dwStyle */
127         WORD flags;                     /* flags that are not in es->style or wnd->flags (EF_XXX) */
128         INT undo_insert_count;          /* number of characters inserted in sequence */
129         UINT undo_position;             /* character index of the insertion and deletion */
130         LPWSTR undo_text;               /* deleted text */
131         UINT undo_buffer_size;          /* size of the deleted text buffer */
132         INT selection_start;            /* == selection_end if no selection */
133         INT selection_end;              /* == current caret position */
134         WCHAR password_char;            /* == 0 if no password char, and for multi line controls */
135         INT left_margin;                /* in pixels */
136         INT right_margin;               /* in pixels */
137         RECT format_rect;
138         INT text_width;                 /* width of the widest line in pixels for multi line controls
139                                            and just line width for single line controls */
140         INT region_posx;                /* Position of cursor relative to region: */
141         INT region_posy;                /* -1: to left, 0: within, 1: to right */
142         EDITWORDBREAKPROC16 word_break_proc16;
143         void *word_break_proc;          /* 32-bit word break proc: ANSI or Unicode */
144         INT line_count;                 /* number of lines */
145         INT y_offset;                   /* scroll offset in number of lines */
146         BOOL bCaptureState;             /* flag indicating whether mouse was captured */
147         BOOL bEnableState;              /* flag keeping the enable state */
148         HWND hwndSelf;                  /* the our window handle */
149         HWND hwndParent;                /* Handle of parent for sending EN_* messages.
150                                            Even if parent will change, EN_* messages
151                                            should be sent to the first parent. */
152         HWND hwndListBox;               /* handle of ComboBox's listbox or NULL */
153         /*
154          *      only for multi line controls
155          */
156         INT lock_count;                 /* amount of re-entries in the EditWndProc */
157         INT tabs_count;
158         LPINT tabs;
159         LINEDEF *first_line_def;        /* linked list of (soft) linebreaks */
160         HLOCAL hloc32W;                 /* our unicode local memory block */
161         HLOCAL16 hloc16;                /* alias for 16-bit control receiving EM_GETHANDLE16
162                                            or EM_SETHANDLE16 */
163         HLOCAL hloc32A;                 /* alias for ANSI control receiving EM_GETHANDLE
164                                            or EM_SETHANDLE */
165 } EDITSTATE;
166
167
168 #define SWAP_UINT32(x,y) do { UINT temp = (UINT)(x); (x) = (UINT)(y); (y) = temp; } while(0)
169 #define ORDER_UINT(x,y) do { if ((UINT)(y) < (UINT)(x)) SWAP_UINT32((x),(y)); } while(0)
170
171 /* used for disabled or read-only edit control */
172 #define EDIT_NOTIFY_PARENT(es, wNotifyCode, str) \
173         do \
174         { /* Notify parent which has created this edit control */ \
175             TRACE("notification " str " sent to hwnd=%p\n", es->hwndParent); \
176             SendMessageW(es->hwndParent, WM_COMMAND, \
177                      MAKEWPARAM(GetWindowLongPtrW((es->hwndSelf),GWLP_ID), wNotifyCode), \
178                      (LPARAM)(es->hwndSelf)); \
179         } while(0)
180
181 /*********************************************************************
182  *
183  *      Declarations
184  *
185  */
186
187 /*
188  *      These functions have trivial implementations
189  *      We still like to call them internally
190  *      "static inline" makes them more like macro's
191  */
192 static inline BOOL      EDIT_EM_CanUndo(EDITSTATE *es);
193 static inline void      EDIT_EM_EmptyUndoBuffer(EDITSTATE *es);
194 static inline void      EDIT_WM_Clear(EDITSTATE *es);
195 static inline void      EDIT_WM_Cut(EDITSTATE *es);
196
197 /*
198  *      Helper functions only valid for one type of control
199  */
200 static void     EDIT_BuildLineDefs_ML(EDITSTATE *es, INT iStart, INT iEnd, INT delta, HRGN hrgn);
201 static void     EDIT_CalcLineWidth_SL(EDITSTATE *es);
202 static LPWSTR   EDIT_GetPasswordPointer_SL(EDITSTATE *es);
203 static void     EDIT_MoveDown_ML(EDITSTATE *es, BOOL extend);
204 static void     EDIT_MovePageDown_ML(EDITSTATE *es, BOOL extend);
205 static void     EDIT_MovePageUp_ML(EDITSTATE *es, BOOL extend);
206 static void     EDIT_MoveUp_ML(EDITSTATE *es, BOOL extend);
207 /*
208  *      Helper functions valid for both single line _and_ multi line controls
209  */
210 static INT      EDIT_CallWordBreakProc(EDITSTATE *es, INT start, INT index, INT count, INT action);
211 static INT      EDIT_CharFromPos(EDITSTATE *es, INT x, INT y, LPBOOL after_wrap);
212 static void     EDIT_ConfinePoint(EDITSTATE *es, LPINT x, LPINT y);
213 static void     EDIT_GetLineRect(EDITSTATE *es, INT line, INT scol, INT ecol, LPRECT rc);
214 static void     EDIT_InvalidateText(EDITSTATE *es, INT start, INT end);
215 static void     EDIT_LockBuffer(EDITSTATE *es);
216 static BOOL     EDIT_MakeFit(EDITSTATE *es, UINT size);
217 static BOOL     EDIT_MakeUndoFit(EDITSTATE *es, UINT size);
218 static void     EDIT_MoveBackward(EDITSTATE *es, BOOL extend);
219 static void     EDIT_MoveEnd(EDITSTATE *es, BOOL extend);
220 static void     EDIT_MoveForward(EDITSTATE *es, BOOL extend);
221 static void     EDIT_MoveHome(EDITSTATE *es, BOOL extend);
222 static void     EDIT_MoveWordBackward(EDITSTATE *es, BOOL extend);
223 static void     EDIT_MoveWordForward(EDITSTATE *es, BOOL extend);
224 static void     EDIT_PaintLine(EDITSTATE *es, HDC hdc, INT line, BOOL rev);
225 static INT      EDIT_PaintText(EDITSTATE *es, HDC hdc, INT x, INT y, INT line, INT col, INT count, BOOL rev);
226 static void     EDIT_SetCaretPos(EDITSTATE *es, INT pos, BOOL after_wrap);
227 static void     EDIT_SetRectNP(EDITSTATE *es, LPRECT lprc);
228 static void     EDIT_UnlockBuffer(EDITSTATE *es, BOOL force);
229 static void     EDIT_UpdateScrollInfo(EDITSTATE *es);
230 static INT CALLBACK EDIT_WordBreakProc(LPWSTR s, INT index, INT count, INT action);
231 /*
232  *      EM_XXX message handlers
233  */
234 static LRESULT  EDIT_EM_CharFromPos(EDITSTATE *es, INT x, INT y);
235 static BOOL     EDIT_EM_FmtLines(EDITSTATE *es, BOOL add_eol);
236 static HLOCAL   EDIT_EM_GetHandle(EDITSTATE *es);
237 static HLOCAL16 EDIT_EM_GetHandle16(EDITSTATE *es);
238 static INT      EDIT_EM_GetLine(EDITSTATE *es, INT line, LPWSTR dst, BOOL unicode);
239 static LRESULT  EDIT_EM_GetSel(EDITSTATE *es, PUINT start, PUINT end);
240 static LRESULT  EDIT_EM_GetThumb(EDITSTATE *es);
241 static INT      EDIT_EM_LineFromChar(EDITSTATE *es, INT index);
242 static INT      EDIT_EM_LineIndex(EDITSTATE *es, INT line);
243 static INT      EDIT_EM_LineLength(EDITSTATE *es, INT index);
244 static BOOL     EDIT_EM_LineScroll(EDITSTATE *es, INT dx, INT dy);
245 static BOOL     EDIT_EM_LineScroll_internal(EDITSTATE *es, INT dx, INT dy);
246 static LRESULT  EDIT_EM_PosFromChar(EDITSTATE *es, INT index, BOOL after_wrap);
247 static void     EDIT_EM_ReplaceSel(EDITSTATE *es, BOOL can_undo, LPCWSTR lpsz_replace, BOOL send_update, BOOL honor_limit);
248 static LRESULT  EDIT_EM_Scroll(EDITSTATE *es, INT action);
249 static void     EDIT_EM_ScrollCaret(EDITSTATE *es);
250 static void     EDIT_EM_SetHandle(EDITSTATE *es, HLOCAL hloc);
251 static void     EDIT_EM_SetHandle16(EDITSTATE *es, HLOCAL16 hloc);
252 static void     EDIT_EM_SetLimitText(EDITSTATE *es, INT limit);
253 static void     EDIT_EM_SetMargins(EDITSTATE *es, INT action, INT left, INT right);
254 static void     EDIT_EM_SetPasswordChar(EDITSTATE *es, WCHAR c);
255 static void     EDIT_EM_SetSel(EDITSTATE *es, UINT start, UINT end, BOOL after_wrap);
256 static BOOL     EDIT_EM_SetTabStops(EDITSTATE *es, INT count, LPINT tabs);
257 static BOOL     EDIT_EM_SetTabStops16(EDITSTATE *es, INT count, LPINT16 tabs);
258 static void     EDIT_EM_SetWordBreakProc(EDITSTATE *es, void *wbp);
259 static void     EDIT_EM_SetWordBreakProc16(EDITSTATE *es, EDITWORDBREAKPROC16 wbp);
260 static BOOL     EDIT_EM_Undo(EDITSTATE *es);
261 /*
262  *      WM_XXX message handlers
263  */
264 static void     EDIT_WM_Char(EDITSTATE *es, WCHAR c);
265 static void     EDIT_WM_Command(EDITSTATE *es, INT code, INT id, HWND conrtol);
266 static void     EDIT_WM_ContextMenu(EDITSTATE *es, INT x, INT y);
267 static void     EDIT_WM_Copy(EDITSTATE *es);
268 static LRESULT  EDIT_WM_Create(EDITSTATE *es, LPCWSTR name);
269 static LRESULT  EDIT_WM_Destroy(EDITSTATE *es);
270 static LRESULT  EDIT_WM_EraseBkGnd(EDITSTATE *es, HDC dc);
271 static INT      EDIT_WM_GetText(EDITSTATE *es, INT count, LPWSTR dst, BOOL unicode);
272 static LRESULT  EDIT_WM_HScroll(EDITSTATE *es, INT action, INT pos);
273 static LRESULT  EDIT_WM_KeyDown(EDITSTATE *es, INT key);
274 static LRESULT  EDIT_WM_KillFocus(EDITSTATE *es);
275 static LRESULT  EDIT_WM_LButtonDblClk(EDITSTATE *es);
276 static LRESULT  EDIT_WM_LButtonDown(EDITSTATE *es, DWORD keys, INT x, INT y);
277 static LRESULT  EDIT_WM_LButtonUp(EDITSTATE *es);
278 static LRESULT  EDIT_WM_MButtonDown(EDITSTATE *es);
279 static LRESULT  EDIT_WM_MouseMove(EDITSTATE *es, INT x, INT y);
280 static LRESULT  EDIT_WM_NCCreate(HWND hwnd, LPCREATESTRUCTW lpcs, BOOL unicode);
281 static void     EDIT_WM_Paint(EDITSTATE *es, HDC hdc);
282 static void     EDIT_WM_Paste(EDITSTATE *es);
283 static void     EDIT_WM_SetFocus(EDITSTATE *es);
284 static void     EDIT_WM_SetFont(EDITSTATE *es, HFONT font, BOOL redraw);
285 static void     EDIT_WM_SetText(EDITSTATE *es, LPCWSTR text, BOOL unicode);
286 static void     EDIT_WM_Size(EDITSTATE *es, UINT action, INT width, INT height);
287 static LRESULT  EDIT_WM_StyleChanged(EDITSTATE *es, WPARAM which, const STYLESTRUCT *style);
288 static LRESULT  EDIT_WM_SysKeyDown(EDITSTATE *es, INT key, DWORD key_data);
289 static void     EDIT_WM_Timer(EDITSTATE *es);
290 static LRESULT  EDIT_WM_VScroll(EDITSTATE *es, INT action, INT pos);
291 static void     EDIT_UpdateText(EDITSTATE *es, LPRECT rc, BOOL bErase);
292 static void     EDIT_UpdateTextRegion(EDITSTATE *es, HRGN hrgn, BOOL bErase);
293
294 LRESULT WINAPI EditWndProcA(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
295 LRESULT WINAPI EditWndProcW(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
296
297 /*********************************************************************
298  * edit class descriptor
299  */
300 const struct builtin_class_descr EDIT_builtin_class =
301 {
302     "Edit",               /* name */
303     CS_DBLCLKS | CS_PARENTDC,   /* style */
304     EditWndProcA,         /* procA */
305     EditWndProcW,         /* procW */
306     sizeof(EDITSTATE *),  /* extra */
307     IDC_IBEAM,            /* cursor */
308     0                     /* brush */
309 };
310
311
312 /*********************************************************************
313  *
314  *      EM_CANUNDO
315  *
316  */
317 static inline BOOL EDIT_EM_CanUndo(EDITSTATE *es)
318 {
319         return (es->undo_insert_count || strlenW(es->undo_text));
320 }
321
322
323 /*********************************************************************
324  *
325  *      EM_EMPTYUNDOBUFFER
326  *
327  */
328 static inline void EDIT_EM_EmptyUndoBuffer(EDITSTATE *es)
329 {
330         es->undo_insert_count = 0;
331         *es->undo_text = '\0';
332 }
333
334
335 /*********************************************************************
336  *
337  *      WM_CLEAR
338  *
339  */
340 static inline void EDIT_WM_Clear(EDITSTATE *es)
341 {
342         static const WCHAR empty_stringW[] = {0};
343
344         /* Protect read-only edit control from modification */
345         if(es->style & ES_READONLY)
346             return;
347
348         EDIT_EM_ReplaceSel(es, TRUE, empty_stringW, TRUE, TRUE);
349 }
350
351
352 /*********************************************************************
353  *
354  *      WM_CUT
355  *
356  */
357 static inline void EDIT_WM_Cut(EDITSTATE *es)
358 {
359         EDIT_WM_Copy(es);
360         EDIT_WM_Clear(es);
361 }
362
363
364 /**********************************************************************
365  *         get_app_version
366  *
367  * Returns the window version in case Wine emulates a later version
368  * of windows than the application expects.
369  *
370  * In a number of cases when windows runs an application that was
371  * designed for an earlier windows version, windows reverts
372  * to "old" behaviour of that earlier version.
373  *
374  * An example is a disabled  edit control that needs to be painted.
375  * Old style behaviour is to send a WM_CTLCOLOREDIT message. This was
376  * changed in Win95, NT4.0 by a WM_CTLCOLORSTATIC message _only_ for
377  * applications with an expected version 0f 4.0 or higher.
378  *
379  */
380 static DWORD get_app_version(void)
381 {
382     static DWORD version;
383     if (!version)
384     {
385         DWORD dwEmulatedVersion;
386         OSVERSIONINFOW info;
387         DWORD dwProcVersion = GetProcessVersion(0);
388
389         info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
390         GetVersionExW( &info );
391         dwEmulatedVersion = MAKELONG( info.dwMinorVersion, info.dwMajorVersion );
392         /* FIXME: this may not be 100% correct; see discussion on the
393          * wine developer list in Nov 1999 */
394         version = dwProcVersion < dwEmulatedVersion ? dwProcVersion : dwEmulatedVersion;
395     }
396     return version;
397 }
398
399
400 static HBRUSH EDIT_NotifyCtlColor(EDITSTATE *es, HDC hdc)
401 {
402         UINT msg;
403
404         if ( get_app_version() >= 0x40000 && (!es->bEnableState || (es->style & ES_READONLY)))
405                 msg = WM_CTLCOLORSTATIC;
406         else
407                 msg = WM_CTLCOLOREDIT;
408
409         /* why do we notify to es->hwndParent, and we send this one to GetParent()? */
410         return (HBRUSH)SendMessageW(GetParent(es->hwndSelf), msg, (WPARAM)hdc, (LPARAM)es->hwndSelf);
411 }
412
413 static inline LRESULT DefWindowProcT(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, BOOL unicode)
414 {
415         if(unicode)
416                 return DefWindowProcW(hwnd, msg, wParam, lParam);
417         else
418                 return DefWindowProcA(hwnd, msg, wParam, lParam);
419 }
420
421 /*********************************************************************
422  *
423  *      EditWndProc_common
424  *
425  *      The messages are in the order of the actual integer values
426  *      (which can be found in include/windows.h)
427  *      Wherever possible the 16 bit versions are converted to
428  *      the 32 bit ones, so that we can 'fall through' to the
429  *      helper functions.  These are mostly 32 bit (with a few
430  *      exceptions, clearly indicated by a '16' extension to their
431  *      names).
432  *
433  */
434 static LRESULT WINAPI EditWndProc_common( HWND hwnd, UINT msg,
435                                           WPARAM wParam, LPARAM lParam, BOOL unicode )
436 {
437         EDITSTATE *es = (EDITSTATE *)GetWindowLongW( hwnd, 0 );
438         LRESULT result = 0;
439
440         TRACE("hwnd=%p msg=%x (%s) wparam=%x lparam=%lx\n", hwnd, msg, SPY_GetMsgName(msg, hwnd), wParam, lParam);
441         
442         if (!es && msg != WM_NCCREATE)
443                 return DefWindowProcT(hwnd, msg, wParam, lParam, unicode);
444         else if (msg == WM_NCCREATE)
445                 return EDIT_WM_NCCreate(hwnd, (LPCREATESTRUCTW)lParam, unicode);
446         else if (msg == WM_DESTROY)
447                 return EDIT_WM_Destroy(es);
448
449
450         if (es) EDIT_LockBuffer(es);
451         
452         switch (msg) {
453         case EM_GETSEL16:
454                 wParam = 0;
455                 lParam = 0;
456                 /* fall through */
457         case EM_GETSEL:
458                 result = EDIT_EM_GetSel(es, (PUINT)wParam, (PUINT)lParam);
459                 break;
460
461         case EM_SETSEL16:
462                 if ((short)LOWORD(lParam) == -1)
463                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
464                 else
465                         EDIT_EM_SetSel(es, LOWORD(lParam), HIWORD(lParam), FALSE);
466                 if (!wParam)
467                         EDIT_EM_ScrollCaret(es);
468                 result = 1;
469                 break;
470         case EM_SETSEL:
471                 EDIT_EM_SetSel(es, wParam, lParam, FALSE);
472                 EDIT_EM_ScrollCaret(es);
473                 result = 1;
474                 break;
475
476         case EM_GETRECT16:
477                 if (lParam)
478                 {
479                     RECT16 *r16 = MapSL(lParam);
480                     r16->left   = es->format_rect.left;
481                     r16->top    = es->format_rect.top;
482                     r16->right  = es->format_rect.right;
483                     r16->bottom = es->format_rect.bottom;
484                 }
485                 break;
486         case EM_GETRECT:
487                 if (lParam)
488                         CopyRect((LPRECT)lParam, &es->format_rect);
489                 break;
490
491         case EM_SETRECT16:
492                 if ((es->style & ES_MULTILINE) && lParam) {
493                         RECT rc;
494                         RECT16 *r16 = MapSL(lParam);
495                         rc.left   = r16->left;
496                         rc.top    = r16->top;
497                         rc.right  = r16->right;
498                         rc.bottom = r16->bottom;
499                         EDIT_SetRectNP(es, &rc);
500                         EDIT_UpdateText(es, NULL, TRUE);
501                 }
502                 break;
503         case EM_SETRECT:
504                 if ((es->style & ES_MULTILINE) && lParam) {
505                         EDIT_SetRectNP(es, (LPRECT)lParam);
506                         EDIT_UpdateText(es, NULL, TRUE);
507                 }
508                 break;
509
510         case EM_SETRECTNP16:
511                 if ((es->style & ES_MULTILINE) && lParam) {
512                         RECT rc;
513                         RECT16 *r16 = MapSL(lParam);
514                         rc.left   = r16->left;
515                         rc.top    = r16->top;
516                         rc.right  = r16->right;
517                         rc.bottom = r16->bottom;
518                         EDIT_SetRectNP(es, &rc);
519                 }
520                 break;
521         case EM_SETRECTNP:
522                 if ((es->style & ES_MULTILINE) && lParam)
523                         EDIT_SetRectNP(es, (LPRECT)lParam);
524                 break;
525
526         case EM_SCROLL16:
527         case EM_SCROLL:
528                 result = EDIT_EM_Scroll(es, (INT)wParam);
529                 break;
530
531         case EM_LINESCROLL16:
532                 wParam = (WPARAM)(INT)(SHORT)HIWORD(lParam);
533                 lParam = (LPARAM)(INT)(SHORT)LOWORD(lParam);
534                 /* fall through */
535         case EM_LINESCROLL:
536                 result = (LRESULT)EDIT_EM_LineScroll(es, (INT)wParam, (INT)lParam);
537                 break;
538
539         case EM_SCROLLCARET16:
540         case EM_SCROLLCARET:
541                 EDIT_EM_ScrollCaret(es);
542                 result = 1;
543                 break;
544
545         case EM_GETMODIFY16:
546         case EM_GETMODIFY:
547                 result = ((es->flags & EF_MODIFIED) != 0);
548                 break;
549
550         case EM_SETMODIFY16:
551         case EM_SETMODIFY:
552                 if (wParam)
553                         es->flags |= EF_MODIFIED;
554                 else
555                         es->flags &= ~(EF_MODIFIED | EF_UPDATE);  /* reset pending updates */
556                 break;
557
558         case EM_GETLINECOUNT16:
559         case EM_GETLINECOUNT:
560                 result = (es->style & ES_MULTILINE) ? es->line_count : 1;
561                 break;
562
563         case EM_LINEINDEX16:
564                 if ((INT16)wParam == -1)
565                         wParam = (WPARAM)-1;
566                 /* fall through */
567         case EM_LINEINDEX:
568                 result = (LRESULT)EDIT_EM_LineIndex(es, (INT)wParam);
569                 break;
570
571         case EM_SETHANDLE16:
572                 EDIT_EM_SetHandle16(es, (HLOCAL16)wParam);
573                 break;
574         case EM_SETHANDLE:
575                 EDIT_EM_SetHandle(es, (HLOCAL)wParam);
576                 break;
577
578         case EM_GETHANDLE16:
579                 result = (LRESULT)EDIT_EM_GetHandle16(es);
580                 break;
581         case EM_GETHANDLE:
582                 result = (LRESULT)EDIT_EM_GetHandle(es);
583                 break;
584
585         case EM_GETTHUMB16:
586         case EM_GETTHUMB:
587                 result = EDIT_EM_GetThumb(es);
588                 break;
589
590         /* these messages missing from specs */
591         case WM_USER+15:
592         case 0x00bf:
593         case WM_USER+16:
594         case 0x00c0:
595         case WM_USER+19:
596         case 0x00c3:
597         case WM_USER+26:
598         case 0x00ca:
599                 FIXME("undocumented message 0x%x, please report\n", msg);
600                 result = DefWindowProcW(hwnd, msg, wParam, lParam);
601                 break;
602                 
603         case EM_LINELENGTH16:
604         case EM_LINELENGTH:
605                 result = (LRESULT)EDIT_EM_LineLength(es, (INT)wParam);
606                 break;
607
608         case EM_REPLACESEL16:
609                 lParam = (LPARAM)MapSL(lParam);
610                 unicode = FALSE;  /* 16-bit message is always ascii */
611                 /* fall through */
612         case EM_REPLACESEL:
613         {
614                 LPWSTR textW;
615
616                 if(unicode)
617                     textW = (LPWSTR)lParam;
618                 else
619                 {
620                     LPSTR textA = (LPSTR)lParam;
621                     INT countW = MultiByteToWideChar(CP_ACP, 0, textA, -1, NULL, 0);
622                     if((textW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR))))
623                         MultiByteToWideChar(CP_ACP, 0, textA, -1, textW, countW);
624                 }
625
626                 EDIT_EM_ReplaceSel(es, (BOOL)wParam, textW, TRUE, TRUE);
627                 result = 1;
628
629                 if(!unicode)
630                     HeapFree(GetProcessHeap(), 0, textW);
631                 break;
632         }
633
634         case EM_GETLINE16:
635                 lParam = (LPARAM)MapSL(lParam);
636                 unicode = FALSE;  /* 16-bit message is always ascii */
637                 /* fall through */
638         case EM_GETLINE:
639                 result = (LRESULT)EDIT_EM_GetLine(es, (INT)wParam, (LPWSTR)lParam, unicode);
640                 break;
641
642         case EM_LIMITTEXT16:
643         case EM_SETLIMITTEXT:
644                 EDIT_EM_SetLimitText(es, (INT)wParam);
645                 break;
646
647         case EM_CANUNDO16:
648         case EM_CANUNDO:
649                 result = (LRESULT)EDIT_EM_CanUndo(es);
650                 break;
651
652         case EM_UNDO16:
653         case EM_UNDO:
654         case WM_UNDO:
655                 result = (LRESULT)EDIT_EM_Undo(es);
656                 break;
657
658         case EM_FMTLINES16:
659         case EM_FMTLINES:
660                 result = (LRESULT)EDIT_EM_FmtLines(es, (BOOL)wParam);
661                 break;
662
663         case EM_LINEFROMCHAR16:
664         case EM_LINEFROMCHAR:
665                 result = (LRESULT)EDIT_EM_LineFromChar(es, (INT)wParam);
666                 break;
667
668         case EM_SETTABSTOPS16:
669                 result = (LRESULT)EDIT_EM_SetTabStops16(es, (INT)wParam, MapSL(lParam));
670                 break;
671         case EM_SETTABSTOPS:
672                 result = (LRESULT)EDIT_EM_SetTabStops(es, (INT)wParam, (LPINT)lParam);
673                 break;
674
675         case EM_SETPASSWORDCHAR16:
676                 unicode = FALSE;  /* 16-bit message is always ascii */
677                 /* fall through */
678         case EM_SETPASSWORDCHAR:
679         {
680                 WCHAR charW = 0;
681
682                 if(unicode)
683                     charW = (WCHAR)wParam;
684                 else
685                 {
686                     CHAR charA = wParam;
687                     MultiByteToWideChar(CP_ACP, 0, &charA, 1, &charW, 1);
688                 }
689
690                 EDIT_EM_SetPasswordChar(es, charW);
691                 break;
692         }
693
694         case EM_EMPTYUNDOBUFFER16:
695         case EM_EMPTYUNDOBUFFER:
696                 EDIT_EM_EmptyUndoBuffer(es);
697                 break;
698
699         case EM_GETFIRSTVISIBLELINE16:
700                 result = es->y_offset;
701                 break;
702         case EM_GETFIRSTVISIBLELINE:
703                 result = (es->style & ES_MULTILINE) ? es->y_offset : es->x_offset;
704                 break;
705
706         case EM_SETREADONLY16:
707         case EM_SETREADONLY:
708                 if (wParam) {
709                     SetWindowLongW( hwnd, GWL_STYLE,
710                                     GetWindowLongW( hwnd, GWL_STYLE ) | ES_READONLY );
711                     es->style |= ES_READONLY;
712                 } else {
713                     SetWindowLongW( hwnd, GWL_STYLE,
714                                     GetWindowLongW( hwnd, GWL_STYLE ) & ~ES_READONLY );
715                     es->style &= ~ES_READONLY;
716                 }
717                 result = 1;
718                 break;
719
720         case EM_SETWORDBREAKPROC16:
721                 EDIT_EM_SetWordBreakProc16(es, (EDITWORDBREAKPROC16)lParam);
722                 break;
723         case EM_SETWORDBREAKPROC:
724                 EDIT_EM_SetWordBreakProc(es, (void *)lParam);
725                 break;
726
727         case EM_GETWORDBREAKPROC16:
728                 result = (LRESULT)es->word_break_proc16;
729                 break;
730         case EM_GETWORDBREAKPROC:
731                 result = (LRESULT)es->word_break_proc;
732                 break;
733
734         case EM_GETPASSWORDCHAR16:
735                 unicode = FALSE;  /* 16-bit message is always ascii */
736                 /* fall through */
737         case EM_GETPASSWORDCHAR:
738         {
739                 if(unicode)
740                     result = es->password_char;
741                 else
742                 {
743                     WCHAR charW = es->password_char;
744                     CHAR charA = 0;
745                     WideCharToMultiByte(CP_ACP, 0, &charW, 1, &charA, 1, NULL, NULL);
746                     result = charA;
747                 }
748                 break;
749         }
750
751         /* The following EM_xxx are new to win95 and don't exist for 16 bit */
752
753         case EM_SETMARGINS:
754                 EDIT_EM_SetMargins(es, (INT)wParam, (short)LOWORD(lParam), (short)HIWORD(lParam));
755                 break;
756
757         case EM_GETMARGINS:
758                 result = MAKELONG(es->left_margin, es->right_margin);
759                 break;
760
761         case EM_GETLIMITTEXT:
762                 result = es->buffer_limit;
763                 break;
764
765         case EM_POSFROMCHAR:
766                 result = EDIT_EM_PosFromChar(es, (INT)wParam, FALSE);
767                 break;
768
769         case EM_CHARFROMPOS:
770                 result = EDIT_EM_CharFromPos(es, (short)LOWORD(lParam), (short)HIWORD(lParam));
771                 break;
772
773         /* End of the EM_ messages which were in numerical order; what order
774          * are these in?  vaguely alphabetical?
775          */
776
777         case WM_GETDLGCODE:
778                 result = DLGC_HASSETSEL | DLGC_WANTCHARS | DLGC_WANTARROWS;
779                 
780                 if (es->style & ES_MULTILINE)
781                 {
782                    result |= DLGC_WANTALLKEYS;
783                    break;
784                 }
785
786                 if (lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
787                 {
788                    int vk = (int)((LPMSG)lParam)->wParam;
789
790                    if (es->hwndListBox && (vk == VK_RETURN || vk == VK_ESCAPE))
791                    {
792                       if (SendMessageW(GetParent(hwnd), CB_GETDROPPEDSTATE, 0, 0))
793                          result |= DLGC_WANTMESSAGE;
794                    }
795                 }
796                 break;
797
798         case WM_IME_CHAR:
799             if (!unicode)
800             {
801                 WCHAR charW;
802                 CHAR  strng[2];
803
804                 strng[0] = wParam >> 8;
805                 strng[1] = wParam & 0xff;
806                 if (strng[0]) MultiByteToWideChar(CP_ACP, 0, strng, 2, &charW, 1);
807                 else MultiByteToWideChar(CP_ACP, 0, &strng[1], 1, &charW, 1);
808                 EDIT_WM_Char(es, charW);
809                 break;
810             }
811             /* fall through */
812         case WM_CHAR:
813         {
814                 WCHAR charW;
815
816                 if(unicode)
817                     charW = wParam;
818                 else
819                 {
820                     CHAR charA = wParam;
821                     MultiByteToWideChar(CP_ACP, 0, &charA, 1, &charW, 1);
822                 }
823
824                 if ((charW == VK_RETURN || charW == VK_ESCAPE) && es->hwndListBox)
825                 {
826                    if (SendMessageW(GetParent(hwnd), CB_GETDROPPEDSTATE, 0, 0))
827                       SendMessageW(GetParent(hwnd), WM_KEYDOWN, charW, 0);
828                    break;
829                 }
830                 EDIT_WM_Char(es, charW);
831                 break;
832         }
833
834         case WM_CLEAR:
835                 EDIT_WM_Clear(es);
836                 break;
837
838         case WM_COMMAND:
839                 EDIT_WM_Command(es, HIWORD(wParam), LOWORD(wParam), (HWND)lParam);
840                 break;
841
842         case WM_CONTEXTMENU:
843                 EDIT_WM_ContextMenu(es, (short)LOWORD(lParam), (short)HIWORD(lParam));
844                 break;
845
846         case WM_COPY:
847                 EDIT_WM_Copy(es);
848                 break;
849
850         case WM_CREATE:
851                 if(unicode)
852                     result = EDIT_WM_Create(es, ((LPCREATESTRUCTW)lParam)->lpszName);
853                 else
854                 {
855                     LPCSTR nameA = ((LPCREATESTRUCTA)lParam)->lpszName;
856                     LPWSTR nameW = NULL;
857                     if(nameA)
858                     {
859                         INT countW = MultiByteToWideChar(CP_ACP, 0, nameA, -1, NULL, 0);
860                         if((nameW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR))))
861                             MultiByteToWideChar(CP_ACP, 0, nameA, -1, nameW, countW);
862                     }
863                     result = EDIT_WM_Create(es, nameW);
864                     HeapFree(GetProcessHeap(), 0, nameW);
865                 }
866                 break;
867
868         case WM_CUT:
869                 EDIT_WM_Cut(es);
870                 break;
871
872         case WM_ENABLE:
873                 es->bEnableState = (BOOL) wParam;
874                 EDIT_UpdateText(es, NULL, TRUE);
875                 break;
876
877         case WM_ERASEBKGND:
878                 result = EDIT_WM_EraseBkGnd(es, (HDC)wParam);
879                 break;
880
881         case WM_GETFONT:
882                 result = (LRESULT)es->font;
883                 break;
884
885         case WM_GETTEXT:
886                 result = (LRESULT)EDIT_WM_GetText(es, (INT)wParam, (LPWSTR)lParam, unicode);
887                 break;
888
889         case WM_GETTEXTLENGTH:
890                 if (unicode) result = strlenW(es->text);
891                 else result = WideCharToMultiByte( CP_ACP, 0, es->text, strlenW(es->text),
892                                                    NULL, 0, NULL, NULL );
893                 break;
894
895         case WM_HSCROLL:
896                 result = EDIT_WM_HScroll(es, LOWORD(wParam), (short)HIWORD(wParam));
897                 break;
898
899         case WM_KEYDOWN:
900                 result = EDIT_WM_KeyDown(es, (INT)wParam);
901                 break;
902
903         case WM_KILLFOCUS:
904                 result = EDIT_WM_KillFocus(es);
905                 break;
906
907         case WM_LBUTTONDBLCLK:
908                 result = EDIT_WM_LButtonDblClk(es);
909                 break;
910
911         case WM_LBUTTONDOWN:
912                 result = EDIT_WM_LButtonDown(es, wParam, (short)LOWORD(lParam), (short)HIWORD(lParam));
913                 break;
914
915         case WM_LBUTTONUP:
916                 result = EDIT_WM_LButtonUp(es);
917                 break;
918
919         case WM_MBUTTONDOWN:
920                 result = EDIT_WM_MButtonDown(es);
921                 break;
922
923         case WM_MOUSEACTIVATE:
924                 result = MA_ACTIVATE;
925                 break;
926
927         case WM_MOUSEMOVE:
928                 result = EDIT_WM_MouseMove(es, (short)LOWORD(lParam), (short)HIWORD(lParam));
929                 break;
930
931         case WM_PAINT:
932                 EDIT_WM_Paint(es, (HDC)wParam);
933                 break;
934
935         case WM_PASTE:
936                 EDIT_WM_Paste(es);
937                 break;
938
939         case WM_SETFOCUS:
940                 EDIT_WM_SetFocus(es);
941                 break;
942
943         case WM_SETFONT:
944                 EDIT_WM_SetFont(es, (HFONT)wParam, LOWORD(lParam) != 0);
945                 break;
946
947         case WM_SETREDRAW:
948                 /* FIXME: actually set an internal flag and behave accordingly */
949                 break;
950
951         case WM_SETTEXT:
952                 EDIT_WM_SetText(es, (LPCWSTR)lParam, unicode);
953                 result = TRUE;
954                 break;
955
956         case WM_SIZE:
957                 EDIT_WM_Size(es, (UINT)wParam, LOWORD(lParam), HIWORD(lParam));
958                 break;
959
960         case WM_STYLECHANGED:
961                 result = EDIT_WM_StyleChanged(es, wParam, (const STYLESTRUCT *)lParam);
962                 break;
963
964         case WM_STYLECHANGING:
965                 result = 0; /* See EDIT_WM_StyleChanged */
966                 break;
967
968         case WM_SYSKEYDOWN:
969                 result = EDIT_WM_SysKeyDown(es, (INT)wParam, (DWORD)lParam);
970                 break;
971
972         case WM_TIMER:
973                 EDIT_WM_Timer(es);
974                 break;
975
976         case WM_VSCROLL:
977                 result = EDIT_WM_VScroll(es, LOWORD(wParam), (short)HIWORD(wParam));
978                 break;
979
980         case WM_MOUSEWHEEL:
981                 {
982                     int gcWheelDelta = 0;
983                     UINT pulScrollLines = 3;
984                     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
985
986                     if (wParam & (MK_SHIFT | MK_CONTROL)) {
987                         result = DefWindowProcW(hwnd, msg, wParam, lParam);
988                         break;
989                     }
990                     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
991                     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
992                     {
993                         int cLineScroll= (int) min((UINT) es->line_count, pulScrollLines);
994                         cLineScroll *= (gcWheelDelta / WHEEL_DELTA);
995                         result = EDIT_EM_LineScroll(es, 0, cLineScroll);
996                     }
997                 }
998                 break;
999         default:
1000                 result = DefWindowProcT(hwnd, msg, wParam, lParam, unicode);
1001                 break;
1002         }
1003         
1004         if (es) EDIT_UnlockBuffer(es, FALSE);
1005
1006         TRACE("hwnd=%p msg=%x (%s) -- 0x%08lx\n", hwnd, msg, SPY_GetMsgName(msg, hwnd), result);
1007
1008         return result;
1009 }
1010
1011 /*********************************************************************
1012  *
1013  *      EditWndProcW   (USER32.@)
1014  */
1015 LRESULT WINAPI EditWndProcW(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1016 {
1017     return EditWndProc_common(hWnd, uMsg, wParam, lParam, TRUE);
1018 }
1019
1020 /*********************************************************************
1021  *
1022  *      EditWndProc   (USER32.@)
1023  */
1024 LRESULT WINAPI EditWndProcA(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1025 {
1026     return EditWndProc_common(hWnd, uMsg, wParam, lParam, FALSE);
1027 }
1028
1029 /*********************************************************************
1030  *
1031  *      EDIT_BuildLineDefs_ML
1032  *
1033  *      Build linked list of text lines.
1034  *      Lines can end with '\0' (last line), a character (if it is wrapped),
1035  *      a soft return '\r\r\n' or a hard return '\r\n'
1036  *
1037  */
1038 static void EDIT_BuildLineDefs_ML(EDITSTATE *es, INT istart, INT iend, INT delta, HRGN hrgn)
1039 {
1040         HDC dc;
1041         HFONT old_font = 0;
1042         LPWSTR current_position, cp;
1043         INT fw;
1044         LINEDEF *current_line;
1045         LINEDEF *previous_line;
1046         LINEDEF *start_line;
1047         INT line_index = 0, nstart_line = 0, nstart_index = 0;
1048         INT line_count = es->line_count;
1049         INT orig_net_length;
1050         RECT rc;
1051
1052         if (istart == iend && delta == 0)
1053                 return;
1054
1055         dc = GetDC(es->hwndSelf);
1056         if (es->font)
1057                 old_font = SelectObject(dc, es->font);
1058
1059         previous_line = NULL;
1060         current_line = es->first_line_def;
1061
1062         /* Find starting line. istart must lie inside an existing line or
1063          * at the end of buffer */
1064         do {
1065                 if (istart < current_line->index + current_line->length ||
1066                                 current_line->ending == END_0)
1067                         break;
1068
1069                 previous_line = current_line;
1070                 current_line = current_line->next;
1071                 line_index++;
1072         } while (current_line);
1073
1074         if (!current_line) /* Error occurred start is not inside previous buffer */
1075         {
1076                 FIXME(" modification occurred outside buffer\n");
1077                 ReleaseDC(es->hwndSelf, dc);
1078                 return;
1079         }
1080
1081         /* Remember start of modifications in order to calculate update region */
1082         nstart_line = line_index;
1083         nstart_index = current_line->index;
1084
1085         /* We must start to reformat from the previous line since the modifications
1086          * may have caused the line to wrap upwards. */
1087         if (!(es->style & ES_AUTOHSCROLL) && line_index > 0)
1088         {
1089                 line_index--;
1090                 current_line = previous_line;
1091         }
1092         start_line = current_line;
1093
1094         fw = es->format_rect.right - es->format_rect.left;
1095         current_position = es->text + current_line->index;
1096         do {
1097                 if (current_line != start_line)
1098                 {
1099                         if (!current_line || current_line->index + delta > current_position - es->text)
1100                         {
1101                                 /* The buffer has been expanded, create a new line and
1102                                    insert it into the link list */
1103                                 LINEDEF *new_line = HeapAlloc(GetProcessHeap(), 0, sizeof(LINEDEF));
1104                                 new_line->next = previous_line->next;
1105                                 previous_line->next = new_line;
1106                                 current_line = new_line;
1107                                 es->line_count++;
1108                         }
1109                         else if (current_line->index + delta < current_position - es->text)
1110                         {
1111                                 /* The previous line merged with this line so we delete this extra entry */
1112                                 previous_line->next = current_line->next;
1113                                 HeapFree(GetProcessHeap(), 0, current_line);
1114                                 current_line = previous_line->next;
1115                                 es->line_count--;
1116                                 continue;
1117                         }
1118                         else /* current_line->index + delta == current_position */
1119                         {
1120                                 if (current_position - es->text > iend)
1121                                         break; /* We reached end of line modifications */
1122                                 /* else recalulate this line */
1123                         }
1124                 }
1125
1126                 current_line->index = current_position - es->text;
1127                 orig_net_length = current_line->net_length;
1128
1129                 /* Find end of line */
1130                 cp = current_position;
1131                 while (*cp) {
1132                     if (*cp == '\n') break;
1133                         if ((*cp == '\r') && (*(cp + 1) == '\n'))
1134                                 break;
1135                         cp++;
1136                 }
1137
1138                 /* Mark type of line termination */
1139                 if (!(*cp)) {
1140                         current_line->ending = END_0;
1141                         current_line->net_length = strlenW(current_position);
1142                 } else if ((cp > current_position) && (*(cp - 1) == '\r')) {
1143                         current_line->ending = END_SOFT;
1144                         current_line->net_length = cp - current_position - 1;
1145                 } else if (*cp == '\n') {
1146                         current_line->ending = END_RICH;
1147                         current_line->net_length = cp - current_position;
1148                 } else {
1149                         current_line->ending = END_HARD;
1150                         current_line->net_length = cp - current_position;
1151                 }
1152
1153                 /* Calculate line width */
1154                 current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
1155                                         current_position, current_line->net_length,
1156                                         es->tabs_count, es->tabs));
1157
1158                 /* FIXME: check here for lines that are too wide even in AUTOHSCROLL (> 32767 ???) */
1159                 if (!(es->style & ES_AUTOHSCROLL)) {
1160                    if (current_line->width > fw) {
1161                         INT next = 0;
1162                         INT prev;
1163                         do {
1164                                 prev = next;
1165                                 next = EDIT_CallWordBreakProc(es, current_position - es->text,
1166                                                 prev + 1, current_line->net_length, WB_RIGHT);
1167                                 current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
1168                                                         current_position, next, es->tabs_count, es->tabs));
1169                         } while (current_line->width <= fw);
1170                         if (!prev) { /* Didn't find a line break so force a break */
1171                                 next = 0;
1172                                 do {
1173                                         prev = next;
1174                                         next++;
1175                                         current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
1176                                                                 current_position, next, es->tabs_count, es->tabs));
1177                                 } while (current_line->width <= fw);
1178                                 if (!prev)
1179                                         prev = 1;
1180                         }
1181
1182                         /* If the first line we are calculating, wrapped before istart, we must
1183                          * adjust istart in order for this to be reflected in the update region. */
1184                         if (current_line->index == nstart_index && istart > current_line->index + prev)
1185                                 istart = current_line->index + prev;
1186                         /* else if we are updating the previous line before the first line we
1187                          * are re-calculating and it expanded */
1188                         else if (current_line == start_line &&
1189                                         current_line->index != nstart_index && orig_net_length < prev)
1190                         {
1191                           /* Line expanded due to an upwards line wrap so we must partially include
1192                            * previous line in update region */
1193                                 nstart_line = line_index;
1194                                 nstart_index = current_line->index;
1195                                 istart = current_line->index + orig_net_length;
1196                         }
1197
1198                         current_line->net_length = prev;
1199                         current_line->ending = END_WRAP;
1200                         current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc, current_position,
1201                                         current_line->net_length, es->tabs_count, es->tabs));
1202                     }
1203                     else if (orig_net_length <  current_line->net_length  &&
1204                         current_line == start_line &&
1205                         current_line->index != nstart_index) {
1206                         /* The previous line expanded but it's still not as wide as the client rect */
1207                         /* The expansion is due to an upwards line wrap so we must partially include
1208                            it in the update region */
1209                         nstart_line = line_index;
1210                         nstart_index = current_line->index;
1211                         istart = current_line->index + orig_net_length;
1212                     }
1213                 }
1214
1215
1216                 /* Adjust length to include line termination */
1217                 switch (current_line->ending) {
1218                 case END_SOFT:
1219                         current_line->length = current_line->net_length + 3;
1220                         break;
1221                 case END_RICH:
1222                         current_line->length = current_line->net_length + 1;
1223                         break;
1224                 case END_HARD:
1225                         current_line->length = current_line->net_length + 2;
1226                         break;
1227                 case END_WRAP:
1228                 case END_0:
1229                         current_line->length = current_line->net_length;
1230                         break;
1231                 }
1232                 es->text_width = max(es->text_width, current_line->width);
1233                 current_position += current_line->length;
1234                 previous_line = current_line;
1235                 current_line = current_line->next;
1236                 line_index++;
1237         } while (previous_line->ending != END_0);
1238
1239         /* Finish adjusting line indexes by delta or remove hanging lines */
1240         if (previous_line->ending == END_0)
1241         {
1242                 LINEDEF *pnext = NULL;
1243
1244                 previous_line->next = NULL;
1245                 while (current_line)
1246                 {
1247                         pnext = current_line->next;
1248                         HeapFree(GetProcessHeap(), 0, current_line);
1249                         current_line = pnext;
1250                         es->line_count--;
1251                 }
1252         }
1253         else if (delta != 0)
1254         {
1255                 while (current_line)
1256                 {
1257                         current_line->index += delta;
1258                         current_line = current_line->next;
1259                 }
1260         }
1261
1262         /* Calculate rest of modification rectangle */
1263         if (hrgn)
1264         {
1265                 HRGN tmphrgn;
1266            /*
1267                 * We calculate two rectangles. One for the first line which may have
1268                 * an indent with respect to the format rect. The other is a format-width
1269                 * rectangle that spans the rest of the lines that changed or moved.
1270                 */
1271                 rc.top = es->format_rect.top + nstart_line * es->line_height -
1272                         (es->y_offset * es->line_height); /* Adjust for vertical scrollbar */
1273                 rc.bottom = rc.top + es->line_height;
1274                 if ((es->style & ES_CENTER) || (es->style & ES_RIGHT))
1275                         rc.left = es->format_rect.left;
1276                 else
1277                         rc.left = es->format_rect.left + (INT)LOWORD(GetTabbedTextExtentW(dc,
1278                                         es->text + nstart_index, istart - nstart_index,
1279                                         es->tabs_count, es->tabs)) - es->x_offset; /* Adjust for horz scroll */
1280                 rc.right = es->format_rect.right;
1281                 SetRectRgn(hrgn, rc.left, rc.top, rc.right, rc.bottom);
1282
1283                 rc.top = rc.bottom;
1284                 rc.left = es->format_rect.left;
1285                 rc.right = es->format_rect.right;
1286            /*
1287                 * If lines were added or removed we must re-paint the remainder of the
1288             * lines since the remaining lines were either shifted up or down.
1289                 */
1290                 if (line_count < es->line_count) /* We added lines */
1291                         rc.bottom = es->line_count * es->line_height;
1292                 else if (line_count > es->line_count) /* We removed lines */
1293                         rc.bottom = line_count * es->line_height;
1294                 else
1295                         rc.bottom = line_index * es->line_height;
1296                 rc.bottom -= (es->y_offset * es->line_height); /* Adjust for vertical scrollbar */
1297                 tmphrgn = CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
1298                 CombineRgn(hrgn, hrgn, tmphrgn, RGN_OR);
1299                 DeleteObject(tmphrgn);
1300         }
1301
1302         if (es->font)
1303                 SelectObject(dc, old_font);
1304
1305         ReleaseDC(es->hwndSelf, dc);
1306 }
1307
1308 /*********************************************************************
1309  *
1310  *      EDIT_CalcLineWidth_SL
1311  *
1312  */
1313 static void EDIT_CalcLineWidth_SL(EDITSTATE *es)
1314 {
1315         SIZE size;
1316         LPWSTR text;
1317         HDC dc;
1318         HFONT old_font = 0;
1319
1320         text = EDIT_GetPasswordPointer_SL(es);
1321
1322         dc = GetDC(es->hwndSelf);
1323         if (es->font)
1324                 old_font = SelectObject(dc, es->font);
1325
1326         GetTextExtentPoint32W(dc, text, strlenW(text), &size);
1327
1328         if (es->font)
1329                 SelectObject(dc, old_font);
1330         ReleaseDC(es->hwndSelf, dc);
1331
1332         if (es->style & ES_PASSWORD)
1333                 HeapFree(GetProcessHeap(), 0, text);
1334
1335         es->text_width = size.cx;
1336 }
1337
1338 /*********************************************************************
1339  *
1340  *      EDIT_CallWordBreakProc
1341  *
1342  *      Call appropriate WordBreakProc (internal or external).
1343  *
1344  *      Note: The "start" argument should always be an index referring
1345  *              to es->text.  The actual wordbreak proc might be
1346  *              16 bit, so we can't always pass any 32 bit LPSTR.
1347  *              Hence we assume that es->text is the buffer that holds
1348  *              the string under examination (we can decide this for ourselves).
1349  *
1350  */
1351 static INT EDIT_CallWordBreakProc(EDITSTATE *es, INT start, INT index, INT count, INT action)
1352 {
1353         INT ret;
1354
1355         if (es->word_break_proc16) {
1356             HGLOBAL16 hglob16;
1357             SEGPTR segptr;
1358             INT countA;
1359             WORD args[5];
1360             DWORD result;
1361
1362             countA = WideCharToMultiByte(CP_ACP, 0, es->text + start, count, NULL, 0, NULL, NULL);
1363             hglob16 = GlobalAlloc16(GMEM_MOVEABLE | GMEM_ZEROINIT, countA);
1364             segptr = K32WOWGlobalLock16(hglob16);
1365             WideCharToMultiByte(CP_ACP, 0, es->text + start, count, MapSL(segptr), countA, NULL, NULL);
1366             args[4] = SELECTOROF(segptr);
1367             args[3] = OFFSETOF(segptr);
1368             args[2] = index;
1369             args[1] = countA;
1370             args[0] = action;
1371             WOWCallback16Ex((DWORD)es->word_break_proc16, WCB16_PASCAL, sizeof(args), args, &result);
1372             ret = LOWORD(result);
1373             GlobalUnlock16(hglob16);
1374             GlobalFree16(hglob16);
1375         }
1376         else if (es->word_break_proc)
1377         {
1378             if(es->is_unicode)
1379             {
1380                 EDITWORDBREAKPROCW wbpW = (EDITWORDBREAKPROCW)es->word_break_proc;
1381
1382                 TRACE_(relay)("(UNICODE wordbrk=%p,str=%s,idx=%d,cnt=%d,act=%d)\n",
1383                         es->word_break_proc, debugstr_wn(es->text + start, count), index, count, action);
1384                 ret = wbpW(es->text + start, index, count, action);
1385             }
1386             else
1387             {
1388                 EDITWORDBREAKPROCA wbpA = (EDITWORDBREAKPROCA)es->word_break_proc;
1389                 INT countA;
1390                 CHAR *textA;
1391
1392                 countA = WideCharToMultiByte(CP_ACP, 0, es->text + start, count, NULL, 0, NULL, NULL);
1393                 textA = HeapAlloc(GetProcessHeap(), 0, countA);
1394                 WideCharToMultiByte(CP_ACP, 0, es->text + start, count, textA, countA, NULL, NULL);
1395                 TRACE_(relay)("(ANSI wordbrk=%p,str=%s,idx=%d,cnt=%d,act=%d)\n",
1396                         es->word_break_proc, debugstr_an(textA, countA), index, countA, action);
1397                 ret = wbpA(textA, index, countA, action);
1398                 HeapFree(GetProcessHeap(), 0, textA);
1399             }
1400         }
1401         else
1402             ret = EDIT_WordBreakProc(es->text + start, index, count, action);
1403
1404         return ret;
1405 }
1406
1407
1408 /*********************************************************************
1409  *
1410  *      EDIT_CharFromPos
1411  *
1412  *      Beware: This is not the function called on EM_CHARFROMPOS
1413  *              The position _can_ be outside the formatting / client
1414  *              rectangle
1415  *              The return value is only the character index
1416  *
1417  */
1418 static INT EDIT_CharFromPos(EDITSTATE *es, INT x, INT y, LPBOOL after_wrap)
1419 {
1420         INT index;
1421         HDC dc;
1422         HFONT old_font = 0;
1423
1424         if (es->style & ES_MULTILINE) {
1425                 INT line = (y - es->format_rect.top) / es->line_height + es->y_offset;
1426                 INT line_index = 0;
1427                 LINEDEF *line_def = es->first_line_def;
1428                 INT low, high;
1429                 while ((line > 0) && line_def->next) {
1430                         line_index += line_def->length;
1431                         line_def = line_def->next;
1432                         line--;
1433                 }
1434                 x += es->x_offset - es->format_rect.left;
1435                 if (es->style & ES_RIGHT)
1436                         x -= (es->format_rect.right - es->format_rect.left) - line_def->width;
1437                 else if (es->style & ES_CENTER)
1438                         x -= ((es->format_rect.right - es->format_rect.left) - line_def->width) / 2;
1439                 if (x >= line_def->width) {
1440                         if (after_wrap)
1441                                 *after_wrap = (line_def->ending == END_WRAP);
1442                         return line_index + line_def->net_length;
1443                 }
1444                 if (x <= 0) {
1445                         if (after_wrap)
1446                                 *after_wrap = FALSE;
1447                         return line_index;
1448                 }
1449                 dc = GetDC(es->hwndSelf);
1450                 if (es->font)
1451                         old_font = SelectObject(dc, es->font);
1452                     low = line_index + 1;
1453                     high = line_index + line_def->net_length + 1;
1454                     while (low < high - 1)
1455                     {
1456                         INT mid = (low + high) / 2;
1457                         if (LOWORD(GetTabbedTextExtentW(dc, es->text + line_index,mid - line_index, es->tabs_count, es->tabs)) > x) high = mid;
1458                         else low = mid;
1459                     }
1460                     index = low;
1461
1462                 if (after_wrap)
1463                         *after_wrap = ((index == line_index + line_def->net_length) &&
1464                                                         (line_def->ending == END_WRAP));
1465         } else {
1466                 LPWSTR text;
1467                 SIZE size;
1468                 if (after_wrap)
1469                         *after_wrap = FALSE;
1470                 x -= es->format_rect.left;
1471                 if (!x)
1472                         return es->x_offset;
1473
1474                 if (!es->x_offset)
1475                 {
1476                         INT indent = (es->format_rect.right - es->format_rect.left) - es->text_width;
1477                         if (es->style & ES_RIGHT)
1478                                 x -= indent;
1479                         else if (es->style & ES_CENTER)
1480                                 x -= indent / 2;
1481                 }
1482
1483                 text = EDIT_GetPasswordPointer_SL(es);
1484                 dc = GetDC(es->hwndSelf);
1485                 if (es->font)
1486                         old_font = SelectObject(dc, es->font);
1487                 if (x < 0)
1488                 {
1489                     INT low = 0;
1490                     INT high = es->x_offset;
1491                     while (low < high - 1)
1492                     {
1493                         INT mid = (low + high) / 2;
1494                         GetTextExtentPoint32W( dc, text + mid,
1495                                                es->x_offset - mid, &size );
1496                         if (size.cx > -x) low = mid;
1497                         else high = mid;
1498                     }
1499                     index = low;
1500                 }
1501                 else
1502                 {
1503                     INT low = es->x_offset;
1504                     INT high = strlenW(es->text) + 1;
1505                     while (low < high - 1)
1506                     {
1507                         INT mid = (low + high) / 2;
1508                         GetTextExtentPoint32W( dc, text + es->x_offset,
1509                                                mid - es->x_offset, &size );
1510                         if (size.cx > x) high = mid;
1511                         else low = mid;
1512                     }
1513                     index = low;
1514                 }
1515                 if (es->style & ES_PASSWORD)
1516                         HeapFree(GetProcessHeap(), 0, text);
1517         }
1518         if (es->font)
1519                 SelectObject(dc, old_font);
1520         ReleaseDC(es->hwndSelf, dc);
1521         return index;
1522 }
1523
1524
1525 /*********************************************************************
1526  *
1527  *      EDIT_ConfinePoint
1528  *
1529  *      adjusts the point to be within the formatting rectangle
1530  *      (so CharFromPos returns the nearest _visible_ character)
1531  *
1532  */
1533 static void EDIT_ConfinePoint(EDITSTATE *es, LPINT x, LPINT y)
1534 {
1535         *x = min(max(*x, es->format_rect.left), es->format_rect.right - 1);
1536         *y = min(max(*y, es->format_rect.top), es->format_rect.bottom - 1);
1537 }
1538
1539
1540 /*********************************************************************
1541  *
1542  *      EDIT_GetLineRect
1543  *
1544  *      Calculates the bounding rectangle for a line from a starting
1545  *      column to an ending column.
1546  *
1547  */
1548 static void EDIT_GetLineRect(EDITSTATE *es, INT line, INT scol, INT ecol, LPRECT rc)
1549 {
1550         INT line_index =  EDIT_EM_LineIndex(es, line);
1551
1552         if (es->style & ES_MULTILINE)
1553                 rc->top = es->format_rect.top + (line - es->y_offset) * es->line_height;
1554         else
1555                 rc->top = es->format_rect.top;
1556         rc->bottom = rc->top + es->line_height;
1557         rc->left = (scol == 0) ? es->format_rect.left : (short)LOWORD(EDIT_EM_PosFromChar(es, line_index + scol, TRUE));
1558         rc->right = (ecol == -1) ? es->format_rect.right : (short)LOWORD(EDIT_EM_PosFromChar(es, line_index + ecol, TRUE));
1559 }
1560
1561
1562 /*********************************************************************
1563  *
1564  *      EDIT_GetPasswordPointer_SL
1565  *
1566  *      note: caller should free the (optionally) allocated buffer
1567  *
1568  */
1569 static LPWSTR EDIT_GetPasswordPointer_SL(EDITSTATE *es)
1570 {
1571         if (es->style & ES_PASSWORD) {
1572                 INT len = strlenW(es->text);
1573                 LPWSTR text = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1574                 text[len] = '\0';
1575                 while(len) text[--len] = es->password_char;
1576                 return text;
1577         } else
1578                 return es->text;
1579 }
1580
1581
1582 /*********************************************************************
1583  *
1584  *      EDIT_LockBuffer
1585  *
1586  *      This acts as a LOCAL_Lock(), but it locks only once.  This way
1587  *      you can call it whenever you like, without unlocking.
1588  *
1589  *      Initially the edit control allocates a HLOCAL32 buffer 
1590  *      (32 bit linear memory handler).  However, 16 bit application
1591  *      might send a EM_GETHANDLE message and expect a HLOCAL16 (16 bit SEG:OFF
1592  *      handler).  From that moment on we have to keep using this 16 bit memory
1593  *      handler, because it is supposed to be valid at all times after EM_GETHANDLE.
1594  *      What we do is create a HLOCAL16 buffer, copy the text, and do pointer
1595  *      conversion.
1596  *
1597  */
1598 static void EDIT_LockBuffer(EDITSTATE *es)
1599 {
1600         HINSTANCE16 hInstance = GetWindowLongPtrW( es->hwndSelf, GWLP_HINSTANCE );
1601         if (!es->text) {
1602             CHAR *textA = NULL;
1603             UINT countA = 0;
1604             BOOL _16bit = FALSE;
1605
1606             if(es->hloc32W)
1607             {
1608                 if(es->hloc32A)
1609                 {
1610                     TRACE("Synchronizing with 32-bit ANSI buffer\n");
1611                     textA = LocalLock(es->hloc32A);
1612                     countA = strlen(textA) + 1;
1613                 }
1614                 else if(es->hloc16)
1615                 {
1616                     TRACE("Synchronizing with 16-bit ANSI buffer\n");
1617                     textA = LOCAL_Lock(hInstance, es->hloc16);
1618                     countA = strlen(textA) + 1;
1619                     _16bit = TRUE;
1620                 }
1621             }
1622             else {
1623                 ERR("no buffer ... please report\n");
1624                 return;
1625             }
1626
1627             if(textA)
1628             {
1629                 HLOCAL hloc32W_new;
1630                 UINT countW_new = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
1631                 TRACE("%d bytes translated to %d WCHARs\n", countA, countW_new);
1632                 if(countW_new > es->buffer_size + 1)
1633                 {
1634                     UINT alloc_size = ROUND_TO_GROW(countW_new * sizeof(WCHAR));
1635                     TRACE("Resizing 32-bit UNICODE buffer from %d+1 to %d WCHARs\n", es->buffer_size, countW_new);
1636                     hloc32W_new = LocalReAlloc(es->hloc32W, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
1637                     if(hloc32W_new)
1638                     {
1639                         es->hloc32W = hloc32W_new;
1640                         es->buffer_size = LocalSize(hloc32W_new)/sizeof(WCHAR) - 1;
1641                         TRACE("Real new size %d+1 WCHARs\n", es->buffer_size);
1642                     }
1643                     else
1644                         WARN("FAILED! Will synchronize partially\n");
1645                 }
1646             }
1647
1648             /*TRACE("Locking 32-bit UNICODE buffer\n");*/
1649             es->text = LocalLock(es->hloc32W);
1650
1651             if(textA)
1652             {
1653                 MultiByteToWideChar(CP_ACP, 0, textA, countA, es->text, es->buffer_size + 1);
1654                 if(_16bit)
1655                     LOCAL_Unlock(hInstance, es->hloc16);
1656                 else
1657                     LocalUnlock(es->hloc32A);
1658             }
1659         }
1660         es->lock_count++;
1661 }
1662
1663
1664 /*********************************************************************
1665  *
1666  *      EDIT_SL_InvalidateText
1667  *
1668  *      Called from EDIT_InvalidateText().
1669  *      Does the job for single-line controls only.
1670  *
1671  */
1672 static void EDIT_SL_InvalidateText(EDITSTATE *es, INT start, INT end)
1673 {
1674         RECT line_rect;
1675         RECT rc;
1676
1677         EDIT_GetLineRect(es, 0, start, end, &line_rect);
1678         if (IntersectRect(&rc, &line_rect, &es->format_rect))
1679                 EDIT_UpdateText(es, &rc, TRUE);
1680 }
1681
1682
1683 /*********************************************************************
1684  *
1685  *      EDIT_ML_InvalidateText
1686  *
1687  *      Called from EDIT_InvalidateText().
1688  *      Does the job for multi-line controls only.
1689  *
1690  */
1691 static void EDIT_ML_InvalidateText(EDITSTATE *es, INT start, INT end)
1692 {
1693         INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
1694         INT sl = EDIT_EM_LineFromChar(es, start);
1695         INT el = EDIT_EM_LineFromChar(es, end);
1696         INT sc;
1697         INT ec;
1698         RECT rc1;
1699         RECT rcWnd;
1700         RECT rcLine;
1701         RECT rcUpdate;
1702         INT l;
1703
1704         if ((el < es->y_offset) || (sl > es->y_offset + vlc))
1705                 return;
1706
1707         sc = start - EDIT_EM_LineIndex(es, sl);
1708         ec = end - EDIT_EM_LineIndex(es, el);
1709         if (sl < es->y_offset) {
1710                 sl = es->y_offset;
1711                 sc = 0;
1712         }
1713         if (el > es->y_offset + vlc) {
1714                 el = es->y_offset + vlc;
1715                 ec = EDIT_EM_LineLength(es, EDIT_EM_LineIndex(es, el));
1716         }
1717         GetClientRect(es->hwndSelf, &rc1);
1718         IntersectRect(&rcWnd, &rc1, &es->format_rect);
1719         if (sl == el) {
1720                 EDIT_GetLineRect(es, sl, sc, ec, &rcLine);
1721                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1722                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1723         } else {
1724                 EDIT_GetLineRect(es, sl, sc,
1725                                 EDIT_EM_LineLength(es,
1726                                         EDIT_EM_LineIndex(es, sl)),
1727                                 &rcLine);
1728                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1729                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1730                 for (l = sl + 1 ; l < el ; l++) {
1731                         EDIT_GetLineRect(es, l, 0,
1732                                 EDIT_EM_LineLength(es,
1733                                         EDIT_EM_LineIndex(es, l)),
1734                                 &rcLine);
1735                         if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1736                                 EDIT_UpdateText(es, &rcUpdate, TRUE);
1737                 }
1738                 EDIT_GetLineRect(es, el, 0, ec, &rcLine);
1739                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1740                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1741         }
1742 }
1743
1744
1745 /*********************************************************************
1746  *
1747  *      EDIT_InvalidateText
1748  *
1749  *      Invalidate the text from offset start upto, but not including,
1750  *      offset end.  Useful for (re)painting the selection.
1751  *      Regions outside the linewidth are not invalidated.
1752  *      end == -1 means end == TextLength.
1753  *      start and end need not be ordered.
1754  *
1755  */
1756 static void EDIT_InvalidateText(EDITSTATE *es, INT start, INT end)
1757 {
1758         if (end == start)
1759                 return;
1760
1761         if (end == -1)
1762                 end = strlenW(es->text);
1763
1764         if (end < start) {
1765             INT tmp = start;
1766             start = end;
1767             end = tmp;
1768         }
1769
1770         if (es->style & ES_MULTILINE)
1771                 EDIT_ML_InvalidateText(es, start, end);
1772         else
1773                 EDIT_SL_InvalidateText(es, start, end);
1774 }
1775
1776
1777 /*********************************************************************
1778  *
1779  *      EDIT_MakeFit
1780  *
1781  * Try to fit size + 1 characters in the buffer.
1782  */
1783 static BOOL EDIT_MakeFit(EDITSTATE *es, UINT size)
1784 {
1785         HLOCAL hNew32W;
1786
1787         if (size <= es->buffer_size)
1788                 return TRUE;
1789
1790         TRACE("trying to ReAlloc to %d+1 characters\n", size);
1791
1792         /* Force edit to unlock it's buffer. es->text now NULL */
1793         EDIT_UnlockBuffer(es, TRUE);
1794
1795         if (es->hloc32W) {
1796             UINT alloc_size = ROUND_TO_GROW((size + 1) * sizeof(WCHAR));
1797             if ((hNew32W = LocalReAlloc(es->hloc32W, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT))) {
1798                 TRACE("Old 32 bit handle %p, new handle %p\n", es->hloc32W, hNew32W);
1799                 es->hloc32W = hNew32W;
1800                 es->buffer_size = LocalSize(hNew32W)/sizeof(WCHAR) - 1;
1801             }
1802         }
1803
1804         EDIT_LockBuffer(es);
1805
1806         if (es->buffer_size < size) {
1807                 WARN("FAILED !  We now have %d+1\n", es->buffer_size);
1808                 EDIT_NOTIFY_PARENT(es, EN_ERRSPACE, "EN_ERRSPACE");
1809                 return FALSE;
1810         } else {
1811                 TRACE("We now have %d+1\n", es->buffer_size);
1812                 return TRUE;
1813         }
1814 }
1815
1816
1817 /*********************************************************************
1818  *
1819  *      EDIT_MakeUndoFit
1820  *
1821  *      Try to fit size + 1 bytes in the undo buffer.
1822  *
1823  */
1824 static BOOL EDIT_MakeUndoFit(EDITSTATE *es, UINT size)
1825 {
1826         UINT alloc_size;
1827
1828         if (size <= es->undo_buffer_size)
1829                 return TRUE;
1830
1831         TRACE("trying to ReAlloc to %d+1\n", size);
1832
1833         alloc_size = ROUND_TO_GROW((size + 1) * sizeof(WCHAR));
1834         if ((es->undo_text = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, es->undo_text, alloc_size))) {
1835                 es->undo_buffer_size = alloc_size/sizeof(WCHAR) - 1;
1836                 return TRUE;
1837         }
1838         else
1839         {
1840                 WARN("FAILED !  We now have %d+1\n", es->undo_buffer_size);
1841                 return FALSE;
1842         }
1843 }
1844
1845
1846 /*********************************************************************
1847  *
1848  *      EDIT_MoveBackward
1849  *
1850  */
1851 static void EDIT_MoveBackward(EDITSTATE *es, BOOL extend)
1852 {
1853         INT e = es->selection_end;
1854
1855         if (e) {
1856                 e--;
1857                 if ((es->style & ES_MULTILINE) && e &&
1858                                 (es->text[e - 1] == '\r') && (es->text[e] == '\n')) {
1859                         e--;
1860                         if (e && (es->text[e - 1] == '\r'))
1861                                 e--;
1862                 }
1863         }
1864         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1865         EDIT_EM_ScrollCaret(es);
1866 }
1867
1868
1869 /*********************************************************************
1870  *
1871  *      EDIT_MoveDown_ML
1872  *
1873  *      Only for multi line controls
1874  *      Move the caret one line down, on a column with the nearest
1875  *      x coordinate on the screen (might be a different column).
1876  *
1877  */
1878 static void EDIT_MoveDown_ML(EDITSTATE *es, BOOL extend)
1879 {
1880         INT s = es->selection_start;
1881         INT e = es->selection_end;
1882         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1883         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1884         INT x = (short)LOWORD(pos);
1885         INT y = (short)HIWORD(pos);
1886
1887         e = EDIT_CharFromPos(es, x, y + es->line_height, &after_wrap);
1888         if (!extend)
1889                 s = e;
1890         EDIT_EM_SetSel(es, s, e, after_wrap);
1891         EDIT_EM_ScrollCaret(es);
1892 }
1893
1894
1895 /*********************************************************************
1896  *
1897  *      EDIT_MoveEnd
1898  *
1899  */
1900 static void EDIT_MoveEnd(EDITSTATE *es, BOOL extend)
1901 {
1902         BOOL after_wrap = FALSE;
1903         INT e;
1904
1905         /* Pass a high value in x to make sure of receiving the end of the line */
1906         if (es->style & ES_MULTILINE)
1907                 e = EDIT_CharFromPos(es, 0x3fffffff,
1908                         HIWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP)), &after_wrap);
1909         else
1910                 e = strlenW(es->text);
1911         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, after_wrap);
1912         EDIT_EM_ScrollCaret(es);
1913 }
1914
1915
1916 /*********************************************************************
1917  *
1918  *      EDIT_MoveForward
1919  *
1920  */
1921 static void EDIT_MoveForward(EDITSTATE *es, BOOL extend)
1922 {
1923         INT e = es->selection_end;
1924
1925         if (es->text[e]) {
1926                 e++;
1927                 if ((es->style & ES_MULTILINE) && (es->text[e - 1] == '\r')) {
1928                         if (es->text[e] == '\n')
1929                                 e++;
1930                         else if ((es->text[e] == '\r') && (es->text[e + 1] == '\n'))
1931                                 e += 2;
1932                 }
1933         }
1934         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1935         EDIT_EM_ScrollCaret(es);
1936 }
1937
1938
1939 /*********************************************************************
1940  *
1941  *      EDIT_MoveHome
1942  *
1943  *      Home key: move to beginning of line.
1944  *
1945  */
1946 static void EDIT_MoveHome(EDITSTATE *es, BOOL extend)
1947 {
1948         INT e;
1949
1950         /* Pass the x_offset in x to make sure of receiving the first position of the line */
1951         if (es->style & ES_MULTILINE)
1952                 e = EDIT_CharFromPos(es, -es->x_offset,
1953                         HIWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP)), NULL);
1954         else
1955                 e = 0;
1956         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1957         EDIT_EM_ScrollCaret(es);
1958 }
1959
1960
1961 /*********************************************************************
1962  *
1963  *      EDIT_MovePageDown_ML
1964  *
1965  *      Only for multi line controls
1966  *      Move the caret one page down, on a column with the nearest
1967  *      x coordinate on the screen (might be a different column).
1968  *
1969  */
1970 static void EDIT_MovePageDown_ML(EDITSTATE *es, BOOL extend)
1971 {
1972         INT s = es->selection_start;
1973         INT e = es->selection_end;
1974         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1975         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1976         INT x = (short)LOWORD(pos);
1977         INT y = (short)HIWORD(pos);
1978
1979         e = EDIT_CharFromPos(es, x,
1980                 y + (es->format_rect.bottom - es->format_rect.top),
1981                 &after_wrap);
1982         if (!extend)
1983                 s = e;
1984         EDIT_EM_SetSel(es, s, e, after_wrap);
1985         EDIT_EM_ScrollCaret(es);
1986 }
1987
1988
1989 /*********************************************************************
1990  *
1991  *      EDIT_MovePageUp_ML
1992  *
1993  *      Only for multi line controls
1994  *      Move the caret one page up, on a column with the nearest
1995  *      x coordinate on the screen (might be a different column).
1996  *
1997  */
1998 static void EDIT_MovePageUp_ML(EDITSTATE *es, BOOL extend)
1999 {
2000         INT s = es->selection_start;
2001         INT e = es->selection_end;
2002         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
2003         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
2004         INT x = (short)LOWORD(pos);
2005         INT y = (short)HIWORD(pos);
2006
2007         e = EDIT_CharFromPos(es, x,
2008                 y - (es->format_rect.bottom - es->format_rect.top),
2009                 &after_wrap);
2010         if (!extend)
2011                 s = e;
2012         EDIT_EM_SetSel(es, s, e, after_wrap);
2013         EDIT_EM_ScrollCaret(es);
2014 }
2015
2016
2017 /*********************************************************************
2018  *
2019  *      EDIT_MoveUp_ML
2020  *
2021  *      Only for multi line controls
2022  *      Move the caret one line up, on a column with the nearest
2023  *      x coordinate on the screen (might be a different column).
2024  *
2025  */
2026 static void EDIT_MoveUp_ML(EDITSTATE *es, BOOL extend)
2027 {
2028         INT s = es->selection_start;
2029         INT e = es->selection_end;
2030         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
2031         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
2032         INT x = (short)LOWORD(pos);
2033         INT y = (short)HIWORD(pos);
2034
2035         e = EDIT_CharFromPos(es, x, y - es->line_height, &after_wrap);
2036         if (!extend)
2037                 s = e;
2038         EDIT_EM_SetSel(es, s, e, after_wrap);
2039         EDIT_EM_ScrollCaret(es);
2040 }
2041
2042
2043 /*********************************************************************
2044  *
2045  *      EDIT_MoveWordBackward
2046  *
2047  */
2048 static void EDIT_MoveWordBackward(EDITSTATE *es, BOOL extend)
2049 {
2050         INT s = es->selection_start;
2051         INT e = es->selection_end;
2052         INT l;
2053         INT ll;
2054         INT li;
2055
2056         l = EDIT_EM_LineFromChar(es, e);
2057         ll = EDIT_EM_LineLength(es, e);
2058         li = EDIT_EM_LineIndex(es, l);
2059         if (e - li == 0) {
2060                 if (l) {
2061                         li = EDIT_EM_LineIndex(es, l - 1);
2062                         e = li + EDIT_EM_LineLength(es, li);
2063                 }
2064         } else {
2065                 e = li + (INT)EDIT_CallWordBreakProc(es,
2066                                 li, e - li, ll, WB_LEFT);
2067         }
2068         if (!extend)
2069                 s = e;
2070         EDIT_EM_SetSel(es, s, e, FALSE);
2071         EDIT_EM_ScrollCaret(es);
2072 }
2073
2074
2075 /*********************************************************************
2076  *
2077  *      EDIT_MoveWordForward
2078  *
2079  */
2080 static void EDIT_MoveWordForward(EDITSTATE *es, BOOL extend)
2081 {
2082         INT s = es->selection_start;
2083         INT e = es->selection_end;
2084         INT l;
2085         INT ll;
2086         INT li;
2087
2088         l = EDIT_EM_LineFromChar(es, e);
2089         ll = EDIT_EM_LineLength(es, e);
2090         li = EDIT_EM_LineIndex(es, l);
2091         if (e - li == ll) {
2092                 if ((es->style & ES_MULTILINE) && (l != es->line_count - 1))
2093                         e = EDIT_EM_LineIndex(es, l + 1);
2094         } else {
2095                 e = li + EDIT_CallWordBreakProc(es,
2096                                 li, e - li + 1, ll, WB_RIGHT);
2097         }
2098         if (!extend)
2099                 s = e;
2100         EDIT_EM_SetSel(es, s, e, FALSE);
2101         EDIT_EM_ScrollCaret(es);
2102 }
2103
2104
2105 /*********************************************************************
2106  *
2107  *      EDIT_PaintLine
2108  *
2109  */
2110 static void EDIT_PaintLine(EDITSTATE *es, HDC dc, INT line, BOOL rev)
2111 {
2112         INT s = es->selection_start;
2113         INT e = es->selection_end;
2114         INT li;
2115         INT ll;
2116         INT x;
2117         INT y;
2118         LRESULT pos;
2119
2120         if (es->style & ES_MULTILINE) {
2121                 INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
2122                 if ((line < es->y_offset) || (line > es->y_offset + vlc) || (line >= es->line_count))
2123                         return;
2124         } else if (line)
2125                 return;
2126
2127         TRACE("line=%d\n", line);
2128
2129         pos = EDIT_EM_PosFromChar(es, EDIT_EM_LineIndex(es, line), FALSE);
2130         x = (short)LOWORD(pos);
2131         y = (short)HIWORD(pos);
2132         li = EDIT_EM_LineIndex(es, line);
2133         ll = EDIT_EM_LineLength(es, li);
2134         s = min(es->selection_start, es->selection_end);
2135         e = max(es->selection_start, es->selection_end);
2136         s = min(li + ll, max(li, s));
2137         e = min(li + ll, max(li, e));
2138         if (rev && (s != e) &&
2139                         ((es->flags & EF_FOCUSED) || (es->style & ES_NOHIDESEL))) {
2140                 x += EDIT_PaintText(es, dc, x, y, line, 0, s - li, FALSE);
2141                 x += EDIT_PaintText(es, dc, x, y, line, s - li, e - s, TRUE);
2142                 x += EDIT_PaintText(es, dc, x, y, line, e - li, li + ll - e, FALSE);
2143         } else
2144                 x += EDIT_PaintText(es, dc, x, y, line, 0, ll, FALSE);
2145 }
2146
2147
2148 /*********************************************************************
2149  *
2150  *      EDIT_PaintText
2151  *
2152  */
2153 static INT EDIT_PaintText(EDITSTATE *es, HDC dc, INT x, INT y, INT line, INT col, INT count, BOOL rev)
2154 {
2155         COLORREF BkColor;
2156         COLORREF TextColor;
2157         INT ret;
2158         INT li;
2159         INT BkMode;
2160         SIZE size;
2161
2162         if (!count)
2163                 return 0;
2164         BkMode = GetBkMode(dc);
2165         BkColor = GetBkColor(dc);
2166         TextColor = GetTextColor(dc);
2167         if (rev) {
2168                 SetBkColor(dc, GetSysColor(COLOR_HIGHLIGHT));
2169                 SetTextColor(dc, GetSysColor(COLOR_HIGHLIGHTTEXT));
2170                 SetBkMode( dc, OPAQUE);
2171         }
2172         li = EDIT_EM_LineIndex(es, line);
2173         if (es->style & ES_MULTILINE) {
2174                 ret = (INT)LOWORD(TabbedTextOutW(dc, x, y, es->text + li + col, count,
2175                                         es->tabs_count, es->tabs, es->format_rect.left - es->x_offset));
2176         } else {
2177                 LPWSTR text = EDIT_GetPasswordPointer_SL(es);
2178                 TextOutW(dc, x, y, text + li + col, count);
2179                 GetTextExtentPoint32W(dc, text + li + col, count, &size);
2180                 ret = size.cx;
2181                 if (es->style & ES_PASSWORD)
2182                         HeapFree(GetProcessHeap(), 0, text);
2183         }
2184         if (rev) {
2185                 SetBkColor(dc, BkColor);
2186                 SetTextColor(dc, TextColor);
2187                 SetBkMode( dc, BkMode);
2188         }
2189         return ret;
2190 }
2191
2192
2193 /*********************************************************************
2194  *
2195  *      EDIT_SetCaretPos
2196  *
2197  */
2198 static void EDIT_SetCaretPos(EDITSTATE *es, INT pos,
2199                              BOOL after_wrap)
2200 {
2201         LRESULT res = EDIT_EM_PosFromChar(es, pos, after_wrap);
2202         TRACE("%d - %dx%d\n", pos, (short)LOWORD(res), (short)HIWORD(res));
2203         SetCaretPos((short)LOWORD(res), (short)HIWORD(res));
2204 }
2205
2206
2207 /*********************************************************************
2208  *
2209  *      EDIT_SetRectNP
2210  *
2211  *      note:   this is not (exactly) the handler called on EM_SETRECTNP
2212  *              it is also used to set the rect of a single line control
2213  *
2214  */
2215 static void EDIT_SetRectNP(EDITSTATE *es, LPRECT rc)
2216 {
2217         RECT ClientRect;
2218         LONG_PTR ExStyle;
2219
2220         CopyRect(&es->format_rect, rc);
2221         if (es->style & ES_MULTILINE)
2222         {
2223                 if (es->style & WS_BORDER) {
2224                         INT bw = GetSystemMetrics(SM_CXBORDER) + 1;
2225                         es->format_rect.left += bw;
2226                         es->format_rect.right -= bw;
2227                         es->format_rect.top += bw;
2228                         es->format_rect.bottom -= bw;
2229                 }
2230         }
2231         else
2232         {
2233                 ExStyle = GetWindowLongPtrW(es->hwndSelf, GWL_EXSTYLE);
2234                 if (ExStyle & WS_EX_CLIENTEDGE) {
2235                         if (es->line_height + 2 <=
2236                             es->format_rect.bottom - es->format_rect.top) {
2237                                 es->format_rect.top++;
2238                                 es->format_rect.bottom--;
2239                         }
2240                 } else if (es->style & WS_BORDER) {
2241                         INT bw = GetSystemMetrics(SM_CXBORDER) + 1;
2242                         es->format_rect.left += bw;
2243                         es->format_rect.right -= bw;
2244                         if (es->line_height + 2 * bw <=
2245                             es->format_rect.bottom - es->format_rect.top) {
2246                                 es->format_rect.top += bw;
2247                                 es->format_rect.bottom -= bw;
2248                         }
2249                 }
2250         }
2251         es->format_rect.left += es->left_margin;
2252         es->format_rect.right -= es->right_margin;
2253         es->format_rect.right = max(es->format_rect.right, es->format_rect.left + es->char_width);
2254         if (es->style & ES_MULTILINE)
2255         {
2256             INT fw, vlc, max_x_offset, max_y_offset;
2257
2258             vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
2259             es->format_rect.bottom = es->format_rect.top + max(1, vlc) * es->line_height;
2260
2261             /* correct es->x_offset */
2262             fw = es->format_rect.right - es->format_rect.left;
2263             max_x_offset = es->text_width - fw;
2264             if(max_x_offset < 0) max_x_offset = 0;
2265             if(es->x_offset > max_x_offset)
2266                 es->x_offset = max_x_offset;
2267
2268             /* correct es->y_offset */
2269             max_y_offset = es->line_count - vlc;
2270             if(max_y_offset < 0) max_y_offset = 0;
2271             if(es->y_offset > max_y_offset)
2272                 es->y_offset = max_y_offset;
2273
2274             /* force scroll info update */
2275             EDIT_UpdateScrollInfo(es);
2276         }
2277         else
2278         /* Windows doesn't care to fix text placement for SL controls */
2279                 es->format_rect.bottom = es->format_rect.top + es->line_height;
2280
2281         /* Always stay within the client area */
2282         GetClientRect(es->hwndSelf, &ClientRect);
2283         es->format_rect.bottom = min(es->format_rect.bottom, ClientRect.bottom);
2284
2285         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL))
2286                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
2287         
2288         EDIT_SetCaretPos(es, es->selection_end, es->flags & EF_AFTER_WRAP);
2289 }
2290
2291
2292 /*********************************************************************
2293  *
2294  *      EDIT_UnlockBuffer
2295  *
2296  */
2297 static void EDIT_UnlockBuffer(EDITSTATE *es, BOOL force)
2298 {
2299         HINSTANCE16 hInstance = GetWindowLongPtrW( es->hwndSelf, GWLP_HINSTANCE );
2300
2301         /* Edit window might be already destroyed */
2302         if(!IsWindow(es->hwndSelf))
2303         {
2304             WARN("edit hwnd %p already destroyed\n", es->hwndSelf);
2305             return;
2306         }
2307
2308         if (!es->lock_count) {
2309                 ERR("lock_count == 0 ... please report\n");
2310                 return;
2311         }
2312         if (!es->text) {
2313                 ERR("es->text == 0 ... please report\n");
2314                 return;
2315         }
2316
2317         if (force || (es->lock_count == 1)) {
2318             if (es->hloc32W) {
2319                 CHAR *textA = NULL;
2320                 BOOL _16bit = FALSE;
2321                 UINT countA = 0;
2322                 UINT countW = strlenW(es->text) + 1;
2323
2324                 if(es->hloc32A)
2325                 {
2326                     UINT countA_new = WideCharToMultiByte(CP_ACP, 0, es->text, countW, NULL, 0, NULL, NULL);
2327                     TRACE("Synchronizing with 32-bit ANSI buffer\n");
2328                     TRACE("%d WCHARs translated to %d bytes\n", countW, countA_new);
2329                     countA = LocalSize(es->hloc32A);
2330                     if(countA_new > countA)
2331                     {
2332                         HLOCAL hloc32A_new;
2333                         UINT alloc_size = ROUND_TO_GROW(countA_new);
2334                         TRACE("Resizing 32-bit ANSI buffer from %d to %d bytes\n", countA, alloc_size);
2335                         hloc32A_new = LocalReAlloc(es->hloc32A, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
2336                         if(hloc32A_new)
2337                         {
2338                             es->hloc32A = hloc32A_new;
2339                             countA = LocalSize(hloc32A_new);
2340                             TRACE("Real new size %d bytes\n", countA);
2341                         }
2342                         else
2343                             WARN("FAILED! Will synchronize partially\n");
2344                     }
2345                     textA = LocalLock(es->hloc32A);
2346                 }
2347                 else if(es->hloc16)
2348                 {
2349                     UINT countA_new = WideCharToMultiByte(CP_ACP, 0, es->text, countW, NULL, 0, NULL, NULL);
2350                     TRACE("Synchronizing with 16-bit ANSI buffer\n");
2351                     TRACE("%d WCHARs translated to %d bytes\n", countW, countA_new);
2352                     countA = LOCAL_Size(hInstance, es->hloc16);
2353                     if(countA_new > countA)
2354                     {
2355                         HLOCAL16 hloc16_new;
2356                         UINT alloc_size = ROUND_TO_GROW(countA_new);
2357                         TRACE("Resizing 16-bit ANSI buffer from %d to %d bytes\n", countA, alloc_size);
2358                         hloc16_new = LOCAL_ReAlloc(hInstance, es->hloc16, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
2359                         if(hloc16_new)
2360                         {
2361                             es->hloc16 = hloc16_new;
2362                             countA = LOCAL_Size(hInstance, hloc16_new);
2363                             TRACE("Real new size %d bytes\n", countA);
2364                         }
2365                         else
2366                             WARN("FAILED! Will synchronize partially\n");
2367                     }
2368                     textA = LOCAL_Lock(hInstance, es->hloc16);
2369                     _16bit = TRUE;
2370                 }
2371
2372                 if(textA)
2373                 {
2374                     WideCharToMultiByte(CP_ACP, 0, es->text, countW, textA, countA, NULL, NULL);
2375                     if(_16bit)
2376                         LOCAL_Unlock(hInstance, es->hloc16);
2377                     else
2378                         LocalUnlock(es->hloc32A);
2379                 }
2380
2381                 LocalUnlock(es->hloc32W);
2382                 es->text = NULL;
2383             }
2384             else {
2385                 ERR("no buffer ... please report\n");
2386                 return;
2387             }
2388         }
2389         es->lock_count--;
2390 }
2391
2392
2393 /*********************************************************************
2394  *
2395  *      EDIT_UpdateScrollInfo
2396  *
2397  */
2398 static void EDIT_UpdateScrollInfo(EDITSTATE *es)
2399 {
2400     if ((es->style & WS_VSCROLL) && !(es->flags & EF_VSCROLL_TRACK))
2401     {
2402         SCROLLINFO si;
2403         si.cbSize       = sizeof(SCROLLINFO);
2404         si.fMask        = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
2405         si.nMin         = 0;
2406         si.nMax         = es->line_count - 1;
2407         si.nPage        = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
2408         si.nPos         = es->y_offset;
2409         TRACE("SB_VERT, nMin=%d, nMax=%d, nPage=%d, nPos=%d\n",
2410                 si.nMin, si.nMax, si.nPage, si.nPos);
2411         SetScrollInfo(es->hwndSelf, SB_VERT, &si, TRUE);
2412     }
2413
2414     if ((es->style & WS_HSCROLL) && !(es->flags & EF_HSCROLL_TRACK))
2415     {
2416         SCROLLINFO si;
2417         si.cbSize       = sizeof(SCROLLINFO);
2418         si.fMask        = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
2419         si.nMin         = 0;
2420         si.nMax         = es->text_width - 1;
2421         si.nPage        = es->format_rect.right - es->format_rect.left;
2422         si.nPos         = es->x_offset;
2423         TRACE("SB_HORZ, nMin=%d, nMax=%d, nPage=%d, nPos=%d\n",
2424                 si.nMin, si.nMax, si.nPage, si.nPos);
2425         SetScrollInfo(es->hwndSelf, SB_HORZ, &si, TRUE);
2426     }
2427 }
2428
2429 /*********************************************************************
2430  *
2431  *      EDIT_WordBreakProc
2432  *
2433  *      Find the beginning of words.
2434  *      Note:   unlike the specs for a WordBreakProc, this function only
2435  *              allows to be called without linebreaks between s[0] upto
2436  *              s[count - 1].  Remember it is only called
2437  *              internally, so we can decide this for ourselves.
2438  *
2439  */
2440 static INT CALLBACK EDIT_WordBreakProc(LPWSTR s, INT index, INT count, INT action)
2441 {
2442         INT ret = 0;
2443
2444         TRACE("s=%p, index=%d, count=%d, action=%d\n", s, index, count, action);
2445
2446         if(!s) return 0;
2447
2448         switch (action) {
2449         case WB_LEFT:
2450                 if (!count)
2451                         break;
2452                 if (index)
2453                         index--;
2454                 if (s[index] == ' ') {
2455                         while (index && (s[index] == ' '))
2456                                 index--;
2457                         if (index) {
2458                                 while (index && (s[index] != ' '))
2459                                         index--;
2460                                 if (s[index] == ' ')
2461                                         index++;
2462                         }
2463                 } else {
2464                         while (index && (s[index] != ' '))
2465                                 index--;
2466                         if (s[index] == ' ')
2467                                 index++;
2468                 }
2469                 ret = index;
2470                 break;
2471         case WB_RIGHT:
2472                 if (!count)
2473                         break;
2474                 if (index)
2475                         index--;
2476                 if (s[index] == ' ')
2477                         while ((index < count) && (s[index] == ' ')) index++;
2478                 else {
2479                         while (s[index] && (s[index] != ' ') && (index < count))
2480                                 index++;
2481                         while ((s[index] == ' ') && (index < count)) index++;
2482                 }
2483                 ret = index;
2484                 break;
2485         case WB_ISDELIMITER:
2486                 ret = (s[index] == ' ');
2487                 break;
2488         default:
2489                 ERR("unknown action code, please report !\n");
2490                 break;
2491         }
2492         return ret;
2493 }
2494
2495
2496 /*********************************************************************
2497  *
2498  *      EM_CHARFROMPOS
2499  *
2500  *      returns line number (not index) in high-order word of result.
2501  *      NB : Q137805 is unclear about this. POINT * pointer in lParam apply
2502  *      to Richedit, not to the edit control. Original documentation is valid.
2503  *      FIXME: do the specs mean to return -1 if outside client area or
2504  *              if outside formatting rectangle ???
2505  *
2506  */
2507 static LRESULT EDIT_EM_CharFromPos(EDITSTATE *es, INT x, INT y)
2508 {
2509         POINT pt;
2510         RECT rc;
2511         INT index;
2512
2513         pt.x = x;
2514         pt.y = y;
2515         GetClientRect(es->hwndSelf, &rc);
2516         if (!PtInRect(&rc, pt))
2517                 return -1;
2518
2519         index = EDIT_CharFromPos(es, x, y, NULL);
2520         return MAKELONG(index, EDIT_EM_LineFromChar(es, index));
2521 }
2522
2523
2524 /*********************************************************************
2525  *
2526  *      EM_FMTLINES
2527  *
2528  * Enable or disable soft breaks.
2529  * 
2530  * This means: insert or remove the soft linebreak character (\r\r\n).
2531  * Take care to check if the text still fits the buffer after insertion.
2532  * If not, notify with EN_ERRSPACE.
2533  * 
2534  */
2535 static BOOL EDIT_EM_FmtLines(EDITSTATE *es, BOOL add_eol)
2536 {
2537         es->flags &= ~EF_USE_SOFTBRK;
2538         if (add_eol) {
2539                 es->flags |= EF_USE_SOFTBRK;
2540                 FIXME("soft break enabled, not implemented\n");
2541         }
2542         return add_eol;
2543 }
2544
2545
2546 /*********************************************************************
2547  *
2548  *      EM_GETHANDLE
2549  *
2550  *      Hopefully this won't fire back at us.
2551  *      We always start with a fixed buffer in the local heap.
2552  *      Despite of the documentation says that the local heap is used
2553  *      only if DS_LOCALEDIT flag is set, NT and 2000 always allocate
2554  *      buffer on the local heap.
2555  *
2556  */
2557 static HLOCAL EDIT_EM_GetHandle(EDITSTATE *es)
2558 {
2559         HLOCAL hLocal;
2560
2561         if (!(es->style & ES_MULTILINE))
2562                 return 0;
2563
2564         if(es->is_unicode)
2565             hLocal = es->hloc32W;
2566         else
2567         {
2568             if(!es->hloc32A)
2569             {
2570                 CHAR *textA;
2571                 UINT countA, alloc_size;
2572                 TRACE("Allocating 32-bit ANSI alias buffer\n");
2573                 countA = WideCharToMultiByte(CP_ACP, 0, es->text, -1, NULL, 0, NULL, NULL);
2574                 alloc_size = ROUND_TO_GROW(countA);
2575                 if(!(es->hloc32A = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size)))
2576                 {
2577                     ERR("Could not allocate %d bytes for 32-bit ANSI alias buffer\n", alloc_size);
2578                     return 0;
2579                 }
2580                 textA = LocalLock(es->hloc32A);
2581                 WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, countA, NULL, NULL);
2582                 LocalUnlock(es->hloc32A);
2583             }
2584             hLocal = es->hloc32A;
2585         }
2586
2587         TRACE("Returning %p, LocalSize() = %ld\n", hLocal, LocalSize(hLocal));
2588         return hLocal;
2589 }
2590
2591
2592 /*********************************************************************
2593  *
2594  *      EM_GETHANDLE16
2595  *
2596  *      Hopefully this won't fire back at us.
2597  *      We always start with a buffer in 32 bit linear memory.
2598  *      However, with this message a 16 bit application requests
2599  *      a handle of 16 bit local heap memory, where it expects to find
2600  *      the text.
2601  *      It's a pitty that from this moment on we have to use this
2602  *      local heap, because applications may rely on the handle
2603  *      in the future.
2604  *
2605  *      In this function we'll try to switch to local heap.
2606  */
2607 static HLOCAL16 EDIT_EM_GetHandle16(EDITSTATE *es)
2608 {
2609         HINSTANCE16 hInstance = GetWindowLongPtrW( es->hwndSelf, GWLP_HINSTANCE );
2610         CHAR *textA;
2611         UINT countA, alloc_size;
2612
2613         if (!(es->style & ES_MULTILINE))
2614                 return 0;
2615
2616         if (es->hloc16)
2617                 return es->hloc16;
2618
2619         if (!LOCAL_HeapSize(hInstance)) {
2620                 if (!LocalInit16(hInstance, 0,
2621                                 GlobalSize16(hInstance))) {
2622                         ERR("could not initialize local heap\n");
2623                         return 0;
2624                 }
2625                 TRACE("local heap initialized\n");
2626         }
2627
2628         countA = WideCharToMultiByte(CP_ACP, 0, es->text, -1, NULL, 0, NULL, NULL);
2629         alloc_size = ROUND_TO_GROW(countA);
2630
2631         TRACE("Allocating 16-bit ANSI alias buffer\n");
2632         if (!(es->hloc16 = LOCAL_Alloc(hInstance, LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size))) {
2633                 ERR("could not allocate new 16 bit buffer\n");
2634                 return 0;
2635         }
2636
2637         if (!(textA = (LPSTR)LOCAL_Lock(hInstance, es->hloc16))) {
2638                 ERR("could not lock new 16 bit buffer\n");
2639                 LOCAL_Free(hInstance, es->hloc16);
2640                 es->hloc16 = 0;
2641                 return 0;
2642         }
2643
2644         WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, countA, NULL, NULL);
2645         LOCAL_Unlock(hInstance, es->hloc16);
2646
2647         TRACE("Returning %04X, LocalSize() = %d\n", es->hloc16, LOCAL_Size(hInstance, es->hloc16));
2648         return es->hloc16;
2649 }
2650
2651
2652 /*********************************************************************
2653  *
2654  *      EM_GETLINE
2655  *
2656  */
2657 static INT EDIT_EM_GetLine(EDITSTATE *es, INT line, LPWSTR dst, BOOL unicode)
2658 {
2659         LPWSTR src;
2660         INT line_len, dst_len;
2661         INT i;
2662
2663         if (es->style & ES_MULTILINE) {
2664                 if (line >= es->line_count)
2665                         return 0;
2666         } else
2667                 line = 0;
2668         i = EDIT_EM_LineIndex(es, line);
2669         src = es->text + i;
2670         line_len = EDIT_EM_LineLength(es, i);
2671         dst_len = *(WORD *)dst;
2672         if(unicode)
2673         {
2674             if(dst_len <= line_len)
2675             {
2676                 memcpy(dst, src, dst_len * sizeof(WCHAR));
2677                 return dst_len;
2678             }
2679             else /* Append 0 if enough space */
2680             {
2681                 memcpy(dst, src, line_len * sizeof(WCHAR));
2682                 dst[line_len] = 0;
2683                 return line_len;
2684             }
2685         }
2686         else
2687         {
2688             INT ret = WideCharToMultiByte(CP_ACP, 0, src, line_len, (LPSTR)dst, dst_len, NULL, NULL);
2689             if(!ret) /* Insufficient buffer size */
2690                 return dst_len;
2691             if(ret < dst_len) /* Append 0 if enough space */
2692                 ((LPSTR)dst)[ret] = 0;
2693             return ret;
2694         }
2695 }
2696
2697
2698 /*********************************************************************
2699  *
2700  *      EM_GETSEL
2701  *
2702  */
2703 static LRESULT EDIT_EM_GetSel(EDITSTATE *es, PUINT start, PUINT end)
2704 {
2705         UINT s = es->selection_start;
2706         UINT e = es->selection_end;
2707
2708         ORDER_UINT(s, e);
2709         if (start)
2710                 *start = s;
2711         if (end)
2712                 *end = e;
2713         return MAKELONG(s, e);
2714 }
2715
2716
2717 /*********************************************************************
2718  *
2719  *      EM_GETTHUMB
2720  *
2721  *      FIXME: is this right ?  (or should it be only VSCROLL)
2722  *      (and maybe only for edit controls that really have their
2723  *      own scrollbars) (and maybe only for multiline controls ?)
2724  *      All in all: very poorly documented
2725  *
2726  */
2727 static LRESULT EDIT_EM_GetThumb(EDITSTATE *es)
2728 {
2729         return MAKELONG(EDIT_WM_VScroll(es, EM_GETTHUMB16, 0),
2730                 EDIT_WM_HScroll(es, EM_GETTHUMB16, 0));
2731 }
2732
2733
2734 /*********************************************************************
2735  *
2736  *      EM_LINEFROMCHAR
2737  *
2738  */
2739 static INT EDIT_EM_LineFromChar(EDITSTATE *es, INT index)
2740 {
2741         INT line;
2742         LINEDEF *line_def;
2743
2744         if (!(es->style & ES_MULTILINE))
2745                 return 0;
2746         if (index > (INT)strlenW(es->text))
2747                 return es->line_count - 1;
2748         if (index == -1)
2749                 index = min(es->selection_start, es->selection_end);
2750
2751         line = 0;
2752         line_def = es->first_line_def;
2753         index -= line_def->length;
2754         while ((index >= 0) && line_def->next) {
2755                 line++;
2756                 line_def = line_def->next;
2757                 index -= line_def->length;
2758         }
2759         return line;
2760 }
2761
2762
2763 /*********************************************************************
2764  *
2765  *      EM_LINEINDEX
2766  *
2767  */
2768 static INT EDIT_EM_LineIndex(EDITSTATE *es, INT line)
2769 {
2770         INT line_index;
2771         LINEDEF *line_def;
2772
2773         if (!(es->style & ES_MULTILINE))
2774                 return 0;
2775         if (line >= es->line_count)
2776                 return -1;
2777
2778         line_index = 0;
2779         line_def = es->first_line_def;
2780         if (line == -1) {
2781                 INT index = es->selection_end - line_def->length;
2782                 while ((index >= 0) && line_def->next) {
2783                         line_index += line_def->length;
2784                         line_def = line_def->next;
2785                         index -= line_def->length;
2786                 }
2787         } else {
2788                 while (line > 0) {
2789                         line_index += line_def->length;
2790                         line_def = line_def->next;
2791                         line--;
2792                 }
2793         }
2794         return line_index;
2795 }
2796
2797
2798 /*********************************************************************
2799  *
2800  *      EM_LINELENGTH
2801  *
2802  */
2803 static INT EDIT_EM_LineLength(EDITSTATE *es, INT index)
2804 {
2805         LINEDEF *line_def;
2806
2807         if (!(es->style & ES_MULTILINE))
2808                 return strlenW(es->text);
2809
2810         if (index == -1) {
2811                 /* get the number of remaining non-selected chars of selected lines */
2812                 INT32 l; /* line number */
2813                 INT32 li; /* index of first char in line */
2814                 INT32 count;
2815                 l = EDIT_EM_LineFromChar(es, es->selection_start);
2816                 /* # chars before start of selection area */
2817                 count = es->selection_start - EDIT_EM_LineIndex(es, l);
2818                 l = EDIT_EM_LineFromChar(es, es->selection_end);
2819                 /* # chars after end of selection */
2820                 li = EDIT_EM_LineIndex(es, l);
2821                 count += li + EDIT_EM_LineLength(es, li) - es->selection_end;
2822                 return count;
2823         }
2824         line_def = es->first_line_def;
2825         index -= line_def->length;
2826         while ((index >= 0) && line_def->next) {
2827                 line_def = line_def->next;
2828                 index -= line_def->length;
2829         }
2830         return line_def->net_length;
2831 }
2832
2833
2834 /*********************************************************************
2835  *
2836  *      EM_LINESCROLL
2837  *
2838  *      NOTE: dx is in average character widths, dy - in lines;
2839  *
2840  */
2841 static BOOL EDIT_EM_LineScroll(EDITSTATE *es, INT dx, INT dy)
2842 {
2843         if (!(es->style & ES_MULTILINE))
2844                 return FALSE;
2845
2846         dx *= es->char_width;
2847         return EDIT_EM_LineScroll_internal(es, dx, dy);
2848 }
2849
2850 /*********************************************************************
2851  *
2852  *      EDIT_EM_LineScroll_internal
2853  *
2854  *      Version of EDIT_EM_LineScroll for internal use.
2855  *      It doesn't refuse if ES_MULTILINE is set and assumes that
2856  *      dx is in pixels, dy - in lines.
2857  *
2858  */
2859 static BOOL EDIT_EM_LineScroll_internal(EDITSTATE *es, INT dx, INT dy)
2860 {
2861         INT nyoff;
2862         INT x_offset_in_pixels;
2863         INT lines_per_page = (es->format_rect.bottom - es->format_rect.top) /
2864                               es->line_height;
2865
2866         if (es->style & ES_MULTILINE)
2867         {
2868             x_offset_in_pixels = es->x_offset;
2869         }
2870         else
2871         {
2872             dy = 0;
2873             x_offset_in_pixels = (short)LOWORD(EDIT_EM_PosFromChar(es, es->x_offset, FALSE));
2874         }
2875
2876         if (-dx > x_offset_in_pixels)
2877                 dx = -x_offset_in_pixels;
2878         if (dx > es->text_width - x_offset_in_pixels)
2879                 dx = es->text_width - x_offset_in_pixels;
2880         nyoff = max(0, es->y_offset + dy);
2881         if (nyoff >= es->line_count - lines_per_page)
2882                 nyoff = max(0, es->line_count - lines_per_page);
2883         dy = (es->y_offset - nyoff) * es->line_height;
2884         if (dx || dy) {
2885                 RECT rc1;
2886                 RECT rc;
2887
2888                 es->y_offset = nyoff;
2889                 if(es->style & ES_MULTILINE)
2890                     es->x_offset += dx;
2891                 else
2892                     es->x_offset += dx / es->char_width;
2893
2894                 GetClientRect(es->hwndSelf, &rc1);
2895                 IntersectRect(&rc, &rc1, &es->format_rect);
2896                 ScrollWindowEx(es->hwndSelf, -dx, dy,
2897                                 NULL, &rc, NULL, NULL, SW_INVALIDATE);
2898                 /* force scroll info update */
2899                 EDIT_UpdateScrollInfo(es);
2900         }
2901         if (dx && !(es->flags & EF_HSCROLL_TRACK))
2902                 EDIT_NOTIFY_PARENT(es, EN_HSCROLL, "EN_HSCROLL");
2903         if (dy && !(es->flags & EF_VSCROLL_TRACK))
2904                 EDIT_NOTIFY_PARENT(es, EN_VSCROLL, "EN_VSCROLL");
2905         return TRUE;
2906 }
2907
2908
2909 /*********************************************************************
2910  *
2911  *      EM_POSFROMCHAR
2912  *
2913  */
2914 static LRESULT EDIT_EM_PosFromChar(EDITSTATE *es, INT index, BOOL after_wrap)
2915 {
2916         INT len = strlenW(es->text);
2917         INT l;
2918         INT li;
2919         INT x;
2920         INT y = 0;
2921         INT w;
2922         INT lw = 0;
2923         INT ll = 0;
2924         HDC dc;
2925         HFONT old_font = 0;
2926         SIZE size;
2927         LINEDEF *line_def;
2928
2929         index = min(index, len);
2930         dc = GetDC(es->hwndSelf);
2931         if (es->font)
2932                 old_font = SelectObject(dc, es->font);
2933         if (es->style & ES_MULTILINE) {
2934                 l = EDIT_EM_LineFromChar(es, index);
2935                 y = (l - es->y_offset) * es->line_height;
2936                 li = EDIT_EM_LineIndex(es, l);
2937                 if (after_wrap && (li == index) && l) {
2938                         INT l2 = l - 1;
2939                         line_def = es->first_line_def;
2940                         while (l2) {
2941                                 line_def = line_def->next;
2942                                 l2--;
2943                         }
2944                         if (line_def->ending == END_WRAP) {
2945                                 l--;
2946                                 y -= es->line_height;
2947                                 li = EDIT_EM_LineIndex(es, l);
2948                         }
2949                 }
2950
2951                 line_def = es->first_line_def;
2952                 while (line_def->index != li)
2953                         line_def = line_def->next;
2954
2955                 ll = line_def->net_length;
2956                 lw = line_def->width;
2957
2958                 w = es->format_rect.right - es->format_rect.left;
2959                 if (es->style & ES_RIGHT)
2960                 {
2961                         x = LOWORD(GetTabbedTextExtentW(dc, es->text + li + (index - li), ll - (index - li),
2962                                 es->tabs_count, es->tabs)) - es->x_offset;
2963                         x = w - x;
2964                 }
2965                 else if (es->style & ES_CENTER)
2966                 {
2967                         x = LOWORD(GetTabbedTextExtentW(dc, es->text + li, index - li,
2968                                 es->tabs_count, es->tabs)) - es->x_offset;
2969                         x += (w - lw) / 2;
2970                 }
2971                 else /* ES_LEFT */
2972                 {
2973                     x = LOWORD(GetTabbedTextExtentW(dc, es->text + li, index - li,
2974                                 es->tabs_count, es->tabs)) - es->x_offset;
2975                 }
2976         } else {
2977                 LPWSTR text = EDIT_GetPasswordPointer_SL(es);
2978                 if (index < es->x_offset) {
2979                         GetTextExtentPoint32W(dc, text + index,
2980                                         es->x_offset - index, &size);
2981                         x = -size.cx;
2982                 } else {
2983                         GetTextExtentPoint32W(dc, text + es->x_offset,
2984                                         index - es->x_offset, &size);
2985                          x = size.cx;
2986
2987                         if (!es->x_offset && (es->style & (ES_RIGHT | ES_CENTER)))
2988                         {
2989                                 w = es->format_rect.right - es->format_rect.left;
2990                                 if (w > es->text_width)
2991                                 {
2992                                         if (es->style & ES_RIGHT)
2993                                                 x += w - es->text_width;
2994                                         else if (es->style & ES_CENTER)
2995                                                 x += (w - es->text_width) / 2;
2996                                 }
2997                         }
2998                 }
2999                 y = 0;
3000                 if (es->style & ES_PASSWORD)
3001                         HeapFree(GetProcessHeap(), 0, text);
3002         }
3003         x += es->format_rect.left;
3004         y += es->format_rect.top;
3005         if (es->font)
3006                 SelectObject(dc, old_font);
3007         ReleaseDC(es->hwndSelf, dc);
3008         return MAKELONG((INT16)x, (INT16)y);
3009 }
3010
3011
3012 /*********************************************************************
3013  *
3014  *      EM_REPLACESEL
3015  *
3016  *      FIXME: handle ES_NUMBER and ES_OEMCONVERT here
3017  *
3018  */
3019 static void EDIT_EM_ReplaceSel(EDITSTATE *es, BOOL can_undo, LPCWSTR lpsz_replace, BOOL send_update, BOOL honor_limit)
3020 {
3021         UINT strl = strlenW(lpsz_replace);
3022         UINT tl = strlenW(es->text);
3023         UINT utl;
3024         UINT s;
3025         UINT e;
3026         UINT i;
3027         UINT size;
3028         LPWSTR p;
3029         HRGN hrgn = 0;
3030
3031         TRACE("%s, can_undo %d, send_update %d\n",
3032             debugstr_w(lpsz_replace), can_undo, send_update);
3033
3034         s = es->selection_start;
3035         e = es->selection_end;
3036
3037         if ((s == e) && !strl)
3038                 return;
3039
3040         ORDER_UINT(s, e);
3041
3042         /* Issue the EN_MAXTEXT notification and continue with replacing text
3043          * such that buffer limit is honored. */
3044         size = tl - (e - s) + strl;
3045         if ((honor_limit) && (es->buffer_limit > 0) && (size > es->buffer_limit)) {
3046                 EDIT_NOTIFY_PARENT(es, EN_MAXTEXT, "EN_MAXTEXT");
3047                 strl = es->buffer_limit - (tl - (e-s));
3048         }
3049
3050         if (!EDIT_MakeFit(es, tl - (e - s) + strl))
3051                 return;
3052
3053         if (e != s) {
3054                 /* there is something to be deleted */
3055                 TRACE("deleting stuff.\n");
3056                 if (can_undo) {
3057                         utl = strlenW(es->undo_text);
3058                         if (!es->undo_insert_count && (*es->undo_text && (s == es->undo_position))) {
3059                                 /* undo-buffer is extended to the right */
3060                                 EDIT_MakeUndoFit(es, utl + e - s);
3061                                 strncpyW(es->undo_text + utl, es->text + s, e - s + 1);
3062                                 (es->undo_text + utl)[e - s] = 0; /* ensure 0 termination */
3063                         } else if (!es->undo_insert_count && (*es->undo_text && (e == es->undo_position))) {
3064                                 /* undo-buffer is extended to the left */
3065                                 EDIT_MakeUndoFit(es, utl + e - s);
3066                                 for (p = es->undo_text + utl ; p >= es->undo_text ; p--)
3067                                         p[e - s] = p[0];
3068                                 for (i = 0 , p = es->undo_text ; i < e - s ; i++)
3069                                         p[i] = (es->text + s)[i];
3070                                 es->undo_position = s;
3071                         } else {
3072                                 /* new undo-buffer */
3073                                 EDIT_MakeUndoFit(es, e - s);
3074                                 strncpyW(es->undo_text, es->text + s, e - s + 1);
3075                                 es->undo_text[e - s] = 0; /* ensure 0 termination */
3076                                 es->undo_position = s;
3077                         }
3078                         /* any deletion makes the old insertion-undo invalid */
3079                         es->undo_insert_count = 0;
3080                 } else
3081                         EDIT_EM_EmptyUndoBuffer(es);
3082
3083                 /* now delete */
3084                 strcpyW(es->text + s, es->text + e);
3085         }
3086         if (strl) {
3087                 /* there is an insertion */
3088                 if (can_undo) {
3089                         if ((s == es->undo_position) ||
3090                                         ((es->undo_insert_count) &&
3091                                         (s == es->undo_position + es->undo_insert_count)))
3092                                 /*
3093                                  * insertion is new and at delete position or
3094                                  * an extension to either left or right
3095                                  */
3096                                 es->undo_insert_count += strl;
3097                         else {
3098                                 /* new insertion undo */
3099                                 es->undo_position = s;
3100                                 es->undo_insert_count = strl;
3101                                 /* new insertion makes old delete-buffer invalid */
3102                                 *es->undo_text = '\0';
3103                         }
3104                 } else
3105                         EDIT_EM_EmptyUndoBuffer(es);
3106
3107                 /* now insert */
3108                 tl = strlenW(es->text);
3109                 TRACE("inserting stuff (tl %d, strl %d, selstart %d ('%s'), text '%s')\n", tl, strl, s, debugstr_w(es->text + s), debugstr_w(es->text));
3110                 for (p = es->text + tl ; p >= es->text + s ; p--)
3111                         p[strl] = p[0];
3112                 for (i = 0 , p = es->text + s ; i < strl ; i++)
3113                         p[i] = lpsz_replace[i];
3114                 if(es->style & ES_UPPERCASE)
3115                         CharUpperBuffW(p, strl);
3116                 else if(es->style & ES_LOWERCASE)
3117                         CharLowerBuffW(p, strl);
3118                 s += strl;
3119         }
3120         if (es->style & ES_MULTILINE)
3121         {
3122                 INT s = min(es->selection_start, es->selection_end);
3123
3124                 hrgn = CreateRectRgn(0, 0, 0, 0);
3125                 EDIT_BuildLineDefs_ML(es, s, s + strl,
3126                                 strl - abs(es->selection_end - es->selection_start), hrgn);
3127         }
3128         else
3129             EDIT_CalcLineWidth_SL(es);
3130
3131         /* If text has been deleted and we're right or center aligned then scroll rightward */
3132         if (es->style & (ES_RIGHT | ES_CENTER))
3133         {
3134                 INT delta = strl - abs(es->selection_end - es->selection_start);
3135
3136                 if (delta < 0 && es->x_offset)
3137                 {
3138                         if (abs(delta) > es->x_offset)
3139                                 es->x_offset = 0;
3140                         else
3141                                 es->x_offset += delta;
3142                 }
3143         }
3144
3145         EDIT_EM_SetSel(es, s, s, FALSE);
3146         es->flags |= EF_MODIFIED;
3147         if (send_update) es->flags |= EF_UPDATE;
3148         if (hrgn)
3149         {
3150                 EDIT_UpdateTextRegion(es, hrgn, TRUE);
3151                 DeleteObject(hrgn);
3152         }
3153         else
3154             EDIT_UpdateText(es, NULL, TRUE);
3155
3156         EDIT_EM_ScrollCaret(es);
3157
3158         /* force scroll info update */
3159         EDIT_UpdateScrollInfo(es);
3160
3161
3162         if(es->flags & EF_UPDATE)
3163         {
3164             es->flags &= ~EF_UPDATE;
3165             EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
3166         }
3167 }
3168
3169
3170 /*********************************************************************
3171  *
3172  *      EM_SCROLL
3173  *
3174  */
3175 static LRESULT EDIT_EM_Scroll(EDITSTATE *es, INT action)
3176 {
3177         INT dy;
3178
3179         if (!(es->style & ES_MULTILINE))
3180                 return (LRESULT)FALSE;
3181
3182         dy = 0;
3183
3184         switch (action) {
3185         case SB_LINEUP:
3186                 if (es->y_offset)
3187                         dy = -1;
3188                 break;
3189         case SB_LINEDOWN:
3190                 if (es->y_offset < es->line_count - 1)
3191                         dy = 1;
3192                 break;
3193         case SB_PAGEUP:
3194                 if (es->y_offset)
3195                         dy = -(es->format_rect.bottom - es->format_rect.top) / es->line_height;
3196                 break;
3197         case SB_PAGEDOWN:
3198                 if (es->y_offset < es->line_count - 1)
3199                         dy = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
3200                 break;
3201         default:
3202                 return (LRESULT)FALSE;
3203         }
3204         if (dy) {
3205             INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
3206             /* check if we are going to move too far */
3207             if(es->y_offset + dy > es->line_count - vlc)
3208                 dy = es->line_count - vlc - es->y_offset;
3209
3210             /* Notification is done in EDIT_EM_LineScroll */
3211             if(dy)
3212                 EDIT_EM_LineScroll(es, 0, dy);
3213         }
3214         return MAKELONG((INT16)dy, (BOOL16)TRUE);
3215 }
3216
3217
3218 /*********************************************************************
3219  *
3220  *      EM_SCROLLCARET
3221  *
3222  */
3223 static void EDIT_EM_ScrollCaret(EDITSTATE *es)
3224 {
3225         if (es->style & ES_MULTILINE) {
3226                 INT l;
3227                 INT li;
3228                 INT vlc;
3229                 INT ww;
3230                 INT cw = es->char_width;
3231                 INT x;
3232                 INT dy = 0;
3233                 INT dx = 0;
3234
3235                 l = EDIT_EM_LineFromChar(es, es->selection_end);
3236                 li = EDIT_EM_LineIndex(es, l);
3237                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP));
3238                 vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
3239                 if (l >= es->y_offset + vlc)
3240                         dy = l - vlc + 1 - es->y_offset;
3241                 if (l < es->y_offset)
3242                         dy = l - es->y_offset;
3243                 ww = es->format_rect.right - es->format_rect.left;
3244                 if (x < es->format_rect.left)
3245                         dx = x - es->format_rect.left - ww / HSCROLL_FRACTION / cw * cw;
3246                 if (x > es->format_rect.right)
3247                         dx = x - es->format_rect.left - (HSCROLL_FRACTION - 1) * ww / HSCROLL_FRACTION / cw * cw;
3248                 if (dy || dx)
3249                 {
3250                     /* check if we are going to move too far */
3251                     if(es->x_offset + dx + ww > es->text_width)
3252                         dx = es->text_width - ww - es->x_offset;
3253                     if(dx || dy)
3254                         EDIT_EM_LineScroll_internal(es, dx, dy);
3255                 }
3256         } else {
3257                 INT x;
3258                 INT goal;
3259                 INT format_width;
3260
3261                 if (!(es->style & ES_AUTOHSCROLL))
3262                         return;
3263
3264                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
3265                 format_width = es->format_rect.right - es->format_rect.left;
3266                 if (x < es->format_rect.left) {
3267                         goal = es->format_rect.left + format_width / HSCROLL_FRACTION;
3268                         do {
3269                                 es->x_offset--;
3270                                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
3271                         } while ((x < goal) && es->x_offset);
3272                         /* FIXME: use ScrollWindow() somehow to improve performance */
3273                         EDIT_UpdateText(es, NULL, TRUE);
3274                 } else if (x > es->format_rect.right) {
3275                         INT x_last;
3276                         INT len = strlenW(es->text);
3277                         goal = es->format_rect.right - format_width / HSCROLL_FRACTION;
3278                         do {
3279                                 es->x_offset++;
3280                                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
3281                                 x_last = (short)LOWORD(EDIT_EM_PosFromChar(es, len, FALSE));
3282                         } while ((x > goal) && (x_last > es->format_rect.right));
3283                         /* FIXME: use ScrollWindow() somehow to improve performance */
3284                         EDIT_UpdateText(es, NULL, TRUE);
3285                 }
3286         }
3287
3288     if(es->flags & EF_FOCUSED)
3289         EDIT_SetCaretPos(es, es->selection_end, es->flags & EF_AFTER_WRAP);
3290 }
3291
3292
3293 /*********************************************************************
3294  *
3295  *      EM_SETHANDLE
3296  *
3297  *      FIXME:  ES_LOWERCASE, ES_UPPERCASE, ES_OEMCONVERT, ES_NUMBER ???
3298  *
3299  */
3300 static void EDIT_EM_SetHandle(EDITSTATE *es, HLOCAL hloc)
3301 {
3302         HINSTANCE16 hInstance = GetWindowLongPtrW( es->hwndSelf, GWLP_HINSTANCE );
3303
3304         if (!(es->style & ES_MULTILINE))
3305                 return;
3306
3307         if (!hloc) {
3308                 WARN("called with NULL handle\n");
3309                 return;
3310         }
3311
3312         EDIT_UnlockBuffer(es, TRUE);
3313
3314         if(es->hloc16)
3315         {
3316             LOCAL_Free(hInstance, es->hloc16);
3317             es->hloc16 = (HLOCAL16)NULL;
3318         }
3319
3320         if(es->is_unicode)
3321         {
3322             if(es->hloc32A)
3323             {
3324                 LocalFree(es->hloc32A);
3325                 es->hloc32A = NULL;
3326             }
3327             es->hloc32W = hloc;
3328         }
3329         else
3330         {
3331             INT countW, countA;
3332             HLOCAL hloc32W_new;
3333             WCHAR *textW;
3334             CHAR *textA;
3335
3336             countA = LocalSize(hloc);
3337             textA = LocalLock(hloc);
3338             countW = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
3339             if(!(hloc32W_new = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, countW * sizeof(WCHAR))))
3340             {
3341                 ERR("Could not allocate new unicode buffer\n");
3342                 return;
3343             }
3344             textW = LocalLock(hloc32W_new);
3345             MultiByteToWideChar(CP_ACP, 0, textA, countA, textW, countW);
3346             LocalUnlock(hloc32W_new);
3347             LocalUnlock(hloc);
3348
3349             if(es->hloc32W)
3350                 LocalFree(es->hloc32W);
3351
3352             es->hloc32W = hloc32W_new;
3353             es->hloc32A = hloc;
3354         }
3355
3356         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
3357
3358         EDIT_LockBuffer(es);
3359
3360         es->x_offset = es->y_offset = 0;
3361         es->selection_start = es->selection_end = 0;
3362         EDIT_EM_EmptyUndoBuffer(es);
3363         es->flags &= ~EF_MODIFIED;
3364         es->flags &= ~EF_UPDATE;
3365         EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3366         EDIT_UpdateText(es, NULL, TRUE);
3367         EDIT_EM_ScrollCaret(es);
3368         /* force scroll info update */
3369         EDIT_UpdateScrollInfo(es);
3370 }
3371
3372
3373 /*********************************************************************
3374  *
3375  *      EM_SETHANDLE16
3376  *
3377  *      FIXME:  ES_LOWERCASE, ES_UPPERCASE, ES_OEMCONVERT, ES_NUMBER ???
3378  *
3379  */
3380 static void EDIT_EM_SetHandle16(EDITSTATE *es, HLOCAL16 hloc)
3381 {
3382         HINSTANCE16 hInstance = GetWindowLongPtrW( es->hwndSelf, GWLP_HINSTANCE );
3383         INT countW, countA;
3384         HLOCAL hloc32W_new;
3385         WCHAR *textW;
3386         CHAR *textA;
3387
3388         if (!(es->style & ES_MULTILINE))
3389                 return;
3390
3391         if (!hloc) {
3392                 WARN("called with NULL handle\n");
3393                 return;
3394         }
3395
3396         EDIT_UnlockBuffer(es, TRUE);
3397
3398         if(es->hloc32A)
3399         {
3400             LocalFree(es->hloc32A);
3401             es->hloc32A = NULL;
3402         }
3403
3404         countA = LOCAL_Size(hInstance, hloc);
3405         textA = LOCAL_Lock(hInstance, hloc);
3406         countW = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
3407         if(!(hloc32W_new = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, countW * sizeof(WCHAR))))
3408         {
3409             ERR("Could not allocate new unicode buffer\n");
3410             return;
3411         }
3412         textW = LocalLock(hloc32W_new);
3413         MultiByteToWideChar(CP_ACP, 0, textA, countA, textW, countW);
3414         LocalUnlock(hloc32W_new);
3415         LOCAL_Unlock(hInstance, hloc);
3416
3417         if(es->hloc32W)
3418             LocalFree(es->hloc32W);
3419
3420         es->hloc32W = hloc32W_new;
3421         es->hloc16 = hloc;
3422
3423         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
3424
3425         EDIT_LockBuffer(es);
3426
3427         es->x_offset = es->y_offset = 0;
3428         es->selection_start = es->selection_end = 0;
3429         EDIT_EM_EmptyUndoBuffer(es);
3430         es->flags &= ~EF_MODIFIED;
3431         es->flags &= ~EF_UPDATE;
3432         EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3433         EDIT_UpdateText(es, NULL, TRUE);
3434         EDIT_EM_ScrollCaret(es);
3435         /* force scroll info update */
3436         EDIT_UpdateScrollInfo(es);
3437 }
3438
3439
3440 /*********************************************************************
3441  *
3442  *      EM_SETLIMITTEXT
3443  *
3444  *      FIXME: in WinNT maxsize is 0x7FFFFFFF / 0xFFFFFFFF
3445  *      However, the windows version is not complied to yet in all of edit.c
3446  *
3447  *  Additionally as the wrapper for RichEdit controls we need larger buffers
3448  *  at present -1 will represent nolimit
3449  */
3450 static void EDIT_EM_SetLimitText(EDITSTATE *es, INT limit)
3451 {
3452     if (limit == 0xFFFFFFFF)
3453         es->buffer_limit = -1;
3454     else if (es->style & ES_MULTILINE) {
3455                 if (limit)
3456                         es->buffer_limit = min(limit, BUFLIMIT_MULTI);
3457                 else
3458                         es->buffer_limit = BUFLIMIT_MULTI;
3459         } else {
3460                 if (limit)
3461                         es->buffer_limit = min(limit, BUFLIMIT_SINGLE);
3462                 else
3463                         es->buffer_limit = BUFLIMIT_SINGLE;
3464         }
3465 }
3466
3467
3468 /*********************************************************************
3469  *
3470  *      EM_SETMARGINS
3471  *
3472  * EC_USEFONTINFO is used as a left or right value i.e. lParam and not as an
3473  * action wParam despite what the docs say. EC_USEFONTINFO calculates the
3474  * margin according to the textmetrics of the current font.
3475  *
3476  * FIXME - With TrueType or vector fonts EC_USEFONTINFO currently sets one third
3477  * of the char's width as the margin, but this is not how Windows handles this.
3478  * For all other fonts Windows sets the margins to zero.
3479  *
3480  */
3481 static void EDIT_EM_SetMargins(EDITSTATE *es, INT action,
3482                                INT left, INT right)
3483 {
3484         TEXTMETRICW tm;
3485         INT default_left_margin  = 0; /* in pixels */
3486         INT default_right_margin = 0; /* in pixels */
3487
3488         /* Set the default margins depending on the font */
3489         if (es->font && (left == EC_USEFONTINFO || right == EC_USEFONTINFO)) {
3490             HDC dc = GetDC(es->hwndSelf);
3491             HFONT old_font = SelectObject(dc, es->font);
3492             GetTextMetricsW(dc, &tm);
3493             /* The default margins are only non zero for TrueType or Vector fonts */
3494             if (tm.tmPitchAndFamily & ( TMPF_VECTOR | TMPF_TRUETYPE )) {
3495                 /* This must be calculated more exactly! But how? */
3496                 default_left_margin = tm.tmAveCharWidth / 3;
3497                 default_right_margin = tm.tmAveCharWidth / 3;
3498             }
3499             SelectObject(dc, old_font);
3500             ReleaseDC(es->hwndSelf, dc);
3501         }
3502
3503         if (action & EC_LEFTMARGIN) {
3504                 if (left != EC_USEFONTINFO)
3505                         es->left_margin = left;
3506                 else
3507                         es->left_margin = default_left_margin;
3508         }
3509
3510         if (action & EC_RIGHTMARGIN) {
3511                 if (right != EC_USEFONTINFO)
3512                         es->right_margin = right;
3513                 else
3514                         es->right_margin = default_right_margin;
3515         }
3516         TRACE("left=%d, right=%d\n", es->left_margin, es->right_margin);
3517 }
3518
3519
3520 /*********************************************************************
3521  *
3522  *      EM_SETPASSWORDCHAR
3523  *
3524  */
3525 static void EDIT_EM_SetPasswordChar(EDITSTATE *es, WCHAR c)
3526 {
3527         LONG style;
3528
3529         if (es->style & ES_MULTILINE)
3530                 return;
3531
3532         if (es->password_char == c)
3533                 return;
3534
3535         style = GetWindowLongW( es->hwndSelf, GWL_STYLE );
3536         es->password_char = c;
3537         if (c) {
3538             SetWindowLongW( es->hwndSelf, GWL_STYLE, style | ES_PASSWORD );
3539             es->style |= ES_PASSWORD;
3540         } else {
3541             SetWindowLongW( es->hwndSelf, GWL_STYLE, style & ~ES_PASSWORD );
3542             es->style &= ~ES_PASSWORD;
3543         }
3544         EDIT_UpdateText(es, NULL, TRUE);
3545 }
3546
3547
3548 /*********************************************************************
3549  *
3550  *      EDIT_EM_SetSel
3551  *
3552  *      note:   unlike the specs say: the order of start and end
3553  *              _is_ preserved in Windows.  (i.e. start can be > end)
3554  *              In other words: this handler is OK
3555  *
3556  */
3557 static void EDIT_EM_SetSel(EDITSTATE *es, UINT start, UINT end, BOOL after_wrap)
3558 {
3559         UINT old_start = es->selection_start;
3560         UINT old_end = es->selection_end;
3561         UINT len = strlenW(es->text);
3562
3563         if (start == (UINT)-1) {
3564                 start = es->selection_end;
3565                 end = es->selection_end;
3566         } else {
3567                 start = min(start, len);
3568                 end = min(end, len);
3569         }
3570         es->selection_start = start;
3571         es->selection_end = end;
3572         if (after_wrap)
3573                 es->flags |= EF_AFTER_WRAP;
3574         else
3575                 es->flags &= ~EF_AFTER_WRAP;
3576 /* This is a little bit more efficient than before, not sure if it can be improved. FIXME? */
3577         ORDER_UINT(start, end);
3578         ORDER_UINT(end, old_end);
3579         ORDER_UINT(start, old_start);
3580         ORDER_UINT(old_start, old_end);
3581         if (end != old_start)
3582         {
3583 /*
3584  * One can also do
3585  *          ORDER_UINT32(end, old_start);
3586  *          EDIT_InvalidateText(es, start, end);
3587  *          EDIT_InvalidateText(es, old_start, old_end);
3588  * in place of the following if statement.
3589  */
3590             if (old_start > end )
3591             {
3592                 EDIT_InvalidateText(es, start, end);
3593                 EDIT_InvalidateText(es, old_start, old_end);
3594             }
3595             else
3596             {
3597                 EDIT_InvalidateText(es, start, old_start);
3598                 EDIT_InvalidateText(es, end, old_end);
3599             }
3600         }
3601         else EDIT_InvalidateText(es, start, old_end);
3602 }
3603
3604
3605 /*********************************************************************
3606  *
3607  *      EM_SETTABSTOPS
3608  *
3609  */
3610 static BOOL EDIT_EM_SetTabStops(EDITSTATE *es, INT count, LPINT tabs)
3611 {
3612         if (!(es->style & ES_MULTILINE))
3613                 return FALSE;
3614         HeapFree(GetProcessHeap(), 0, es->tabs);
3615         es->tabs_count = count;
3616         if (!count)
3617                 es->tabs = NULL;
3618         else {
3619                 es->tabs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(INT));
3620                 memcpy(es->tabs, tabs, count * sizeof(INT));
3621         }
3622         return TRUE;
3623 }
3624
3625
3626 /*********************************************************************
3627  *
3628  *      EM_SETTABSTOPS16
3629  *
3630  */
3631 static BOOL EDIT_EM_SetTabStops16(EDITSTATE *es, INT count, LPINT16 tabs)
3632 {
3633         if (!(es->style & ES_MULTILINE))
3634                 return FALSE;
3635         HeapFree(GetProcessHeap(), 0, es->tabs);
3636         es->tabs_count = count;
3637         if (!count)
3638                 es->tabs = NULL;
3639         else {
3640                 INT i;
3641                 es->tabs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(INT));
3642                 for (i = 0 ; i < count ; i++)
3643                         es->tabs[i] = *tabs++;
3644         }
3645         return TRUE;
3646 }
3647
3648
3649 /*********************************************************************
3650  *
3651  *      EM_SETWORDBREAKPROC
3652  *
3653  */
3654 static void EDIT_EM_SetWordBreakProc(EDITSTATE *es, void *wbp)
3655 {
3656         if (es->word_break_proc == wbp)
3657                 return;
3658
3659         es->word_break_proc = wbp;
3660         es->word_break_proc16 = NULL;
3661
3662         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL)) {
3663                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3664                 EDIT_UpdateText(es, NULL, TRUE);
3665         }
3666 }
3667
3668
3669 /*********************************************************************
3670  *
3671  *      EM_SETWORDBREAKPROC16
3672  *
3673  */
3674 static void EDIT_EM_SetWordBreakProc16(EDITSTATE *es, EDITWORDBREAKPROC16 wbp)
3675 {
3676         if (es->word_break_proc16 == wbp)
3677                 return;
3678
3679         es->word_break_proc = NULL;
3680         es->word_break_proc16 = wbp;
3681         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL)) {
3682                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3683                 EDIT_UpdateText(es, NULL, TRUE);
3684         }
3685 }
3686
3687
3688 /*********************************************************************
3689  *
3690  *      EM_UNDO / WM_UNDO
3691  *
3692  */
3693 static BOOL EDIT_EM_Undo(EDITSTATE *es)
3694 {
3695         INT ulength;
3696         LPWSTR utext;
3697
3698         /* As per MSDN spec, for a single-line edit control,
3699            the return value is always TRUE */
3700         if( es->style & ES_READONLY )
3701             return !(es->style & ES_MULTILINE);
3702
3703         ulength = strlenW(es->undo_text);
3704
3705         utext = HeapAlloc(GetProcessHeap(), 0, (ulength + 1) * sizeof(WCHAR));
3706
3707         strcpyW(utext, es->undo_text);
3708
3709         TRACE("before UNDO:insertion length = %d, deletion buffer = %s\n",
3710                      es->undo_insert_count, debugstr_w(utext));
3711
3712         EDIT_EM_SetSel(es, es->undo_position, es->undo_position + es->undo_insert_count, FALSE);
3713         EDIT_EM_EmptyUndoBuffer(es);
3714         EDIT_EM_ReplaceSel(es, TRUE, utext, TRUE, TRUE);
3715         EDIT_EM_SetSel(es, es->undo_position, es->undo_position + es->undo_insert_count, FALSE);
3716         /* send the notification after the selection start and end are set */
3717         EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
3718         EDIT_EM_ScrollCaret(es);
3719         HeapFree(GetProcessHeap(), 0, utext);
3720
3721         TRACE("after UNDO:insertion length = %d, deletion buffer = %s\n",
3722                         es->undo_insert_count, debugstr_w(es->undo_text));
3723         return TRUE;
3724 }
3725
3726
3727 /*********************************************************************
3728  *
3729  *      WM_CHAR
3730  *
3731  */
3732 static void EDIT_WM_Char(EDITSTATE *es, WCHAR c)
3733 {
3734         BOOL control;
3735
3736         control = GetKeyState(VK_CONTROL) & 0x8000;
3737
3738         switch (c) {
3739         case '\r':
3740             /* If the edit doesn't want the return and it's not a multiline edit, do nothing */
3741             if(!(es->style & ES_MULTILINE) && !(es->style & ES_WANTRETURN))
3742                 break;
3743         case '\n':
3744                 if (es->style & ES_MULTILINE) {
3745                         if (es->style & ES_READONLY) {
3746                                 EDIT_MoveHome(es, FALSE);
3747                                 EDIT_MoveDown_ML(es, FALSE);
3748                         } else {
3749                                 static const WCHAR cr_lfW[] = {'\r','\n',0};
3750                                 EDIT_EM_ReplaceSel(es, TRUE, cr_lfW, TRUE, TRUE);
3751                         }
3752                 }
3753                 break;
3754         case '\t':
3755                 if ((es->style & ES_MULTILINE) && !(es->style & ES_READONLY))
3756                 {
3757                         static const WCHAR tabW[] = {'\t',0};
3758                         EDIT_EM_ReplaceSel(es, TRUE, tabW, TRUE, TRUE);
3759                 }
3760                 break;
3761         case VK_BACK:
3762                 if (!(es->style & ES_READONLY) && !control) {
3763                         if (es->selection_start != es->selection_end)
3764                                 EDIT_WM_Clear(es);
3765                         else {
3766                                 /* delete character left of caret */
3767                                 EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
3768                                 EDIT_MoveBackward(es, TRUE);
3769                                 EDIT_WM_Clear(es);
3770                         }
3771                 }
3772                 break;
3773         case 0x03: /* ^C */
3774                 SendMessageW(es->hwndSelf, WM_COPY, 0, 0);
3775                 break;
3776         case 0x16: /* ^V */
3777                 if (!(es->style & ES_READONLY))
3778                     SendMessageW(es->hwndSelf, WM_PASTE, 0, 0);
3779                 break;
3780         case 0x18: /* ^X */
3781                 if (!(es->style & ES_READONLY))
3782                     SendMessageW(es->hwndSelf, WM_CUT, 0, 0);
3783                 break;
3784
3785         default:
3786                 /*If Edit control style is ES_NUMBER allow users to key in only numeric values*/
3787                 if( (es->style & ES_NUMBER) && !( c >= '0' && c <= '9') )
3788                         break;
3789                         
3790                 if (!(es->style & ES_READONLY) && (c >= ' ') && (c != 127)) {
3791                         WCHAR str[2];
3792                         str[0] = c;
3793                         str[1] = '\0';
3794                         EDIT_EM_ReplaceSel(es, TRUE, str, TRUE, TRUE);
3795                 }
3796                 break;
3797         }
3798 }
3799
3800
3801 /*********************************************************************
3802  *
3803  *      WM_COMMAND
3804  *
3805  */
3806 static void EDIT_WM_Command(EDITSTATE *es, INT code, INT id, HWND control)
3807 {
3808         if (code || control)
3809                 return;
3810
3811         switch (id) {
3812                 case EM_UNDO:
3813                         EDIT_EM_Undo(es);
3814                         break;
3815                 case WM_CUT:
3816                         EDIT_WM_Cut(es);
3817                         break;
3818                 case WM_COPY:
3819                         EDIT_WM_Copy(es);
3820                         break;
3821                 case WM_PASTE:
3822                         EDIT_WM_Paste(es);
3823                         break;
3824                 case WM_CLEAR:
3825                         EDIT_WM_Clear(es);
3826                         break;
3827                 case EM_SETSEL:
3828                         EDIT_EM_SetSel(es, 0, (UINT)-1, FALSE);
3829                         EDIT_EM_ScrollCaret(es);
3830                         break;
3831                 default:
3832                         ERR("unknown menu item, please report\n");
3833                         break;
3834         }
3835 }
3836
3837
3838 /*********************************************************************
3839  *
3840  *      WM_CONTEXTMENU
3841  *
3842  *      Note: the resource files resource/sysres_??.rc cannot define a
3843  *              single popup menu.  Hence we use a (dummy) menubar
3844  *              containing the single popup menu as its first item.
3845  *
3846  *      FIXME: the message identifiers have been chosen arbitrarily,
3847  *              hence we use MF_BYPOSITION.
3848  *              We might as well use the "real" values (anybody knows ?)
3849  *              The menu definition is in resources/sysres_??.rc.
3850  *              Once these are OK, we better use MF_BYCOMMAND here
3851  *              (as we do in EDIT_WM_Command()).
3852  *
3853  */
3854 static void EDIT_WM_ContextMenu(EDITSTATE *es, INT x, INT y)
3855 {
3856         HMENU menu = LoadMenuA(user32_module, "EDITMENU");
3857         HMENU popup = GetSubMenu(menu, 0);
3858         UINT start = es->selection_start;
3859         UINT end = es->selection_end;
3860
3861         ORDER_UINT(start, end);
3862
3863         /* undo */
3864         EnableMenuItem(popup, 0, MF_BYPOSITION | (EDIT_EM_CanUndo(es) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3865         /* cut */
3866         EnableMenuItem(popup, 2, MF_BYPOSITION | ((end - start) && !(es->style & ES_PASSWORD) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3867         /* copy */
3868         EnableMenuItem(popup, 3, MF_BYPOSITION | ((end - start) && !(es->style & ES_PASSWORD) ? MF_ENABLED : MF_GRAYED));
3869         /* paste */
3870         EnableMenuItem(popup, 4, MF_BYPOSITION | (IsClipboardFormatAvailable(CF_UNICODETEXT) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3871         /* delete */
3872         EnableMenuItem(popup, 5, MF_BYPOSITION | ((end - start) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3873         /* select all */
3874         EnableMenuItem(popup, 7, MF_BYPOSITION | (start || (end != strlenW(es->text)) ? MF_ENABLED : MF_GRAYED));
3875
3876         TrackPopupMenu(popup, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, es->hwndSelf, NULL);
3877         DestroyMenu(menu);
3878 }
3879
3880
3881 /*********************************************************************
3882  *
3883  *      WM_COPY
3884  *
3885  */
3886 static void EDIT_WM_Copy(EDITSTATE *es)
3887 {
3888         INT s = min(es->selection_start, es->selection_end);
3889         INT e = max(es->selection_start, es->selection_end);
3890         HGLOBAL hdst;
3891         LPWSTR dst;
3892
3893         if (e == s) return;
3894
3895         hdst = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (DWORD)(e - s + 1) * sizeof(WCHAR));
3896         dst = GlobalLock(hdst);
3897         strncpyW(dst, es->text + s, e - s);
3898         dst[e - s] = 0; /* ensure 0 termination */
3899         TRACE("%s\n", debugstr_w(dst));
3900         GlobalUnlock(hdst);
3901         OpenClipboard(es->hwndSelf);
3902         EmptyClipboard();
3903         SetClipboardData(CF_UNICODETEXT, hdst);
3904         CloseClipboard();
3905 }
3906
3907
3908 /*********************************************************************
3909  *
3910  *      WM_CREATE
3911  *
3912  */
3913 static LRESULT EDIT_WM_Create(EDITSTATE *es, LPCWSTR name)
3914 {
3915         TRACE("%s\n", debugstr_w(name));
3916        /*
3917         *       To initialize some final structure members, we call some helper
3918         *       functions.  However, since the EDITSTATE is not consistent (i.e.
3919         *       not fully initialized), we should be very careful which
3920         *       functions can be called, and in what order.
3921         */
3922         EDIT_WM_SetFont(es, 0, FALSE);
3923         EDIT_EM_EmptyUndoBuffer(es);
3924
3925        if (name && *name) {
3926            EDIT_EM_ReplaceSel(es, FALSE, name, FALSE, TRUE);
3927            /* if we insert text to the editline, the text scrolls out
3928             * of the window, as the caret is placed after the insert
3929             * pos normally; thus we reset es->selection... to 0 and
3930             * update caret
3931             */
3932            es->selection_start = es->selection_end = 0;
3933            /* Adobe Photoshop does NOT like this. and MSDN says that EN_CHANGE
3934             * Messages are only to be sent when the USER does something to
3935             * change the contents. So I am removing this EN_CHANGE
3936             *
3937             * EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
3938             */
3939            EDIT_EM_ScrollCaret(es);
3940        }
3941        /* force scroll info update */
3942        EDIT_UpdateScrollInfo(es);
3943        /* The rule seems to return 1 here for success */
3944        /* Power Builder masked edit controls will crash  */
3945        /* if not. */
3946        /* FIXME: is that in all cases so ? */
3947        return 1;
3948 }
3949
3950
3951 /*********************************************************************
3952  *
3953  *      WM_DESTROY
3954  *
3955  */
3956 static LRESULT EDIT_WM_Destroy(EDITSTATE *es)
3957 {
3958         LINEDEF *pc, *pp;
3959
3960         if (es->hloc32W) {
3961                 while (LocalUnlock(es->hloc32W)) ;
3962                 LocalFree(es->hloc32W);
3963         }
3964         if (es->hloc32A) {
3965                 while (LocalUnlock(es->hloc32A)) ;
3966                 LocalFree(es->hloc32A);
3967         }
3968         if (es->hloc16) {
3969                 HINSTANCE16 hInstance = GetWindowLongPtrW( es->hwndSelf, GWLP_HINSTANCE );
3970                 while (LOCAL_Unlock(hInstance, es->hloc16)) ;
3971                 LOCAL_Free(hInstance, es->hloc16);
3972         }
3973
3974         pc = es->first_line_def;
3975         while (pc)
3976         {
3977                 pp = pc->next;
3978                 HeapFree(GetProcessHeap(), 0, pc);
3979                 pc = pp;
3980         }
3981
3982         SetWindowLongW( es->hwndSelf, 0, 0 );
3983         HeapFree(GetProcessHeap(), 0, es);
3984
3985         return 0;
3986 }
3987
3988
3989 /*********************************************************************
3990  *
3991  *      WM_ERASEBKGND
3992  *
3993  */
3994 static LRESULT EDIT_WM_EraseBkGnd(EDITSTATE *es, HDC dc)
3995 {
3996     /* we do the proper erase in EDIT_WM_Paint */
3997     return -1;
3998 }
3999
4000
4001 /*********************************************************************
4002  *
4003  *      WM_GETTEXT
4004  *
4005  */
4006 static INT EDIT_WM_GetText(EDITSTATE *es, INT count, LPWSTR dst, BOOL unicode)
4007 {
4008     if(!count) return 0;
4009
4010     if(unicode)
4011     {
4012         lstrcpynW(dst, es->text, count);
4013         return strlenW(dst);
4014     }
4015     else
4016     {
4017         LPSTR textA = (LPSTR)dst;
4018         if (!WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, count, NULL, NULL))
4019             textA[count - 1] = 0; /* ensure 0 termination */
4020         return strlen(textA);
4021     }
4022 }
4023
4024 /*********************************************************************
4025  *
4026  *      WM_HSCROLL
4027  *
4028  */
4029 static LRESULT EDIT_WM_HScroll(EDITSTATE *es, INT action, INT pos)
4030 {
4031         INT dx;
4032         INT fw;
4033
4034         if (!(es->style & ES_MULTILINE))
4035                 return 0;
4036
4037         if (!(es->style & ES_AUTOHSCROLL))
4038                 return 0;
4039
4040         dx = 0;
4041         fw = es->format_rect.right - es->format_rect.left;
4042         switch (action) {
4043         case SB_LINELEFT:
4044                 TRACE("SB_LINELEFT\n");
4045                 if (es->x_offset)
4046                         dx = -es->char_width;
4047                 break;
4048         case SB_LINERIGHT:
4049                 TRACE("SB_LINERIGHT\n");
4050                 if (es->x_offset < es->text_width)
4051                         dx = es->char_width;
4052                 break;
4053         case SB_PAGELEFT:
4054                 TRACE("SB_PAGELEFT\n");
4055                 if (es->x_offset)
4056                         dx = -fw / HSCROLL_FRACTION / es->char_width * es->char_width;
4057                 break;
4058         case SB_PAGERIGHT:
4059                 TRACE("SB_PAGERIGHT\n");
4060                 if (es->x_offset < es->text_width)
4061                         dx = fw / HSCROLL_FRACTION / es->char_width * es->char_width;
4062                 break;
4063         case SB_LEFT:
4064                 TRACE("SB_LEFT\n");
4065                 if (es->x_offset)
4066                         dx = -es->x_offset;
4067                 break;
4068         case SB_RIGHT:
4069                 TRACE("SB_RIGHT\n");
4070                 if (es->x_offset < es->text_width)
4071                         dx = es->text_width - es->x_offset;
4072                 break;
4073         case SB_THUMBTRACK:
4074                 TRACE("SB_THUMBTRACK %d\n", pos);
4075                 es->flags |= EF_HSCROLL_TRACK;
4076                 if(es->style & WS_HSCROLL)
4077                     dx = pos - es->x_offset;
4078                 else
4079                 {
4080                     INT fw, new_x;
4081                     /* Sanity check */
4082                     if(pos < 0 || pos > 100) return 0;
4083                     /* Assume default scroll range 0-100 */
4084                     fw = es->format_rect.right - es->format_rect.left;
4085                     new_x = pos * (es->text_width - fw) / 100;
4086                     dx = es->text_width ? (new_x - es->x_offset) : 0;
4087                 }
4088                 break;
4089         case SB_THUMBPOSITION:
4090                 TRACE("SB_THUMBPOSITION %d\n", pos);
4091                 es->flags &= ~EF_HSCROLL_TRACK;
4092                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_HSCROLL)
4093                     dx = pos - es->x_offset;
4094                 else
4095                 {
4096                     INT fw, new_x;
4097                     /* Sanity check */
4098                     if(pos < 0 || pos > 100) return 0;
4099                     /* Assume default scroll range 0-100 */
4100                     fw = es->format_rect.right - es->format_rect.left;
4101                     new_x = pos * (es->text_width - fw) / 100;
4102                     dx = es->text_width ? (new_x - es->x_offset) : 0;
4103                 }
4104                 if (!dx) {
4105                         /* force scroll info update */
4106                         EDIT_UpdateScrollInfo(es);
4107                         EDIT_NOTIFY_PARENT(es, EN_HSCROLL, "EN_HSCROLL");
4108                 }
4109                 break;
4110         case SB_ENDSCROLL:
4111                 TRACE("SB_ENDSCROLL\n");
4112                 break;
4113         /*
4114          *      FIXME : the next two are undocumented !
4115          *      Are we doing the right thing ?
4116          *      At least Win 3.1 Notepad makes use of EM_GETTHUMB this way,
4117          *      although it's also a regular control message.
4118          */
4119         case EM_GETTHUMB: /* this one is used by NT notepad */
4120         case EM_GETTHUMB16:
4121         {
4122                 LRESULT ret;
4123                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_HSCROLL)
4124                     ret = GetScrollPos(es->hwndSelf, SB_HORZ);
4125                 else
4126                 {
4127                     /* Assume default scroll range 0-100 */
4128                     INT fw = es->format_rect.right - es->format_rect.left;
4129                     ret = es->text_width ? es->x_offset * 100 / (es->text_width - fw) : 0;
4130                 }
4131                 TRACE("EM_GETTHUMB: returning %ld\n", ret);
4132                 return ret;
4133         }
4134         case EM_LINESCROLL16:
4135                 TRACE("EM_LINESCROLL16\n");
4136                 dx = pos;
4137                 break;
4138
4139         default:
4140                 ERR("undocumented WM_HSCROLL action %d (0x%04x), please report\n",
4141                     action, action);
4142                 return 0;
4143         }
4144         if (dx)
4145         {
4146             INT fw = es->format_rect.right - es->format_rect.left;
4147             /* check if we are going to move too far */
4148             if(es->x_offset + dx + fw > es->text_width)
4149                 dx = es->text_width - fw - es->x_offset;
4150             if(dx)
4151                 EDIT_EM_LineScroll_internal(es, dx, 0);
4152         }
4153         return 0;
4154 }
4155
4156
4157 /*********************************************************************
4158  *
4159  *      EDIT_CheckCombo
4160  *
4161  */
4162 static BOOL EDIT_CheckCombo(EDITSTATE *es, UINT msg, INT key)
4163 {
4164    HWND hLBox = es->hwndListBox;
4165    HWND hCombo;
4166    BOOL bDropped;
4167    int  nEUI;
4168
4169    if (!hLBox)
4170       return FALSE;
4171
4172    hCombo   = GetParent(es->hwndSelf);
4173    bDropped = TRUE;
4174    nEUI     = 0;
4175
4176    TRACE_(combo)("[%p]: handling msg %x (%x)\n", es->hwndSelf, msg, key);
4177
4178    if (key == VK_UP || key == VK_DOWN)
4179    {
4180       if (SendMessageW(hCombo, CB_GETEXTENDEDUI, 0, 0))
4181          nEUI = 1;
4182
4183       if (msg == WM_KEYDOWN || nEUI)
4184           bDropped = (BOOL)SendMessageW(hCombo, CB_GETDROPPEDSTATE, 0, 0);
4185    }
4186
4187    switch (msg)
4188    {
4189       case WM_KEYDOWN:
4190          if (!bDropped && nEUI && (key == VK_UP || key == VK_DOWN))
4191          {
4192             /* make sure ComboLBox pops up */
4193             SendMessageW(hCombo, CB_SETEXTENDEDUI, FALSE, 0);
4194             key = VK_F4;
4195             nEUI = 2;
4196          }
4197
4198          SendMessageW(hLBox, WM_KEYDOWN, (WPARAM)key, 0);
4199          break;
4200
4201       case WM_SYSKEYDOWN: /* Handle Alt+up/down arrows */
4202          if (nEUI)
4203             SendMessageW(hCombo, CB_SHOWDROPDOWN, bDropped ? FALSE : TRUE, 0);
4204          else
4205             SendMessageW(hLBox, WM_KEYDOWN, (WPARAM)VK_F4, 0);
4206          break;
4207    }
4208
4209    if(nEUI == 2)
4210       SendMessageW(hCombo, CB_SETEXTENDEDUI, TRUE, 0);
4211
4212    return TRUE;
4213 }
4214
4215
4216 /*********************************************************************
4217  *
4218  *      WM_KEYDOWN
4219  *
4220  *      Handling of special keys that don't produce a WM_CHAR
4221  *      (i.e. non-printable keys) & Backspace & Delete
4222  *
4223  */
4224 static LRESULT EDIT_WM_KeyDown(EDITSTATE *es, INT key)
4225 {
4226         BOOL shift;
4227         BOOL control;
4228
4229         if (GetKeyState(VK_MENU) & 0x8000)
4230                 return 0;
4231
4232         shift = GetKeyState(VK_SHIFT) & 0x8000;
4233         control = GetKeyState(VK_CONTROL) & 0x8000;
4234
4235         switch (key) {
4236         case VK_F4:
4237         case VK_UP:
4238                 if (EDIT_CheckCombo(es, WM_KEYDOWN, key) || key == VK_F4)
4239                         break;
4240
4241                 /* fall through */
4242         case VK_LEFT:
4243                 if ((es->style & ES_MULTILINE) && (key == VK_UP))
4244                         EDIT_MoveUp_ML(es, shift);
4245                 else
4246                         if (control)
4247                                 EDIT_MoveWordBackward(es, shift);
4248                         else
4249                                 EDIT_MoveBackward(es, shift);
4250                 break;
4251         case VK_DOWN:
4252                 if (EDIT_CheckCombo(es, WM_KEYDOWN, key))
4253                         break;
4254                 /* fall through */
4255         case VK_RIGHT:
4256                 if ((es->style & ES_MULTILINE) && (key == VK_DOWN))
4257                         EDIT_MoveDown_ML(es, shift);
4258                 else if (control)
4259                         EDIT_MoveWordForward(es, shift);
4260                 else
4261                         EDIT_MoveForward(es, shift);
4262                 break;
4263         case VK_HOME:
4264                 EDIT_MoveHome(es, shift);
4265                 break;
4266         case VK_END:
4267                 EDIT_MoveEnd(es, shift);
4268                 break;
4269         case VK_PRIOR:
4270                 if (es->style & ES_MULTILINE)
4271                         EDIT_MovePageUp_ML(es, shift);
4272                 else
4273                         EDIT_CheckCombo(es, WM_KEYDOWN, key);
4274                 break;
4275         case VK_NEXT:
4276                 if (es->style & ES_MULTILINE)
4277                         EDIT_MovePageDown_ML(es, shift);
4278                 else
4279                         EDIT_CheckCombo(es, WM_KEYDOWN, key);
4280                 break;
4281         case VK_DELETE:
4282                 if (!(es->style & ES_READONLY) && !(shift && control)) {
4283                         if (es->selection_start != es->selection_end) {
4284                                 if (shift)
4285                                         EDIT_WM_Cut(es);
4286                                 else
4287                                         EDIT_WM_Clear(es);
4288                         } else {
4289                                 if (shift) {
4290                                         /* delete character left of caret */
4291                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
4292                                         EDIT_MoveBackward(es, TRUE);
4293                                         EDIT_WM_Clear(es);
4294                                 } else if (control) {
4295                                         /* delete to end of line */
4296                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
4297                                         EDIT_MoveEnd(es, TRUE);
4298                                         EDIT_WM_Clear(es);
4299                                 } else {
4300                                         /* delete character right of caret */
4301                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
4302                                         EDIT_MoveForward(es, TRUE);
4303                                         EDIT_WM_Clear(es);
4304                                 }
4305                         }
4306                 }
4307                 break;
4308         case VK_INSERT:
4309                 if (shift) {
4310                         if (!(es->style & ES_READONLY))
4311                                 EDIT_WM_Paste(es);
4312                 } else if (control)
4313                         EDIT_WM_Copy(es);
4314                 break;
4315         case VK_RETURN:
4316             /* If the edit doesn't want the return send a message to the default object */
4317             if(!(es->style & ES_WANTRETURN))
4318             {
4319                 HWND hwndParent = GetParent(es->hwndSelf);
4320                 DWORD dw = SendMessageW( hwndParent, DM_GETDEFID, 0, 0 );
4321                 if (HIWORD(dw) == DC_HASDEFID)
4322                 {
4323                     SendMessageW( hwndParent, WM_COMMAND,
4324                                   MAKEWPARAM( LOWORD(dw), BN_CLICKED ),
4325                               (LPARAM)GetDlgItem( hwndParent, LOWORD(dw) ) );
4326                 }
4327             }
4328             break;
4329         }
4330         return 0;
4331 }
4332
4333
4334 /*********************************************************************
4335  *
4336  *      WM_KILLFOCUS
4337  *
4338  */
4339 static LRESULT EDIT_WM_KillFocus(EDITSTATE *es)
4340 {
4341         es->flags &= ~EF_FOCUSED;
4342         DestroyCaret();
4343         if(!(es->style & ES_NOHIDESEL))
4344                 EDIT_InvalidateText(es, es->selection_start, es->selection_end);
4345         EDIT_NOTIFY_PARENT(es, EN_KILLFOCUS, "EN_KILLFOCUS");
4346         return 0;
4347 }
4348
4349
4350 /*********************************************************************
4351  *
4352  *      WM_LBUTTONDBLCLK
4353  *
4354  *      The caret position has been set on the WM_LBUTTONDOWN message
4355  *
4356  */
4357 static LRESULT EDIT_WM_LButtonDblClk(EDITSTATE *es)
4358 {
4359         INT s;
4360         INT e = es->selection_end;
4361         INT l;
4362         INT li;
4363         INT ll;
4364
4365         if (!(es->flags & EF_FOCUSED))
4366                 return 0;
4367
4368         l = EDIT_EM_LineFromChar(es, e);
4369         li = EDIT_EM_LineIndex(es, l);
4370         ll = EDIT_EM_LineLength(es, e);
4371         s = li + EDIT_CallWordBreakProc(es, li, e - li, ll, WB_LEFT);
4372         e = li + EDIT_CallWordBreakProc(es, li, e - li, ll, WB_RIGHT);
4373         EDIT_EM_SetSel(es, s, e, FALSE);
4374         EDIT_EM_ScrollCaret(es);
4375         return 0;
4376 }
4377
4378
4379 /*********************************************************************
4380  *
4381  *      WM_LBUTTONDOWN
4382  *
4383  */
4384 static LRESULT EDIT_WM_LButtonDown(EDITSTATE *es, DWORD keys, INT x, INT y)
4385 {
4386         INT e;
4387         BOOL after_wrap;
4388
4389         SetFocus(es->hwndSelf);
4390         if (!(es->flags & EF_FOCUSED))
4391                 return 0;
4392
4393         es->bCaptureState = TRUE;
4394         SetCapture(es->hwndSelf);
4395         EDIT_ConfinePoint(es, &x, &y);
4396         e = EDIT_CharFromPos(es, x, y, &after_wrap);
4397         EDIT_EM_SetSel(es, (keys & MK_SHIFT) ? es->selection_start : e, e, after_wrap);
4398         EDIT_EM_ScrollCaret(es);
4399         es->region_posx = es->region_posy = 0;
4400         SetTimer(es->hwndSelf, 0, 100, NULL);
4401         return 0;
4402 }
4403
4404
4405 /*********************************************************************
4406  *
4407  *      WM_LBUTTONUP
4408  *
4409  */
4410 static LRESULT EDIT_WM_LButtonUp(EDITSTATE *es)
4411 {
4412         if (es->bCaptureState) {
4413                 KillTimer(es->hwndSelf, 0);
4414                 if (GetCapture() == es->hwndSelf) ReleaseCapture();
4415         }
4416         es->bCaptureState = FALSE;
4417         return 0;
4418 }
4419
4420
4421 /*********************************************************************
4422  *
4423  *      WM_MBUTTONDOWN
4424  *
4425  */
4426 static LRESULT EDIT_WM_MButtonDown(EDITSTATE *es)
4427 {
4428     SendMessageW(es->hwndSelf, WM_PASTE, 0, 0);
4429     return 0;
4430 }
4431
4432
4433 /*********************************************************************
4434  *
4435  *      WM_MOUSEMOVE
4436  *
4437  */
4438 static LRESULT EDIT_WM_MouseMove(EDITSTATE *es, INT x, INT y)
4439 {
4440         INT e;
4441         BOOL after_wrap;
4442         INT prex, prey;
4443
4444         if (GetCapture() != es->hwndSelf)
4445                 return 0;
4446
4447         /*
4448          *      FIXME: gotta do some scrolling if outside client
4449          *              area.  Maybe reset the timer ?
4450          */
4451         prex = x; prey = y;
4452         EDIT_ConfinePoint(es, &x, &y);
4453         es->region_posx = (prex < x) ? -1 : ((prex > x) ? 1 : 0);
4454         es->region_posy = (prey < y) ? -1 : ((prey > y) ? 1 : 0);
4455         e = EDIT_CharFromPos(es, x, y, &after_wrap);
4456         EDIT_EM_SetSel(es, es->selection_start, e, after_wrap);
4457         EDIT_SetCaretPos(es,es->selection_end,es->flags & EF_AFTER_WRAP);
4458         return 0;
4459 }
4460
4461
4462 /*********************************************************************
4463  *
4464  *      WM_NCCREATE
4465  *
4466  * See also EDIT_WM_StyleChanged
4467  */
4468 static LRESULT EDIT_WM_NCCreate(HWND hwnd, LPCREATESTRUCTW lpcs, BOOL unicode)
4469 {
4470         EDITSTATE *es;
4471         UINT alloc_size;
4472
4473         TRACE("Creating %s edit control, style = %08lx\n",
4474                 unicode ? "Unicode" : "ANSI", lpcs->style);
4475
4476         if (!(es = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*es))))
4477                 return FALSE;
4478         SetWindowLongW( hwnd, 0, (LONG)es );
4479
4480        /*
4481         *      Note: since the EDITSTATE has not been fully initialized yet,
4482         *            we can't use any API calls that may send
4483         *            WM_XXX messages before WM_NCCREATE is completed.
4484         */
4485
4486         es->is_unicode = unicode;
4487         es->style = lpcs->style;
4488
4489         es->bEnableState = !(es->style & WS_DISABLED);
4490
4491         es->hwndSelf = hwnd;
4492         /* Save parent, which will be notified by EN_* messages */
4493         es->hwndParent = lpcs->hwndParent;
4494
4495         if (es->style & ES_COMBO)
4496            es->hwndListBox = GetDlgItem(es->hwndParent, ID_CB_LISTBOX);
4497
4498         /* Number overrides lowercase overrides uppercase (at least it
4499          * does in Win95).  However I'll bet that ES_NUMBER would be
4500          * invalid under Win 3.1.
4501          */
4502         if (es->style & ES_NUMBER) {
4503                 ; /* do not override the ES_NUMBER */
4504         }  else if (es->style & ES_LOWERCASE) {
4505                 es->style &= ~ES_UPPERCASE;
4506         }
4507         if (es->style & ES_MULTILINE) {
4508                 es->buffer_limit = BUFLIMIT_MULTI;
4509                 if (es->style & WS_VSCROLL)
4510                         es->style |= ES_AUTOVSCROLL;
4511                 if (es->style & WS_HSCROLL)
4512                         es->style |= ES_AUTOHSCROLL;
4513                 es->style &= ~ES_PASSWORD;
4514                 if ((es->style & ES_CENTER) || (es->style & ES_RIGHT)) {
4515                         /* Confirmed - RIGHT overrides CENTER */
4516                         if (es->style & ES_RIGHT)
4517                                 es->style &= ~ES_CENTER;
4518                         es->style &= ~WS_HSCROLL;
4519                 }
4520
4521                 /* FIXME: for now, all multi line controls are AUTOVSCROLL */
4522                 es->style |= ES_AUTOVSCROLL;
4523         } else {
4524                 es->buffer_limit = BUFLIMIT_SINGLE;
4525                 if ((es->style & ES_RIGHT) && (es->style & ES_CENTER))
4526                         es->style &= ~ES_CENTER;
4527                 es->style &= ~WS_HSCROLL;
4528                 es->style &= ~WS_VSCROLL;
4529                 if (es->style & ES_PASSWORD)
4530                         es->password_char = '*';
4531
4532                 /* FIXME: for now, all single line controls are AUTOHSCROLL */
4533                 es->style |= ES_AUTOHSCROLL;
4534         }
4535
4536         alloc_size = ROUND_TO_GROW((es->buffer_size + 1) * sizeof(WCHAR));
4537         if(!(es->hloc32W = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size)))
4538             return FALSE;
4539         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
4540
4541         if (!(es->undo_text = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (es->buffer_size + 1) * sizeof(WCHAR))))
4542                 return FALSE;
4543         es->undo_buffer_size = es->buffer_size;
4544
4545         if (es->style & ES_MULTILINE)
4546                 if (!(es->first_line_def = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(LINEDEF))))
4547                         return FALSE;
4548         es->line_count = 1;
4549
4550         /*
4551          * In Win95 look and feel, the WS_BORDER style is replaced by the
4552          * WS_EX_CLIENTEDGE style for the edit control. This gives the edit
4553          * control a nonclient area so we don't need to draw the border.
4554          * If WS_BORDER without WS_EX_CLIENTEDGE is specified we shouldn't have
4555          * a nonclient area and we should handle painting the border ourselves.
4556          *
4557          * When making modifications please ensure that the code still works 
4558          * for edit controls created directly with style 0x50800000, exStyle 0
4559          * (which should have a single pixel border)
4560          */
4561         if (lpcs->dwExStyle & WS_EX_CLIENTEDGE)
4562                 es->style &= ~WS_BORDER;
4563         else if (es->style & WS_BORDER)
4564                 SetWindowLongW(hwnd, GWL_STYLE, es->style & ~WS_BORDER);
4565
4566         return TRUE;
4567 }
4568
4569 /*********************************************************************
4570  *
4571  *      WM_PAINT
4572  *
4573  */
4574 static void EDIT_WM_Paint(EDITSTATE *es, HDC hdc)
4575 {
4576         PAINTSTRUCT ps;
4577         INT i;
4578         HDC dc;
4579         HFONT old_font = 0;
4580         RECT rc;
4581         RECT rcClient;
4582         RECT rcLine;
4583         RECT rcRgn;
4584         HBRUSH brush;
4585         BOOL rev = es->bEnableState &&
4586                                 ((es->flags & EF_FOCUSED) ||
4587                                         (es->style & ES_NOHIDESEL));
4588         dc = hdc ? hdc : BeginPaint(es->hwndSelf, &ps);
4589
4590         GetClientRect(es->hwndSelf, &rcClient);
4591
4592         /* paint the background */
4593         if (!(brush = EDIT_NotifyCtlColor(es, dc)))
4594                 brush = (HBRUSH)GetStockObject(WHITE_BRUSH);
4595         IntersectClipRect(dc, rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
4596         GetClipBox(dc, &rc);
4597         FillRect(dc, &rc, brush);
4598
4599         /* draw the border */
4600         if(es->style & WS_BORDER) {
4601                 rc = rcClient;
4602                 if(es->style & ES_MULTILINE) {
4603                         if(es->style & WS_HSCROLL) rc.bottom++;
4604                         if(es->style & WS_VSCROLL) rc.right++;
4605                 }
4606                 Rectangle(dc, rc.left, rc.top, rc.right, rc.bottom);
4607         }
4608         IntersectClipRect(dc, es->format_rect.left,
4609                                 es->format_rect.top,
4610                                 es->format_rect.right,
4611                                 es->format_rect.bottom);
4612         if (es->style & ES_MULTILINE) {
4613                 rc = rcClient;
4614                 IntersectClipRect(dc, rc.left, rc.top, rc.right, rc.bottom);
4615         }
4616         if (es->font)
4617                 old_font = SelectObject(dc, es->font);
4618         EDIT_NotifyCtlColor(es, dc);
4619
4620         if (!es->bEnableState)
4621                 SetTextColor(dc, GetSysColor(COLOR_GRAYTEXT));
4622         GetClipBox(dc, &rcRgn);
4623         if (es->style & ES_MULTILINE) {
4624                 INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
4625                 for (i = es->y_offset ; i <= min(es->y_offset + vlc, es->y_offset + es->line_count - 1) ; i++) {
4626                         EDIT_GetLineRect(es, i, 0, -1, &rcLine);
4627                         if (IntersectRect(&rc, &rcRgn, &rcLine))
4628                                 EDIT_PaintLine(es, dc, i, rev);
4629                 }
4630         } else {
4631                 EDIT_GetLineRect(es, 0, 0, -1, &rcLine);
4632                 if (IntersectRect(&rc, &rcRgn, &rcLine))
4633                         EDIT_PaintLine(es, dc, 0, rev);
4634         }
4635         if (es->font)
4636                 SelectObject(dc, old_font);
4637
4638         if (!hdc)
4639             EndPaint(es->hwndSelf, &ps);
4640 }
4641
4642
4643 /*********************************************************************
4644  *
4645  *      WM_PASTE
4646  *
4647  */
4648 static void EDIT_WM_Paste(EDITSTATE *es)
4649 {
4650         HGLOBAL hsrc;
4651         LPWSTR src;
4652
4653         /* Protect read-only edit control from modification */
4654         if(es->style & ES_READONLY)
4655             return;
4656
4657         OpenClipboard(es->hwndSelf);
4658         if ((hsrc = GetClipboardData(CF_UNICODETEXT))) {
4659                 src = (LPWSTR)GlobalLock(hsrc);
4660                 EDIT_EM_ReplaceSel(es, TRUE, src, TRUE, TRUE);
4661                 GlobalUnlock(hsrc);
4662         }
4663         CloseClipboard();
4664 }
4665
4666
4667 /*********************************************************************
4668  *
4669  *      WM_SETFOCUS
4670  *
4671  */
4672 static void EDIT_WM_SetFocus(EDITSTATE *es)
4673 {
4674         es->flags |= EF_FOCUSED;
4675         CreateCaret(es->hwndSelf, 0, 2, es->line_height);
4676         EDIT_SetCaretPos(es, es->selection_end,
4677                          es->flags & EF_AFTER_WRAP);
4678         if(!(es->style & ES_NOHIDESEL))
4679                 EDIT_InvalidateText(es, es->selection_start, es->selection_end);
4680         ShowCaret(es->hwndSelf);
4681         EDIT_NOTIFY_PARENT(es, EN_SETFOCUS, "EN_SETFOCUS");
4682 }
4683
4684
4685 /*********************************************************************
4686  *
4687  *      WM_SETFONT
4688  *
4689  * With Win95 look the margins are set to default font value unless
4690  * the system font (font == 0) is being set, in which case they are left
4691  * unchanged.
4692  *
4693  */
4694 static void EDIT_WM_SetFont(EDITSTATE *es, HFONT font, BOOL redraw)
4695 {
4696         TEXTMETRICW tm;
4697         HDC dc;
4698         HFONT old_font = 0;
4699         RECT r;
4700
4701         es->font = font;
4702         dc = GetDC(es->hwndSelf);
4703         if (font)
4704                 old_font = SelectObject(dc, font);
4705         GetTextMetricsW(dc, &tm);
4706         es->line_height = tm.tmHeight;
4707         es->char_width = tm.tmAveCharWidth;
4708         if (font)
4709                 SelectObject(dc, old_font);
4710         ReleaseDC(es->hwndSelf, dc);
4711         EDIT_EM_SetMargins(es, EC_LEFTMARGIN | EC_RIGHTMARGIN,
4712                            EC_USEFONTINFO, EC_USEFONTINFO);
4713
4714         /* Force the recalculation of the format rect for each font change */
4715         GetClientRect(es->hwndSelf, &r);
4716         EDIT_SetRectNP(es, &r);
4717
4718         if (es->style & ES_MULTILINE)
4719                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
4720         else
4721             EDIT_CalcLineWidth_SL(es);
4722
4723         if (redraw)
4724                 EDIT_UpdateText(es, NULL, TRUE);
4725         if (es->flags & EF_FOCUSED) {
4726                 DestroyCaret();
4727                 CreateCaret(es->hwndSelf, 0, 2, es->line_height);
4728                 EDIT_SetCaretPos(es, es->selection_end,
4729                                  es->flags & EF_AFTER_WRAP);
4730                 ShowCaret(es->hwndSelf);
4731         }
4732 }
4733
4734
4735 /*********************************************************************
4736  *
4737  *      WM_SETTEXT
4738  *
4739  * NOTES
4740  *  For multiline controls (ES_MULTILINE), reception of WM_SETTEXT triggers:
4741  *  The modified flag is reset. No notifications are sent.
4742  *
4743  *  For single-line controls, reception of WM_SETTEXT triggers:
4744  *  The modified flag is reset. EN_UPDATE and EN_CHANGE notifications are sent.
4745  *
4746  */
4747 static void EDIT_WM_SetText(EDITSTATE *es, LPCWSTR text, BOOL unicode)
4748 {
4749     if (!unicode && text)
4750     {
4751         LPCSTR textA = (LPCSTR)text;
4752         INT countW = MultiByteToWideChar(CP_ACP, 0, textA, -1, NULL, 0);
4753         LPWSTR textW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR));
4754         if (textW)
4755             MultiByteToWideChar(CP_ACP, 0, textA, -1, textW, countW);
4756         text = textW;
4757     }
4758
4759     EDIT_EM_SetSel(es, 0, (UINT)-1, FALSE);
4760     if (text) 
4761     {
4762         TRACE("%s\n", debugstr_w(text));
4763         EDIT_EM_ReplaceSel(es, FALSE, text, FALSE, FALSE);
4764         if(!unicode)
4765             HeapFree(GetProcessHeap(), 0, (LPWSTR)text);
4766     } 
4767     else 
4768     {
4769         static const WCHAR empty_stringW[] = {0};
4770         TRACE("<NULL>\n");
4771         EDIT_EM_ReplaceSel(es, FALSE, empty_stringW, FALSE, FALSE);
4772     }
4773     es->x_offset = 0;
4774     es->flags &= ~EF_MODIFIED;
4775     EDIT_EM_SetSel(es, 0, 0, FALSE);
4776
4777     /* Send the notification after the selection start and end have been set
4778      * edit control doesn't send notification on WM_SETTEXT
4779      * if it is multiline, or it is part of combobox
4780      */
4781     if( !((es->style & ES_MULTILINE) || es->hwndListBox))
4782     {
4783         EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
4784         EDIT_NOTIFY_PARENT(es, EN_UPDATE, "EN_UPDATE");
4785     }
4786     EDIT_EM_ScrollCaret(es);
4787     EDIT_UpdateScrollInfo(es);    
4788 }
4789
4790
4791 /*********************************************************************
4792  *
4793  *      WM_SIZE
4794  *
4795  */
4796 static void EDIT_WM_Size(EDITSTATE *es, UINT action, INT width, INT height)
4797 {
4798         if ((action == SIZE_MAXIMIZED) || (action == SIZE_RESTORED)) {
4799                 RECT rc;
4800                 TRACE("width = %d, height = %d\n", width, height);
4801                 SetRect(&rc, 0, 0, width, height);
4802                 EDIT_SetRectNP(es, &rc);
4803                 EDIT_UpdateText(es, NULL, TRUE);
4804         }
4805 }
4806
4807
4808 /*********************************************************************
4809  *
4810  *      WM_STYLECHANGED
4811  *
4812  * This message is sent by SetWindowLong on having changed either the Style
4813  * or the extended style.
4814  *
4815  * We ensure that the window's version of the styles and the EDITSTATE's agree.
4816  *
4817  * See also EDIT_WM_NCCreate
4818  *
4819  * It appears that the Windows version of the edit control allows the style
4820  * (as retrieved by GetWindowLong) to be any value and maintains an internal
4821  * style variable which will generally be different.  In this function we
4822  * update the internal style based on what changed in the externally visible
4823  * style.
4824  *
4825  * Much of this content as based upon the MSDN, especially:
4826  *  Platform SDK Documentation -> User Interface Services ->
4827  *      Windows User Interface -> Edit Controls -> Edit Control Reference ->
4828  *      Edit Control Styles
4829  */
4830 static LRESULT  EDIT_WM_StyleChanged ( EDITSTATE *es, WPARAM which, const STYLESTRUCT *style)
4831 {
4832         if (GWL_STYLE == which) {
4833                 DWORD style_change_mask;
4834                 DWORD new_style;
4835                 /* Only a subset of changes can be applied after the control
4836                  * has been created.
4837                  */
4838                 style_change_mask = ES_UPPERCASE | ES_LOWERCASE |
4839                                     ES_NUMBER;
4840                 if (es->style & ES_MULTILINE)
4841                         style_change_mask |= ES_WANTRETURN;
4842
4843                 new_style = style->styleNew & style_change_mask;
4844
4845                 /* Number overrides lowercase overrides uppercase (at least it
4846                  * does in Win95).  However I'll bet that ES_NUMBER would be
4847                  * invalid under Win 3.1.
4848                  */
4849                 if (new_style & ES_NUMBER) {
4850                         ; /* do not override the ES_NUMBER */
4851                 }  else if (new_style & ES_LOWERCASE) {
4852                         new_style &= ~ES_UPPERCASE;
4853                 }
4854
4855                 es->style = (es->style & ~style_change_mask) | new_style;
4856         } else if (GWL_EXSTYLE == which) {
4857                 ; /* FIXME - what is needed here */
4858         } else {
4859                 WARN ("Invalid style change %d\n",which);
4860         }
4861
4862         return 0;
4863 }
4864
4865 /*********************************************************************
4866  *
4867  *      WM_SYSKEYDOWN
4868  *
4869  */
4870 static LRESULT EDIT_WM_SysKeyDown(EDITSTATE *es, INT key, DWORD key_data)
4871 {
4872         if ((key == VK_BACK) && (key_data & 0x2000)) {
4873                 if (EDIT_EM_CanUndo(es))
4874                         EDIT_EM_Undo(es);
4875                 return 0;
4876         } else if (key == VK_UP || key == VK_DOWN) {
4877                 if (EDIT_CheckCombo(es, WM_SYSKEYDOWN, key))
4878                         return 0;
4879         }
4880         return DefWindowProcW(es->hwndSelf, WM_SYSKEYDOWN, (WPARAM)key, (LPARAM)key_data);
4881 }
4882
4883
4884 /*********************************************************************
4885  *
4886  *      WM_TIMER
4887  *
4888  */
4889 static void EDIT_WM_Timer(EDITSTATE *es)
4890 {
4891         if (es->region_posx < 0) {
4892                 EDIT_MoveBackward(es, TRUE);
4893         } else if (es->region_posx > 0) {
4894                 EDIT_MoveForward(es, TRUE);
4895         }
4896 /*
4897  *      FIXME: gotta do some vertical scrolling here, like
4898  *              EDIT_EM_LineScroll(hwnd, 0, 1);
4899  */
4900 }
4901
4902 /*********************************************************************
4903  *
4904  *      WM_VSCROLL
4905  *
4906  */
4907 static LRESULT EDIT_WM_VScroll(EDITSTATE *es, INT action, INT pos)
4908 {
4909         INT dy;
4910
4911         if (!(es->style & ES_MULTILINE))
4912                 return 0;
4913
4914         if (!(es->style & ES_AUTOVSCROLL))
4915                 return 0;
4916
4917         dy = 0;
4918         switch (action) {
4919         case SB_LINEUP:
4920         case SB_LINEDOWN:
4921         case SB_PAGEUP:
4922         case SB_PAGEDOWN:
4923                 TRACE("action %d (%s)\n", action, (action == SB_LINEUP ? "SB_LINEUP" :
4924                                                    (action == SB_LINEDOWN ? "SB_LINEDOWN" :
4925                                                     (action == SB_PAGEUP ? "SB_PAGEUP" :
4926                                                      "SB_PAGEDOWN"))));
4927                 EDIT_EM_Scroll(es, action);
4928                 return 0;
4929         case SB_TOP:
4930                 TRACE("SB_TOP\n");
4931                 dy = -es->y_offset;
4932                 break;
4933         case SB_BOTTOM:
4934                 TRACE("SB_BOTTOM\n");
4935                 dy = es->line_count - 1 - es->y_offset;
4936                 break;
4937         case SB_THUMBTRACK:
4938                 TRACE("SB_THUMBTRACK %d\n", pos);
4939                 es->flags |= EF_VSCROLL_TRACK;
4940                 if(es->style & WS_VSCROLL)
4941                     dy = pos - es->y_offset;
4942                 else
4943                 {
4944                     /* Assume default scroll range 0-100 */
4945                     INT vlc, new_y;
4946                     /* Sanity check */
4947                     if(pos < 0 || pos > 100) return 0;
4948                     vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
4949                     new_y = pos * (es->line_count - vlc) / 100;
4950                     dy = es->line_count ? (new_y - es->y_offset) : 0;
4951                     TRACE("line_count=%d, y_offset=%d, pos=%d, dy = %d\n",
4952                             es->line_count, es->y_offset, pos, dy);
4953                 }
4954                 break;
4955         case SB_THUMBPOSITION:
4956                 TRACE("SB_THUMBPOSITION %d\n", pos);
4957                 es->flags &= ~EF_VSCROLL_TRACK;
4958                 if(es->style & WS_VSCROLL)
4959                     dy = pos - es->y_offset;
4960                 else
4961                 {
4962                     /* Assume default scroll range 0-100 */
4963                     INT vlc, new_y;
4964                     /* Sanity check */
4965                     if(pos < 0 || pos > 100) return 0;
4966                     vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
4967                     new_y = pos * (es->line_count - vlc) / 100;
4968                     dy = es->line_count ? (new_y - es->y_offset) : 0;
4969                     TRACE("line_count=%d, y_offset=%d, pos=%d, dy = %d\n",
4970                             es->line_count, es->y_offset, pos, dy);
4971                 }
4972                 if (!dy)
4973                 {
4974                         /* force scroll info update */
4975                         EDIT_UpdateScrollInfo(es);
4976                         EDIT_NOTIFY_PARENT(es, EN_VSCROLL, "EN_VSCROLL");
4977                 }
4978                 break;
4979         case SB_ENDSCROLL:
4980                 TRACE("SB_ENDSCROLL\n");
4981                 break;
4982         /*
4983          *      FIXME : the next two are undocumented !
4984          *      Are we doing the right thing ?
4985          *      At least Win 3.1 Notepad makes use of EM_GETTHUMB this way,
4986          *      although it's also a regular control message.
4987          */
4988         case EM_GETTHUMB: /* this one is used by NT notepad */
4989         case EM_GETTHUMB16:
4990         {
4991                 LRESULT ret;
4992                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_VSCROLL)
4993                     ret = GetScrollPos(es->hwndSelf, SB_VERT);
4994                 else
4995                 {
4996                     /* Assume default scroll range 0-100 */
4997                     INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
4998                     ret = es->line_count ? es->y_offset * 100 / (es->line_count - vlc) : 0;
4999                 }
5000                 TRACE("EM_GETTHUMB: returning %ld\n", ret);
5001                 return ret;
5002         }
5003         case EM_LINESCROLL16:
5004                 TRACE("EM_LINESCROLL16 %d\n", pos);
5005                 dy = pos;
5006                 break;
5007
5008         default:
5009                 ERR("undocumented WM_VSCROLL action %d (0x%04x), please report\n",
5010                     action, action);
5011                 return 0;
5012         }
5013         if (dy)
5014                 EDIT_EM_LineScroll(es, 0, dy);
5015         return 0;
5016 }
5017
5018 /*********************************************************************
5019  *
5020  *      EDIT_UpdateText
5021  *
5022  */
5023 static void EDIT_UpdateTextRegion(EDITSTATE *es, HRGN hrgn, BOOL bErase)
5024 {
5025     if (es->flags & EF_UPDATE) EDIT_NOTIFY_PARENT(es, EN_UPDATE, "EN_UPDATE");
5026     InvalidateRgn(es->hwndSelf, hrgn, bErase);
5027 }
5028
5029
5030 /*********************************************************************
5031  *
5032  *      EDIT_UpdateText
5033  *
5034  */
5035 static void EDIT_UpdateText(EDITSTATE *es, LPRECT rc, BOOL bErase)
5036 {
5037     if (es->flags & EF_UPDATE) EDIT_NOTIFY_PARENT(es, EN_UPDATE, "EN_UPDATE");
5038     InvalidateRect(es->hwndSelf, rc, bErase);
5039 }