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