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