richedit: Don't allow recursive EN_REQUESTRESIZE notifications.
[wine] / dlls / riched20 / editor.c
1 /*
2  * RichEdit - functions dealing with editor object
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  * Copyright 2005 by Cihan Altinay
6  * Copyright 2005 by Phil Krylov
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 /* 
24   API implementation status:
25   
26   Messages (ANSI versions not done yet)
27   + EM_AUTOURLDETECT 2.0
28   + EM_CANPASTE
29   + EM_CANREDO 2.0
30   + EM_CANUNDO
31   + EM_CHARFROMPOS
32   - EM_DISPLAYBAND
33   + EM_EMPTYUNDOBUFFER
34   + EM_EXGETSEL
35   + EM_EXLIMITTEXT
36   + EM_EXLINEFROMCHAR
37   + EM_EXSETSEL
38   + EM_FINDTEXT (only FR_DOWN flag implemented)
39   + EM_FINDTEXTEX (only FR_DOWN flag implemented)
40   - EM_FINDWORDBREAK
41   - EM_FMTLINES
42   - EM_FORMATRANGE
43   + EM_GETAUTOURLDETECT 2.0
44   - EM_GETBIDIOPTIONS 3.0
45   - EM_GETCHARFORMAT (partly done)
46   - EM_GETEDITSTYLE
47   + EM_GETEVENTMASK
48   + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
49   - EM_GETIMECOLOR 1.0asian
50   - EM_GETIMECOMPMODE 2.0
51   - EM_GETIMEOPTIONS 1.0asian
52   - EM_GETIMESTATUS
53   - EM_GETLANGOPTIONS 2.0
54   + EM_GETLIMITTEXT
55   + EM_GETLINE
56   + EM_GETLINECOUNT   returns number of rows, not of paragraphs
57   + EM_GETMODIFY
58   - EM_GETOLEINTERFACE
59   + EM_GETOPTIONS
60   + EM_GETPARAFORMAT
61   + EM_GETPASSWORDCHAR 2.0
62   - EM_GETPUNCTUATION 1.0asian
63   + EM_GETRECT
64   - EM_GETREDONAME 2.0
65   + EM_GETSEL
66   + EM_GETSELTEXT (ANSI&Unicode)
67   + EM_GETSCROLLPOS 3.0 (only Y value valid)
68 ! - EM_GETTHUMB
69   + EM_GETTEXTEX 2.0
70   + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
71   - EM_GETTEXTMODE 2.0
72 ? + EM_GETTEXTRANGE (ANSI&Unicode)
73   - EM_GETTYPOGRAPHYOPTIONS 3.0
74   - EM_GETUNDONAME
75   + EM_GETWORDBREAKPROC
76   - EM_GETWORDBREAKPROCEX
77   - EM_GETWORDWRAPMODE 1.0asian
78   + EM_GETZOOM 3.0
79   + EM_HIDESELECTION
80   + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
81   + EM_LINEFROMCHAR
82   + EM_LINEINDEX
83   + EM_LINELENGTH
84   + EM_LINESCROLL
85   - EM_PASTESPECIAL
86   + EM_POSFROMCHAR
87   + EM_REDO 2.0
88   + EM_REQUESTRESIZE
89   + EM_REPLACESEL (proper style?) ANSI&Unicode
90   + EM_SCROLL
91   + EM_SCROLLCARET
92   - EM_SELECTIONTYPE
93   - EM_SETBIDIOPTIONS 3.0
94   + EM_SETBKGNDCOLOR
95   + EM_SETCHARFORMAT (partly done, no ANSI)
96   - EM_SETEDITSTYLE
97   + EM_SETEVENTMASK (few notifications supported)
98   - EM_SETFONTSIZE
99   - EM_SETIMECOLOR 1.0asian
100   - EM_SETIMEOPTIONS 1.0asian
101   - EM_SETLANGOPTIONS 2.0
102   - EM_SETLIMITTEXT
103   + EM_SETMODIFY (not sure if implementation is correct)
104   - EM_SETOLECALLBACK
105   + EM_SETOPTIONS (partially implemented)
106   - EM_SETPALETTE 2.0
107   + EM_SETPARAFORMAT
108   + EM_SETPASSWORDCHAR 2.0
109   - EM_SETPUNCTUATION 1.0asian
110   + EM_SETREADONLY no beep on modification attempt
111   + EM_SETRECT
112   + EM_SETRECTNP (EM_SETRECT without repainting)
113   + EM_SETSEL
114   + EM_SETSCROLLPOS 3.0
115   - EM_SETTABSTOPS 3.0
116   - EM_SETTARGETDEVICE
117   + EM_SETTEXTEX 3.0 (no rich text insertion handling, proper style?)
118   - EM_SETTEXTMODE 2.0
119   - EM_SETTYPOGRAPHYOPTIONS 3.0
120   + EM_SETUNDOLIMIT 2.0
121   + EM_SETWORDBREAKPROC (used only for word movement at the moment)
122   - EM_SETWORDBREAKPROCEX
123   - EM_SETWORDWRAPMODE 1.0asian
124   + EM_SETZOOM 3.0
125   + EM_SHOWSCROLLBAR 2.0
126   - EM_STOPGROUPTYPING 2.0
127   + EM_STREAMIN
128   + EM_STREAMOUT
129   + EM_UNDO
130   + WM_CHAR
131   + WM_CLEAR
132   + WM_COPY
133   + WM_CUT
134   + WM_GETDLGCODE (the current implementation is incomplete)
135   + WM_GETTEXT (ANSI&Unicode)
136   + WM_GETTEXTLENGTH (ANSI version sucks)
137   + WM_PASTE
138   + WM_SETFONT
139   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
140   - WM_STYLECHANGING
141   - WM_STYLECHANGED (things like read-only flag)
142   - WM_UNICHAR
143   
144   Notifications
145   
146   * EN_CHANGE (sent from the wrong place)
147   - EN_CORRECTTEXT
148   - EN_DROPFILES
149   - EN_ERRSPACE
150   - EN_HSCROLL
151   - EN_IMECHANGE
152   + EN_KILLFOCUS
153   - EN_LINK
154   - EN_MAXTEXT
155   - EN_MSGFILTER
156   - EN_OLEOPFAILED
157   - EN_PROTECTED
158   + EN_REQUESTRESIZE
159   - EN_SAVECLIPBOARD
160   + EN_SELCHANGE 
161   + EN_SETFOCUS
162   - EN_STOPNOUNDO
163   * EN_UPDATE (sent from the wrong place)
164   - EN_VSCROLL
165   
166   Styles
167   
168   - ES_AUTOHSCROLL
169   - ES_AUTOVSCROLL
170   - ES_CENTER
171   + ES_DISABLENOSCROLL (scrollbar is always visible)
172   - ES_EX_NOCALLOLEINIT
173   - ES_LEFT
174   - ES_MULTILINE (currently single line controls aren't supported)
175   - ES_NOIME
176   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
177   - ES_RIGHT
178   - ES_SAVESEL
179   - ES_SELFIME
180   - ES_SUNKEN
181   - ES_VERTICAL
182   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
183   - WS_SETFONT
184   - WS_HSCROLL
185   + WS_VSCROLL
186 */
187
188 /*
189  * RICHED20 TODO (incomplete):
190  *
191  * - messages/styles/notifications listed above 
192  * - Undo coalescing 
193  * - add remaining CHARFORMAT/PARAFORMAT fields
194  * - right/center align should strip spaces from the beginning
195  * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
196  * - COM interface (looks like a major pain in the TODO list)
197  * - calculate heights of pictures (half-done)
198  * - horizontal scrolling (not even started)
199  * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
200  * - find/replace
201  * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
202  * - italic caret with italic fonts
203  * - IME
204  * - most notifications aren't sent at all (the most important ones are)
205  * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
206  * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
207  * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
208  * - full justification
209  * - hyphenation
210  * - tables
211  * - ListBox & ComboBox not implemented
212  *
213  * Bugs that are probably fixed, but not so easy to verify:
214  * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
215  * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
216  * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
217  * - caret shouldn't be displayed when selection isn't empty
218  * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
219  * - undo for setting default format (done, might be buggy)
220  * - styles might be not released properly (looks like they work like charm, but who knows?
221  *
222  */
223
224 #include "editor.h"
225 #include "commdlg.h"
226 #include "winreg.h"
227 #define NO_SHLWAPI_STREAM 
228 #include "shlwapi.h"
229 #include "rtf.h"
230 #include "imm.h"
231 #include "res.h"
232
233 #define STACK_SIZE_DEFAULT  100
234 #define STACK_SIZE_MAX     1000
235
236 #define TEXT_LIMIT_DEFAULT 32767
237  
238 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
239
240 static BOOL ME_RegisterEditorClass(HINSTANCE);
241
242 static const WCHAR RichEdit20W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
243 static const WCHAR RichEdit50W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
244 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
245 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
246 static HCURSOR hLeft;
247 static HCURSOR hBeam;
248
249 int me_debug = 0;
250 HANDLE me_heap = NULL;
251
252 static BOOL ME_ListBoxRegistered = FALSE;
253 static BOOL ME_ComboBoxRegistered = FALSE;
254
255 static inline int is_version_nt(void)
256 {
257     return !(GetVersion() & 0x80000000);
258 }
259
260 static ME_TextBuffer *ME_MakeText(void) {
261   
262   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
263
264   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
265   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
266   
267   p1->prev = NULL;
268   p1->next = p2;
269   p2->prev = p1;
270   p2->next = NULL;
271   p1->member.para.next_para = p2;
272   p2->member.para.prev_para = p1;
273   p2->member.para.nCharOfs = 0;  
274   
275   buf->pFirst = p1;
276   buf->pLast = p2;
277   buf->pCharStyle = NULL;
278   
279   return buf;
280 }
281
282
283 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
284 {
285   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
286   WCHAR *pText;
287   
288   TRACE("%08x %p\n", dwFormat, stream);
289   
290   do {
291     long nWideChars = 0;
292
293     if (!stream->dwSize)
294     {
295       ME_StreamInFill(stream);
296       if (stream->editstream->dwError)
297         break;
298       if (!stream->dwSize)
299         break;
300     }
301       
302     if (!(dwFormat & SF_UNICODE))
303     {
304       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
305       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
306       pText = wszText;
307     }
308     else
309     {
310       nWideChars = stream->dwSize >> 1;
311       pText = (WCHAR *)stream->buffer;
312     }
313     
314     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
315     if (stream->dwSize == 0)
316       break;
317     stream->dwSize = 0;
318   } while(1);
319   ME_CommitUndo(editor);
320   ME_UpdateRepaint(editor);
321   return 0;
322 }
323
324 static void ME_RTFCharAttrHook(RTF_Info *info)
325 {
326   CHARFORMAT2W fmt;
327   fmt.cbSize = sizeof(fmt);
328   fmt.dwMask = 0;
329   fmt.dwEffects = 0;
330
331   switch(info->rtfMinor)
332   {
333     case rtfPlain:
334       /* FIXME add more flags once they're implemented */
335       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
336       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
337       fmt.yHeight = 12*20; /* 12pt */
338       fmt.wWeight = 400;
339       break;
340     case rtfBold:
341       fmt.dwMask = CFM_BOLD;
342       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
343       break;
344     case rtfItalic:
345       fmt.dwMask = CFM_ITALIC;
346       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
347       break;
348     case rtfUnderline:
349       fmt.dwMask = CFM_UNDERLINE;
350       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
351       fmt.bUnderlineType = CFU_CF1UNDERLINE;
352       break;
353     case rtfNoUnderline:
354       fmt.dwMask = CFM_UNDERLINE;
355       fmt.dwEffects = 0;
356       break;
357     case rtfStrikeThru:
358       fmt.dwMask = CFM_STRIKEOUT;
359       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
360       break;
361     case rtfSubScript:
362     case rtfSuperScript:
363     case rtfSubScrShrink:
364     case rtfSuperScrShrink:
365     case rtfNoSuperSub:
366       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
367       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
368       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
369       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
370       break;
371     case rtfInvisible:
372       fmt.dwMask = CFM_HIDDEN;
373       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
374       break;
375     case rtfBackColor:
376       fmt.dwMask = CFM_BACKCOLOR;
377       fmt.dwEffects = 0;
378       if (info->rtfParam == 0)
379         fmt.dwEffects = CFE_AUTOBACKCOLOR;
380       else if (info->rtfParam != rtfNoParam)
381       {
382         RTFColor *c = RTFGetColor(info, info->rtfParam);
383         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
384       }
385       break;
386     case rtfForeColor:
387       fmt.dwMask = CFM_COLOR;
388       fmt.dwEffects = 0;
389       if (info->rtfParam == 0)
390         fmt.dwEffects = CFE_AUTOCOLOR;
391       else if (info->rtfParam != rtfNoParam)
392       {
393         RTFColor *c = RTFGetColor(info, info->rtfParam);
394         if (c)
395           fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
396         else
397           fmt.crTextColor = 0;
398       }
399       break;
400     case rtfFontNum:
401       if (info->rtfParam != rtfNoParam)
402       {
403         RTFFont *f = RTFGetFont(info, info->rtfParam);
404         if (f)
405         {
406           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
407           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
408           fmt.bCharSet = f->rtfFCharSet;
409           fmt.dwMask = CFM_FACE | CFM_CHARSET;
410         }
411       }
412       break;
413     case rtfFontSize:
414       fmt.dwMask = CFM_SIZE;
415       if (info->rtfParam != rtfNoParam)
416         fmt.yHeight = info->rtfParam*10;
417       break;
418   }
419   if (fmt.dwMask) {
420     ME_Style *style2;
421     RTFFlushOutputBuffer(info);
422     /* FIXME too slow ? how come ? */
423     style2 = ME_ApplyStyle(info->style, &fmt);
424     ME_ReleaseStyle(info->style);
425     info->style = style2;
426     info->styleChanged = TRUE;
427   }
428 }
429
430 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
431    the same tags mean different things in different contexts */
432 static void ME_RTFParAttrHook(RTF_Info *info)
433 {
434   PARAFORMAT2 fmt;
435   fmt.cbSize = sizeof(fmt);
436   fmt.dwMask = 0;
437   
438   switch(info->rtfMinor)
439   {
440   case rtfParDef: /* restores default paragraph attributes */
441     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
442     fmt.wAlignment = PFA_LEFT;
443     fmt.cTabCount = 0;
444     fmt.dxOffset = fmt.dxStartIndent = 0;
445     RTFFlushOutputBuffer(info);
446     ME_GetParagraph(info->editor->pCursors[0].pRun)->member.para.bTable = FALSE;
447     break;
448   case rtfInTable:
449   {
450     ME_DisplayItem *para;
451     
452     RTFFlushOutputBuffer(info);
453     para = ME_GetParagraph(info->editor->pCursors[0].pRun);
454     assert(para->member.para.pCells);
455     para->member.para.bTable = TRUE;
456     return;
457   }
458   case rtfFirstIndent:
459     ME_GetSelectionParaFormat(info->editor, &fmt);
460     fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
461     fmt.dxStartIndent += info->rtfParam + fmt.dxOffset;
462     fmt.dxOffset = -info->rtfParam;
463     break;
464   case rtfLeftIndent:
465     ME_GetSelectionParaFormat(info->editor, &fmt);
466     fmt.dwMask = PFM_STARTINDENT;
467     fmt.dxStartIndent = -fmt.dxOffset + info->rtfParam;
468     break;
469   case rtfRightIndent:
470     fmt.dwMask = PFM_RIGHTINDENT;
471     fmt.dxRightIndent = info->rtfParam;
472     break;
473   case rtfQuadLeft:
474   case rtfQuadJust:
475     fmt.dwMask = PFM_ALIGNMENT;
476     fmt.wAlignment = PFA_LEFT;
477     break;
478   case rtfQuadRight:
479     fmt.dwMask = PFM_ALIGNMENT;
480     fmt.wAlignment = PFA_RIGHT;
481     break;
482   case rtfQuadCenter:
483     fmt.dwMask = PFM_ALIGNMENT;
484     fmt.wAlignment = PFA_CENTER;
485     break;
486   case rtfTabPos:
487     ME_GetSelectionParaFormat(info->editor, &fmt);
488     if (!(fmt.dwMask & PFM_TABSTOPS))
489     {
490       fmt.dwMask |= PFM_TABSTOPS;
491       fmt.cTabCount = 0;
492     }
493     if (fmt.cTabCount < MAX_TAB_STOPS)
494       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
495     break;
496   }  
497   if (fmt.dwMask) {
498     RTFFlushOutputBuffer(info);
499     /* FIXME too slow ? how come ?*/
500     ME_SetSelectionParaFormat(info->editor, &fmt);
501   }
502 }
503
504 static void ME_RTFTblAttrHook(RTF_Info *info)
505 {
506   ME_DisplayItem *para;
507   
508   switch (info->rtfMinor)
509   {
510     case rtfRowDef:
511       RTFFlushOutputBuffer(info);
512       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
513       
514       /* Release possibly inherited cell definitions */
515       ME_DestroyTableCellList(para);
516       
517       para->member.para.pCells = ALLOC_OBJ(ME_TableCell);
518       para->member.para.pCells->nRightBoundary = 0;
519       para->member.para.pCells->next = NULL;
520       para->member.para.pLastCell = para->member.para.pCells;
521       break;
522     case rtfCellPos:
523       RTFFlushOutputBuffer(info);
524       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
525       
526       if (para->member.para.pLastCell->nRightBoundary)
527       {
528         ME_TableCell *pCell = ALLOC_OBJ(ME_TableCell);
529         
530         pCell->next = NULL;
531         para->member.para.pLastCell->next = pCell;
532         para->member.para.pLastCell = pCell;
533       }
534       para->member.para.pLastCell->nRightBoundary = info->rtfParam;
535       break;
536   }
537 }
538
539 static void ME_RTFReadHook(RTF_Info *info) {
540   switch(info->rtfClass)
541   {
542     case rtfGroup:
543       switch(info->rtfMajor)
544       {
545         case rtfBeginGroup:
546           if (info->stackTop < maxStack) {
547             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
548             info->stack[info->stackTop].codePage = info->codePage;
549             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
550           }
551           info->stackTop++;
552           info->styleChanged = FALSE;
553           break;
554         case rtfEndGroup:
555         {
556           ME_Style *s;
557           RTFFlushOutputBuffer(info);
558           if (info->stackTop<=1) {
559             info->rtfClass = rtfEOF;
560             return;
561           }
562           info->stackTop--;
563           assert(info->stackTop >= 0);
564           if (info->styleChanged)
565           {
566             /* FIXME too slow ? how come ? */
567             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
568             ME_ReleaseStyle(info->style);
569             info->style = s;
570             info->codePage = info->stack[info->stackTop].codePage;
571             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
572           }
573           break;
574         }
575       }
576       break;
577     case rtfControl:
578       switch(info->rtfMajor)
579       {
580         case rtfCharAttr:
581           ME_RTFCharAttrHook(info);
582           break;
583         case rtfParAttr:
584           ME_RTFParAttrHook(info);
585           break;
586         case rtfTblAttr:
587           ME_RTFTblAttrHook(info);
588           break;
589         case rtfSpecialChar:
590           if (info->rtfMinor == rtfCell)
591           {
592             RTFFlushOutputBuffer(info);
593             ME_InsertTableCellFromCursor(info->editor, 0);
594           }
595       }
596       break;
597   }
598 }
599
600 void
601 ME_StreamInFill(ME_InStream *stream)
602 {
603   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
604                                                                 (BYTE *)stream->buffer,
605                                                                 sizeof(stream->buffer),
606                                                                 (LONG *)&stream->dwSize);
607   stream->dwUsed = 0;
608 }
609
610 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
611 {
612   RTF_Info parser;
613   ME_Style *style;
614   int from, to, to2, nUndoMode;
615   int nEventMask = editor->nEventMask;
616   ME_InStream inStream;
617
618   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
619   editor->nEventMask = 0;
620   
621   ME_GetSelection(editor, &from, &to);
622   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
623     style = ME_GetSelectionInsertStyle(editor);
624
625     ME_InternalDeleteText(editor, from, to-from);
626   }
627   else {
628     style = editor->pBuffer->pDefaultStyle;
629     ME_AddRefStyle(style);
630     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
631     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
632     from = to = 0;
633     ME_ClearTempStyle(editor);
634     /* FIXME restore default paragraph formatting ! */
635   }
636
637
638   /* Back up undo mode to a local variable */
639   nUndoMode = editor->nUndoMode;
640
641   /* Only create an undo if SFF_SELECTION is set */
642   if (!(format & SFF_SELECTION))
643     editor->nUndoMode = umIgnore;
644
645   inStream.editstream = stream;
646   inStream.editstream->dwError = 0;
647   inStream.dwSize = 0;
648   inStream.dwUsed = 0;
649
650   if (format & SF_RTF)
651   {
652     /* Check if it's really RTF, and if it is not, use plain text */
653     ME_StreamInFill(&inStream);
654     if (!inStream.editstream->dwError)
655     {
656       if (strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
657       {
658         format &= ~SF_RTF;
659         format |= SF_TEXT;
660       }
661     }
662   }
663
664   if (!inStream.editstream->dwError)
665   {
666     if (format & SF_RTF) {
667       /* setup the RTF parser */
668       memset(&parser, 0, sizeof parser);
669       RTFSetEditStream(&parser, &inStream);
670       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
671       parser.hwndEdit = editor->hWnd;
672       parser.editor = editor;
673       parser.style = style;
674       WriterInit(&parser);
675       RTFInit(&parser);
676       RTFSetReadHook(&parser, ME_RTFReadHook);
677       BeginFile(&parser);
678   
679       /* do the parsing */
680       RTFRead(&parser);
681       RTFFlushOutputBuffer(&parser);
682       RTFDestroy(&parser);
683
684       style = parser.style;
685     }
686     else if (format & SF_TEXT)
687       ME_StreamInText(editor, format, &inStream, style);
688     else
689       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
690     ME_GetSelection(editor, &to, &to2);
691     /* put the cursor at the top */
692     if (!(format & SFF_SELECTION))
693       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
694   }
695
696   /* Restore saved undo mode */
697   editor->nUndoMode = nUndoMode;
698
699   /* even if we didn't add an undo, we need to commit anything on the stack */
700   ME_CommitUndo(editor);
701
702   /* If SFF_SELECTION isn't set, delete any undos from before we started too */
703   if (!(format & SFF_SELECTION))
704     ME_EmptyUndoStack(editor);
705
706   ME_ReleaseStyle(style);
707   editor->nEventMask = nEventMask;
708   if (editor->bRedraw)
709   {
710     ME_UpdateRepaint(editor);
711   }
712   if (!(format & SFF_SELECTION)) {
713     ME_ClearTempStyle(editor);
714   }
715   ME_MoveCaret(editor);
716   ME_SendSelChange(editor);
717   ME_SendRequestResize(editor, FALSE);
718
719   return 0;
720 }
721
722
723 typedef struct tagME_RTFStringStreamStruct
724 {
725   char *string;
726   int pos;
727   int length;
728 } ME_RTFStringStreamStruct;
729
730 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
731 {
732   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
733   int count;
734
735   count = min(cb, pStruct->length - pStruct->pos);
736   memmove(lpBuff, pStruct->string + pStruct->pos, count);
737   pStruct->pos += count;
738   *pcb = count;
739   return 0;
740 }
741
742 static void
743 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
744 {
745   EDITSTREAM es;
746   ME_RTFStringStreamStruct data;
747
748   data.string = string;
749   data.length = strlen(string);
750   data.pos = 0;
751   es.dwCookie = (DWORD)&data;
752   es.pfnCallback = ME_ReadFromRTFString;
753   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es);
754 }
755
756
757 ME_DisplayItem *
758 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
759 {
760   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
761   
762   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
763     item = ME_FindItemFwd(item, diParagraph);
764
765   if (!item)
766     return item;
767
768   nOffset -= item->member.para.nCharOfs;
769   if (nItemType == diParagraph) {
770     if (nItemOffset)
771       *nItemOffset = nOffset;
772     return item;
773   }
774   
775   do {
776     item = ME_FindItemFwd(item, diRun);
777   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
778   if (item) {
779     nOffset -= item->member.run.nCharOfs;
780     if (nItemOffset)
781       *nItemOffset = nOffset;
782   }
783   return item;
784 }
785
786
787 static int
788 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
789 {
790   const int nLen = lstrlenW(text);
791   const int nTextLen = ME_GetTextLength(editor);
792   int nStart, nEnd;
793   int nMin, nMax;
794   ME_DisplayItem *item;
795   ME_DisplayItem *para;
796   WCHAR wLastChar = ' ';
797
798   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
799         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
800   
801   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
802     FIXME("Flags 0x%08x not implemented\n",
803         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
804
805   nMin = chrg->cpMin;
806   if (chrg->cpMax == -1)
807     nMax = nTextLen;
808   else
809     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
810   
811   /* when searching up, if cpMin < cpMax, then instead of searching
812    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
813    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
814    * case, it is always bigger than cpMin.
815    */
816   if (!(flags & FR_DOWN))
817   {
818     int nSwap = nMax;
819
820     nMax = nMin > nTextLen ? nTextLen : nMin;
821     if (nMin < nSwap || chrg->cpMax == -1)
822       nMin = 0;
823     else
824       nMin = nSwap;
825   }
826
827   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
828   {
829     if (chrgText)
830       chrgText->cpMin = chrgText->cpMax = -1;
831     return -1;
832   }
833  
834   if (flags & FR_DOWN) /* Forward search */
835   {
836     /* If possible, find the character before where the search starts */
837     if ((flags & FR_WHOLEWORD) && nMin)
838     {
839       nStart = nMin - 1;
840       item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
841       if (!item)
842       {
843         if (chrgText)
844           chrgText->cpMin = chrgText->cpMax = -1;
845         return -1;
846       }
847       wLastChar = item->member.run.strText->szData[nStart];
848     }
849
850     nStart = nMin;
851     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
852     if (!item)
853     {
854       if (chrgText)
855         chrgText->cpMin = chrgText->cpMax = -1;
856       return -1;
857     }
858
859     para = ME_GetParagraph(item);
860     while (item
861            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
862     {
863       ME_DisplayItem *pCurItem = item;
864       int nCurStart = nStart;
865       int nMatched = 0;
866     
867       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
868       {
869         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
870           break;
871
872         nMatched++;
873         if (nMatched == nLen)
874         {
875           ME_DisplayItem *pNextItem = pCurItem;
876           int nNextStart = nCurStart;
877           WCHAR wNextChar;
878
879           /* Check to see if next character is a whitespace */
880           if (flags & FR_WHOLEWORD)
881           {
882             if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
883             {
884               pNextItem = ME_FindItemFwd(pCurItem, diRun);
885               nNextStart = -nMatched;
886             }
887
888             if (pNextItem)
889               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
890             else
891               wNextChar = ' ';
892
893             if (isalnumW(wNextChar))
894               break;
895           }
896
897           nStart += para->member.para.nCharOfs + pCurItem->member.run.nCharOfs;
898           if (chrgText)
899           {
900             chrgText->cpMin = nStart;
901             chrgText->cpMax = nStart + nLen;
902           }
903           TRACE("found at %d-%d\n", nStart, nStart + nLen);
904           return nStart;
905         }
906         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
907         {
908           pCurItem = ME_FindItemFwd(pCurItem, diRun);
909           para = ME_GetParagraph(pCurItem);
910           nCurStart = -nMatched;
911         }
912       }
913       if (pCurItem)
914         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
915       else
916         wLastChar = ' ';
917
918       nStart++;
919       if (nStart == ME_StrLen(item->member.run.strText))
920       {
921         item = ME_FindItemFwd(item, diRun);
922         para = ME_GetParagraph(item);
923         nStart = 0;
924       }
925     }
926   }
927   else /* Backward search */
928   {
929     /* If possible, find the character after where the search ends */
930     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
931     {
932       nEnd = nMax + 1;
933       item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
934       if (!item)
935       {
936         if (chrgText)
937           chrgText->cpMin = chrgText->cpMax = -1;
938         return -1;
939       }
940       wLastChar = item->member.run.strText->szData[nEnd];
941     }
942
943     nEnd = nMax;
944     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
945     if (!item)
946     {
947       if (chrgText)
948         chrgText->cpMin = chrgText->cpMax = -1;
949       return -1;
950     }
951     
952     para = ME_GetParagraph(item);
953     
954     while (item
955            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
956     {
957       ME_DisplayItem *pCurItem = item;
958       int nCurEnd = nEnd;
959       int nMatched = 0;
960       
961       if (nCurEnd - nMatched == 0)
962       {
963         pCurItem = ME_FindItemBack(pCurItem, diRun);
964         para = ME_GetParagraph(pCurItem);
965         nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
966       }
967       
968       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
969       {
970         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
971           break;
972
973         nMatched++;
974         if (nMatched == nLen)
975         {
976           ME_DisplayItem *pPrevItem = pCurItem;
977           int nPrevEnd = nCurEnd;
978           WCHAR wPrevChar;
979
980           /* Check to see if previous character is a whitespace */
981           if (flags & FR_WHOLEWORD)
982           {
983             if (nPrevEnd - nMatched == 0)
984             {
985               pPrevItem = ME_FindItemBack(pCurItem, diRun);
986               if (pPrevItem)
987                 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
988             }
989
990             if (pPrevItem)
991               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
992             else
993               wPrevChar = ' ';
994
995             if (isalnumW(wPrevChar))
996               break;
997           }
998
999           nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1000           if (chrgText)
1001           {
1002             chrgText->cpMin = nStart;
1003             chrgText->cpMax = nStart + nLen;
1004           }
1005           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1006           return nStart;
1007         }
1008         if (nCurEnd - nMatched == 0)
1009         {
1010           pCurItem = ME_FindItemBack(pCurItem, diRun);
1011           /* Don't care about pCurItem becoming NULL here; it's already taken
1012            * care of in the exterior loop condition */
1013           para = ME_GetParagraph(pCurItem);
1014           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1015         }
1016       }
1017       if (pCurItem)
1018         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1019       else
1020         wLastChar = ' ';
1021
1022       nEnd--;
1023       if (nEnd < 0)
1024       {
1025         item = ME_FindItemBack(item, diRun);
1026         para = ME_GetParagraph(item);
1027         nEnd = ME_StrLen(item->member.run.strText);
1028       }
1029     }
1030   }
1031   TRACE("not found\n");
1032   if (chrgText)
1033     chrgText->cpMin = chrgText->cpMax = -1;
1034   return -1;
1035 }
1036
1037 /* helper to send a msg filter notification */
1038 static BOOL
1039 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1040 {
1041     MSGFILTER msgf;
1042
1043     msgf.nmhdr.hwndFrom = editor->hWnd;
1044     msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1045     msgf.nmhdr.code = EN_MSGFILTER;
1046     msgf.msg = msg;
1047
1048     msgf.wParam = *wParam;
1049     msgf.lParam = *lParam;
1050     if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1051         return FALSE;
1052     *wParam = msgf.wParam;
1053     *lParam = msgf.lParam;
1054     msgf.wParam = *wParam;
1055
1056     return TRUE;
1057 }
1058
1059 static BOOL
1060 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1061 {
1062   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1063   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1064   
1065   switch (nKey)
1066   {
1067     case VK_LEFT:
1068     case VK_RIGHT:
1069     case VK_UP:
1070     case VK_DOWN:
1071     case VK_HOME:
1072     case VK_END:
1073     case VK_PRIOR:
1074     case VK_NEXT:
1075       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1076       return TRUE;
1077     case VK_BACK:
1078     case VK_DELETE:
1079       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1080       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1081         return FALSE;
1082       if (ME_IsSelection(editor))
1083         ME_DeleteSelection(editor);
1084       else if (nKey == VK_DELETE || ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1085         ME_DeleteTextAtCursor(editor, 1, 1);
1086       else
1087         return TRUE;
1088       ME_CommitUndo(editor);
1089       ME_UpdateRepaint(editor);
1090       ME_SendRequestResize(editor, FALSE);
1091       return TRUE;
1092
1093     default:
1094       if (ctrl_is_down)
1095       {
1096         if (nKey == 'W')
1097         {
1098           CHARFORMAT2W chf;
1099           char buf[2048];
1100           chf.cbSize = sizeof(chf);
1101           
1102           ME_GetSelectionCharFormat(editor, &chf);
1103           ME_DumpStyleToBuf(&chf, buf);
1104           MessageBoxA(NULL, buf, "Style dump", MB_OK);
1105         }
1106         if (nKey == 'Q')
1107         {
1108           ME_CheckCharOffsets(editor);
1109         }
1110       }
1111   }
1112   return FALSE;
1113 }
1114
1115 static void ME_SetCursor(ME_TextEditor *editor, int x)
1116 {
1117     if (x < editor->selofs || editor->linesel)
1118       SetCursor(hLeft);
1119     else
1120       SetCursor(hBeam);
1121 }
1122
1123 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1124 {
1125   CHARRANGE selrange;
1126   HMENU menu;
1127   int seltype = 0;
1128   if(!editor->lpOleCallback)
1129     return FALSE;
1130   ME_GetSelection(editor, (int *)&selrange.cpMin, (int *)&selrange.cpMax);
1131   if(selrange.cpMin == selrange.cpMax)
1132     seltype |= SEL_EMPTY;
1133   else
1134   {
1135     /* FIXME: Handle objects */
1136     seltype |= SEL_TEXT;
1137     if(selrange.cpMax-selrange.cpMin > 1)
1138       seltype |= SEL_MULTICHAR;
1139   }
1140   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1141   {
1142     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1143     DestroyMenu(menu);
1144   }
1145   return TRUE;
1146 }
1147
1148 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1149   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1150   HDC hDC;
1151   int i;
1152   ed->hWnd = hWnd;
1153   ed->bEmulateVersion10 = FALSE;
1154   ed->pBuffer = ME_MakeText();
1155   hDC = GetDC(hWnd);
1156   ME_MakeFirstParagraph(hDC, ed->pBuffer);
1157   ReleaseDC(hWnd, hDC);
1158   ed->bCaretShown = FALSE;
1159   ed->nCursors = 4;
1160   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1161   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1162   ed->pCursors[0].nOffset = 0;
1163   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1164   ed->pCursors[1].nOffset = 0;
1165   ed->nLastTotalLength = ed->nTotalLength = 0;
1166   ed->nHeight = 0;
1167   ed->nUDArrowX = -1;
1168   ed->nSequence = 0;
1169   ed->rgbBackColor = -1;
1170   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1171   ed->bCaretAtEnd = FALSE;
1172   ed->nEventMask = 0;
1173   ed->nModifyStep = 0;
1174   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1175   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1176   ed->nUndoStackSize = 0;
1177   ed->nUndoLimit = STACK_SIZE_DEFAULT;
1178   ed->nUndoMode = umAddToUndo;
1179   ed->nParagraphs = 1;
1180   ed->nLastSelStart = ed->nLastSelEnd = 0;
1181   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1182   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1183   ed->bRedraw = TRUE;
1184   ed->bHideSelection = FALSE;
1185   ed->nInvalidOfs = -1;
1186   ed->pfnWordBreak = NULL;
1187   ed->lpOleCallback = NULL;
1188   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1189   ed->AutoURLDetect_bEnable = FALSE;
1190   ed->bHaveFocus = FALSE;
1191   GetClientRect(hWnd, &ed->rcFormat);
1192   for (i=0; i<HFONT_CACHE_SIZE; i++)
1193   {
1194     ed->pFontCache[i].nRefs = 0;
1195     ed->pFontCache[i].nAge = 0;
1196     ed->pFontCache[i].hFont = NULL;
1197   }
1198   
1199   ME_CheckCharOffsets(ed);
1200   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
1201     ed->selofs = 16;
1202   else
1203     ed->selofs = 0;
1204   ed->linesel = 0;
1205
1206   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1207     ed->cPasswordMask = '*';
1208   else
1209     ed->cPasswordMask = 0;
1210   
1211   return ed;
1212 }
1213
1214 typedef struct tagME_GlobalDestStruct
1215 {
1216   HGLOBAL hData;
1217   int nLength;
1218 } ME_GlobalDestStruct;
1219
1220 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1221 {
1222   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1223   int i;
1224   WORD *pSrc, *pDest;
1225   
1226   cb = cb >> 1;
1227   pDest = (WORD *)lpBuff;
1228   pSrc = (WORD *)GlobalLock(pData->hData);
1229   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1230     pDest[i] = pSrc[pData->nLength+i];
1231   }    
1232   pData->nLength += i;
1233   *pcb = 2*i;
1234   GlobalUnlock(pData->hData);
1235   return 0;
1236 }
1237
1238 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1239 {
1240   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1241   int i;
1242   BYTE *pSrc, *pDest;
1243   
1244   pDest = lpBuff;
1245   pSrc = (BYTE *)GlobalLock(pData->hData);
1246   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1247     pDest[i] = pSrc[pData->nLength+i];
1248   }    
1249   pData->nLength += i;
1250   *pcb = i;
1251   GlobalUnlock(pData->hData);
1252   return 0;
1253 }
1254
1255
1256 void ME_DestroyEditor(ME_TextEditor *editor)
1257 {
1258   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1259   ME_DisplayItem *p = pFirst, *pNext = NULL;
1260   int i;
1261
1262   ME_ClearTempStyle(editor);
1263   ME_EmptyUndoStack(editor);
1264   while(p) {
1265     pNext = p->next;
1266     ME_DestroyDisplayItem(p);
1267     p = pNext;
1268   }
1269   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1270   for (i=0; i<HFONT_CACHE_SIZE; i++)
1271   {
1272     if (editor->pFontCache[i].hFont)
1273       DeleteObject(editor->pFontCache[i].hFont);
1274   }
1275   DeleteObject(editor->hbrBackground);
1276   if(editor->lpOleCallback)
1277     IUnknown_Release(editor->lpOleCallback);
1278
1279   FREE_OBJ(editor->pBuffer);
1280   FREE_OBJ(editor->pCursors);
1281
1282   FREE_OBJ(editor);
1283 }
1284
1285 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1286 {
1287     TRACE("\n");
1288     switch (fdwReason)
1289     {
1290     case DLL_PROCESS_ATTACH:
1291       DisableThreadLibraryCalls(hinstDLL);
1292       me_heap = HeapCreate (0, 0x10000, 0);
1293       if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
1294       hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
1295       hBeam = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
1296       LookupInit();
1297       break;
1298
1299     case DLL_PROCESS_DETACH:
1300       UnregisterClassW(RichEdit20W, 0);
1301       UnregisterClassW(RichEdit50W, 0);
1302       UnregisterClassA("RichEdit20A", 0);
1303       UnregisterClassA("RichEdit50A", 0);
1304       if (ME_ListBoxRegistered)
1305           UnregisterClassW(REListBox20W, 0);
1306       if (ME_ComboBoxRegistered)
1307           UnregisterClassW(REComboBox20W, 0);
1308       LookupCleanup();
1309       HeapDestroy (me_heap);
1310       me_heap = NULL;
1311       break;
1312     }
1313     return TRUE;
1314 }
1315
1316
1317 #define UNSUPPORTED_MSG(e) \
1318   case e: \
1319     FIXME(#e ": stub\n"); \
1320     return DefWindowProcW(hWnd, msg, wParam, lParam);
1321
1322 static const char * const edit_messages[] = {
1323   "EM_GETSEL",
1324   "EM_SETSEL",
1325   "EM_GETRECT",
1326   "EM_SETRECT",
1327   "EM_SETRECTNP",
1328   "EM_SCROLL",
1329   "EM_LINESCROLL",
1330   "EM_SCROLLCARET",
1331   "EM_GETMODIFY",
1332   "EM_SETMODIFY",
1333   "EM_GETLINECOUNT",
1334   "EM_LINEINDEX",
1335   "EM_SETHANDLE",
1336   "EM_GETHANDLE",
1337   "EM_GETTHUMB",
1338   "EM_UNKNOWN_BF",
1339   "EM_UNKNOWN_C0",
1340   "EM_LINELENGTH",
1341   "EM_REPLACESEL",
1342   "EM_UNKNOWN_C3",
1343   "EM_GETLINE",
1344   "EM_LIMITTEXT",
1345   "EM_CANUNDO",
1346   "EM_UNDO",
1347   "EM_FMTLINES",
1348   "EM_LINEFROMCHAR",
1349   "EM_UNKNOWN_CA",
1350   "EM_SETTABSTOPS",
1351   "EM_SETPASSWORDCHAR",
1352   "EM_EMPTYUNDOBUFFER",
1353   "EM_GETFIRSTVISIBLELINE",
1354   "EM_SETREADONLY",
1355   "EM_SETWORDBREAKPROC",
1356   "EM_GETWORDBREAKPROC",
1357   "EM_GETPASSWORDCHAR",
1358   "EM_SETMARGINS",
1359   "EM_GETMARGINS",
1360   "EM_GETLIMITTEXT",
1361   "EM_POSFROMCHAR",
1362   "EM_CHARFROMPOS"
1363 };
1364
1365 static const char * const richedit_messages[] = {
1366   "EM_CANPASTE",
1367   "EM_DISPLAYBAND",
1368   "EM_EXGETSEL",
1369   "EM_EXLIMITTEXT",
1370   "EM_EXLINEFROMCHAR",
1371   "EM_EXSETSEL",
1372   "EM_FINDTEXT",
1373   "EM_FORMATRANGE",
1374   "EM_GETCHARFORMAT",
1375   "EM_GETEVENTMASK",
1376   "EM_GETOLEINTERFACE",
1377   "EM_GETPARAFORMAT",
1378   "EM_GETSELTEXT",
1379   "EM_HIDESELECTION", 
1380   "EM_PASTESPECIAL",
1381   "EM_REQUESTRESIZE",
1382   "EM_SELECTIONTYPE",
1383   "EM_SETBKGNDCOLOR",
1384   "EM_SETCHARFORMAT",
1385   "EM_SETEVENTMASK",
1386   "EM_SETOLECALLBACK",
1387   "EM_SETPARAFORMAT",
1388   "EM_SETTARGETDEVICE",
1389   "EM_STREAMIN",
1390   "EM_STREAMOUT",
1391   "EM_GETTEXTRANGE",
1392   "EM_FINDWORDBREAK",
1393   "EM_SETOPTIONS",
1394   "EM_GETOPTIONS",
1395   "EM_FINDTEXTEX",
1396   "EM_GETWORDBREAKPROCEX",
1397   "EM_SETWORDBREAKPROCEX",
1398   "EM_SETUNDOLIMIT",
1399   "EM_UNKNOWN_USER_83",
1400   "EM_REDO",
1401   "EM_CANREDO",
1402   "EM_GETUNDONAME",
1403   "EM_GETREDONAME",
1404   "EM_STOPGROUPTYPING",
1405   "EM_SETTEXTMODE",
1406   "EM_GETTEXTMODE",
1407   "EM_AUTOURLDETECT",
1408   "EM_GETAUTOURLDETECT",
1409   "EM_SETPALETTE",
1410   "EM_GETTEXTEX",
1411   "EM_GETTEXTLENGTHEX",
1412   "EM_SHOWSCROLLBAR",
1413   "EM_SETTEXTEX",
1414   "EM_UNKNOWN_USER_98",
1415   "EM_UNKNOWN_USER_99",
1416   "EM_SETPUNCTUATION",
1417   "EM_GETPUNCTUATION",
1418   "EM_SETWORDWRAPMODE",
1419   "EM_GETWORDWRAPMODE",
1420   "EM_SETIMECOLOR",
1421   "EM_GETIMECOLOR",
1422   "EM_SETIMEOPTIONS",
1423   "EM_GETIMEOPTIONS",
1424   "EM_CONVPOSITION",
1425   "EM_UNKNOWN_USER_109",
1426   "EM_UNKNOWN_USER_110",
1427   "EM_UNKNOWN_USER_111",
1428   "EM_UNKNOWN_USER_112",
1429   "EM_UNKNOWN_USER_113",
1430   "EM_UNKNOWN_USER_114",
1431   "EM_UNKNOWN_USER_115",
1432   "EM_UNKNOWN_USER_116",
1433   "EM_UNKNOWN_USER_117",
1434   "EM_UNKNOWN_USER_118",
1435   "EM_UNKNOWN_USER_119",
1436   "EM_SETLANGOPTIONS",
1437   "EM_GETLANGOPTIONS",
1438   "EM_GETIMECOMPMODE",
1439   "EM_FINDTEXTW",
1440   "EM_FINDTEXTEXW",
1441   "EM_RECONVERSION",
1442   "EM_SETIMEMODEBIAS",
1443   "EM_GETIMEMODEBIAS"
1444 };
1445
1446 static const char *
1447 get_msg_name(UINT msg)
1448 {
1449   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
1450     return edit_messages[msg - EM_GETSEL];
1451   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1452     return richedit_messages[msg - EM_CANPASTE];
1453   return "";
1454 }
1455
1456 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
1457                                       LPARAM lParam, BOOL unicode)
1458 {
1459   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
1460   
1461   TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
1462         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
1463   
1464   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
1465     ERR("called with invalid hWnd %p - application bug?\n", hWnd);
1466     return 0; 
1467   }
1468
1469   switch(msg) {
1470   
1471   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1472   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1473   UNSUPPORTED_MSG(EM_FMTLINES)
1474   UNSUPPORTED_MSG(EM_FORMATRANGE)
1475   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1476   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1477   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1478   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1479   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1480   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1481   UNSUPPORTED_MSG(EM_GETREDONAME)
1482   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1483   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1484   UNSUPPORTED_MSG(EM_GETUNDONAME)
1485   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1486   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1487   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1488   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1489   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1490   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1491   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1492   UNSUPPORTED_MSG(EM_SETPALETTE)
1493   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1494   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1495   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1496   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1497   UNSUPPORTED_MSG(WM_STYLECHANGING)
1498   UNSUPPORTED_MSG(WM_STYLECHANGED)
1499 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1500     
1501 /* Messages specific to Richedit controls */
1502   
1503   case EM_STREAMIN:
1504    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1505   case EM_STREAMOUT:
1506    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1507   case WM_GETDLGCODE:
1508   {
1509     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1510     if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
1511     {
1512       int vk = (int)((LPMSG)lParam)->wParam;
1513       /* if style says we want return key */
1514       if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
1515       {
1516         code |= DLGC_WANTMESSAGE;
1517       }
1518       /* we always handle ctrl-tab */
1519       if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
1520       {
1521         code |= DLGC_WANTMESSAGE;
1522       }
1523     }
1524     return code;
1525   }
1526   case WM_NCCREATE:
1527   {
1528     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1529     TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
1530     editor = ME_MakeEditor(hWnd);
1531     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
1532     return TRUE;
1533   }
1534   case EM_EMPTYUNDOBUFFER:
1535     ME_EmptyUndoStack(editor);
1536     return 0;
1537   case EM_GETSEL:
1538   {
1539     /* Note: wParam/lParam can be NULL */
1540     UINT from, to;
1541     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1542     PUINT pto = lParam ? (PUINT)lParam : &to;
1543     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1544     if ((*pfrom|*pto) & 0xFFFF0000)
1545       return -1;
1546     return MAKELONG(*pfrom,*pto);
1547   }
1548   case EM_EXGETSEL:
1549   {
1550     CHARRANGE *pRange = (CHARRANGE *)lParam;
1551     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1552     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
1553     return 0;
1554   }
1555   case EM_SETUNDOLIMIT:
1556   {
1557     if ((int)wParam < 0)
1558       editor->nUndoLimit = STACK_SIZE_DEFAULT;
1559     else
1560       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
1561     /* Setting a max stack size keeps wine from getting killed 
1562       for hogging memory. Windows allocates all this memory at once, so
1563       no program would realistically set a value above our maximum. */
1564     return editor->nUndoLimit;
1565   }
1566   case EM_CANUNDO:
1567     return editor->pUndoStack != NULL;
1568   case EM_CANREDO:
1569     return editor->pRedoStack != NULL;
1570   case WM_UNDO: /* FIXME: actually not the same */
1571   case EM_UNDO:
1572     ME_Undo(editor);
1573     return 0;
1574   case EM_REDO:
1575     ME_Redo(editor);
1576     return 0;
1577   case EM_GETOPTIONS:
1578   {
1579     /* these flags are equivalent to the ES_* counterparts */
1580     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1581                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1582     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
1583
1584     return settings;
1585   }
1586   case EM_SETOPTIONS:
1587   {
1588     /* these flags are equivalent to ES_* counterparts                      
1589      * ECO_READONLY is already implemented in the code, only requires 
1590      * setting the bit to work                                        
1591      */
1592     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1593                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
1594     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
1595     DWORD settings = mask & raw;
1596
1597     switch(wParam)
1598     {
1599       case ECOOP_SET:
1600         settings = lParam;
1601         break;
1602       case ECOOP_OR:
1603         settings |= lParam;
1604         break;
1605       case ECOOP_AND:
1606         settings &= lParam;
1607         break;
1608       case ECOOP_XOR:
1609         settings ^= lParam;
1610     }
1611     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
1612
1613     if (settings & ECO_AUTOWORDSELECTION)
1614       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
1615     if (settings & ECO_SELECTIONBAR)
1616         editor->selofs = 16;
1617     else
1618         editor->selofs = 0;
1619     ME_WrapMarkedParagraphs(editor);
1620
1621     if (settings & ECO_VERTICAL)
1622       FIXME("ECO_VERTICAL not implemented yet!\n");
1623     if (settings & ECO_AUTOHSCROLL)
1624       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
1625     if (settings & ECO_AUTOVSCROLL)
1626       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
1627     if (settings & ECO_NOHIDESEL)
1628       FIXME("ECO_NOHIDESEL not implemented yet!\n");
1629     if (settings & ECO_WANTRETURN)
1630       FIXME("ECO_WANTRETURN not implemented yet!\n");
1631
1632     return settings;
1633   }
1634   case EM_SETSEL:
1635   {
1636     ME_InvalidateSelection(editor);
1637     ME_SetSelection(editor, wParam, lParam);
1638     ME_InvalidateSelection(editor);
1639     ME_SendSelChange(editor);
1640     return 0;
1641   }
1642   case EM_SETSCROLLPOS:
1643   {
1644     POINT *point = (POINT *)lParam;
1645     ME_ScrollAbs(editor, point->y);
1646     return 0;
1647   }
1648   case EM_AUTOURLDETECT:
1649   {
1650     if (wParam==1 || wParam ==0) 
1651     {
1652         editor->AutoURLDetect_bEnable = (BOOL)wParam;
1653         return 0;
1654     }
1655     return E_INVALIDARG;
1656   }
1657   case EM_GETAUTOURLDETECT:
1658   {
1659     return editor->AutoURLDetect_bEnable;
1660   }
1661   case EM_EXSETSEL:
1662   {
1663     int end;
1664     CHARRANGE range = *(CHARRANGE *)lParam;
1665
1666     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
1667
1668     ME_InvalidateSelection(editor);
1669     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
1670     ME_InvalidateSelection(editor);
1671     ME_SendSelChange(editor);
1672
1673     return end;
1674   }
1675   case EM_SHOWSCROLLBAR:
1676   {
1677     ShowScrollBar(editor->hWnd, wParam, lParam);
1678     return 0;
1679   }
1680   case EM_SETTEXTEX:
1681   {
1682     LPWSTR wszText;
1683     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1684     size_t len;
1685     int from, to;
1686     ME_Style *style;
1687     int oldModify = editor->nModifyStep;
1688
1689     if (!pStruct) return 0;
1690
1691     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
1692           pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
1693           pStruct->flags, pStruct->codepage);
1694
1695     /* FIXME: make use of pStruct->codepage in the to unicode translation */
1696     wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
1697     len = wszText ? lstrlenW(wszText) : 0;
1698
1699     /* FIXME: this should support RTF strings too, according to MSDN */
1700     if (pStruct->flags & ST_SELECTION) {
1701       ME_GetSelection(editor, &from, &to);
1702       style = ME_GetSelectionInsertStyle(editor);
1703       ME_InternalDeleteText(editor, from, to - from);
1704       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1705       ME_ReleaseStyle(style);
1706     }
1707     else {
1708       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1709       ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1710       len = 1;
1711     }
1712     ME_CommitUndo(editor);
1713     if (!(pStruct->flags & ST_KEEPUNDO))
1714     {
1715       editor->nModifyStep = oldModify;
1716       ME_EmptyUndoStack(editor);
1717     }
1718     ME_UpdateRepaint(editor);
1719     return len;
1720   }
1721   case EM_SETBKGNDCOLOR:
1722   {
1723     LRESULT lColor = ME_GetBackColor(editor);
1724     if (editor->rgbBackColor != -1)
1725       DeleteObject(editor->hbrBackground);
1726     if (wParam)
1727     {
1728       editor->rgbBackColor = -1;
1729       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1730     }
1731     else
1732     {
1733       editor->rgbBackColor = lParam;
1734       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
1735     }
1736     if (editor->bRedraw)
1737     {
1738       InvalidateRect(hWnd, NULL, TRUE);
1739       UpdateWindow(hWnd);
1740     }
1741     return lColor;
1742   }
1743   case EM_GETMODIFY:
1744     return editor->nModifyStep == 0 ? 0 : 1;
1745   case EM_SETMODIFY:
1746   {
1747     if (wParam)
1748       editor->nModifyStep = 1;
1749     else
1750       editor->nModifyStep = 0;
1751     
1752     return 0;
1753   }
1754   case EM_SETREADONLY:
1755   {
1756     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1757     if (wParam)
1758       nStyle |= ES_READONLY;
1759     else
1760       nStyle &= ~ES_READONLY;
1761     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1762     return 0;
1763   }
1764   case EM_SETEVENTMASK:
1765   {
1766     DWORD nOldMask = editor->nEventMask;
1767     
1768     editor->nEventMask = lParam;
1769     return nOldMask;
1770   }
1771   case EM_GETEVENTMASK:
1772     return editor->nEventMask;
1773   case EM_SETCHARFORMAT:
1774   {
1775     CHARFORMAT2W buf, *p;
1776     BOOL bRepaint = TRUE;
1777     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1778     if (p == NULL) return 0;
1779     if (!wParam)
1780       ME_SetDefaultCharFormat(editor, p);
1781     else if (wParam == (SCF_WORD | SCF_SELECTION)) {
1782       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1783       return 0;
1784     } else if (wParam == SCF_ALL) {
1785       if (editor->mode & TM_PLAINTEXT)
1786         ME_SetDefaultCharFormat(editor, p);
1787       else
1788         ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1789     } else if (editor->mode & TM_PLAINTEXT) {
1790       return 0;
1791     } else {
1792       int from, to;
1793       ME_GetSelection(editor, &from, &to);
1794       bRepaint = (from != to);
1795       ME_SetSelectionCharFormat(editor, p);
1796     }
1797     editor->nModifyStep = 1;
1798     ME_CommitUndo(editor);
1799     if (bRepaint)
1800       ME_RewrapRepaint(editor);
1801     return 1;
1802   }
1803   case EM_GETCHARFORMAT:
1804   {
1805     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1806     if (dst->cbSize != sizeof(CHARFORMATA) &&
1807         dst->cbSize != sizeof(CHARFORMATW) &&
1808         dst->cbSize != sizeof(CHARFORMAT2A) &&
1809         dst->cbSize != sizeof(CHARFORMAT2W))
1810       return 0;
1811     tmp.cbSize = sizeof(tmp);
1812     if (!wParam)
1813       ME_GetDefaultCharFormat(editor, &tmp);
1814     else
1815       ME_GetSelectionCharFormat(editor, &tmp);
1816     ME_CopyToCFAny(dst, &tmp);
1817     return tmp.dwMask;
1818   }
1819   case EM_SETPARAFORMAT:
1820     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1821     ME_RewrapRepaint(editor);
1822     ME_CommitUndo(editor);
1823     return 0;
1824   case EM_GETPARAFORMAT:
1825     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1826     return 0;
1827   case EM_GETFIRSTVISIBLELINE:
1828   {
1829     ME_DisplayItem *p = editor->pBuffer->pFirst;
1830     int y = ME_GetYScrollPos(editor);
1831     int ypara = 0;
1832     int count = 0;
1833     int ystart, yend;
1834     while(p) {
1835       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
1836       if (p->type == diTextEnd)
1837         break;
1838       if (p->type == diParagraph) {
1839         ypara = p->member.para.nYPos;
1840         continue;
1841       }
1842       ystart = ypara + p->member.row.nYPos;
1843       yend = ystart + p->member.row.nHeight;
1844       if (y < yend) {
1845         break;
1846       }
1847       count++;
1848     }
1849     return count;
1850   }
1851   case EM_HIDESELECTION:
1852   {
1853      editor->bHideSelection = (wParam != 0);
1854      ME_InvalidateSelection(editor);
1855      return 0;
1856   }
1857   case EM_LINESCROLL:
1858   {
1859     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
1860     return TRUE; /* Should return false if a single line richedit control */
1861   }
1862   case WM_CLEAR:
1863   {
1864     int from, to;
1865     ME_GetSelection(editor, &from, &to);
1866     ME_InternalDeleteText(editor, from, to-from);
1867     ME_CommitUndo(editor);
1868     ME_UpdateRepaint(editor);
1869     return 0;
1870   }
1871   case EM_REPLACESEL:
1872   {
1873     int from, to;
1874     ME_Style *style;
1875     LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
1876     size_t len = wszText ? lstrlenW(wszText) : 0;
1877     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1878
1879     ME_GetSelection(editor, &from, &to);
1880     style = ME_GetSelectionInsertStyle(editor);
1881     ME_InternalDeleteText(editor, from, to-from);
1882     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1883     ME_ReleaseStyle(style);
1884     /* drop temporary style if line end */
1885     /*
1886      * FIXME question: does abc\n mean: put abc,
1887      * clear temp style, put \n? (would require a change)
1888      */
1889     if (len>0 && wszText[len-1] == '\n')
1890       ME_ClearTempStyle(editor);
1891     ME_EndToUnicode(unicode, wszText);
1892     ME_CommitUndo(editor);
1893     if (!wParam)
1894       ME_EmptyUndoStack(editor);
1895     ME_UpdateRepaint(editor);
1896     return len;
1897   }
1898   case EM_SCROLLCARET:
1899   {
1900     int top, bottom; /* row's edges relative to document top */
1901     int nPos;
1902     ME_DisplayItem *para, *row;
1903     
1904     nPos = ME_GetYScrollPos(editor);
1905     row = ME_RowStart(editor->pCursors[0].pRun);
1906     para = ME_GetParagraph(row);
1907     top = para->member.para.nYPos + row->member.row.nYPos;
1908     bottom = top + row->member.row.nHeight;
1909     
1910     if (top < nPos) /* caret above window */
1911       ME_ScrollAbs(editor,  top);
1912     else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
1913       ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
1914     return 0;
1915   }
1916   case WM_SETFONT:
1917   {
1918     LOGFONTW lf;
1919     CHARFORMAT2W fmt;
1920     HDC hDC;
1921     BOOL bRepaint = LOWORD(lParam);
1922     
1923     if (!wParam)
1924       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
1925     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
1926     hDC = GetDC(hWnd);
1927     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
1928     ReleaseDC(hWnd, hDC);   
1929     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
1930     ME_SetDefaultCharFormat(editor, &fmt);
1931
1932     ME_CommitUndo(editor);
1933     if (bRepaint)
1934       ME_RewrapRepaint(editor);
1935     return 0;
1936   }
1937   case WM_SETTEXT:
1938   {
1939     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1940     if (lParam)
1941     {
1942       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1943       if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
1944       {
1945         /* Undocumented: WM_SETTEXT supports RTF text */
1946         ME_StreamInRTFString(editor, 0, (char *)lParam);
1947       }
1948       else
1949       {
1950         LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
1951         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1952         if (lstrlenW(wszText) > 0)
1953         {
1954           int len = -1;
1955
1956           /* uses default style! */
1957           if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
1958           {
1959             WCHAR * p;
1960
1961             p = wszText;
1962             while (*p != '\0' && *p != '\r' && *p != '\n') p++;
1963             len = p - wszText;
1964           }
1965           ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1966         }
1967         ME_EndToUnicode(unicode, wszText);
1968       }
1969     }
1970     else
1971       TRACE("WM_SETTEXT - NULL\n");
1972     ME_CommitUndo(editor);
1973     ME_EmptyUndoStack(editor);
1974     ME_SetSelection(editor, 0, 0);
1975     editor->nModifyStep = 0;
1976     ME_UpdateRepaint(editor);
1977     return 1;
1978   }
1979   case EM_CANPASTE:
1980   {
1981     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1982     if (IsClipboardFormatAvailable(nRTFFormat))
1983       return TRUE;
1984     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1985       return TRUE;
1986     return FALSE;
1987   }
1988   case WM_PASTE:
1989   {    
1990     DWORD dwFormat = 0;
1991     EDITSTREAM es;
1992     ME_GlobalDestStruct gds;
1993     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1994     UINT cf = 0;
1995
1996     if (IsClipboardFormatAvailable(nRTFFormat))
1997       cf = nRTFFormat, dwFormat = SF_RTF;
1998     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1999       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2000     else
2001       return 0;
2002
2003     if (!OpenClipboard(hWnd))
2004       return 0;
2005     gds.hData = GetClipboardData(cf);
2006     gds.nLength = 0;
2007     es.dwCookie = (DWORD)&gds;
2008     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2009     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es);
2010
2011     CloseClipboard();
2012     return 0;
2013   }
2014   case WM_CUT:
2015   case WM_COPY:
2016   {
2017     LPDATAOBJECT dataObj = NULL;
2018     CHARRANGE range;
2019     HRESULT hr = S_OK;
2020     
2021     if (editor->cPasswordMask)
2022       return 0; /* Copying or Cutting masked text isn't allowed */
2023     
2024     ME_GetSelection(editor, (int*)&range.cpMin, (int*)&range.cpMax);
2025     if(editor->lpOleCallback)
2026         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2027     if(FAILED(hr) || !dataObj)
2028         hr = ME_GetDataObject(editor, &range, &dataObj);
2029     if(SUCCEEDED(hr)) {
2030         hr = OleSetClipboard(dataObj);
2031         IDataObject_Release(dataObj);
2032     }
2033     if (SUCCEEDED(hr) && msg == WM_CUT)
2034     {
2035       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
2036       ME_CommitUndo(editor);
2037       ME_UpdateRepaint(editor);
2038     }
2039     return 0;
2040   }
2041   case WM_GETTEXTLENGTH:
2042   {
2043     GETTEXTLENGTHEX how;
2044
2045     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2046     how.codepage = unicode ? 1200 : CP_ACP;
2047     return ME_GetTextLengthEx(editor, &how);
2048   }
2049   case EM_GETTEXTLENGTHEX:
2050     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2051   case WM_GETTEXT:
2052   {
2053     GETTEXTEX ex;
2054     LRESULT rc;
2055     LPSTR bufferA = NULL;
2056     LPWSTR bufferW = NULL;
2057
2058     if (unicode)
2059         bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2060     else
2061         bufferA = heap_alloc(wParam + 2);
2062
2063     ex.cb = wParam + (unicode ? 2*sizeof(WCHAR) : 2);
2064     ex.flags = GT_USECRLF;
2065     ex.codepage = unicode ? 1200 : CP_ACP;
2066     ex.lpDefaultChar = NULL;
2067     ex.lpUsedDefaultChar = NULL;
2068     rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
2069
2070     if (unicode)
2071     {
2072         memcpy((LPWSTR)lParam, bufferW, wParam);
2073         if (lstrlenW(bufferW) >= wParam / sizeof(WCHAR)) rc = 0;
2074     }
2075     else
2076     {
2077         memcpy((LPSTR)lParam, bufferA, wParam);
2078         if (strlen(bufferA) >= wParam) rc = 0;
2079     }
2080     heap_free(bufferA);
2081     heap_free(bufferW);
2082     return rc;
2083   }
2084   case EM_GETTEXTEX:
2085   {
2086     GETTEXTEX *ex = (GETTEXTEX*)wParam;
2087     int nStart, nCount;
2088
2089     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2090       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2091
2092     if (ex->flags & GT_SELECTION)
2093     {
2094       ME_GetSelection(editor, &nStart, &nCount);
2095       nCount -= nStart;
2096       nCount = min(nCount, ex->cb - 1);
2097     }
2098     else
2099     {
2100       nStart = 0;
2101       nCount = ex->cb - 1;
2102     }
2103     if (ex->codepage == 1200)
2104     {
2105       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2106       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2107     }
2108     else
2109     {
2110       /* potentially each char may be a CR, why calculate the exact value with O(N) when
2111         we can just take a bigger buffer? :) */
2112       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2113       LPWSTR buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
2114       DWORD buflen = ex->cb;
2115       LRESULT rc;
2116       DWORD flags = 0;
2117
2118       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2119       rc = WideCharToMultiByte(ex->codepage, flags, buffer, -1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
2120       if (rc) rc--; /* do not count 0 terminator */
2121
2122       heap_free(buffer);
2123       return rc;
2124     }
2125   }
2126   case EM_GETSELTEXT:
2127   {
2128     int from, to;
2129     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2130     ME_GetSelection(editor, &from, &to);
2131     tr.chrg.cpMin = from;
2132     tr.chrg.cpMax = to;
2133     tr.lpstrText = (WCHAR *)lParam;
2134     return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
2135   }
2136   case EM_GETSCROLLPOS:
2137   {
2138       POINT *point = (POINT *)lParam;
2139       point->x = 0; /* FIXME side scrolling not implemented */
2140       point->y = ME_GetYScrollPos(editor);
2141       return 1;
2142   }
2143   case EM_GETTEXTRANGE:
2144   {
2145     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2146     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2147       rng->chrg.cpMin, rng->chrg.cpMax, unicode,
2148       editor->bEmulateVersion10, ME_GetTextLength(editor));
2149     if (unicode)
2150       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
2151     else
2152     {
2153       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2154       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2155       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
2156       /* FIXME this is a potential security hole (buffer overrun) 
2157          if you know more about wchar->mbyte conversion please explain
2158       */
2159       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2160       FREE_OBJ(p);
2161       return nChars;
2162     }
2163   }
2164   case EM_GETLINE:
2165   {
2166     ME_DisplayItem *run;
2167     const unsigned int nMaxChars = *(WORD *) lParam;
2168     unsigned int nEndChars, nCharsLeft = nMaxChars;
2169     char *dest = (char *) lParam;
2170     /* rich text editor 1.0 uses \r\n for line end, 2.0 uses just \r; 
2171     we need to know how if we have the extra \n or not */
2172     int nLF = editor->bEmulateVersion10;
2173
2174     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2175           unicode ? "Unicode" : "Ansi");
2176
2177     run = ME_FindRowWithNumber(editor, wParam);
2178     if (run == NULL)
2179       return 0;
2180
2181     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2182            && !(run->member.run.nFlags & MERF_ENDPARA))
2183     {
2184       unsigned int nCopy;
2185       ME_String *strText;
2186       if (run->type != diRun)
2187         break;
2188       strText = run->member.run.strText;
2189       nCopy = min(nCharsLeft, strText->nLen);
2190
2191       if (unicode)
2192         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2193       else
2194         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2195                                     nCharsLeft, NULL, NULL);
2196       dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
2197       nCharsLeft -= nCopy;
2198     }
2199
2200     /* append \r\0 (or \r\n\0 in 1.0), space allowing */
2201     nEndChars = min(nCharsLeft, 2 + nLF);
2202     nCharsLeft -= nEndChars;
2203     if (unicode)
2204     {
2205       const WCHAR src[] = {'\r', '\0'};
2206       const WCHAR src10[] = {'\r', '\n', '\0'};
2207       lstrcpynW((LPWSTR) dest, nLF ? src10 : src, nEndChars);
2208     }
2209     else
2210       lstrcpynA(dest, nLF ? "\r\n" : "\r", nEndChars);
2211
2212     TRACE("EM_GETLINE: got %u bytes\n", nMaxChars - nCharsLeft);
2213
2214     if (nEndChars == 2 + nLF)
2215       return nMaxChars - nCharsLeft - 1; /* don't count \0 */
2216     else
2217       return nMaxChars - nCharsLeft;
2218   }
2219   case EM_GETLINECOUNT:
2220   {
2221     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2222     int nRows = 0;
2223
2224     while (item != editor->pBuffer->pLast)
2225     {
2226       assert(item->type == diParagraph);
2227       nRows += item->member.para.nRows;
2228       item = item->member.para.next_para;
2229     }
2230     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2231     return max(1, nRows);
2232   }
2233   case EM_LINEFROMCHAR:
2234   {
2235     if (wParam == -1)
2236       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2237     else
2238       return ME_RowNumberFromCharOfs(editor, wParam);
2239   }
2240   case EM_EXLINEFROMCHAR:
2241   {
2242     if (lParam == -1)
2243       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2244     else    
2245       return ME_RowNumberFromCharOfs(editor, lParam);
2246   }
2247   case EM_LINEINDEX:
2248   {
2249     ME_DisplayItem *item, *para;
2250     int nCharOfs;
2251     
2252     if (wParam == -1)
2253       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2254     else
2255       item = ME_FindRowWithNumber(editor, wParam);
2256     if (!item)
2257       return -1;
2258     para = ME_GetParagraph(item);
2259     item = ME_FindItemFwd(item, diRun);
2260     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2261     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2262     return nCharOfs;
2263   }
2264   case EM_LINELENGTH:
2265   {
2266     ME_DisplayItem *item, *item_end;
2267     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2268     
2269     if (wParam > ME_GetTextLength(editor))
2270       return 0;
2271     if (wParam == -1)
2272     {
2273       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2274       return 0;
2275     }
2276     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2277     item = ME_RowStart(item);
2278     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2279     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2280     if (item_end->type == diStartRow)
2281       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2282     else
2283       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs
2284        - (editor->bEmulateVersion10?2:1);
2285     nChars = nNextLineOfs - nThisLineOfs;
2286     TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
2287     return nChars;
2288   }
2289   case EM_EXLIMITTEXT:
2290   {
2291     if ((int)lParam < 0)
2292      return 0;
2293     if (lParam == 0)
2294       editor->nTextLimit = 65536;
2295     else
2296       editor->nTextLimit = (int) lParam;
2297     return 0;
2298   }
2299   case EM_LIMITTEXT:
2300   {
2301     if (wParam == 0)
2302       editor->nTextLimit = 65536;
2303     else
2304       editor->nTextLimit = (int) wParam;
2305     return 0;
2306   }
2307   case EM_GETLIMITTEXT:
2308   {
2309     return editor->nTextLimit;
2310   }
2311   case EM_FINDTEXT:
2312   {
2313     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2314     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2315     WCHAR *tmp;
2316     LRESULT r;
2317
2318     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2319       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2320     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2321     FREE_OBJ( tmp );
2322     return r;
2323   }
2324   case EM_FINDTEXTEX:
2325   {
2326     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2327     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2328     WCHAR *tmp;
2329     LRESULT r;
2330
2331     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2332       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2333     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2334     FREE_OBJ( tmp );
2335     return r;
2336   }
2337   case EM_FINDTEXTW:
2338   {
2339     FINDTEXTW *ft = (FINDTEXTW *)lParam;
2340     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2341   }
2342   case EM_FINDTEXTEXW:
2343   {
2344     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2345     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2346   }
2347   case EM_GETZOOM:
2348     if (!wParam || !lParam)
2349       return FALSE;
2350     *(int *)wParam = editor->nZoomNumerator;
2351     *(int *)lParam = editor->nZoomDenominator;
2352     return TRUE;
2353   case EM_SETZOOM:
2354     return ME_SetZoom(editor, wParam, lParam);
2355   case EM_CHARFROMPOS:
2356     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2357   case EM_POSFROMCHAR:
2358   {
2359     ME_DisplayItem *pRun;
2360     int nCharOfs, nOffset, nLength;
2361     POINTL pt = {0,0};
2362     
2363     nCharOfs = wParam; 
2364     /* detect which API version we're dealing with */
2365     if (wParam >= 0x40000)
2366         nCharOfs = lParam;
2367     nLength = ME_GetTextLength(editor);
2368     
2369     if (nCharOfs < nLength) { 
2370         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2371         assert(pRun->type == diRun);
2372         pt.y = pRun->member.run.pt.y;
2373         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
2374         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
2375     } else {
2376         pt.x = 0;
2377         pt.y = editor->pBuffer->pLast->member.para.nYPos;
2378     }
2379     if (wParam >= 0x40000) {
2380         *(POINTL *)wParam = pt;
2381     }
2382     return MAKELONG( pt.x, pt.y );
2383   }
2384   case WM_CREATE:
2385     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
2386     { /* Squelch the default horizontal scrollbar it would make */
2387       ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
2388     }
2389     ME_CommitUndo(editor);
2390     ME_WrapMarkedParagraphs(editor);
2391     ME_MoveCaret(editor);
2392     return 0;
2393   case WM_DESTROY:
2394     ME_DestroyEditor(editor);
2395     SetWindowLongPtrW(hWnd, 0, 0);
2396     return 0;
2397   case WM_LBUTTONDOWN:
2398     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2399         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2400       return 0;
2401     SetFocus(hWnd);
2402     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2403     SetCapture(hWnd);
2404     ME_LinkNotify(editor,msg,wParam,lParam);
2405     ME_SetCursor(editor, LOWORD(lParam));
2406     break;
2407   case WM_MOUSEMOVE:
2408     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2409         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2410       return 0;
2411     if (GetCapture() == hWnd)
2412       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2413     ME_LinkNotify(editor,msg,wParam,lParam);
2414     ME_SetCursor(editor, LOWORD(lParam));
2415     break;
2416   case WM_LBUTTONUP:
2417     if (GetCapture() == hWnd)
2418       ReleaseCapture();
2419     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2420         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2421       return 0;
2422     editor->linesel = 0;
2423     ME_SetCursor(editor, LOWORD(lParam));
2424     ME_LinkNotify(editor,msg,wParam,lParam);
2425     break;
2426   case WM_LBUTTONDBLCLK:
2427     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2428         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2429       return 0;
2430     ME_LinkNotify(editor,msg,wParam,lParam);
2431     ME_SelectWord(editor);
2432     break;
2433   case WM_RBUTTONUP:
2434   case WM_RBUTTONDOWN:
2435     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2436         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2437       return 0;
2438     goto do_default;
2439   case WM_CONTEXTMENU:
2440     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
2441       goto do_default;
2442     break;
2443   case WM_PAINT:
2444     if (editor->bRedraw)
2445     {
2446       HDC hDC;
2447       PAINTSTRUCT ps;
2448
2449       hDC = BeginPaint(hWnd, &ps);
2450       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
2451       EndPaint(hWnd, &ps);
2452     }
2453     break;
2454   case WM_SETFOCUS:
2455     editor->bHaveFocus = TRUE;
2456     ME_ShowCaret(editor);
2457     ME_SendOldNotify(editor, EN_SETFOCUS);
2458     return 0;
2459   case WM_KILLFOCUS:
2460     ME_HideCaret(editor);
2461     editor->bHaveFocus = FALSE;
2462     ME_SendOldNotify(editor, EN_KILLFOCUS);
2463     return 0;
2464   case WM_ERASEBKGND:
2465   {
2466     if (editor->bRedraw)
2467     {
2468       HDC hDC = (HDC)wParam;
2469       RECT rc;
2470       if (GetUpdateRect(hWnd,&rc,TRUE))
2471       {
2472         FillRect(hDC, &rc, editor->hbrBackground);
2473       }
2474     }
2475     return 1;
2476   }
2477   case WM_COMMAND:
2478     TRACE("editor wnd command = %d\n", LOWORD(wParam));
2479     return 0;
2480   case WM_KEYUP:
2481     if ((editor->nEventMask & ENM_KEYEVENTS) &&
2482         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2483       return 0;
2484     goto do_default;
2485   case WM_KEYDOWN:
2486     if ((editor->nEventMask & ENM_KEYEVENTS) &&
2487         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2488       return 0;
2489     if (ME_KeyDown(editor, LOWORD(wParam)))
2490       return 0;
2491     goto do_default;
2492   case WM_CHAR: 
2493   {
2494     WCHAR wstr;
2495
2496     if (unicode)
2497         wstr = (WCHAR)wParam;
2498     else
2499     {
2500         CHAR charA = wParam;
2501         MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2502     }
2503     if (editor->AutoURLDetect_bEnable)
2504       ME_AutoURLDetect(editor, wstr);
2505         
2506     switch (wstr)
2507     {
2508     case 1: /* Ctrl-A */
2509       ME_SetSelection(editor, 0, -1);
2510       return 0;
2511     case 3: /* Ctrl-C */
2512       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
2513       return 0;
2514     }
2515     
2516     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
2517       MessageBeep(MB_ICONERROR);
2518       return 0; /* FIXME really 0 ? */
2519     }
2520
2521     switch (wstr)
2522     {
2523     case 22: /* Ctrl-V */
2524       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
2525       return 0;
2526     case 24: /* Ctrl-X */
2527       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
2528       return 0;
2529     case 25: /* Ctrl-Y */
2530       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
2531       return 0;
2532     case 26: /* Ctrl-Z */
2533       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
2534       return 0;
2535     }
2536     if (((unsigned)wstr)>=' '
2537         || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2538         || wstr=='\t') {
2539       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2540       /* WM_CHAR is restricted to nTextLimit */
2541       int from, to;
2542       ME_GetSelection(editor, &from, &to);
2543       if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2544       {
2545         ME_Style *style = ME_GetInsertStyle(editor, 0);
2546         ME_SaveTempStyle(editor);
2547         ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2548         ME_ReleaseStyle(style);
2549         ME_CommitUndo(editor);
2550       }
2551       ME_UpdateRepaint(editor);
2552     }
2553     return 0;
2554   }
2555   case EM_SCROLL: /* fall through */
2556   case WM_VSCROLL: 
2557   {
2558     int origNPos;
2559     int lineHeight;
2560     
2561     origNPos = ME_GetYScrollPos(editor);
2562     lineHeight = 24;
2563     
2564     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
2565       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2566     if (lineHeight <= 0) lineHeight = 24;
2567     
2568     switch(LOWORD(wParam)) 
2569     {
2570       case SB_LINEUP:
2571         ME_ScrollUp(editor,lineHeight);
2572         break;
2573       case SB_LINEDOWN:
2574         ME_ScrollDown(editor,lineHeight);
2575         break;
2576       case SB_PAGEUP:
2577         ME_ScrollUp(editor,editor->sizeWindow.cy);
2578         break;
2579       case SB_PAGEDOWN:
2580         ME_ScrollDown(editor,editor->sizeWindow.cy);
2581         break;
2582       case SB_THUMBTRACK:
2583       case SB_THUMBPOSITION:
2584         ME_ScrollAbs(editor,HIWORD(wParam));
2585         break;
2586     }
2587     if (msg == EM_SCROLL)
2588       return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
2589     break;
2590   }
2591   case WM_MOUSEWHEEL:
2592   {
2593     int gcWheelDelta;
2594     UINT pulScrollLines;
2595
2596     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2597         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2598       return 0;
2599
2600     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
2601     gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
2602     
2603     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
2604     {
2605       /* FIXME follow the original */
2606       ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8); 
2607     }
2608     break;
2609   }
2610   case EM_GETRECT:
2611   {
2612     *((RECT *)lParam) = editor->rcFormat;
2613     return 0;
2614   }
2615   case EM_SETRECT:
2616   case EM_SETRECTNP:
2617   {
2618     if (lParam)
2619     {
2620       RECT *rc = (RECT *)lParam;
2621       
2622       if (wParam)
2623       {
2624         editor->rcFormat.left += rc->left;
2625         editor->rcFormat.top += rc->top;
2626         editor->rcFormat.right += rc->right;
2627         editor->rcFormat.bottom += rc->bottom;
2628       }
2629       else
2630       {
2631         editor->rcFormat = *rc;
2632       }
2633     }
2634     else
2635     {
2636       GetClientRect(hWnd, &editor->rcFormat);
2637     }
2638     if (msg != EM_SETRECTNP)
2639       ME_RewrapRepaint(editor);
2640     return 0;
2641   }
2642   case EM_REQUESTRESIZE:
2643     ME_SendRequestResize(editor, TRUE);
2644     return 0;
2645   case WM_SETREDRAW:
2646     editor->bRedraw = wParam;
2647     return 0;
2648   case WM_SIZE:
2649   {
2650     GetClientRect(hWnd, &editor->rcFormat);
2651     ME_RewrapRepaint(editor);
2652     return DefWindowProcW(hWnd, msg, wParam, lParam);
2653   }
2654   /* IME messages to make richedit controls IME aware */
2655   case WM_IME_SETCONTEXT:
2656   case WM_IME_CONTROL:
2657   case WM_IME_SELECT:
2658   case WM_IME_COMPOSITIONFULL:
2659     return 0;
2660   case WM_IME_STARTCOMPOSITION:
2661   {
2662     editor->imeStartIndex=ME_GetCursorOfs(editor,0);
2663     ME_DeleteSelection(editor);
2664     ME_CommitUndo(editor);
2665     ME_UpdateRepaint(editor);
2666     return 0;
2667   }
2668   case WM_IME_COMPOSITION:
2669   {
2670     HIMC hIMC;
2671
2672     ME_Style *style = ME_GetInsertStyle(editor, 0);
2673     hIMC = ImmGetContext(hWnd);
2674     ME_DeleteSelection(editor);
2675     ME_CommitUndo(editor);
2676     ME_SaveTempStyle(editor);
2677     if (lParam & GCS_RESULTSTR)
2678     {
2679         LPWSTR lpCompStr = NULL;
2680         DWORD dwBufLen;
2681
2682         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2683         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
2684         ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
2685         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
2686         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
2687     }
2688     else if (lParam & GCS_COMPSTR)
2689     {
2690         LPWSTR lpCompStr = NULL;
2691         DWORD dwBufLen;
2692
2693         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
2694         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
2695         ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
2696         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
2697
2698         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
2699         ME_SetSelection(editor,editor->imeStartIndex,
2700                         editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
2701     }
2702     ME_ReleaseStyle(style);
2703     ME_UpdateRepaint(editor);
2704     return 0;
2705   }
2706   case WM_IME_ENDCOMPOSITION:
2707   {
2708     ME_DeleteSelection(editor);
2709     editor->imeStartIndex=-1;
2710     return 0;
2711   }
2712   case EM_GETOLEINTERFACE:
2713   {
2714     LPVOID *ppvObj = (LPVOID*) lParam;
2715     return CreateIRichEditOle(editor, ppvObj);
2716   }
2717   case EM_GETPASSWORDCHAR:
2718   {
2719     return editor->cPasswordMask;
2720   }
2721   case EM_SETOLECALLBACK:
2722     if(editor->lpOleCallback)
2723       IUnknown_Release(editor->lpOleCallback);
2724     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
2725     if(editor->lpOleCallback)
2726       IUnknown_AddRef(editor->lpOleCallback);
2727     return TRUE;
2728   case EM_GETWORDBREAKPROC:
2729     return (LRESULT)editor->pfnWordBreak;
2730   case EM_SETWORDBREAKPROC:
2731   {
2732     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
2733
2734     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
2735     return (LRESULT)pfnOld;
2736   }
2737   case EM_SETTEXTMODE:
2738   {
2739     LRESULT ret;
2740     int mask = 0;
2741     int changes = 0;
2742     ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
2743     if (!ret)
2744     {
2745       /*Check for valid wParam*/
2746       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
2747           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
2748           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
2749         return 1;
2750       else
2751       {
2752         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
2753         {
2754           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
2755           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
2756         }
2757         /*FIXME: Currently no support for undo level and code page options*/ 
2758         editor->mode = (editor->mode & (~mask)) | changes;
2759         return 0;
2760       }
2761     }
2762     return ret;
2763   }
2764   case EM_SETPASSWORDCHAR:
2765   {
2766     editor->cPasswordMask = wParam;
2767     ME_RewrapRepaint(editor);
2768     return 0;
2769   }
2770   default:
2771   do_default:
2772     return DefWindowProcW(hWnd, msg, wParam, lParam);
2773   }
2774   return 0L;
2775 }
2776
2777 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2778 {
2779     BOOL unicode = TRUE;
2780
2781     /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
2782     if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
2783         unicode = FALSE;
2784
2785     return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
2786 }
2787
2788 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2789 {
2790     return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
2791 }
2792
2793 /******************************************************************
2794  *        RichEditANSIWndProc (RICHED20.10)
2795  */
2796 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2797 {
2798     return RichEditWndProcA(hWnd, msg, wParam, lParam);
2799 }
2800
2801 /******************************************************************
2802  *        RichEdit10ANSIWndProc (RICHED20.9)
2803  */
2804 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2805 {
2806   LRESULT result;
2807   
2808   /* FIXME: this is NOT the same as 2.0 version */
2809   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
2810   if (msg == WM_NCCREATE)
2811   {
2812     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2813     
2814     editor->bEmulateVersion10 = TRUE;
2815     editor->pBuffer->pLast->member.para.nCharOfs = 2;
2816   }
2817   return result;
2818 }
2819
2820 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
2821 {
2822   HWND hWnd = editor->hWnd;
2823   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
2824 }
2825
2826 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2827 {
2828   int x,y;
2829   ME_Cursor tmpCursor;
2830   int nCharOfs; /* The start of the clicked text. Absolute character offset */
2831
2832   ME_Run *tmpRun;
2833
2834   ENLINK info;
2835   x = (short)LOWORD(lParam);
2836   y = (short)HIWORD(lParam);
2837   nCharOfs = ME_CharFromPos(editor, x, y);
2838   if (nCharOfs < 0) return;
2839
2840   ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
2841   tmpRun = &tmpCursor.pRun->member.run;
2842
2843   if ((tmpRun->style->fmt.dwMask & CFM_LINK)
2844     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
2845   { /* The clicked run has CFE_LINK set */
2846     info.nmhdr.hwndFrom = editor->hWnd;
2847     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2848     info.nmhdr.code = EN_LINK;
2849     info.msg = msg;
2850     info.wParam = wParam;
2851     info.lParam = lParam;
2852     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
2853     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
2854     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
2855   }  
2856 }
2857
2858 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
2859 {
2860   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
2861   int i = 0;
2862   
2863   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
2864     item = item->member.para.next_para;
2865   if (!item)
2866     return 0;
2867   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
2868     item = item->member.para.next_para;
2869     i++;
2870   }
2871   return i;
2872 }
2873
2874
2875 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
2876 {
2877   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
2878   int nWritten = 0;
2879   WCHAR *pStart = buffer;
2880   
2881   if (!item) {
2882     *buffer = 0;
2883     return 0;
2884   }
2885   
2886   if (nStart)
2887   {
2888     int nLen = ME_StrLen(item->member.run.strText) - nStart;
2889     if (nLen > nChars)
2890       nLen = nChars;
2891     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
2892     nChars -= nLen;
2893     nWritten += nLen;
2894     if (!nChars)
2895       return nWritten;
2896     buffer += nLen;
2897     nStart = 0;
2898     item = ME_FindItemFwd(item, diRun);
2899   }
2900   
2901   while(nChars && item)
2902   {
2903     int nLen = ME_StrLen(item->member.run.strText);
2904     if (nLen > nChars)
2905       nLen = nChars;
2906
2907     if (item->member.run.nFlags & MERF_ENDPARA)
2908     {
2909       if (!ME_FindItemFwd(item, diRun))
2910         /* No '\r' is appended to the last paragraph. */
2911         nLen = 0;
2912       else if (bCRLF && nChars == 1) {
2913         nLen = 0;
2914         nChars = 0;
2915       } else {
2916         *buffer = '\r';
2917         if (bCRLF)
2918         {
2919           *(++buffer) = '\n';
2920           nWritten++;
2921         }
2922         assert(nLen == 1);
2923         /* our end paragraph consists of 2 characters now */
2924         if (editor->bEmulateVersion10)
2925           nChars--;
2926       }
2927     }
2928     else
2929       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2930     nChars -= nLen;
2931     nWritten += nLen;
2932     buffer += nLen;    
2933       
2934     if (!nChars)
2935     {
2936       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2937       *buffer = 0;
2938       return nWritten;
2939     }
2940     item = ME_FindItemFwd(item, diRun);
2941   }
2942   *buffer = 0;
2943   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2944   return nWritten;  
2945 }
2946
2947 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
2948 {
2949   WNDCLASSW wcW;
2950   WNDCLASSA wcA;
2951   
2952   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2953   wcW.lpfnWndProc = RichEditWndProcW;
2954   wcW.cbClsExtra = 0;
2955   wcW.cbWndExtra = sizeof(ME_TextEditor *);
2956   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2957   wcW.hIcon = NULL;
2958   wcW.hCursor = hBeam;
2959   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2960   wcW.lpszMenuName = NULL;
2961
2962   if (is_version_nt())
2963   {
2964     wcW.lpszClassName = RichEdit20W;
2965     if (!RegisterClassW(&wcW)) return FALSE;
2966     wcW.lpszClassName = RichEdit50W;
2967     if (!RegisterClassW(&wcW)) return FALSE;
2968   }
2969   else
2970   {
2971     /* WNDCLASSA/W have the same layout */
2972     wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
2973     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
2974     wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
2975     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
2976   }
2977
2978   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2979   wcA.lpfnWndProc = RichEditWndProcA;
2980   wcA.cbClsExtra = 0;
2981   wcA.cbWndExtra = sizeof(ME_TextEditor *);
2982   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
2983   wcA.hIcon = NULL;
2984   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2985   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2986   wcA.lpszMenuName = NULL;
2987   wcA.lpszClassName = "RichEdit20A";
2988   if (!RegisterClassA(&wcA)) return FALSE;
2989   wcA.lpszClassName = "RichEdit50A";
2990   if (!RegisterClassA(&wcA)) return FALSE;
2991
2992   return TRUE;
2993 }
2994
2995 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2996   /* FIXME: Not implemented */
2997   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
2998         hWnd, msg, get_msg_name(msg), wParam, lParam);
2999   return DefWindowProcW(hWnd, msg, wParam, lParam);
3000 }
3001
3002 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3003   /* FIXME: Not implemented */
3004   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3005         hWnd, msg, get_msg_name(msg), wParam, lParam);
3006   return DefWindowProcW(hWnd, msg, wParam, lParam);
3007 }
3008
3009 /******************************************************************
3010  *        REExtendedRegisterClass (RICHED20.8)
3011  *
3012  * FIXME undocumented
3013  * Need to check for errors and implement controls and callbacks 
3014  */
3015 LRESULT WINAPI REExtendedRegisterClass(void)
3016 {
3017   WNDCLASSW wcW;
3018   UINT result;
3019
3020   FIXME("semi stub\n");
3021
3022   wcW.cbClsExtra = 0;
3023   wcW.cbWndExtra = 4;
3024   wcW.hInstance = NULL;
3025   wcW.hIcon = NULL;
3026   wcW.hCursor = NULL;
3027   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
3028   wcW.lpszMenuName = NULL;
3029
3030   if (!ME_ListBoxRegistered)
3031   {
3032       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
3033       wcW.lpfnWndProc = REListWndProc;
3034       wcW.lpszClassName = REListBox20W;
3035       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
3036   }
3037
3038   if (!ME_ComboBoxRegistered)
3039   {
3040       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
3041       wcW.lpfnWndProc = REComboWndProc;
3042       wcW.lpszClassName = REComboBox20W;
3043       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
3044   }
3045
3046   result = 0;
3047   if (ME_ListBoxRegistered)
3048       result += 1;
3049   if (ME_ComboBoxRegistered)
3050       result += 2;
3051
3052   return result;
3053 }
3054
3055 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar) 
3056 {
3057   struct prefix_s {
3058     const char *text;
3059     int length;
3060   } prefixes[12] = {
3061     {"http:", 5},
3062     {"file:", 6},
3063     {"mailto:", 8},
3064     {"ftp:", 5},
3065     {"https:", 7},
3066     {"gopher:", 8},
3067     {"nntp:", 6},
3068     {"prospero:", 10},
3069     {"telnet:", 8},
3070     {"news:", 6},
3071     {"wais:", 6},
3072     {"www.", 5}
3073   };
3074   CHARRANGE ins_pt;
3075   int curf_ef, link_ef, def_ef;
3076   int cur_prefx, prefx_cnt;
3077   int sel_min, sel_max;
3078   int car_pos = 0;
3079   int text_pos=-1;
3080   int URLmin, URLmax = 0;
3081   CHARRANGE url;
3082   FINDTEXTA ft;
3083   CHARFORMAT2W cur_format;
3084   CHARFORMAT2W default_format;
3085   CHARFORMAT2W link;
3086   RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
3087   sel_min = ins_pt.cpMin;
3088   sel_max = ins_pt.cpMax;
3089   if (sel_min==sel_max) 
3090     car_pos = sel_min;
3091   if (sel_min!=sel_max)
3092     car_pos = ME_GetTextLength(editor)+1;   
3093   cur_format.cbSize = sizeof(cur_format);
3094   default_format.cbSize = sizeof(default_format);
3095   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
3096   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
3097   link.cbSize = sizeof(link);
3098   link.dwMask = CFM_LINK;
3099   link.dwEffects = CFE_LINK;
3100   curf_ef = cur_format.dwEffects & link.dwEffects;
3101   def_ef = default_format.dwEffects & link.dwEffects;
3102   link_ef = link.dwEffects & link.dwEffects;
3103   if (curf_ef == link_ef) 
3104   {
3105     if( curChar == '\n' || curChar=='\r' || curChar==' ') 
3106     {
3107       ME_SetSelection(editor, car_pos, car_pos);
3108       RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
3109       text_pos=-1;
3110       return 0;
3111     }
3112   }
3113   if (curf_ef == def_ef)
3114   {
3115     cur_prefx = 0;
3116     prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
3117     while (cur_prefx<=prefx_cnt) 
3118     {
3119       if (text_pos == -1) 
3120       {
3121         ft.lpstrText = prefixes[cur_prefx].text;
3122         URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
3123         URLmax=max(0, car_pos);
3124         if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
3125         {
3126         URLmax = ME_GetTextLength(editor)+1;
3127         }
3128         ft.chrg.cpMin = URLmin;
3129         ft.chrg.cpMax = URLmax;
3130         text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);   
3131         cur_prefx++;
3132       }
3133       if (text_pos != -1) 
3134       {
3135         url.cpMin=text_pos;
3136         url.cpMax=car_pos-1;
3137         ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
3138         ME_RewrapRepaint(editor);
3139         break;
3140       }
3141     }
3142   }
3143   return 0;
3144 }