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