richedit: Flip the big switch and encode actual CR and LF into end-of-paragraph runs.
[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   BOOL invalidRTF = FALSE;
1033
1034   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1035   editor->nEventMask = 0;
1036
1037   ME_GetSelection(editor, &from, &to);
1038   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1039     style = ME_GetSelectionInsertStyle(editor);
1040
1041     ME_InternalDeleteText(editor, from, to-from);
1042   }
1043   else {
1044     style = editor->pBuffer->pDefaultStyle;
1045     ME_AddRefStyle(style);
1046     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
1047     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1048     from = to = 0;
1049     ME_ClearTempStyle(editor);
1050     /* FIXME restore default paragraph formatting ! */
1051   }
1052
1053
1054   /* Back up undo mode to a local variable */
1055   nUndoMode = editor->nUndoMode;
1056
1057   /* Only create an undo if SFF_SELECTION is set */
1058   if (!(format & SFF_SELECTION))
1059     editor->nUndoMode = umIgnore;
1060
1061   inStream.editstream = stream;
1062   inStream.editstream->dwError = 0;
1063   inStream.dwSize = 0;
1064   inStream.dwUsed = 0;
1065
1066   if (format & SF_RTF)
1067   {
1068     /* Check if it's really RTF, and if it is not, use plain text */
1069     ME_StreamInFill(&inStream);
1070     if (!inStream.editstream->dwError)
1071     {
1072       if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1073         || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1074       {
1075         invalidRTF = TRUE;
1076       }
1077     }
1078   }
1079
1080   if (!invalidRTF && !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. This is not affected by
1105          CR/LF counters, since RTF streaming presents only \para tokens, which
1106          are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1107        */
1108       if (stripLastCR) {
1109         int newfrom, newto;
1110         ME_GetSelection(editor, &newfrom, &newto);
1111         if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1112           WCHAR lastchar[3] = {'\0', '\0'};
1113           int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1114
1115           ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1116           if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1117             ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize);
1118           }
1119         }
1120       }
1121
1122       style = parser.style;
1123     }
1124     else if (format & SF_TEXT)
1125       ME_StreamInText(editor, format, &inStream, style);
1126     else
1127       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1128     ME_GetSelection(editor, &to, &to2);
1129     /* put the cursor at the top */
1130     if (!(format & SFF_SELECTION))
1131       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1132   }
1133
1134   /* Restore saved undo mode */
1135   editor->nUndoMode = nUndoMode;
1136
1137   /* even if we didn't add an undo, we need to commit anything on the stack */
1138   ME_CommitUndo(editor);
1139
1140   /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1141   if (!(format & SFF_SELECTION))
1142     ME_EmptyUndoStack(editor);
1143
1144   ME_ReleaseStyle(style);
1145   editor->nEventMask = nEventMask;
1146   ME_UpdateRepaint(editor);
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   int runLength;
1197   
1198   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1199     item = ME_FindItemFwd(item, diParagraph);
1200
1201   if (!item)
1202     return item;
1203
1204   nOffset -= item->member.para.nCharOfs;
1205   if (nItemType == diParagraph) {
1206     if (nItemOffset)
1207       *nItemOffset = nOffset;
1208     return item;
1209   }
1210   
1211   do {
1212     item = ME_FindItemFwd(item, diRun);
1213     runLength = ME_StrLen(item->member.run.strText);
1214     if (item->member.run.nFlags & MERF_ENDPARA)
1215       runLength = item->member.run.nCR + item->member.run.nLF;
1216   } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1217   if (item) {
1218     nOffset -= item->member.run.nCharOfs;
1219
1220     /* Special case: nOffset may not point exactly at the division between the
1221        \r and the \n in 1.0 emulation. If such a case happens, it is sent
1222        into the next run, if one exists
1223      */
1224     if (   item->member.run.nFlags & MERF_ENDPARA
1225         && nOffset == item->member.run.nCR
1226         && item->member.run.nLF > 0) {
1227       ME_DisplayItem *nextItem;
1228       nextItem = ME_FindItemFwd(item, diRun);
1229       if (nextItem) {
1230         nOffset = 0;
1231         item = nextItem;
1232       }
1233     }
1234     if (nItemOffset)
1235       *nItemOffset = nOffset;
1236   }
1237   return item;
1238 }
1239
1240
1241 static int
1242 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1243 {
1244   const int nLen = lstrlenW(text);
1245   const int nTextLen = ME_GetTextLength(editor);
1246   int nStart, nEnd;
1247   int nMin, nMax;
1248   ME_DisplayItem *item;
1249   ME_DisplayItem *para;
1250   WCHAR wLastChar = ' ';
1251
1252   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1253         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1254   
1255   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1256     FIXME("Flags 0x%08x not implemented\n",
1257         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1258
1259   nMin = chrg->cpMin;
1260   if (chrg->cpMax == -1)
1261     nMax = nTextLen;
1262   else
1263     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1264   
1265   /* when searching up, if cpMin < cpMax, then instead of searching
1266    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1267    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1268    * case, it is always bigger than cpMin.
1269    */
1270   if (!(flags & FR_DOWN))
1271   {
1272     int nSwap = nMax;
1273
1274     nMax = nMin > nTextLen ? nTextLen : nMin;
1275     if (nMin < nSwap || chrg->cpMax == -1)
1276       nMin = 0;
1277     else
1278       nMin = nSwap;
1279   }
1280
1281   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1282   {
1283     if (chrgText)
1284       chrgText->cpMin = chrgText->cpMax = -1;
1285     return -1;
1286   }
1287  
1288   if (flags & FR_DOWN) /* Forward search */
1289   {
1290     /* If possible, find the character before where the search starts */
1291     if ((flags & FR_WHOLEWORD) && nMin)
1292     {
1293       nStart = nMin - 1;
1294       item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1295       if (!item)
1296       {
1297         if (chrgText)
1298           chrgText->cpMin = chrgText->cpMax = -1;
1299         return -1;
1300       }
1301       wLastChar = item->member.run.strText->szData[nStart];
1302     }
1303
1304     nStart = nMin;
1305     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1306     if (!item)
1307     {
1308       if (chrgText)
1309         chrgText->cpMin = chrgText->cpMax = -1;
1310       return -1;
1311     }
1312
1313     para = ME_GetParagraph(item);
1314     while (item
1315            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1316     {
1317       ME_DisplayItem *pCurItem = item;
1318       int nCurStart = nStart;
1319       int nMatched = 0;
1320     
1321       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1322       {
1323         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1324           break;
1325
1326         nMatched++;
1327         if (nMatched == nLen)
1328         {
1329           ME_DisplayItem *pNextItem = pCurItem;
1330           int nNextStart = nCurStart;
1331           WCHAR wNextChar;
1332
1333           /* Check to see if next character is a whitespace */
1334           if (flags & FR_WHOLEWORD)
1335           {
1336             if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1337             {
1338               pNextItem = ME_FindItemFwd(pCurItem, diRun);
1339               nNextStart = -nMatched;
1340             }
1341
1342             if (pNextItem)
1343               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1344             else
1345               wNextChar = ' ';
1346
1347             if (isalnumW(wNextChar))
1348               break;
1349           }
1350
1351           nStart += para->member.para.nCharOfs + pCurItem->member.run.nCharOfs;
1352           if (chrgText)
1353           {
1354             chrgText->cpMin = nStart;
1355             chrgText->cpMax = nStart + nLen;
1356           }
1357           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1358           return nStart;
1359         }
1360         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1361         {
1362           pCurItem = ME_FindItemFwd(pCurItem, diRun);
1363           para = ME_GetParagraph(pCurItem);
1364           nCurStart = -nMatched;
1365         }
1366       }
1367       if (pCurItem)
1368         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1369       else
1370         wLastChar = ' ';
1371
1372       nStart++;
1373       if (nStart == ME_StrLen(item->member.run.strText))
1374       {
1375         item = ME_FindItemFwd(item, diRun);
1376         para = ME_GetParagraph(item);
1377         nStart = 0;
1378       }
1379     }
1380   }
1381   else /* Backward search */
1382   {
1383     /* If possible, find the character after where the search ends */
1384     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1385     {
1386       nEnd = nMax + 1;
1387       item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1388       if (!item)
1389       {
1390         if (chrgText)
1391           chrgText->cpMin = chrgText->cpMax = -1;
1392         return -1;
1393       }
1394       wLastChar = item->member.run.strText->szData[nEnd];
1395     }
1396
1397     nEnd = nMax;
1398     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1399     if (!item)
1400     {
1401       if (chrgText)
1402         chrgText->cpMin = chrgText->cpMax = -1;
1403       return -1;
1404     }
1405     
1406     para = ME_GetParagraph(item);
1407     
1408     while (item
1409            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1410     {
1411       ME_DisplayItem *pCurItem = item;
1412       int nCurEnd = nEnd;
1413       int nMatched = 0;
1414       
1415       if (nCurEnd - nMatched == 0)
1416       {
1417         pCurItem = ME_FindItemBack(pCurItem, diRun);
1418         para = ME_GetParagraph(pCurItem);
1419         nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1420       }
1421       
1422       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1423       {
1424         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1425           break;
1426
1427         nMatched++;
1428         if (nMatched == nLen)
1429         {
1430           ME_DisplayItem *pPrevItem = pCurItem;
1431           int nPrevEnd = nCurEnd;
1432           WCHAR wPrevChar;
1433
1434           /* Check to see if previous character is a whitespace */
1435           if (flags & FR_WHOLEWORD)
1436           {
1437             if (nPrevEnd - nMatched == 0)
1438             {
1439               pPrevItem = ME_FindItemBack(pCurItem, diRun);
1440               if (pPrevItem)
1441                 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1442             }
1443
1444             if (pPrevItem)
1445               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1446             else
1447               wPrevChar = ' ';
1448
1449             if (isalnumW(wPrevChar))
1450               break;
1451           }
1452
1453           nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1454           if (chrgText)
1455           {
1456             chrgText->cpMin = nStart;
1457             chrgText->cpMax = nStart + nLen;
1458           }
1459           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1460           return nStart;
1461         }
1462         if (nCurEnd - nMatched == 0)
1463         {
1464           pCurItem = ME_FindItemBack(pCurItem, diRun);
1465           /* Don't care about pCurItem becoming NULL here; it's already taken
1466            * care of in the exterior loop condition */
1467           para = ME_GetParagraph(pCurItem);
1468           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1469         }
1470       }
1471       if (pCurItem)
1472         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1473       else
1474         wLastChar = ' ';
1475
1476       nEnd--;
1477       if (nEnd < 0)
1478       {
1479         item = ME_FindItemBack(item, diRun);
1480         para = ME_GetParagraph(item);
1481         nEnd = ME_StrLen(item->member.run.strText);
1482       }
1483     }
1484   }
1485   TRACE("not found\n");
1486   if (chrgText)
1487     chrgText->cpMin = chrgText->cpMax = -1;
1488   return -1;
1489 }
1490
1491 /* helper to send a msg filter notification */
1492 static BOOL
1493 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1494 {
1495     MSGFILTER msgf;
1496
1497     msgf.nmhdr.hwndFrom = editor->hWnd;
1498     msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1499     msgf.nmhdr.code = EN_MSGFILTER;
1500     msgf.msg = msg;
1501
1502     msgf.wParam = *wParam;
1503     msgf.lParam = *lParam;
1504     if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1505         return FALSE;
1506     *wParam = msgf.wParam;
1507     *lParam = msgf.lParam;
1508     msgf.wParam = *wParam;
1509
1510     return TRUE;
1511 }
1512
1513 static BOOL
1514 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1515 {
1516   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1517   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1518   
1519   switch (nKey)
1520   {
1521     case VK_LEFT:
1522     case VK_RIGHT:
1523     case VK_UP:
1524     case VK_DOWN:
1525     case VK_HOME:
1526     case VK_END:
1527     case VK_PRIOR:
1528     case VK_NEXT:
1529       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1530       return TRUE;
1531     case VK_BACK:
1532     case VK_DELETE:
1533       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1534       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1535         return FALSE;
1536       if (ME_IsSelection(editor))
1537         ME_DeleteSelection(editor);
1538       else if (nKey == VK_DELETE || ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1539         ME_DeleteTextAtCursor(editor, 1, 1);
1540       else
1541         return TRUE;
1542       ME_CommitUndo(editor);
1543       ME_UpdateRepaint(editor);
1544       ME_SendRequestResize(editor, FALSE);
1545       return TRUE;
1546
1547     default:
1548       if (ctrl_is_down)
1549       {
1550         if (nKey == 'W')
1551         {
1552           CHARFORMAT2W chf;
1553           char buf[2048];
1554           chf.cbSize = sizeof(chf);
1555           
1556           ME_GetSelectionCharFormat(editor, &chf);
1557           ME_DumpStyleToBuf(&chf, buf);
1558           MessageBoxA(NULL, buf, "Style dump", MB_OK);
1559         }
1560         if (nKey == 'Q')
1561         {
1562           ME_CheckCharOffsets(editor);
1563         }
1564       }
1565   }
1566   return FALSE;
1567 }
1568
1569 static BOOL ME_SetCursor(ME_TextEditor *editor, int x)
1570 {
1571   if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
1572       (x < editor->selofs || editor->linesel))
1573   {
1574       SetCursor(hLeft);
1575       return TRUE;
1576   }
1577   return FALSE;
1578 }
1579
1580 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1581 {
1582   CHARRANGE selrange;
1583   HMENU menu;
1584   int seltype = 0;
1585   if(!editor->lpOleCallback)
1586     return FALSE;
1587   ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
1588   if(selrange.cpMin == selrange.cpMax)
1589     seltype |= SEL_EMPTY;
1590   else
1591   {
1592     /* FIXME: Handle objects */
1593     seltype |= SEL_TEXT;
1594     if(selrange.cpMax-selrange.cpMin > 1)
1595       seltype |= SEL_MULTICHAR;
1596   }
1597   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1598   {
1599     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1600     DestroyMenu(menu);
1601   }
1602   return TRUE;
1603 }
1604
1605 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1606   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1607   int i;
1608   ed->hWnd = hWnd;
1609   ed->bEmulateVersion10 = FALSE;
1610   ed->pBuffer = ME_MakeText();
1611   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1612   ME_MakeFirstParagraph(ed);
1613   ed->bCaretShown = FALSE;
1614   ed->nCursors = 4;
1615   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1616   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1617   ed->pCursors[0].nOffset = 0;
1618   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1619   ed->pCursors[1].nOffset = 0;
1620   ed->pCursors[2] = ed->pCursors[0];
1621   ed->pCursors[3] = ed->pCursors[1];
1622   ed->nLastTotalLength = ed->nTotalLength = 0;
1623   ed->nHeight = 0;
1624   ed->nUDArrowX = -1;
1625   ed->nSequence = 0;
1626   ed->rgbBackColor = -1;
1627   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1628   ed->bCaretAtEnd = FALSE;
1629   ed->nEventMask = 0;
1630   ed->nModifyStep = 0;
1631   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1632   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1633   ed->nUndoStackSize = 0;
1634   ed->nUndoLimit = STACK_SIZE_DEFAULT;
1635   ed->nUndoMode = umAddToUndo;
1636   ed->nParagraphs = 1;
1637   ed->nLastSelStart = ed->nLastSelEnd = 0;
1638   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1639   ed->bRedraw = TRUE;
1640   ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL) ? FALSE : TRUE;
1641   ed->bHideSelection = FALSE;
1642   ed->nInvalidOfs = -1;
1643   ed->pfnWordBreak = NULL;
1644   ed->lpOleCallback = NULL;
1645   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1646   ed->AutoURLDetect_bEnable = FALSE;
1647   ed->bHaveFocus = FALSE;
1648   GetClientRect(hWnd, &ed->rcFormat);
1649   for (i=0; i<HFONT_CACHE_SIZE; i++)
1650   {
1651     ed->pFontCache[i].nRefs = 0;
1652     ed->pFontCache[i].nAge = 0;
1653     ed->pFontCache[i].hFont = NULL;
1654   }
1655   
1656   ME_CheckCharOffsets(ed);
1657   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
1658     ed->selofs = 16;
1659   else
1660     ed->selofs = 0;
1661   ed->linesel = 0;
1662
1663   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1664     ed->cPasswordMask = '*';
1665   else
1666     ed->cPasswordMask = 0;
1667   
1668   return ed;
1669 }
1670
1671 typedef struct tagME_GlobalDestStruct
1672 {
1673   HGLOBAL hData;
1674   int nLength;
1675 } ME_GlobalDestStruct;
1676
1677 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1678 {
1679   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1680   int i;
1681   WORD *pSrc, *pDest;
1682   
1683   cb = cb >> 1;
1684   pDest = (WORD *)lpBuff;
1685   pSrc = (WORD *)GlobalLock(pData->hData);
1686   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1687     pDest[i] = pSrc[pData->nLength+i];
1688   }    
1689   pData->nLength += i;
1690   *pcb = 2*i;
1691   GlobalUnlock(pData->hData);
1692   return 0;
1693 }
1694
1695 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1696 {
1697   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1698   int i;
1699   BYTE *pSrc, *pDest;
1700   
1701   pDest = lpBuff;
1702   pSrc = (BYTE *)GlobalLock(pData->hData);
1703   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1704     pDest[i] = pSrc[pData->nLength+i];
1705   }    
1706   pData->nLength += i;
1707   *pcb = i;
1708   GlobalUnlock(pData->hData);
1709   return 0;
1710 }
1711
1712
1713 void ME_DestroyEditor(ME_TextEditor *editor)
1714 {
1715   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1716   ME_DisplayItem *p = pFirst, *pNext = NULL;
1717   int i;
1718
1719   ME_ClearTempStyle(editor);
1720   ME_EmptyUndoStack(editor);
1721   while(p) {
1722     pNext = p->next;
1723     ME_DestroyDisplayItem(p);
1724     p = pNext;
1725   }
1726   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1727   for (i=0; i<HFONT_CACHE_SIZE; i++)
1728   {
1729     if (editor->pFontCache[i].hFont)
1730       DeleteObject(editor->pFontCache[i].hFont);
1731   }
1732   if (editor->rgbBackColor != -1)
1733     DeleteObject(editor->hbrBackground);
1734   if(editor->lpOleCallback)
1735     IUnknown_Release(editor->lpOleCallback);
1736
1737   FREE_OBJ(editor->pBuffer);
1738   FREE_OBJ(editor->pCursors);
1739
1740   FREE_OBJ(editor);
1741 }
1742
1743 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1744 {
1745     TRACE("\n");
1746     switch (fdwReason)
1747     {
1748     case DLL_PROCESS_ATTACH:
1749       DisableThreadLibraryCalls(hinstDLL);
1750       me_heap = HeapCreate (0, 0x10000, 0);
1751       if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
1752       hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
1753       LookupInit();
1754       break;
1755
1756     case DLL_PROCESS_DETACH:
1757       UnregisterClassW(RichEdit20W, 0);
1758       UnregisterClassW(RichEdit50W, 0);
1759       UnregisterClassA("RichEdit20A", 0);
1760       UnregisterClassA("RichEdit50A", 0);
1761       if (ME_ListBoxRegistered)
1762           UnregisterClassW(REListBox20W, 0);
1763       if (ME_ComboBoxRegistered)
1764           UnregisterClassW(REComboBox20W, 0);
1765       LookupCleanup();
1766       HeapDestroy (me_heap);
1767       me_heap = NULL;
1768       break;
1769     }
1770     return TRUE;
1771 }
1772
1773
1774 #define UNSUPPORTED_MSG(e) \
1775   case e: \
1776     FIXME(#e ": stub\n"); \
1777     return DefWindowProcW(hWnd, msg, wParam, lParam);
1778
1779 static const char * const edit_messages[] = {
1780   "EM_GETSEL",
1781   "EM_SETSEL",
1782   "EM_GETRECT",
1783   "EM_SETRECT",
1784   "EM_SETRECTNP",
1785   "EM_SCROLL",
1786   "EM_LINESCROLL",
1787   "EM_SCROLLCARET",
1788   "EM_GETMODIFY",
1789   "EM_SETMODIFY",
1790   "EM_GETLINECOUNT",
1791   "EM_LINEINDEX",
1792   "EM_SETHANDLE",
1793   "EM_GETHANDLE",
1794   "EM_GETTHUMB",
1795   "EM_UNKNOWN_BF",
1796   "EM_UNKNOWN_C0",
1797   "EM_LINELENGTH",
1798   "EM_REPLACESEL",
1799   "EM_UNKNOWN_C3",
1800   "EM_GETLINE",
1801   "EM_LIMITTEXT",
1802   "EM_CANUNDO",
1803   "EM_UNDO",
1804   "EM_FMTLINES",
1805   "EM_LINEFROMCHAR",
1806   "EM_UNKNOWN_CA",
1807   "EM_SETTABSTOPS",
1808   "EM_SETPASSWORDCHAR",
1809   "EM_EMPTYUNDOBUFFER",
1810   "EM_GETFIRSTVISIBLELINE",
1811   "EM_SETREADONLY",
1812   "EM_SETWORDBREAKPROC",
1813   "EM_GETWORDBREAKPROC",
1814   "EM_GETPASSWORDCHAR",
1815   "EM_SETMARGINS",
1816   "EM_GETMARGINS",
1817   "EM_GETLIMITTEXT",
1818   "EM_POSFROMCHAR",
1819   "EM_CHARFROMPOS"
1820 };
1821
1822 static const char * const richedit_messages[] = {
1823   "EM_CANPASTE",
1824   "EM_DISPLAYBAND",
1825   "EM_EXGETSEL",
1826   "EM_EXLIMITTEXT",
1827   "EM_EXLINEFROMCHAR",
1828   "EM_EXSETSEL",
1829   "EM_FINDTEXT",
1830   "EM_FORMATRANGE",
1831   "EM_GETCHARFORMAT",
1832   "EM_GETEVENTMASK",
1833   "EM_GETOLEINTERFACE",
1834   "EM_GETPARAFORMAT",
1835   "EM_GETSELTEXT",
1836   "EM_HIDESELECTION", 
1837   "EM_PASTESPECIAL",
1838   "EM_REQUESTRESIZE",
1839   "EM_SELECTIONTYPE",
1840   "EM_SETBKGNDCOLOR",
1841   "EM_SETCHARFORMAT",
1842   "EM_SETEVENTMASK",
1843   "EM_SETOLECALLBACK",
1844   "EM_SETPARAFORMAT",
1845   "EM_SETTARGETDEVICE",
1846   "EM_STREAMIN",
1847   "EM_STREAMOUT",
1848   "EM_GETTEXTRANGE",
1849   "EM_FINDWORDBREAK",
1850   "EM_SETOPTIONS",
1851   "EM_GETOPTIONS",
1852   "EM_FINDTEXTEX",
1853   "EM_GETWORDBREAKPROCEX",
1854   "EM_SETWORDBREAKPROCEX",
1855   "EM_SETUNDOLIMIT",
1856   "EM_UNKNOWN_USER_83",
1857   "EM_REDO",
1858   "EM_CANREDO",
1859   "EM_GETUNDONAME",
1860   "EM_GETREDONAME",
1861   "EM_STOPGROUPTYPING",
1862   "EM_SETTEXTMODE",
1863   "EM_GETTEXTMODE",
1864   "EM_AUTOURLDETECT",
1865   "EM_GETAUTOURLDETECT",
1866   "EM_SETPALETTE",
1867   "EM_GETTEXTEX",
1868   "EM_GETTEXTLENGTHEX",
1869   "EM_SHOWSCROLLBAR",
1870   "EM_SETTEXTEX",
1871   "EM_UNKNOWN_USER_98",
1872   "EM_UNKNOWN_USER_99",
1873   "EM_SETPUNCTUATION",
1874   "EM_GETPUNCTUATION",
1875   "EM_SETWORDWRAPMODE",
1876   "EM_GETWORDWRAPMODE",
1877   "EM_SETIMECOLOR",
1878   "EM_GETIMECOLOR",
1879   "EM_SETIMEOPTIONS",
1880   "EM_GETIMEOPTIONS",
1881   "EM_CONVPOSITION",
1882   "EM_UNKNOWN_USER_109",
1883   "EM_UNKNOWN_USER_110",
1884   "EM_UNKNOWN_USER_111",
1885   "EM_UNKNOWN_USER_112",
1886   "EM_UNKNOWN_USER_113",
1887   "EM_UNKNOWN_USER_114",
1888   "EM_UNKNOWN_USER_115",
1889   "EM_UNKNOWN_USER_116",
1890   "EM_UNKNOWN_USER_117",
1891   "EM_UNKNOWN_USER_118",
1892   "EM_UNKNOWN_USER_119",
1893   "EM_SETLANGOPTIONS",
1894   "EM_GETLANGOPTIONS",
1895   "EM_GETIMECOMPMODE",
1896   "EM_FINDTEXTW",
1897   "EM_FINDTEXTEXW",
1898   "EM_RECONVERSION",
1899   "EM_SETIMEMODEBIAS",
1900   "EM_GETIMEMODEBIAS"
1901 };
1902
1903 static const char *
1904 get_msg_name(UINT msg)
1905 {
1906   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
1907     return edit_messages[msg - EM_GETSEL];
1908   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1909     return richedit_messages[msg - EM_CANPASTE];
1910   return "";
1911 }
1912
1913 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
1914                                       LPARAM lParam, BOOL unicode)
1915 {
1916   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
1917   
1918   TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
1919         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
1920   
1921   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
1922     ERR("called with invalid hWnd %p - application bug?\n", hWnd);
1923     return 0; 
1924   }
1925
1926   switch(msg) {
1927   
1928   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1929   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1930   UNSUPPORTED_MSG(EM_FMTLINES)
1931   UNSUPPORTED_MSG(EM_FORMATRANGE)
1932   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1933   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1934   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1935   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1936   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1937   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1938   UNSUPPORTED_MSG(EM_GETREDONAME)
1939   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1940   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1941   UNSUPPORTED_MSG(EM_GETUNDONAME)
1942   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1943   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1944   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1945   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1946   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1947   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1948   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1949   UNSUPPORTED_MSG(EM_SETPALETTE)
1950   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1951   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1952   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1953   UNSUPPORTED_MSG(WM_STYLECHANGING)
1954   UNSUPPORTED_MSG(WM_STYLECHANGED)
1955 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1956     
1957 /* Messages specific to Richedit controls */
1958   
1959   case EM_STREAMIN:
1960    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
1961   case EM_STREAMOUT:
1962    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1963   case WM_GETDLGCODE:
1964   {
1965     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1966     if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
1967     {
1968       int vk = (int)((LPMSG)lParam)->wParam;
1969       /* if style says we want return key */
1970       if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
1971       {
1972         code |= DLGC_WANTMESSAGE;
1973       }
1974       /* we always handle ctrl-tab */
1975       if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
1976       {
1977         code |= DLGC_WANTMESSAGE;
1978       }
1979     }
1980     return code;
1981   }
1982   case WM_NCCREATE:
1983   {
1984     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1985     TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
1986     editor = ME_MakeEditor(hWnd);
1987     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
1988     return TRUE;
1989   }
1990   case EM_EMPTYUNDOBUFFER:
1991     ME_EmptyUndoStack(editor);
1992     return 0;
1993   case EM_GETSEL:
1994   {
1995     /* Note: wParam/lParam can be NULL */
1996     UINT from, to;
1997     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1998     PUINT pto = lParam ? (PUINT)lParam : &to;
1999     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2000     if ((*pfrom|*pto) & 0xFFFF0000)
2001       return -1;
2002     return MAKELONG(*pfrom,*pto);
2003   }
2004   case EM_EXGETSEL:
2005   {
2006     CHARRANGE *pRange = (CHARRANGE *)lParam;
2007     ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2008     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2009     return 0;
2010   }
2011   case EM_SETUNDOLIMIT:
2012   {
2013     if ((int)wParam < 0)
2014       editor->nUndoLimit = STACK_SIZE_DEFAULT;
2015     else
2016       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2017     /* Setting a max stack size keeps wine from getting killed 
2018       for hogging memory. Windows allocates all this memory at once, so
2019       no program would realistically set a value above our maximum. */
2020     return editor->nUndoLimit;
2021   }
2022   case EM_CANUNDO:
2023     return editor->pUndoStack != NULL;
2024   case EM_CANREDO:
2025     return editor->pRedoStack != NULL;
2026   case WM_UNDO: /* FIXME: actually not the same */
2027   case EM_UNDO:
2028     ME_Undo(editor);
2029     return 0;
2030   case EM_REDO:
2031     ME_Redo(editor);
2032     return 0;
2033   case EM_GETOPTIONS:
2034   {
2035     /* these flags are equivalent to the ES_* counterparts */
2036     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2037                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2038     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2039
2040     return settings;
2041   }
2042   case EM_SETOPTIONS:
2043   {
2044     /* these flags are equivalent to ES_* counterparts                      
2045      * ECO_READONLY is already implemented in the code, only requires 
2046      * setting the bit to work                                        
2047      */
2048     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2049                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2050     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2051     DWORD settings = mask & raw;
2052
2053     switch(wParam)
2054     {
2055       case ECOOP_SET:
2056         settings = lParam;
2057         break;
2058       case ECOOP_OR:
2059         settings |= lParam;
2060         break;
2061       case ECOOP_AND:
2062         settings &= lParam;
2063         break;
2064       case ECOOP_XOR:
2065         settings ^= lParam;
2066     }
2067     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2068
2069     if (settings & ECO_AUTOWORDSELECTION)
2070       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2071     if (settings & ECO_SELECTIONBAR)
2072         editor->selofs = 16;
2073     else
2074         editor->selofs = 0;
2075     ME_WrapMarkedParagraphs(editor);
2076
2077     if (settings & ECO_VERTICAL)
2078       FIXME("ECO_VERTICAL not implemented yet!\n");
2079     if (settings & ECO_AUTOHSCROLL)
2080       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2081     if (settings & ECO_AUTOVSCROLL)
2082       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2083     if (settings & ECO_NOHIDESEL)
2084       FIXME("ECO_NOHIDESEL not implemented yet!\n");
2085     if (settings & ECO_WANTRETURN)
2086       FIXME("ECO_WANTRETURN not implemented yet!\n");
2087
2088     return settings;
2089   }
2090   case EM_SETSEL:
2091   {
2092     ME_InvalidateSelection(editor);
2093     ME_SetSelection(editor, wParam, lParam);
2094     ME_InvalidateSelection(editor);
2095     ME_SendSelChange(editor);
2096     return 0;
2097   }
2098   case EM_SETSCROLLPOS:
2099   {
2100     POINT *point = (POINT *)lParam;
2101     ME_ScrollAbs(editor, point->y);
2102     return 0;
2103   }
2104   case EM_AUTOURLDETECT:
2105   {
2106     if (wParam==1 || wParam ==0) 
2107     {
2108         editor->AutoURLDetect_bEnable = (BOOL)wParam;
2109         return 0;
2110     }
2111     return E_INVALIDARG;
2112   }
2113   case EM_GETAUTOURLDETECT:
2114   {
2115     return editor->AutoURLDetect_bEnable;
2116   }
2117   case EM_EXSETSEL:
2118   {
2119     int end;
2120     CHARRANGE range = *(CHARRANGE *)lParam;
2121
2122     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2123
2124     ME_InvalidateSelection(editor);
2125     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2126     ME_InvalidateSelection(editor);
2127     ME_SendSelChange(editor);
2128
2129     return end;
2130   }
2131   case EM_SHOWSCROLLBAR:
2132   {
2133     ShowScrollBar(editor->hWnd, wParam, lParam);
2134     return 0;
2135   }
2136   case EM_SETTEXTEX:
2137   {
2138     LPWSTR wszText;
2139     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2140     size_t len;
2141     int from, to;
2142     ME_Style *style;
2143     int oldModify = editor->nModifyStep;
2144
2145     if (!pStruct) return 0;
2146
2147     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2148           pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2149           pStruct->flags, pStruct->codepage);
2150
2151     /* FIXME: make use of pStruct->codepage in the to unicode translation */
2152     wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2153     len = wszText ? lstrlenW(wszText) : 0;
2154
2155     if (pStruct->flags & ST_SELECTION) {
2156       ME_GetSelection(editor, &from, &to);
2157       style = ME_GetSelectionInsertStyle(editor);
2158       ME_InternalDeleteText(editor, from, to - from);
2159       if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2160           ME_StreamInRTFString(editor, 0, (char *)lParam);
2161       else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2162       ME_ReleaseStyle(style);
2163     }
2164     else {
2165       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2166       if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2167           ME_StreamInRTFString(editor, 0, (char *)lParam);
2168       else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2169       len = 1;
2170     }
2171     ME_CommitUndo(editor);
2172     if (!(pStruct->flags & ST_KEEPUNDO))
2173     {
2174       editor->nModifyStep = oldModify;
2175       ME_EmptyUndoStack(editor);
2176     }
2177     ME_UpdateRepaint(editor);
2178     return len;
2179   }
2180   case EM_SETBKGNDCOLOR:
2181   {
2182     LRESULT lColor;
2183     if (editor->rgbBackColor != -1) {
2184       DeleteObject(editor->hbrBackground);
2185       lColor = editor->rgbBackColor;
2186     }
2187     else lColor = GetSysColor(COLOR_WINDOW);
2188
2189     if (wParam)
2190     {
2191       editor->rgbBackColor = -1;
2192       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2193     }
2194     else
2195     {
2196       editor->rgbBackColor = lParam;
2197       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2198     }
2199     if (editor->bRedraw)
2200     {
2201       InvalidateRect(hWnd, NULL, TRUE);
2202       UpdateWindow(hWnd);
2203     }
2204     return lColor;
2205   }
2206   case EM_GETMODIFY:
2207     return editor->nModifyStep == 0 ? 0 : 1;
2208   case EM_SETMODIFY:
2209   {
2210     if (wParam)
2211       editor->nModifyStep = 1;
2212     else
2213       editor->nModifyStep = 0;
2214     
2215     return 0;
2216   }
2217   case EM_SETREADONLY:
2218   {
2219     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2220     if (wParam)
2221       nStyle |= ES_READONLY;
2222     else
2223       nStyle &= ~ES_READONLY;
2224     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2225     return 0;
2226   }
2227   case EM_SETEVENTMASK:
2228   {
2229     DWORD nOldMask = editor->nEventMask;
2230     
2231     editor->nEventMask = lParam;
2232     return nOldMask;
2233   }
2234   case EM_GETEVENTMASK:
2235     return editor->nEventMask;
2236   case EM_SETCHARFORMAT:
2237   {
2238     CHARFORMAT2W buf, *p;
2239     BOOL bRepaint = TRUE;
2240     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2241     if (p == NULL) return 0;
2242     if (!wParam)
2243       ME_SetDefaultCharFormat(editor, p);
2244     else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2245       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2246       return 0;
2247     } else if (wParam == SCF_ALL) {
2248       if (editor->mode & TM_PLAINTEXT)
2249         ME_SetDefaultCharFormat(editor, p);
2250       else
2251         ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2252     } else if (editor->mode & TM_PLAINTEXT) {
2253       return 0;
2254     } else {
2255       int from, to;
2256       ME_GetSelection(editor, &from, &to);
2257       bRepaint = (from != to);
2258       ME_SetSelectionCharFormat(editor, p);
2259     }
2260     editor->nModifyStep = 1;
2261     ME_CommitUndo(editor);
2262     if (bRepaint)
2263       ME_RewrapRepaint(editor);
2264     return 1;
2265   }
2266   case EM_GETCHARFORMAT:
2267   {
2268     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2269     if (dst->cbSize != sizeof(CHARFORMATA) &&
2270         dst->cbSize != sizeof(CHARFORMATW) &&
2271         dst->cbSize != sizeof(CHARFORMAT2A) &&
2272         dst->cbSize != sizeof(CHARFORMAT2W))
2273       return 0;
2274     tmp.cbSize = sizeof(tmp);
2275     if (!wParam)
2276       ME_GetDefaultCharFormat(editor, &tmp);
2277     else
2278       ME_GetSelectionCharFormat(editor, &tmp);
2279     ME_CopyToCFAny(dst, &tmp);
2280     return tmp.dwMask;
2281   }
2282   case EM_SETPARAFORMAT:
2283     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2284     ME_RewrapRepaint(editor);
2285     ME_CommitUndo(editor);
2286     return 0;
2287   case EM_GETPARAFORMAT:
2288     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2289     return 0;
2290   case EM_GETFIRSTVISIBLELINE:
2291   {
2292     ME_DisplayItem *p = editor->pBuffer->pFirst;
2293     int y = ME_GetYScrollPos(editor);
2294     int ypara = 0;
2295     int count = 0;
2296     int ystart, yend;
2297     while(p) {
2298       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2299       if (p->type == diTextEnd)
2300         break;
2301       if (p->type == diParagraph) {
2302         ypara = p->member.para.nYPos;
2303         continue;
2304       }
2305       ystart = ypara + p->member.row.nYPos;
2306       yend = ystart + p->member.row.nHeight;
2307       if (y < yend) {
2308         break;
2309       }
2310       count++;
2311     }
2312     return count;
2313   }
2314   case EM_HIDESELECTION:
2315   {
2316      editor->bHideSelection = (wParam != 0);
2317      ME_InvalidateSelection(editor);
2318      return 0;
2319   }
2320   case EM_LINESCROLL:
2321   {
2322     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2323     return TRUE; /* Should return false if a single line richedit control */
2324   }
2325   case WM_CLEAR:
2326   {
2327     int from, to;
2328     ME_GetSelection(editor, &from, &to);
2329     ME_InternalDeleteText(editor, from, to-from);
2330     ME_CommitUndo(editor);
2331     ME_UpdateRepaint(editor);
2332     return 0;
2333   }
2334   case EM_REPLACESEL:
2335   {
2336     int from, to;
2337     ME_Style *style;
2338     LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2339     size_t len = wszText ? lstrlenW(wszText) : 0;
2340     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2341
2342     ME_GetSelection(editor, &from, &to);
2343     style = ME_GetSelectionInsertStyle(editor);
2344     ME_InternalDeleteText(editor, from, to-from);
2345     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2346     ME_ReleaseStyle(style);
2347     /* drop temporary style if line end */
2348     /*
2349      * FIXME question: does abc\n mean: put abc,
2350      * clear temp style, put \n? (would require a change)
2351      */
2352     if (len>0 && wszText[len-1] == '\n')
2353       ME_ClearTempStyle(editor);
2354     ME_EndToUnicode(unicode, wszText);
2355     ME_CommitUndo(editor);
2356     if (!wParam)
2357       ME_EmptyUndoStack(editor);
2358     ME_UpdateRepaint(editor);
2359     return len;
2360   }
2361   case EM_SCROLLCARET:
2362   {
2363     int top, bottom; /* row's edges relative to document top */
2364     int nPos;
2365     ME_DisplayItem *para, *row;
2366     
2367     nPos = ME_GetYScrollPos(editor);
2368     row = ME_RowStart(editor->pCursors[0].pRun);
2369     para = ME_GetParagraph(row);
2370     top = para->member.para.nYPos + row->member.row.nYPos;
2371     bottom = top + row->member.row.nHeight;
2372     
2373     if (top < nPos) /* caret above window */
2374       ME_ScrollAbs(editor,  top);
2375     else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2376       ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2377     return 0;
2378   }
2379   case WM_SETFONT:
2380   {
2381     LOGFONTW lf;
2382     CHARFORMAT2W fmt;
2383     HDC hDC;
2384     BOOL bRepaint = LOWORD(lParam);
2385     
2386     if (!wParam)
2387       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
2388     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
2389     hDC = GetDC(hWnd);
2390     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
2391     ReleaseDC(hWnd, hDC);   
2392     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
2393     ME_SetDefaultCharFormat(editor, &fmt);
2394
2395     ME_CommitUndo(editor);
2396     if (bRepaint)
2397       ME_RewrapRepaint(editor);
2398     return 0;
2399   }
2400   case WM_SETTEXT:
2401   {
2402     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2403     if (lParam)
2404     {
2405       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
2406       if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
2407       {
2408         /* Undocumented: WM_SETTEXT supports RTF text */
2409         ME_StreamInRTFString(editor, 0, (char *)lParam);
2410       }
2411       else
2412       {
2413         LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
2414         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
2415         if (lstrlenW(wszText) > 0)
2416         {
2417           int len = -1;
2418
2419           /* uses default style! */
2420           if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2421           {
2422             WCHAR * p;
2423
2424             p = wszText;
2425             while (*p != '\0' && *p != '\r' && *p != '\n') p++;
2426             len = p - wszText;
2427           }
2428           ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2429         }
2430         ME_EndToUnicode(unicode, wszText);
2431       }
2432     }
2433     else
2434       TRACE("WM_SETTEXT - NULL\n");
2435     ME_CommitUndo(editor);
2436     ME_EmptyUndoStack(editor);
2437     ME_SetSelection(editor, 0, 0);
2438     editor->nModifyStep = 0;
2439     ME_UpdateRepaint(editor);
2440     return 1;
2441   }
2442   case EM_CANPASTE:
2443   {
2444     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2445     if (IsClipboardFormatAvailable(nRTFFormat))
2446       return TRUE;
2447     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2448       return TRUE;
2449     return FALSE;
2450   }
2451   case WM_PASTE:
2452   {    
2453     DWORD dwFormat = 0;
2454     EDITSTREAM es;
2455     ME_GlobalDestStruct gds;
2456     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2457     UINT cf = 0;
2458
2459     if (IsClipboardFormatAvailable(nRTFFormat))
2460       cf = nRTFFormat, dwFormat = SF_RTF;
2461     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2462       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2463     else
2464       return 0;
2465
2466     if (!OpenClipboard(hWnd))
2467       return 0;
2468     gds.hData = GetClipboardData(cf);
2469     gds.nLength = 0;
2470     es.dwCookie = (DWORD)&gds;
2471     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2472     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2473
2474     CloseClipboard();
2475     return 0;
2476   }
2477   case WM_CUT:
2478   case WM_COPY:
2479   {
2480     LPDATAOBJECT dataObj = NULL;
2481     CHARRANGE range;
2482     HRESULT hr = S_OK;
2483
2484     if (editor->cPasswordMask)
2485       return 0; /* Copying or Cutting masked text isn't allowed */
2486
2487     ME_GetSelection(editor, &range.cpMin, &range.cpMax);
2488     if(editor->lpOleCallback)
2489         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2490     if(FAILED(hr) || !dataObj)
2491         hr = ME_GetDataObject(editor, &range, &dataObj);
2492     if(SUCCEEDED(hr)) {
2493         hr = OleSetClipboard(dataObj);
2494         IDataObject_Release(dataObj);
2495     }
2496     if (SUCCEEDED(hr) && msg == WM_CUT)
2497     {
2498       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
2499       ME_CommitUndo(editor);
2500       ME_UpdateRepaint(editor);
2501     }
2502     return 0;
2503   }
2504   case WM_GETTEXTLENGTH:
2505   {
2506     GETTEXTLENGTHEX how;
2507
2508     /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
2509     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2510     how.codepage = unicode ? 1200 : CP_ACP;
2511     return ME_GetTextLengthEx(editor, &how);
2512   }
2513   case EM_GETTEXTLENGTHEX:
2514     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2515   case WM_GETTEXT:
2516   {
2517     GETTEXTEX ex;
2518     LRESULT rc;
2519     LPSTR bufferA = NULL;
2520     LPWSTR bufferW = NULL;
2521
2522     if (unicode)
2523         bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2524     else
2525         bufferA = heap_alloc(wParam + 2);
2526
2527     ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
2528     ex.flags = GT_USECRLF;
2529     ex.codepage = unicode ? 1200 : CP_ACP;
2530     ex.lpDefaultChar = NULL;
2531     ex.lpUsedDefChar = NULL;
2532     rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
2533
2534     if (unicode)
2535     {
2536         memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
2537         if (lstrlenW(bufferW) >= wParam) rc = 0;
2538     }
2539     else
2540     {
2541         memcpy((LPSTR)lParam, bufferA, wParam);
2542         if (strlen(bufferA) >= wParam) rc = 0;
2543     }
2544     heap_free(bufferA);
2545     heap_free(bufferW);
2546     return rc;
2547   }
2548   case EM_GETTEXTEX:
2549   {
2550     GETTEXTEX *ex = (GETTEXTEX*)wParam;
2551     int nStart, nCount; /* in chars */
2552
2553     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2554       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2555
2556     if (ex->flags & GT_SELECTION)
2557     {
2558       ME_GetSelection(editor, &nStart, &nCount);
2559       nCount -= nStart;
2560     }
2561     else
2562     {
2563       nStart = 0;
2564       nCount = 0x7fffffff;
2565     }
2566     if (ex->codepage == 1200)
2567     {
2568       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2569       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2570     }
2571     else
2572     {
2573       /* potentially each char may be a CR, why calculate the exact value with O(N) when
2574         we can just take a bigger buffer? :)
2575         The above assumption still holds with CR/LF counters, since CR->CRLF expansion
2576         occurs only in richedit 2.0 mode, in which line breaks have only one CR
2577        */
2578       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2579       LPWSTR buffer;
2580       DWORD buflen = ex->cb;
2581       LRESULT rc;
2582       DWORD flags = 0;
2583
2584       nCount = min(nCount, ex->cb - 1);
2585       buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
2586
2587       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2588       rc = WideCharToMultiByte(ex->codepage, flags, buffer, -1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
2589       if (rc) rc--; /* do not count 0 terminator */
2590
2591       heap_free(buffer);
2592       return rc;
2593     }
2594   }
2595   case EM_GETSELTEXT:
2596   {
2597     int from, to;
2598     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2599     ME_GetSelection(editor, &from, &to);
2600     tr.chrg.cpMin = from;
2601     tr.chrg.cpMax = to;
2602     tr.lpstrText = (WCHAR *)lParam;
2603     return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
2604   }
2605   case EM_GETSCROLLPOS:
2606   {
2607       POINT *point = (POINT *)lParam;
2608       point->x = 0; /* FIXME side scrolling not implemented */
2609       point->y = ME_GetYScrollPos(editor);
2610       return 1;
2611   }
2612   case EM_GETTEXTRANGE:
2613   {
2614     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2615     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2616       rng->chrg.cpMin, rng->chrg.cpMax, unicode,
2617       editor->bEmulateVersion10, ME_GetTextLength(editor));
2618     if (unicode)
2619       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
2620     else
2621     {
2622       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2623       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2624       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
2625       /* FIXME this is a potential security hole (buffer overrun) 
2626          if you know more about wchar->mbyte conversion please explain
2627       */
2628       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2629       FREE_OBJ(p);
2630       return nChars;
2631     }
2632   }
2633   case EM_GETLINE:
2634   {
2635     ME_DisplayItem *run;
2636     const unsigned int nMaxChars = *(WORD *) lParam;
2637     unsigned int nCharsLeft = nMaxChars;
2638     char *dest = (char *) lParam;
2639     BOOL wroteNull = FALSE;
2640
2641     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2642           unicode ? "Unicode" : "Ansi");
2643
2644     run = ME_FindRowWithNumber(editor, wParam);
2645     if (run == NULL)
2646       return 0;
2647
2648     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2649            && !(run->member.run.nFlags & MERF_ENDPARA))
2650     {
2651       unsigned int nCopy;
2652       ME_String *strText;
2653       if (run->type != diRun)
2654         break;
2655       strText = run->member.run.strText;
2656       nCopy = min(nCharsLeft, strText->nLen);
2657
2658       if (unicode)
2659         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2660       else
2661         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2662                                     nCharsLeft, NULL, NULL);
2663       dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
2664       nCharsLeft -= nCopy;
2665     }
2666
2667     /* append line termination, space allowing */
2668     if (nCharsLeft > 0)
2669     {
2670       if (run && (run->member.run.nFlags & MERF_ENDPARA))
2671       {
2672         unsigned int i;
2673         /* Write as many \r as encoded in end-of-paragraph, space allowing */
2674         for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
2675         {
2676           *((WCHAR *)dest) = '\r';
2677           dest += unicode ? sizeof(WCHAR) : 1;
2678         }
2679         /* Write as many \n as encoded in end-of-paragraph, space allowing */
2680         for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
2681         {
2682           *((WCHAR *)dest) = '\n';
2683           dest += unicode ? sizeof(WCHAR) : 1;
2684         }
2685       }
2686       if (nCharsLeft > 0)
2687       {
2688         if (unicode)
2689           *((WCHAR *)dest) = '\0';
2690         else
2691           *dest = '\0';
2692         nCharsLeft--;
2693         wroteNull = TRUE;
2694       }
2695     }
2696
2697     TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
2698     return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
2699   }
2700   case EM_GETLINECOUNT:
2701   {
2702     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2703     int nRows = 0;
2704
2705     while (item != editor->pBuffer->pLast)
2706     {
2707       assert(item->type == diParagraph);
2708       nRows += item->member.para.nRows;
2709       item = item->member.para.next_para;
2710     }
2711     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2712     return max(1, nRows);
2713   }
2714   case EM_LINEFROMCHAR:
2715   {
2716     if (wParam == -1)
2717       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2718     else
2719       return ME_RowNumberFromCharOfs(editor, wParam);
2720   }
2721   case EM_EXLINEFROMCHAR:
2722   {
2723     if (lParam == -1)
2724       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2725     else    
2726       return ME_RowNumberFromCharOfs(editor, lParam);
2727   }
2728   case EM_LINEINDEX:
2729   {
2730     ME_DisplayItem *item, *para;
2731     int nCharOfs;
2732     
2733     if (wParam == -1)
2734       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2735     else
2736       item = ME_FindRowWithNumber(editor, wParam);
2737     if (!item)
2738       return -1;
2739     para = ME_GetParagraph(item);
2740     item = ME_FindItemFwd(item, diRun);
2741     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2742     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2743     return nCharOfs;
2744   }
2745   case EM_LINELENGTH:
2746   {
2747     ME_DisplayItem *item, *item_end;
2748     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2749     
2750     if (wParam > ME_GetTextLength(editor))
2751       return 0;
2752     if (wParam == -1)
2753     {
2754       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2755       return 0;
2756     }
2757     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2758     item = ME_RowStart(item);
2759     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2760     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2761     if (item_end->type == diStartRow)
2762       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2763     else
2764     {
2765       ME_DisplayItem *endPara;
2766
2767       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
2768       endPara = ME_FindItemFwd(item, diParagraphOrEnd);
2769       endPara = ME_FindItemBack(endPara, diRun);
2770       assert(endPara);
2771       assert(endPara->type == diRun);
2772       assert(endPara->member.run.nFlags & MERF_ENDPARA);
2773       nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
2774     }
2775     nChars = nNextLineOfs - nThisLineOfs;
2776     TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
2777     return nChars;
2778   }
2779   case EM_EXLIMITTEXT:
2780   {
2781     if ((int)lParam < 0)
2782      return 0;
2783     if (lParam == 0)
2784       editor->nTextLimit = 65536;
2785     else
2786       editor->nTextLimit = (int) lParam;
2787     return 0;
2788   }
2789   case EM_LIMITTEXT:
2790   {
2791     if (wParam == 0)
2792       editor->nTextLimit = 65536;
2793     else
2794       editor->nTextLimit = (int) wParam;
2795     return 0;
2796   }
2797   case EM_GETLIMITTEXT:
2798   {
2799     return editor->nTextLimit;
2800   }
2801   case EM_FINDTEXT:
2802   {
2803     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2804     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2805     WCHAR *tmp;
2806     LRESULT r;
2807
2808     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2809       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2810     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2811     FREE_OBJ( tmp );
2812     return r;
2813   }
2814   case EM_FINDTEXTEX:
2815   {
2816     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2817     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2818     WCHAR *tmp;
2819     LRESULT r;
2820
2821     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2822       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2823     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2824     FREE_OBJ( tmp );
2825     return r;
2826   }
2827   case EM_FINDTEXTW:
2828   {
2829     FINDTEXTW *ft = (FINDTEXTW *)lParam;
2830     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2831   }
2832   case EM_FINDTEXTEXW:
2833   {
2834     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2835     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2836   }
2837   case EM_GETZOOM:
2838     if (!wParam || !lParam)
2839       return FALSE;
2840     *(int *)wParam = editor->nZoomNumerator;
2841     *(int *)lParam = editor->nZoomDenominator;
2842     return TRUE;
2843   case EM_SETZOOM:
2844     return ME_SetZoom(editor, wParam, lParam);
2845   case EM_CHARFROMPOS:
2846     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2847   case EM_POSFROMCHAR:
2848   {
2849     ME_DisplayItem *pRun;
2850     int nCharOfs, nOffset, nLength;
2851     POINTL pt = {0,0};
2852     
2853     nCharOfs = wParam; 
2854     /* detect which API version we're dealing with */
2855     if (wParam >= 0x40000)
2856         nCharOfs = lParam;
2857     nLength = ME_GetTextLength(editor);
2858     
2859     if (nCharOfs < nLength) { 
2860         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2861         assert(pRun->type == diRun);
2862         pt.y = pRun->member.run.pt.y;
2863         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
2864         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
2865     } else {
2866         pt.x = 0;
2867         pt.y = editor->pBuffer->pLast->member.para.nYPos;
2868     }
2869     pt.x += editor->selofs;
2870     if (wParam >= 0x40000) {
2871         *(POINTL *)wParam = pt;
2872     }
2873     return MAKELONG( pt.x, pt.y );
2874   }
2875   case WM_CREATE:
2876     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
2877     { /* Squelch the default horizontal scrollbar it would make */
2878       ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
2879     }
2880     ME_CommitUndo(editor);
2881     ME_WrapMarkedParagraphs(editor);
2882     ME_MoveCaret(editor);
2883     return 0;
2884   case WM_DESTROY:
2885     ME_DestroyEditor(editor);
2886     SetWindowLongPtrW(hWnd, 0, 0);
2887     return 0;
2888   case WM_LBUTTONDOWN:
2889     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2890         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2891       return 0;
2892     SetFocus(hWnd);
2893     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2894     SetCapture(hWnd);
2895     ME_LinkNotify(editor,msg,wParam,lParam);
2896     if (!ME_SetCursor(editor, LOWORD(lParam))) goto do_default;
2897     break;
2898   case WM_MOUSEMOVE:
2899     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2900         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2901       return 0;
2902     if (GetCapture() == hWnd)
2903       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2904     ME_LinkNotify(editor,msg,wParam,lParam);
2905     if (!ME_SetCursor(editor, LOWORD(lParam))) goto do_default;
2906     break;
2907   case WM_LBUTTONUP:
2908     if (GetCapture() == hWnd)
2909       ReleaseCapture();
2910     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2911         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2912       return 0;
2913     else
2914     {
2915       BOOL ret;
2916       editor->linesel = 0;
2917       ret = ME_SetCursor(editor, LOWORD(lParam));
2918       ME_LinkNotify(editor,msg,wParam,lParam);
2919       if (!ret) goto do_default;
2920     }
2921     break;
2922   case WM_LBUTTONDBLCLK:
2923     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2924         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2925       return 0;
2926     ME_LinkNotify(editor,msg,wParam,lParam);
2927     ME_SelectWord(editor);
2928     break;
2929   case WM_RBUTTONUP:
2930   case WM_RBUTTONDOWN:
2931     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2932         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2933       return 0;
2934     goto do_default;
2935   case WM_CONTEXTMENU:
2936     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
2937       goto do_default;
2938     break;
2939   case WM_PAINT:
2940     if (editor->bRedraw)
2941     {
2942       HDC hDC;
2943       PAINTSTRUCT ps;
2944
2945       hDC = BeginPaint(hWnd, &ps);
2946       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
2947       EndPaint(hWnd, &ps);
2948     }
2949     break;
2950   case WM_SETFOCUS:
2951     editor->bHaveFocus = TRUE;
2952     ME_ShowCaret(editor);
2953     ME_SendOldNotify(editor, EN_SETFOCUS);
2954     return 0;
2955   case WM_KILLFOCUS:
2956     ME_HideCaret(editor);
2957     editor->bHaveFocus = FALSE;
2958     ME_SendOldNotify(editor, EN_KILLFOCUS);
2959     return 0;
2960   case WM_ERASEBKGND:
2961   {
2962     if (editor->bRedraw)
2963     {
2964       HDC hDC = (HDC)wParam;
2965       RECT rc;
2966       if (GetUpdateRect(hWnd,&rc,TRUE))
2967       {
2968         FillRect(hDC, &rc, editor->hbrBackground);
2969       }
2970     }
2971     return 1;
2972   }
2973   case WM_COMMAND:
2974     TRACE("editor wnd command = %d\n", LOWORD(wParam));
2975     return 0;
2976   case WM_KEYUP:
2977     if ((editor->nEventMask & ENM_KEYEVENTS) &&
2978         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2979       return 0;
2980     goto do_default;
2981   case WM_KEYDOWN:
2982     if ((editor->nEventMask & ENM_KEYEVENTS) &&
2983         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2984       return 0;
2985     if (ME_KeyDown(editor, LOWORD(wParam)))
2986       return 0;
2987     goto do_default;
2988   case WM_CHAR: 
2989   {
2990     WCHAR wstr;
2991
2992     if (unicode)
2993         wstr = (WCHAR)wParam;
2994     else
2995     {
2996         CHAR charA = wParam;
2997         MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2998     }
2999     if (editor->AutoURLDetect_bEnable)
3000       ME_AutoURLDetect(editor, wstr);
3001         
3002     switch (wstr)
3003     {
3004     case 1: /* Ctrl-A */
3005       ME_SetSelection(editor, 0, -1);
3006       return 0;
3007     case 3: /* Ctrl-C */
3008       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3009       return 0;
3010     }
3011     
3012     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3013       MessageBeep(MB_ICONERROR);
3014       return 0; /* FIXME really 0 ? */
3015     }
3016
3017     switch (wstr)
3018     {
3019     case 22: /* Ctrl-V */
3020       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3021       return 0;
3022     case 24: /* Ctrl-X */
3023       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3024       return 0;
3025     case 25: /* Ctrl-Y */
3026       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3027       return 0;
3028     case 26: /* Ctrl-Z */
3029       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3030       return 0;
3031     }
3032     if (((unsigned)wstr)>=' '
3033         || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3034         || wstr=='\t') {
3035       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3036       /* WM_CHAR is restricted to nTextLimit */
3037       int from, to;
3038       ME_GetSelection(editor, &from, &to);
3039       if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3040       {
3041         ME_Style *style = ME_GetInsertStyle(editor, 0);
3042         ME_SaveTempStyle(editor);
3043         if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3044           ME_InsertEndRowFromCursor(editor, 0);
3045         else
3046           ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3047         ME_ReleaseStyle(style);
3048         ME_CommitUndo(editor);
3049       }
3050       ME_UpdateRepaint(editor);
3051     }
3052     return 0;
3053   }
3054   case EM_SCROLL: /* fall through */
3055   case WM_VSCROLL: 
3056   {
3057     int origNPos;
3058     int lineHeight;
3059     
3060     origNPos = ME_GetYScrollPos(editor);
3061     lineHeight = 24;
3062     
3063     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3064       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3065     if (lineHeight <= 0) lineHeight = 24;
3066     
3067     switch(LOWORD(wParam)) 
3068     {
3069       case SB_LINEUP:
3070         ME_ScrollUp(editor,lineHeight);
3071         break;
3072       case SB_LINEDOWN:
3073         ME_ScrollDown(editor,lineHeight);
3074         break;
3075       case SB_PAGEUP:
3076         ME_ScrollUp(editor,editor->sizeWindow.cy);
3077         break;
3078       case SB_PAGEDOWN:
3079         ME_ScrollDown(editor,editor->sizeWindow.cy);
3080         break;
3081       case SB_THUMBTRACK:
3082       case SB_THUMBPOSITION:
3083         ME_ScrollAbs(editor,HIWORD(wParam));
3084         break;
3085     }
3086     if (msg == EM_SCROLL)
3087       return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
3088     break;
3089   }
3090   case WM_MOUSEWHEEL:
3091   {
3092     int gcWheelDelta;
3093     UINT pulScrollLines;
3094
3095     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3096         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3097       return 0;
3098
3099     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
3100     gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
3101     
3102     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
3103     {
3104       /* FIXME follow the original */
3105       ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8); 
3106     }
3107     break;
3108   }
3109   case EM_GETRECT:
3110   {
3111     *((RECT *)lParam) = editor->rcFormat;
3112     return 0;
3113   }
3114   case EM_SETRECT:
3115   case EM_SETRECTNP:
3116   {
3117     if (lParam)
3118     {
3119       RECT *rc = (RECT *)lParam;
3120       
3121       if (wParam)
3122       {
3123         editor->rcFormat.left += rc->left;
3124         editor->rcFormat.top += rc->top;
3125         editor->rcFormat.right += rc->right;
3126         editor->rcFormat.bottom += rc->bottom;
3127       }
3128       else
3129       {
3130         editor->rcFormat = *rc;
3131       }
3132     }
3133     else
3134     {
3135       GetClientRect(hWnd, &editor->rcFormat);
3136     }
3137     if (msg != EM_SETRECTNP)
3138       ME_RewrapRepaint(editor);
3139     return 0;
3140   }
3141   case EM_REQUESTRESIZE:
3142     ME_SendRequestResize(editor, TRUE);
3143     return 0;
3144   case WM_SETREDRAW:
3145     if ((editor->bRedraw = wParam))
3146       ME_RewrapRepaint(editor);
3147     return 0;
3148   case WM_SIZE:
3149   {
3150     GetClientRect(hWnd, &editor->rcFormat);
3151     ME_RewrapRepaint(editor);
3152     return DefWindowProcW(hWnd, msg, wParam, lParam);
3153   }
3154   /* IME messages to make richedit controls IME aware */
3155   case WM_IME_SETCONTEXT:
3156   case WM_IME_CONTROL:
3157   case WM_IME_SELECT:
3158   case WM_IME_COMPOSITIONFULL:
3159     return 0;
3160   case WM_IME_STARTCOMPOSITION:
3161   {
3162     editor->imeStartIndex=ME_GetCursorOfs(editor,0);
3163     ME_DeleteSelection(editor);
3164     ME_CommitUndo(editor);
3165     ME_UpdateRepaint(editor);
3166     return 0;
3167   }
3168   case WM_IME_COMPOSITION:
3169   {
3170     HIMC hIMC;
3171
3172     ME_Style *style = ME_GetInsertStyle(editor, 0);
3173     hIMC = ImmGetContext(hWnd);
3174     ME_DeleteSelection(editor);
3175     ME_CommitUndo(editor);
3176     ME_SaveTempStyle(editor);
3177     if (lParam & GCS_RESULTSTR)
3178     {
3179         LPWSTR lpCompStr = NULL;
3180         DWORD dwBufLen;
3181
3182         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3183         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3184         ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
3185         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3186         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3187     }
3188     else if (lParam & GCS_COMPSTR)
3189     {
3190         LPWSTR lpCompStr = NULL;
3191         DWORD dwBufLen;
3192
3193         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
3194         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3195         ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
3196         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3197
3198         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3199         ME_SetSelection(editor,editor->imeStartIndex,
3200                         editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
3201     }
3202     ME_ReleaseStyle(style);
3203     ME_UpdateRepaint(editor);
3204     return 0;
3205   }
3206   case WM_IME_ENDCOMPOSITION:
3207   {
3208     ME_DeleteSelection(editor);
3209     editor->imeStartIndex=-1;
3210     return 0;
3211   }
3212   case EM_GETOLEINTERFACE:
3213   {
3214     LPVOID *ppvObj = (LPVOID*) lParam;
3215     return CreateIRichEditOle(editor, ppvObj);
3216   }
3217   case EM_GETPASSWORDCHAR:
3218   {
3219     return editor->cPasswordMask;
3220   }
3221   case EM_SETOLECALLBACK:
3222     if(editor->lpOleCallback)
3223       IUnknown_Release(editor->lpOleCallback);
3224     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
3225     if(editor->lpOleCallback)
3226       IUnknown_AddRef(editor->lpOleCallback);
3227     return TRUE;
3228   case EM_GETWORDBREAKPROC:
3229     return (LRESULT)editor->pfnWordBreak;
3230   case EM_SETWORDBREAKPROC:
3231   {
3232     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
3233
3234     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
3235     return (LRESULT)pfnOld;
3236   }
3237   case EM_SETTEXTMODE:
3238   {
3239     LRESULT ret;
3240     int mask = 0;
3241     int changes = 0;
3242     ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
3243     if (!ret)
3244     {
3245       /*Check for valid wParam*/
3246       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
3247           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
3248           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
3249         return 1;
3250       else
3251       {
3252         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
3253         {
3254           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
3255           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
3256         }
3257         /*FIXME: Currently no support for undo level and code page options*/ 
3258         editor->mode = (editor->mode & (~mask)) | changes;
3259         return 0;
3260       }
3261     }
3262     return ret;
3263   }
3264   case EM_SETPASSWORDCHAR:
3265   {
3266     editor->cPasswordMask = wParam;
3267     ME_RewrapRepaint(editor);
3268     return 0;
3269   }
3270   case EM_SETTARGETDEVICE:
3271     if (wParam == 0)
3272     {
3273       BOOL new = (lParam == 0);
3274       if (editor->bWordWrap != new)
3275       {
3276         editor->bWordWrap = new;
3277         ME_RewrapRepaint(editor);
3278       }
3279     }
3280     else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
3281     break;
3282   default:
3283   do_default:
3284     return DefWindowProcW(hWnd, msg, wParam, lParam);
3285   }
3286   return 0L;
3287 }
3288
3289 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3290 {
3291     BOOL unicode = TRUE;
3292
3293     /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
3294     if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
3295         unicode = FALSE;
3296
3297     return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
3298 }
3299
3300 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3301 {
3302     return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
3303 }
3304
3305 /******************************************************************
3306  *        RichEditANSIWndProc (RICHED20.10)
3307  */
3308 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3309 {
3310     return RichEditWndProcA(hWnd, msg, wParam, lParam);
3311 }
3312
3313 /******************************************************************
3314  *        RichEdit10ANSIWndProc (RICHED20.9)
3315  */
3316 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3317 {
3318   LRESULT result;
3319   
3320   /* FIXME: this is NOT the same as 2.0 version */
3321   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
3322   if (msg == WM_NCCREATE)
3323   {
3324     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
3325     
3326     editor->bEmulateVersion10 = TRUE;
3327     editor->pBuffer->pLast->member.para.nCharOfs = 2;
3328     assert(editor->pBuffer->pLast->prev->type == diRun);
3329     assert(editor->pBuffer->pLast->prev->member.run.nFlags & MERF_ENDPARA);
3330     editor->pBuffer->pLast->prev->member.run.nLF = 1;
3331   }
3332   return result;
3333 }
3334
3335 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
3336 {
3337   HWND hWnd = editor->hWnd;
3338   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
3339 }
3340
3341 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3342 {
3343   int x,y;
3344   ME_Cursor tmpCursor;
3345   int nCharOfs; /* The start of the clicked text. Absolute character offset */
3346
3347   ME_Run *tmpRun;
3348
3349   ENLINK info;
3350   x = (short)LOWORD(lParam);
3351   y = (short)HIWORD(lParam);
3352   nCharOfs = ME_CharFromPos(editor, x, y);
3353   if (nCharOfs < 0) return;
3354
3355   ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
3356   tmpRun = &tmpCursor.pRun->member.run;
3357
3358   if ((tmpRun->style->fmt.dwMask & CFM_LINK)
3359     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
3360   { /* The clicked run has CFE_LINK set */
3361     info.nmhdr.hwndFrom = editor->hWnd;
3362     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
3363     info.nmhdr.code = EN_LINK;
3364     info.msg = msg;
3365     info.wParam = wParam;
3366     info.lParam = lParam;
3367     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
3368     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
3369     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
3370   }  
3371 }
3372
3373 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
3374 {
3375   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
3376   int i = 0;
3377   
3378   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
3379     item = item->member.para.next_para;
3380   if (!item)
3381     return 0;
3382   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
3383     item = item->member.para.next_para;
3384     i++;
3385   }
3386   return i;
3387 }
3388
3389
3390 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
3391 {
3392   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
3393   int nWritten = 0;
3394   WCHAR *pStart = buffer;
3395   
3396   if (!item) {
3397     *buffer = 0;
3398     return 0;
3399   }
3400   
3401   /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
3402   if (editor->bEmulateVersion10) bCRLF = 0;
3403
3404   if (nStart)
3405   {
3406     int nLen = ME_StrLen(item->member.run.strText) - nStart;
3407     if (nLen > nChars)
3408       nLen = nChars;
3409     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
3410     nChars -= nLen;
3411     nWritten += nLen;
3412     if (!nChars)
3413       return nWritten;
3414     buffer += nLen;
3415     nStart = 0;
3416     item = ME_FindItemFwd(item, diRun);
3417   }
3418   
3419   while(nChars && item)
3420   {
3421     int nLen = ME_StrLen(item->member.run.strText);
3422     if (item->member.run.nFlags & MERF_ENDPARA)
3423        nLen = item->member.run.nCR + item->member.run.nLF;
3424     if (nLen > nChars)
3425       nLen = nChars;
3426
3427     if (item->member.run.nFlags & MERF_ENDPARA)
3428     {
3429       if (!ME_FindItemFwd(item, diRun))
3430         /* No '\r' is appended to the last paragraph. */
3431         nLen = 0;
3432       else if (bCRLF && nChars == 1) {
3433         nLen = 0;
3434         nChars = 0;
3435       } else {
3436         if (bCRLF)
3437         {
3438           /* richedit 2.0 case - actual line-break is \r but should report \r\n */
3439           assert(nLen == 1);
3440           *buffer++ = '\r';
3441           *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
3442           nWritten++;
3443         }
3444         else
3445         {
3446           int i, j;
3447
3448           /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
3449           i = 0;
3450           while (nChars - i > 0 && i < item->member.run.nCR)
3451           {
3452             buffer[i] = '\r'; i++;
3453           }
3454           j = 0;
3455           while (nChars - i - j > 0 && j < item->member.run.nLF)
3456           {
3457             buffer[i+j] = '\n'; j++;
3458           }
3459         }
3460       }
3461     }
3462     else
3463       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
3464     nChars -= nLen;
3465     nWritten += nLen;
3466     buffer += nLen;    
3467       
3468     if (!nChars)
3469     {
3470       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
3471       *buffer = 0;
3472       return nWritten;
3473     }
3474     item = ME_FindItemFwd(item, diRun);
3475   }
3476   *buffer = 0;
3477   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
3478   return nWritten;  
3479 }
3480
3481 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
3482 {
3483   WNDCLASSW wcW;
3484   WNDCLASSA wcA;
3485   
3486   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
3487   wcW.lpfnWndProc = RichEditWndProcW;
3488   wcW.cbClsExtra = 0;
3489   wcW.cbWndExtra = sizeof(ME_TextEditor *);
3490   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
3491   wcW.hIcon = NULL;
3492   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
3493   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
3494   wcW.lpszMenuName = NULL;
3495
3496   if (is_version_nt())
3497   {
3498     wcW.lpszClassName = RichEdit20W;
3499     if (!RegisterClassW(&wcW)) return FALSE;
3500     wcW.lpszClassName = RichEdit50W;
3501     if (!RegisterClassW(&wcW)) return FALSE;
3502   }
3503   else
3504   {
3505     /* WNDCLASSA/W have the same layout */
3506     wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
3507     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
3508     wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
3509     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
3510   }
3511
3512   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
3513   wcA.lpfnWndProc = RichEditWndProcA;
3514   wcA.cbClsExtra = 0;
3515   wcA.cbWndExtra = sizeof(ME_TextEditor *);
3516   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
3517   wcA.hIcon = NULL;
3518   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
3519   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
3520   wcA.lpszMenuName = NULL;
3521   wcA.lpszClassName = "RichEdit20A";
3522   if (!RegisterClassA(&wcA)) return FALSE;
3523   wcA.lpszClassName = "RichEdit50A";
3524   if (!RegisterClassA(&wcA)) return FALSE;
3525
3526   return TRUE;
3527 }
3528
3529 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3530   /* FIXME: Not implemented */
3531   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3532         hWnd, msg, get_msg_name(msg), wParam, lParam);
3533   return DefWindowProcW(hWnd, msg, wParam, lParam);
3534 }
3535
3536 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3537   /* FIXME: Not implemented */
3538   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3539         hWnd, msg, get_msg_name(msg), wParam, lParam);
3540   return DefWindowProcW(hWnd, msg, wParam, lParam);
3541 }
3542
3543 /******************************************************************
3544  *        REExtendedRegisterClass (RICHED20.8)
3545  *
3546  * FIXME undocumented
3547  * Need to check for errors and implement controls and callbacks 
3548  */
3549 LRESULT WINAPI REExtendedRegisterClass(void)
3550 {
3551   WNDCLASSW wcW;
3552   UINT result;
3553
3554   FIXME("semi stub\n");
3555
3556   wcW.cbClsExtra = 0;
3557   wcW.cbWndExtra = 4;
3558   wcW.hInstance = NULL;
3559   wcW.hIcon = NULL;
3560   wcW.hCursor = NULL;
3561   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
3562   wcW.lpszMenuName = NULL;
3563
3564   if (!ME_ListBoxRegistered)
3565   {
3566       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
3567       wcW.lpfnWndProc = REListWndProc;
3568       wcW.lpszClassName = REListBox20W;
3569       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
3570   }
3571
3572   if (!ME_ComboBoxRegistered)
3573   {
3574       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
3575       wcW.lpfnWndProc = REComboWndProc;
3576       wcW.lpszClassName = REComboBox20W;
3577       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
3578   }
3579
3580   result = 0;
3581   if (ME_ListBoxRegistered)
3582       result += 1;
3583   if (ME_ComboBoxRegistered)
3584       result += 2;
3585
3586   return result;
3587 }
3588
3589 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar) 
3590 {
3591   struct prefix_s {
3592     const char *text;
3593     int length;
3594   } prefixes[12] = {
3595     {"http:", 5},
3596     {"file:", 6},
3597     {"mailto:", 8},
3598     {"ftp:", 5},
3599     {"https:", 7},
3600     {"gopher:", 8},
3601     {"nntp:", 6},
3602     {"prospero:", 10},
3603     {"telnet:", 8},
3604     {"news:", 6},
3605     {"wais:", 6},
3606     {"www.", 5}
3607   };
3608   CHARRANGE ins_pt;
3609   int curf_ef, link_ef, def_ef;
3610   int cur_prefx, prefx_cnt;
3611   int sel_min, sel_max;
3612   int car_pos = 0;
3613   int text_pos=-1;
3614   int URLmin, URLmax = 0;
3615   FINDTEXTA ft;
3616   CHARFORMAT2W cur_format;
3617   CHARFORMAT2W default_format;
3618   CHARFORMAT2W link;
3619   RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
3620   sel_min = ins_pt.cpMin;
3621   sel_max = ins_pt.cpMax;
3622   if (sel_min==sel_max) 
3623     car_pos = sel_min;
3624   if (sel_min!=sel_max)
3625     car_pos = ME_GetTextLength(editor)+1;   
3626   cur_format.cbSize = sizeof(cur_format);
3627   default_format.cbSize = sizeof(default_format);
3628   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
3629   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
3630   link.cbSize = sizeof(link);
3631   link.dwMask = CFM_LINK;
3632   link.dwEffects = CFE_LINK;
3633   curf_ef = cur_format.dwEffects & link.dwEffects;
3634   def_ef = default_format.dwEffects & link.dwEffects;
3635   link_ef = link.dwEffects & link.dwEffects;
3636   if (curf_ef == link_ef) 
3637   {
3638     if( curChar == '\n' || curChar=='\r' || curChar==' ') 
3639     {
3640       ME_SetSelection(editor, car_pos, car_pos);
3641       RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
3642       text_pos=-1;
3643       return 0;
3644     }
3645   }
3646   if (curf_ef == def_ef)
3647   {
3648     cur_prefx = 0;
3649     prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
3650     while (cur_prefx<=prefx_cnt) 
3651     {
3652       if (text_pos == -1) 
3653       {
3654         ft.lpstrText = prefixes[cur_prefx].text;
3655         URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
3656         URLmax=max(0, car_pos);
3657         if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
3658         {
3659         URLmax = ME_GetTextLength(editor)+1;
3660         }
3661         ft.chrg.cpMin = URLmin;
3662         ft.chrg.cpMax = URLmax;
3663         text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);   
3664         cur_prefx++;
3665       }
3666       if (text_pos != -1) 
3667       {
3668         ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
3669         ME_RewrapRepaint(editor);
3670         break;
3671       }
3672     }
3673   }
3674   return 0;
3675 }