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