~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/riched20/editor.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

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