ole32: Use existing MTA in CoGetContextToken and CoGetObjectContext.
[wine] / dlls / riched20 / editor.c
1 /*
2  * RichEdit - functions dealing with editor object
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  * Copyright 2005 by Cihan Altinay
6  * Copyright 2005 by Phil Krylov
7  * Copyright 2008 Eric Pouech
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 /* 
25   API implementation status:
26   
27   Messages (ANSI versions not done yet)
28   + EM_AUTOURLDETECT 2.0
29   + EM_CANPASTE
30   + EM_CANREDO 2.0
31   + EM_CANUNDO
32   + EM_CHARFROMPOS
33   - EM_DISPLAYBAND
34   + EM_EMPTYUNDOBUFFER
35   + EM_EXGETSEL
36   + EM_EXLIMITTEXT
37   + EM_EXLINEFROMCHAR
38   + EM_EXSETSEL
39   + EM_FINDTEXT (only FR_DOWN flag implemented)
40   + EM_FINDTEXTEX (only FR_DOWN flag implemented)
41   - EM_FINDWORDBREAK
42   - EM_FMTLINES
43   - EM_FORMATRANGE
44   + EM_GETAUTOURLDETECT 2.0
45   - EM_GETBIDIOPTIONS 3.0
46   - EM_GETCHARFORMAT (partly done)
47   - EM_GETEDITSTYLE
48   + EM_GETEVENTMASK
49   + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
50   - EM_GETIMECOLOR 1.0asian
51   - EM_GETIMECOMPMODE 2.0
52   - EM_GETIMEOPTIONS 1.0asian
53   - EM_GETIMESTATUS
54   - EM_GETLANGOPTIONS 2.0
55   + EM_GETLIMITTEXT
56   + EM_GETLINE
57   + EM_GETLINECOUNT   returns number of rows, not of paragraphs
58   + EM_GETMODIFY
59   + EM_GETOLEINTERFACE
60   + EM_GETOPTIONS
61   + EM_GETPARAFORMAT
62   + EM_GETPASSWORDCHAR 2.0
63   - EM_GETPUNCTUATION 1.0asian
64   + EM_GETRECT
65   - EM_GETREDONAME 2.0
66   + EM_GETSEL
67   + EM_GETSELTEXT (ANSI&Unicode)
68   + EM_GETSCROLLPOS 3.0
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_HSCROLL
141   + WM_PASTE
142   + WM_SETFONT
143   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
144   - WM_STYLECHANGING
145   - WM_STYLECHANGED (things like read-only flag)
146   + WM_UNICHAR
147   + WM_VSCROLL
148
149   Notifications
150
151   * EN_CHANGE (sent from the wrong place)
152   - EN_CORRECTTEXT
153   - EN_DROPFILES
154   - EN_ERRSPACE
155   - EN_HSCROLL
156   - EN_IMECHANGE
157   + EN_KILLFOCUS
158   - EN_LINK
159   - EN_MAXTEXT
160   - EN_MSGFILTER
161   - EN_OLEOPFAILED
162   - EN_PROTECTED
163   + EN_REQUESTRESIZE
164   - EN_SAVECLIPBOARD
165   + EN_SELCHANGE 
166   + EN_SETFOCUS
167   - EN_STOPNOUNDO
168   * EN_UPDATE (sent from the wrong place)
169   - EN_VSCROLL
170   
171   Styles
172   
173   - ES_AUTOHSCROLL
174   - ES_AUTOVSCROLL
175   - ES_CENTER
176   + ES_DISABLENOSCROLL (scrollbar is always visible)
177   - ES_EX_NOCALLOLEINIT
178   - ES_LEFT
179   - ES_MULTILINE (currently single line controls aren't supported)
180   - ES_NOIME
181   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
182   - ES_RIGHT
183   - ES_SAVESEL
184   - ES_SELFIME
185   - ES_SUNKEN
186   - ES_VERTICAL
187   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
188   - WS_SETFONT
189   + WS_HSCROLL
190   + WS_VSCROLL
191 */
192
193 /*
194  * RICHED20 TODO (incomplete):
195  *
196  * - messages/styles/notifications listed above 
197  * - add remaining CHARFORMAT/PARAFORMAT fields
198  * - right/center align should strip spaces from the beginning
199  * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
200  * - COM interface (looks like a major pain in the TODO list)
201  * - calculate heights of pictures (half-done)
202  * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
203  * - find/replace
204  * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
205  * - italic caret with italic fonts
206  * - IME
207  * - most notifications aren't sent at all (the most important ones are)
208  * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
209  * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
210  * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
211  * - full justification
212  * - hyphenation
213  * - tables
214  * - ListBox & ComboBox not implemented
215  *
216  * Bugs that are probably fixed, but not so easy to verify:
217  * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
218  * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
219  * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
220  * - caret shouldn't be displayed when selection isn't empty
221  * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
222  * - undo for setting default format (done, might be buggy)
223  * - styles might be not released properly (looks like they work like charm, but who knows?
224  *
225  */
226
227 #include "editor.h"
228 #include "commdlg.h"
229 #include "winreg.h"
230 #define NO_SHLWAPI_STREAM 
231 #include "shlwapi.h"
232 #include "rtf.h"
233 #include "imm.h"
234 #include "res.h"
235
236 #define STACK_SIZE_DEFAULT  100
237 #define STACK_SIZE_MAX     1000
238
239 #define TEXT_LIMIT_DEFAULT 32767
240  
241 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
242
243 static BOOL ME_RegisterEditorClass(HINSTANCE);
244 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max);
245
246 static const WCHAR RichEdit20W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
247 static const WCHAR RichEdit50W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
248 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
249 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
250 static HCURSOR hLeft;
251
252 int me_debug = 0;
253 HANDLE me_heap = NULL;
254
255 static BOOL ME_ListBoxRegistered = FALSE;
256 static BOOL ME_ComboBoxRegistered = FALSE;
257
258 static inline int is_version_nt(void)
259 {
260     return !(GetVersion() & 0x80000000);
261 }
262
263 static ME_TextBuffer *ME_MakeText(void) {
264   
265   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
266
267   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
268   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
269   
270   p1->prev = NULL;
271   p1->next = p2;
272   p2->prev = p1;
273   p2->next = NULL;
274   p1->member.para.next_para = p2;
275   p2->member.para.prev_para = p1;
276   p2->member.para.nCharOfs = 0;  
277   
278   buf->pFirst = p1;
279   buf->pLast = p2;
280   buf->pCharStyle = NULL;
281   
282   return buf;
283 }
284
285
286 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
287 {
288   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
289   WCHAR *pText;
290   
291   TRACE("%08x %p\n", dwFormat, stream);
292   
293   do {
294     long nWideChars = 0;
295
296     if (!stream->dwSize)
297     {
298       ME_StreamInFill(stream);
299       if (stream->editstream->dwError)
300         break;
301       if (!stream->dwSize)
302         break;
303     }
304       
305     if (!(dwFormat & SF_UNICODE))
306     {
307       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
308       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
309       pText = wszText;
310     }
311     else
312     {
313       nWideChars = stream->dwSize >> 1;
314       pText = (WCHAR *)stream->buffer;
315     }
316     
317     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
318     if (stream->dwSize == 0)
319       break;
320     stream->dwSize = 0;
321   } while(1);
322   ME_CommitUndo(editor);
323   ME_UpdateRepaint(editor);
324   return 0;
325 }
326
327 static void ME_ApplyBorderProperties(RTF_Info *info,
328                                      ME_BorderRect *borderRect,
329                                      RTFBorder *borderDef)
330 {
331   int i, colorNum;
332   ME_Border *pBorders[] = {&borderRect->top,
333                            &borderRect->left,
334                            &borderRect->bottom,
335                            &borderRect->right};
336   for (i = 0; i < 4; i++)
337   {
338     RTFColor *colorDef = info->colorList;
339     pBorders[i]->width = borderDef[i].width;
340     colorNum = borderDef[i].color;
341     while (colorDef && colorDef->rtfCNum != colorNum)
342       colorDef = colorDef->rtfNextColor;
343     if (colorDef)
344       pBorders[i]->colorRef = RGB(
345                            colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
346                            colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
347                            colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
348     else
349       pBorders[i]->colorRef = RGB(0, 0, 0);
350   }
351 }
352
353 void ME_RTFCharAttrHook(RTF_Info *info)
354 {
355   CHARFORMAT2W fmt;
356   fmt.cbSize = sizeof(fmt);
357   fmt.dwMask = 0;
358   fmt.dwEffects = 0;
359
360   switch(info->rtfMinor)
361   {
362     case rtfPlain:
363       /* FIXME add more flags once they're implemented */
364       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
365       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
366       fmt.yHeight = 12*20; /* 12pt */
367       fmt.wWeight = FW_NORMAL;
368       fmt.bUnderlineType = CFU_UNDERLINENONE;
369       break;
370     case rtfBold:
371       fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
372       fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
373       fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
374       break;
375     case rtfItalic:
376       fmt.dwMask = CFM_ITALIC;
377       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
378       break;
379     case rtfUnderline:
380       fmt.dwMask = CFM_UNDERLINETYPE;
381       fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
382       break;
383     case rtfDotUnderline:
384       fmt.dwMask = CFM_UNDERLINETYPE;
385       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
386       break;
387     case rtfDbUnderline:
388       fmt.dwMask = CFM_UNDERLINETYPE;
389       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
390       break;
391     case rtfWordUnderline:
392       fmt.dwMask = CFM_UNDERLINETYPE;
393       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
394       break;
395     case rtfNoUnderline:
396       fmt.dwMask = CFM_UNDERLINETYPE;
397       fmt.bUnderlineType = CFU_UNDERLINENONE;
398       break;
399     case rtfStrikeThru:
400       fmt.dwMask = CFM_STRIKEOUT;
401       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
402       break;
403     case rtfSubScript:
404     case rtfSuperScript:
405     case rtfSubScrShrink:
406     case rtfSuperScrShrink:
407     case rtfNoSuperSub:
408       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
409       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
410       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
411       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
412       break;
413     case rtfInvisible:
414       fmt.dwMask = CFM_HIDDEN;
415       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
416       break;
417     case rtfBackColor:
418       fmt.dwMask = CFM_BACKCOLOR;
419       fmt.dwEffects = 0;
420       if (info->rtfParam == 0)
421         fmt.dwEffects = CFE_AUTOBACKCOLOR;
422       else if (info->rtfParam != rtfNoParam)
423       {
424         RTFColor *c = RTFGetColor(info, info->rtfParam);
425         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
426       }
427       break;
428     case rtfForeColor:
429       fmt.dwMask = CFM_COLOR;
430       fmt.dwEffects = 0;
431       if (info->rtfParam == 0)
432         fmt.dwEffects = CFE_AUTOCOLOR;
433       else if (info->rtfParam != rtfNoParam)
434       {
435         RTFColor *c = RTFGetColor(info, info->rtfParam);
436         if (c)
437           fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
438         else
439           fmt.crTextColor = 0;
440       }
441       break;
442     case rtfFontNum:
443       if (info->rtfParam != rtfNoParam)
444       {
445         RTFFont *f = RTFGetFont(info, info->rtfParam);
446         if (f)
447         {
448           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
449           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
450           fmt.bCharSet = f->rtfFCharSet;
451           fmt.dwMask = CFM_FACE | CFM_CHARSET;
452           fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
453         }
454       }
455       break;
456     case rtfFontSize:
457       fmt.dwMask = CFM_SIZE;
458       if (info->rtfParam != rtfNoParam)
459         fmt.yHeight = info->rtfParam*10;
460       break;
461   }
462   if (fmt.dwMask) {
463     ME_Style *style2;
464     RTFFlushOutputBuffer(info);
465     /* FIXME too slow ? how come ? */
466     style2 = ME_ApplyStyle(info->style, &fmt);
467     ME_ReleaseStyle(info->style);
468     info->style = style2;
469     info->styleChanged = TRUE;
470   }
471 }
472
473 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
474    the same tags mean different things in different contexts */
475 void ME_RTFParAttrHook(RTF_Info *info)
476 {
477   PARAFORMAT2 fmt;
478   fmt.cbSize = sizeof(fmt);
479   fmt.dwMask = 0;
480   
481   switch(info->rtfMinor)
482   {
483   case rtfParDef: /* restores default paragraph attributes */
484     if (!info->editor->bEmulateVersion10) /* v4.1 */
485       info->borderType = RTFBorderParaLeft;
486     else /* v1.0 - 3.0 */
487       info->borderType = RTFBorderParaTop;
488     fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
489         PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
490         PFM_STARTINDENT;
491     /* TODO: numbering, shading */
492     fmt.wAlignment = PFA_LEFT;
493     fmt.cTabCount = 0;
494     fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
495     fmt.wBorderWidth = fmt.wBorders = 0;
496     fmt.wBorderSpace = 0;
497     fmt.bLineSpacingRule = 0;
498     fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
499     fmt.dyLineSpacing = 0;
500     if (!info->editor->bEmulateVersion10) /* v4.1 */
501     {
502       if (info->tableDef && info->tableDef->tableRowStart &&
503           info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
504       {
505         ME_Cursor cursor;
506         ME_DisplayItem *para;
507         /* We are just after a table row. */
508         RTFFlushOutputBuffer(info);
509         cursor = info->editor->pCursors[0];
510         para = cursor.pPara;
511         if (para  == info->tableDef->tableRowStart->member.para.next_para
512             && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
513         {
514           /* Since the table row end, no text has been inserted, and the \intbl
515            * control word has not be used.  We can confirm that we are not in a
516            * table anymore.
517            */
518           info->tableDef->tableRowStart = NULL;
519           info->canInheritInTbl = FALSE;
520         }
521       }
522     } else { /* v1.0 - v3.0 */
523       fmt.dwMask |= PFM_TABLE;
524       fmt.wEffects &= ~PFE_TABLE;
525     }
526     break;
527   case rtfNestLevel:
528     if (!info->editor->bEmulateVersion10) /* v4.1 */
529     {
530       while (info->rtfParam > info->nestingLevel) {
531         RTFTable *tableDef = ALLOC_OBJ(RTFTable);
532         ZeroMemory(tableDef, sizeof(RTFTable));
533         tableDef->parent = info->tableDef;
534         info->tableDef = tableDef;
535
536         RTFFlushOutputBuffer(info);
537         if (tableDef->tableRowStart &&
538             tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
539         {
540           ME_DisplayItem *para = tableDef->tableRowStart;
541           para = para->member.para.next_para;
542           para = ME_InsertTableRowStartAtParagraph(info->editor, para);
543           tableDef->tableRowStart = para;
544         } else {
545           ME_Cursor cursor;
546           WCHAR endl = '\r';
547           cursor = info->editor->pCursors[0];
548           if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
549             ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
550           tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
551         }
552
553         info->nestingLevel++;
554       }
555       info->canInheritInTbl = FALSE;
556     }
557     break;
558   case rtfInTable:
559   {
560     if (!info->editor->bEmulateVersion10) /* v4.1 */
561     {
562       if (info->nestingLevel < 1)
563       {
564         RTFTable *tableDef;
565         if (!info->tableDef)
566         {
567             info->tableDef = ALLOC_OBJ(RTFTable);
568             ZeroMemory(info->tableDef, sizeof(RTFTable));
569         }
570         tableDef = info->tableDef;
571         RTFFlushOutputBuffer(info);
572         if (tableDef->tableRowStart &&
573             tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
574         {
575           ME_DisplayItem *para = tableDef->tableRowStart;
576           para = para->member.para.next_para;
577           para = ME_InsertTableRowStartAtParagraph(info->editor, para);
578           tableDef->tableRowStart = para;
579         } else {
580           ME_Cursor cursor;
581           WCHAR endl = '\r';
582           cursor = info->editor->pCursors[0];
583           if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
584             ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
585           tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
586         }
587         info->nestingLevel = 1;
588         info->canInheritInTbl = TRUE;
589       }
590       return;
591     } else { /* v1.0 - v3.0 */
592       fmt.dwMask |= PFM_TABLE;
593       fmt.wEffects |= PFE_TABLE;
594     }
595     break;
596   }
597   case rtfFirstIndent:
598     ME_GetSelectionParaFormat(info->editor, &fmt);
599     fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
600     fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
601     fmt.dxOffset = -info->rtfParam;
602     break;
603   case rtfLeftIndent:
604     ME_GetSelectionParaFormat(info->editor, &fmt);
605     fmt.dwMask = PFM_STARTINDENT;
606     fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
607     break;
608   case rtfRightIndent:
609     fmt.dwMask = PFM_RIGHTINDENT;
610     fmt.dxRightIndent = info->rtfParam;
611     break;
612   case rtfQuadLeft:
613   case rtfQuadJust:
614     fmt.dwMask = PFM_ALIGNMENT;
615     fmt.wAlignment = PFA_LEFT;
616     break;
617   case rtfQuadRight:
618     fmt.dwMask = PFM_ALIGNMENT;
619     fmt.wAlignment = PFA_RIGHT;
620     break;
621   case rtfQuadCenter:
622     fmt.dwMask = PFM_ALIGNMENT;
623     fmt.wAlignment = PFA_CENTER;
624     break;
625   case rtfTabPos:
626     ME_GetSelectionParaFormat(info->editor, &fmt);
627     if (!(fmt.dwMask & PFM_TABSTOPS))
628     {
629       fmt.cTabCount = 0;
630     }
631     if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
632       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
633     fmt.dwMask = PFM_TABSTOPS;
634     break;
635   case rtfKeep:
636     fmt.dwMask = PFM_KEEP;
637     fmt.wEffects = PFE_KEEP;
638     break;
639   case rtfNoWidowControl:
640     fmt.dwMask = PFM_NOWIDOWCONTROL;
641     fmt.wEffects = PFE_NOWIDOWCONTROL;
642     break;
643   case rtfKeepNext:
644     fmt.dwMask = PFM_KEEPNEXT;
645     fmt.wEffects = PFE_KEEPNEXT;
646     break;
647   case rtfSpaceAfter:
648     fmt.dwMask = PFM_SPACEAFTER;
649     fmt.dySpaceAfter = info->rtfParam;
650     break;
651   case rtfSpaceBefore:
652     fmt.dwMask = PFM_SPACEBEFORE;
653     fmt.dySpaceBefore = info->rtfParam;
654     break;
655   case rtfSpaceBetween:
656     fmt.dwMask = PFM_LINESPACING;
657     if ((int)info->rtfParam > 0)
658     {
659       fmt.dyLineSpacing = info->rtfParam;
660       fmt.bLineSpacingRule = 3;
661     }
662     else
663     {
664       fmt.dyLineSpacing = info->rtfParam;
665       fmt.bLineSpacingRule = 4;
666     }
667   case rtfSpaceMultiply:
668     fmt.dwMask = PFM_LINESPACING;
669     fmt.dyLineSpacing = info->rtfParam * 20;
670     fmt.bLineSpacingRule = 5;
671     break;
672   case rtfParBullet:
673     fmt.dwMask = PFM_NUMBERING;
674     fmt.wNumbering = PFN_BULLET;
675     break;
676   case rtfParSimple:
677     fmt.dwMask = PFM_NUMBERING;
678     fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
679     break;
680   case rtfParNumDecimal:
681     fmt.dwMask = PFM_NUMBERING;
682     fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
683     break;
684   case rtfParNumIndent:
685     fmt.dwMask = PFM_NUMBERINGTAB;
686     fmt.wNumberingTab = info->rtfParam;
687     break;
688   case rtfParNumStartAt:
689     fmt.dwMask = PFM_NUMBERINGSTART;
690     fmt.wNumberingStart = info->rtfParam;
691     break;
692   case rtfBorderLeft:
693     info->borderType = RTFBorderParaLeft;
694     ME_GetSelectionParaFormat(info->editor, &fmt);
695     if (!(fmt.dwMask & PFM_BORDER))
696     {
697       fmt.wBorderSpace = 0;
698       fmt.wBorderWidth = 1;
699       fmt.wBorders = 0;
700     }
701     fmt.wBorders |= 1;
702     fmt.dwMask = PFM_BORDER;
703     break;
704   case rtfBorderRight:
705     info->borderType = RTFBorderParaRight;
706     ME_GetSelectionParaFormat(info->editor, &fmt);
707     if (!(fmt.dwMask & PFM_BORDER))
708     {
709       fmt.wBorderSpace = 0;
710       fmt.wBorderWidth = 1;
711       fmt.wBorders = 0;
712     }
713     fmt.wBorders |= 2;
714     fmt.dwMask = PFM_BORDER;
715     break;
716   case rtfBorderTop:
717     info->borderType = RTFBorderParaTop;
718     ME_GetSelectionParaFormat(info->editor, &fmt);
719     if (!(fmt.dwMask & PFM_BORDER))
720     {
721       fmt.wBorderSpace = 0;
722       fmt.wBorderWidth = 1;
723       fmt.wBorders = 0;
724     }
725     fmt.wBorders |= 4;
726     fmt.dwMask = PFM_BORDER;
727     break;
728   case rtfBorderBottom:
729     info->borderType = RTFBorderParaBottom;
730     ME_GetSelectionParaFormat(info->editor, &fmt);
731     if (!(fmt.dwMask & PFM_BORDER))
732     {
733       fmt.wBorderSpace = 0;
734       fmt.wBorderWidth = 1;
735       fmt.wBorders = 0;
736     }
737     fmt.wBorders |= 8;
738     fmt.dwMask = PFM_BORDER;
739     break;
740   case rtfBorderSingle:
741     ME_GetSelectionParaFormat(info->editor, &fmt);
742     /* we assume that borders have been created before (RTF spec) */
743     fmt.wBorders &= ~0x700;
744     fmt.wBorders |= 1 << 8;
745     fmt.dwMask = PFM_BORDER;
746     break;
747   case rtfBorderThick:
748     ME_GetSelectionParaFormat(info->editor, &fmt);
749     /* we assume that borders have been created before (RTF spec) */
750     fmt.wBorders &= ~0x700;
751     fmt.wBorders |= 2 << 8;
752     fmt.dwMask = PFM_BORDER;
753     break;
754   case rtfBorderShadow:
755     ME_GetSelectionParaFormat(info->editor, &fmt);
756     /* we assume that borders have been created before (RTF spec) */
757     fmt.wBorders &= ~0x700;
758     fmt.wBorders |= 10 << 8;
759     fmt.dwMask = PFM_BORDER;
760     break;
761   case rtfBorderDouble:
762     ME_GetSelectionParaFormat(info->editor, &fmt);
763     /* we assume that borders have been created before (RTF spec) */
764     fmt.wBorders &= ~0x700;
765     fmt.wBorders |= 7 << 8;
766     fmt.dwMask = PFM_BORDER;
767     break;
768   case rtfBorderDot:
769     ME_GetSelectionParaFormat(info->editor, &fmt);
770     /* we assume that borders have been created before (RTF spec) */
771     fmt.wBorders &= ~0x700;
772     fmt.wBorders |= 11 << 8;
773     fmt.dwMask = PFM_BORDER;
774     break;
775   case rtfBorderWidth:
776   {
777     int borderSide = info->borderType & RTFBorderSideMask;
778     RTFTable *tableDef = info->tableDef;
779     ME_GetSelectionParaFormat(info->editor, &fmt);
780     /* we assume that borders have been created before (RTF spec) */
781     fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
782     if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
783     {
784       RTFBorder *border;
785       if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
786         break;
787       border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
788       border->width = info->rtfParam;
789       break;
790     }
791     fmt.dwMask = PFM_BORDER;
792     break;
793   }
794   case rtfBorderSpace:
795     ME_GetSelectionParaFormat(info->editor, &fmt);
796     /* we assume that borders have been created before (RTF spec) */
797     fmt.wBorderSpace = info->rtfParam;
798     fmt.dwMask = PFM_BORDER;
799     break;
800   case rtfBorderColor:
801   {
802     RTFTable *tableDef = info->tableDef;
803     int borderSide = info->borderType & RTFBorderSideMask;
804     int borderType = info->borderType & RTFBorderTypeMask;
805     switch(borderType)
806     {
807     case RTFBorderTypePara:
808       if (!info->editor->bEmulateVersion10) /* v4.1 */
809         break;
810       /* v1.0 - 3.0 treat paragraph and row borders the same. */
811     case RTFBorderTypeRow:
812       if (tableDef) {
813         tableDef->border[borderSide].color = info->rtfParam;
814       }
815       break;
816     case RTFBorderTypeCell:
817       if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
818         tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
819       }
820       break;
821     }
822     break;
823   }
824   }
825   if (fmt.dwMask) {
826     RTFFlushOutputBuffer(info);
827     /* FIXME too slow ? how come ?*/
828     ME_SetSelectionParaFormat(info->editor, &fmt);
829   }
830 }
831
832 void ME_RTFTblAttrHook(RTF_Info *info)
833 {
834   switch (info->rtfMinor)
835   {
836     case rtfRowDef:
837     {
838       if (!info->editor->bEmulateVersion10) /* v4.1 */
839         info->borderType = 0; /* Not sure */
840       else /* v1.0 - 3.0 */
841         info->borderType = RTFBorderRowTop;
842       if (!info->tableDef) {
843         info->tableDef = ME_MakeTableDef(info->editor);
844       } else {
845         ME_InitTableDef(info->editor, info->tableDef);
846       }
847       break;
848     }
849     case rtfCellPos:
850     {
851       int cellNum;
852       if (!info->tableDef)
853       {
854         info->tableDef = ME_MakeTableDef(info->editor);
855       }
856       cellNum = info->tableDef->numCellsDefined;
857       if (cellNum >= MAX_TABLE_CELLS)
858         break;
859       info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
860       if (cellNum < MAX_TAB_STOPS) {
861         /* Tab stops were used to store cell positions before v4.1 but v4.1
862          * still seems to set the tabstops without using them. */
863         ME_DisplayItem *para = info->editor->pCursors[0].pPara;
864         PARAFORMAT2 *pFmt = para->member.para.pFmt;
865         pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
866         pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
867       }
868       info->tableDef->numCellsDefined++;
869       break;
870     }
871     case rtfRowBordTop:
872       info->borderType = RTFBorderRowTop;
873       break;
874     case rtfRowBordLeft:
875       info->borderType = RTFBorderRowLeft;
876       break;
877     case rtfRowBordBottom:
878       info->borderType = RTFBorderRowBottom;
879       break;
880     case rtfRowBordRight:
881       info->borderType = RTFBorderRowRight;
882       break;
883     case rtfCellBordTop:
884       info->borderType = RTFBorderCellTop;
885       break;
886     case rtfCellBordLeft:
887       info->borderType = RTFBorderCellLeft;
888       break;
889     case rtfCellBordBottom:
890       info->borderType = RTFBorderCellBottom;
891       break;
892     case rtfCellBordRight:
893       info->borderType = RTFBorderCellRight;
894       break;
895     case rtfRowGapH:
896       if (info->tableDef)
897         info->tableDef->gapH = info->rtfParam;
898       break;
899     case rtfRowLeftEdge:
900       if (info->tableDef)
901         info->tableDef->leftEdge = info->rtfParam;
902       break;
903   }
904 }
905
906 void ME_RTFSpecialCharHook(RTF_Info *info)
907 {
908   RTFTable *tableDef = info->tableDef;
909   switch (info->rtfMinor)
910   {
911     case rtfNestCell:
912       if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
913         break;
914       /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
915     case rtfCell:
916       if (!tableDef)
917         break;
918       RTFFlushOutputBuffer(info);
919       if (!info->editor->bEmulateVersion10) { /* v4.1 */
920         if (tableDef->tableRowStart)
921         {
922           if (!info->nestingLevel &&
923               tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
924           {
925             ME_DisplayItem *para = tableDef->tableRowStart;
926             para = para->member.para.next_para;
927             para = ME_InsertTableRowStartAtParagraph(info->editor, para);
928             tableDef->tableRowStart = para;
929             info->nestingLevel = 1;
930           }
931           ME_InsertTableCellFromCursor(info->editor);
932         }
933       } else { /* v1.0 - v3.0 */
934         ME_DisplayItem *para = info->editor->pCursors[0].pPara;
935         PARAFORMAT2 *pFmt = para->member.para.pFmt;
936         if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
937             tableDef->numCellsInserted < tableDef->numCellsDefined)
938         {
939           WCHAR tab = '\t';
940           ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
941           tableDef->numCellsInserted++;
942         }
943       }
944       break;
945     case rtfNestRow:
946       if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
947         break;
948       /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
949     case rtfRow:
950     {
951       ME_DisplayItem *para, *cell, *run;
952       int i;
953
954       if (!tableDef)
955         break;
956       RTFFlushOutputBuffer(info);
957       if (!info->editor->bEmulateVersion10) { /* v4.1 */
958         if (!tableDef->tableRowStart)
959           break;
960         if (!info->nestingLevel &&
961             tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
962         {
963           para = tableDef->tableRowStart;
964           para = para->member.para.next_para;
965           para = ME_InsertTableRowStartAtParagraph(info->editor, para);
966           tableDef->tableRowStart = para;
967           info->nestingLevel++;
968         }
969         para = tableDef->tableRowStart;
970         cell = ME_FindItemFwd(para, diCell);
971         assert(cell && !cell->member.cell.prev_cell);
972         if (tableDef->numCellsDefined < 1)
973         {
974           /* 2000 twips appears to be the cell size that native richedit uses
975            * when no cell sizes are specified. */
976           const int defaultCellSize = 2000;
977           int nRightBoundary = defaultCellSize;
978           cell->member.cell.nRightBoundary = nRightBoundary;
979           while (cell->member.cell.next_cell) {
980             cell = cell->member.cell.next_cell;
981             nRightBoundary += defaultCellSize;
982             cell->member.cell.nRightBoundary = nRightBoundary;
983           }
984           para = ME_InsertTableCellFromCursor(info->editor);
985           cell = para->member.para.pCell;
986           cell->member.cell.nRightBoundary = nRightBoundary;
987         } else {
988           for (i = 0; i < tableDef->numCellsDefined; i++)
989           {
990             RTFCell *cellDef = &tableDef->cells[i];
991             cell->member.cell.nRightBoundary = cellDef->rightBoundary;
992             ME_ApplyBorderProperties(info, &cell->member.cell.border,
993                                      cellDef->border);
994             cell = cell->member.cell.next_cell;
995             if (!cell)
996             {
997               para = ME_InsertTableCellFromCursor(info->editor);
998               cell = para->member.para.pCell;
999             }
1000           }
1001           /* Cell for table row delimiter is empty */
1002           cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1003         }
1004
1005         run = ME_FindItemFwd(cell, diRun);
1006         if (info->editor->pCursors[0].pRun != run ||
1007             info->editor->pCursors[0].nOffset)
1008         {
1009           int nOfs, nChars;
1010           /* Delete inserted cells that aren't defined. */
1011           info->editor->pCursors[1].pRun = run;
1012           info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1013           info->editor->pCursors[1].nOffset = 0;
1014           nOfs = ME_GetCursorOfs(info->editor, 1);
1015           nChars = ME_GetCursorOfs(info->editor, 0) - nOfs;
1016           ME_InternalDeleteText(info->editor, nOfs, nChars, TRUE);
1017         }
1018
1019         para = ME_InsertTableRowEndFromCursor(info->editor);
1020         para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1021         para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1022         ME_ApplyBorderProperties(info, &para->member.para.border,
1023                                  tableDef->border);
1024         info->nestingLevel--;
1025         if (!info->nestingLevel)
1026         {
1027           if (info->canInheritInTbl) {
1028             tableDef->tableRowStart = para;
1029           } else {
1030             while (info->tableDef) {
1031               tableDef = info->tableDef;
1032               info->tableDef = tableDef->parent;
1033               heap_free(tableDef);
1034             }
1035           }
1036         } else {
1037           info->tableDef = tableDef->parent;
1038           heap_free(tableDef);
1039         }
1040       } else { /* v1.0 - v3.0 */
1041         WCHAR endl = '\r';
1042         ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1043         PARAFORMAT2 *pFmt = para->member.para.pFmt;
1044         pFmt->dxOffset = info->tableDef->gapH;
1045         pFmt->dxStartIndent = info->tableDef->leftEdge;
1046
1047         ME_ApplyBorderProperties(info, &para->member.para.border,
1048                                  tableDef->border);
1049         while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1050         {
1051           WCHAR tab = '\t';
1052           ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1053           tableDef->numCellsInserted++;
1054         }
1055         pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1056         if (!tableDef->numCellsDefined)
1057           pFmt->wEffects &= ~PFE_TABLE;
1058         ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1059         tableDef->numCellsInserted = 0;
1060       }
1061       break;
1062     }
1063     case rtfTab:
1064     case rtfPar:
1065       if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1066         ME_DisplayItem *para;
1067         PARAFORMAT2 *pFmt;
1068         RTFFlushOutputBuffer(info);
1069         para = info->editor->pCursors[0].pPara;
1070         pFmt = para->member.para.pFmt;
1071         if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1072         {
1073           /* rtfPar is treated like a space within a table. */
1074           info->rtfClass = rtfText;
1075           info->rtfMajor = ' ';
1076         }
1077         else if (info->rtfMinor == rtfPar && tableDef)
1078           tableDef->numCellsInserted = 0;
1079       }
1080       break;
1081   }
1082 }
1083
1084 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1085                                   const SIZEL* sz)
1086 {
1087   LPOLEOBJECT         lpObject = NULL;
1088   LPSTORAGE           lpStorage = NULL;
1089   LPOLECLIENTSITE     lpClientSite = NULL;
1090   LPDATAOBJECT        lpDataObject = NULL;
1091   LPOLECACHE          lpOleCache = NULL;
1092   STGMEDIUM           stgm;
1093   FORMATETC           fm;
1094   CLSID               clsid;
1095   BOOL                ret = FALSE;
1096   DWORD               conn;
1097
1098   if (hemf)
1099   {
1100       stgm.tymed = TYMED_ENHMF;
1101       stgm.u.hEnhMetaFile = hemf;
1102       fm.cfFormat = CF_ENHMETAFILE;
1103   }
1104   else if (hbmp)
1105   {
1106       stgm.tymed = TYMED_GDI;
1107       stgm.u.hBitmap = hbmp;
1108       fm.cfFormat = CF_BITMAP;
1109   }
1110   stgm.pUnkForRelease = NULL;
1111
1112   fm.ptd = NULL;
1113   fm.dwAspect = DVASPECT_CONTENT;
1114   fm.lindex = -1;
1115   fm.tymed = stgm.tymed;
1116
1117   if (!info->lpRichEditOle)
1118   {
1119     CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1120   }
1121
1122   if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1123 #if 0
1124       /* FIXME: enable it when rich-edit properly implements this method */
1125       IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1126       IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1127 #endif
1128       IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1129       IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1130       IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1131       IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1132       IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1133   {
1134     REOBJECT            reobject;
1135
1136     reobject.cbStruct = sizeof(reobject);
1137     reobject.cp = REO_CP_SELECTION;
1138     reobject.clsid = clsid;
1139     reobject.poleobj = lpObject;
1140     reobject.pstg = lpStorage;
1141     reobject.polesite = lpClientSite;
1142     /* convert from twips to .01 mm */
1143     reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1144     reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1145     reobject.dvaspect = DVASPECT_CONTENT;
1146     reobject.dwFlags = 0; /* FIXME */
1147     reobject.dwUser = 0;
1148
1149     /* FIXME: could be simpler */
1150     ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
1151   }
1152
1153   if (lpObject)       IOleObject_Release(lpObject);
1154   if (lpClientSite)   IOleClientSite_Release(lpClientSite);
1155   if (lpStorage)      IStorage_Release(lpStorage);
1156   if (lpDataObject)   IDataObject_Release(lpDataObject);
1157   if (lpOleCache)     IOleCache_Release(lpOleCache);
1158
1159   return ret;
1160 }
1161
1162 static void ME_RTFReadPictGroup(RTF_Info *info)
1163 {
1164   SIZEL         sz;
1165   BYTE*         buffer = NULL;
1166   unsigned      bufsz, bufidx;
1167   BOOL          flip;
1168   BYTE          val;
1169   METAFILEPICT  mfp;
1170   HENHMETAFILE  hemf;
1171   HBITMAP       hbmp;
1172   enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1173
1174   RTFGetToken (info);
1175   if (info->rtfClass == rtfEOF)
1176     return;
1177   mfp.mm = MM_TEXT;
1178   /* fetch picture type */
1179   if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1180   {
1181     mfp.mm = info->rtfParam;
1182     gfx = gfx_metafile;
1183   }
1184   else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1185   {
1186     if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1187     gfx = gfx_dib;
1188   }
1189   else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1190   {
1191     gfx = gfx_enhmetafile;
1192   }
1193   else
1194   {
1195     FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1196     goto skip_group;
1197   }
1198   sz.cx = sz.cy = 0;
1199   /* fetch picture attributes */
1200   for (;;)
1201   {
1202     RTFGetToken (info);
1203     if (info->rtfClass == rtfEOF)
1204       return;
1205     if (info->rtfClass == rtfText)
1206       break;
1207     if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1208     {
1209       ERR("Expected picture attribute (%d %d)\n",
1210         info->rtfClass, info->rtfMajor);
1211       goto skip_group;
1212     }
1213     else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1214     {
1215       if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1216     }
1217     else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1218     {
1219       if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1220     }
1221     else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1222       sz.cx = info->rtfParam;
1223     else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1224       sz.cy = info->rtfParam;
1225     else
1226       FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1227   }
1228   /* fetch picture data */
1229   bufsz = 1024;
1230   bufidx = 0;
1231   buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1232   val = info->rtfMajor;
1233   for (flip = TRUE;; flip = !flip)
1234   {
1235     RTFGetToken (info);
1236     if (info->rtfClass == rtfEOF)
1237     {
1238       HeapFree(GetProcessHeap(), 0, buffer);
1239       return; /* Warn ?? */
1240     }
1241     if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1242       break;
1243     if (info->rtfClass != rtfText) goto skip_group;
1244     if (flip)
1245     {
1246       if (bufidx >= bufsz &&
1247           !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1248         goto skip_group;
1249       buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1250     }
1251     else
1252       val = info->rtfMajor;
1253   }
1254   if (flip) FIXME("wrong hex string\n");
1255
1256   switch (gfx)
1257   {
1258   case gfx_enhmetafile:
1259     if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1260       ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1261     break;
1262   case gfx_metafile:
1263     if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1264         ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1265     break;
1266   case gfx_dib:
1267     {
1268       BITMAPINFO* bi = (BITMAPINFO*)buffer;
1269       HDC         hdc = GetDC(0);
1270       unsigned    nc = bi->bmiHeader.biClrUsed;
1271
1272       /* not quite right, especially for bitfields type of compression */
1273       if (!nc && bi->bmiHeader.biBitCount <= 8)
1274         nc = 1 << bi->bmiHeader.biBitCount;
1275       if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1276                                  CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1277                                  bi, DIB_RGB_COLORS)))
1278           ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1279       ReleaseDC(0, hdc);
1280     }
1281     break;
1282   default:
1283     break;
1284   }
1285   HeapFree(GetProcessHeap(), 0, buffer);
1286   RTFRouteToken (info); /* feed "}" back to router */
1287   return;
1288 skip_group:
1289   HeapFree(GetProcessHeap(), 0, buffer);
1290   RTFSkipGroup(info);
1291   RTFRouteToken(info);  /* feed "}" back to router */
1292 }
1293
1294 /* for now, lookup the \result part and use it, whatever the object */
1295 static void ME_RTFReadObjectGroup(RTF_Info *info)
1296 {
1297   for (;;)
1298   {
1299     RTFGetToken (info);
1300     if (info->rtfClass == rtfEOF)
1301       return;
1302     if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1303       break;
1304     if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1305     {
1306       RTFGetToken (info);
1307       if (info->rtfClass == rtfEOF)
1308         return;
1309       if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1310       {
1311         int     level = 1;
1312
1313         while (RTFGetToken (info) != rtfEOF)
1314         {
1315           if (info->rtfClass == rtfGroup)
1316           {
1317             if (info->rtfMajor == rtfBeginGroup) level++;
1318             else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1319           }
1320           RTFRouteToken(info);
1321         }
1322       }
1323       else RTFSkipGroup(info);
1324       continue;
1325     }
1326     if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1327     {
1328       FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1329       return;
1330     }
1331   }
1332   RTFRouteToken(info);  /* feed "}" back to router */
1333 }
1334
1335 static void ME_RTFReadHook(RTF_Info *info)
1336 {
1337   switch(info->rtfClass)
1338   {
1339     case rtfGroup:
1340       switch(info->rtfMajor)
1341       {
1342         case rtfBeginGroup:
1343           if (info->stackTop < maxStack) {
1344             info->stack[info->stackTop].fmt = info->style->fmt;
1345             info->stack[info->stackTop].codePage = info->codePage;
1346             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1347           }
1348           info->stackTop++;
1349           info->styleChanged = FALSE;
1350           break;
1351         case rtfEndGroup:
1352         {
1353           ME_Style *s;
1354           RTFFlushOutputBuffer(info);
1355           info->stackTop--;
1356           if (info->stackTop<=0) {
1357             info->rtfClass = rtfEOF;
1358             return;
1359           }
1360           assert(info->stackTop >= 0);
1361           if (info->styleChanged)
1362           {
1363             /* FIXME too slow ? how come ? */
1364             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
1365             ME_ReleaseStyle(info->style);
1366             info->style = s;
1367             info->codePage = info->stack[info->stackTop].codePage;
1368             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1369           }
1370           break;
1371         }
1372       }
1373       break;
1374   }
1375 }
1376
1377 void
1378 ME_StreamInFill(ME_InStream *stream)
1379 {
1380   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1381                                                                 (BYTE *)stream->buffer,
1382                                                                 sizeof(stream->buffer),
1383                                                                 (LONG *)&stream->dwSize);
1384   stream->dwUsed = 0;
1385 }
1386
1387 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1388 {
1389   RTF_Info parser;
1390   ME_Style *style;
1391   int from, to, to2, nUndoMode;
1392   int nEventMask = editor->nEventMask;
1393   ME_InStream inStream;
1394   BOOL invalidRTF = FALSE;
1395
1396   TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1397   editor->nEventMask = 0;
1398
1399   ME_GetSelection(editor, &from, &to);
1400   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1401     style = ME_GetSelectionInsertStyle(editor);
1402
1403     ME_InternalDeleteText(editor, from, to-from, FALSE);
1404
1405     /* Don't insert text at the end of the table row */
1406     if (!editor->bEmulateVersion10) { /* v4.1 */
1407       ME_DisplayItem *para = editor->pCursors->pPara;
1408       if (para->member.para.nFlags & MEPF_ROWEND)
1409       {
1410         para = para->member.para.next_para;
1411         editor->pCursors[0].pPara = para;
1412         editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1413         editor->pCursors[0].nOffset = 0;
1414       }
1415       if (para->member.para.nFlags & MEPF_ROWSTART)
1416       {
1417         para = para->member.para.next_para;
1418         editor->pCursors[0].pPara = para;
1419         editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1420         editor->pCursors[0].nOffset = 0;
1421       }
1422       editor->pCursors[1] = editor->pCursors[0];
1423     } else { /* v1.0 - 3.0 */
1424       if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1425           ME_IsInTable(editor->pCursors[0].pRun))
1426         return 0;
1427     }
1428   }
1429   else {
1430     style = editor->pBuffer->pDefaultStyle;
1431     ME_AddRefStyle(style);
1432     ME_SetSelection(editor, 0, 0);
1433     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
1434     from = to = 0;
1435     ME_ClearTempStyle(editor);
1436     ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1437   }
1438
1439
1440   /* Back up undo mode to a local variable */
1441   nUndoMode = editor->nUndoMode;
1442
1443   /* Only create an undo if SFF_SELECTION is set */
1444   if (!(format & SFF_SELECTION))
1445     editor->nUndoMode = umIgnore;
1446
1447   inStream.editstream = stream;
1448   inStream.editstream->dwError = 0;
1449   inStream.dwSize = 0;
1450   inStream.dwUsed = 0;
1451
1452   if (format & SF_RTF)
1453   {
1454     /* Check if it's really RTF, and if it is not, use plain text */
1455     ME_StreamInFill(&inStream);
1456     if (!inStream.editstream->dwError)
1457     {
1458       if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1459         || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1460       {
1461         invalidRTF = TRUE;
1462         inStream.editstream->dwError = -16;
1463       }
1464     }
1465   }
1466
1467   if (!invalidRTF && !inStream.editstream->dwError)
1468   {
1469     if (format & SF_RTF) {
1470       /* setup the RTF parser */
1471       memset(&parser, 0, sizeof parser);
1472       RTFSetEditStream(&parser, &inStream);
1473       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
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].pPara = para;
1520           editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1521           editor->pCursors[1].nOffset = 0;
1522           nOfs = ME_GetCursorOfs(editor, 1);
1523           nChars = ME_GetCursorOfs(editor, 0) - nOfs;
1524           ME_InternalDeleteText(editor, nOfs, nChars, TRUE);
1525           if (parser.tableDef)
1526             parser.tableDef->tableRowStart = NULL;
1527         }
1528       }
1529       ME_CheckTablesForCorruption(editor);
1530       RTFDestroy(&parser);
1531       if (parser.lpRichEditOle)
1532         IRichEditOle_Release(parser.lpRichEditOle);
1533
1534       if (!inStream.editstream->dwError && parser.stackTop > 0)
1535         inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1536
1537       /* Remove last line break, as mandated by tests. This is not affected by
1538          CR/LF counters, since RTF streaming presents only \para tokens, which
1539          are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1540        */
1541       if (stripLastCR) {
1542         int newfrom, newto;
1543         ME_GetSelection(editor, &newfrom, &newto);
1544         if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1545           WCHAR lastchar[3] = {'\0', '\0'};
1546           int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1547
1548           ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1549           if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1550             ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize, FALSE);
1551           }
1552         }
1553       }
1554
1555       style = parser.style;
1556     }
1557     else if (format & SF_TEXT)
1558       ME_StreamInText(editor, format, &inStream, style);
1559     else
1560       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1561     ME_GetSelection(editor, &to, &to2);
1562     /* put the cursor at the top */
1563     if (!(format & SFF_SELECTION))
1564       ME_SetSelection(editor, 0, 0);
1565   }
1566
1567   /* Restore saved undo mode */
1568   editor->nUndoMode = nUndoMode;
1569
1570   /* even if we didn't add an undo, we need to commit anything on the stack */
1571   ME_CommitUndo(editor);
1572
1573   /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1574   if (!(format & SFF_SELECTION))
1575     ME_EmptyUndoStack(editor);
1576
1577   ME_ReleaseStyle(style);
1578   editor->nEventMask = nEventMask;
1579   ME_UpdateRepaint(editor);
1580   if (!(format & SFF_SELECTION)) {
1581     ME_ClearTempStyle(editor);
1582   }
1583   ITextHost_TxShowCaret(editor->texthost, FALSE);
1584   ME_MoveCaret(editor);
1585   ITextHost_TxShowCaret(editor->texthost, TRUE);
1586   ME_SendSelChange(editor);
1587   ME_SendRequestResize(editor, FALSE);
1588
1589   return 0;
1590 }
1591
1592
1593 typedef struct tagME_RTFStringStreamStruct
1594 {
1595   char *string;
1596   int pos;
1597   int length;
1598 } ME_RTFStringStreamStruct;
1599
1600 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1601 {
1602   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1603   int count;
1604
1605   count = min(cb, pStruct->length - pStruct->pos);
1606   memmove(lpBuff, pStruct->string + pStruct->pos, count);
1607   pStruct->pos += count;
1608   *pcb = count;
1609   return 0;
1610 }
1611
1612 static void
1613 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1614 {
1615   EDITSTREAM es;
1616   ME_RTFStringStreamStruct data;
1617
1618   data.string = string;
1619   data.length = strlen(string);
1620   data.pos = 0;
1621   es.dwCookie = (DWORD_PTR)&data;
1622   es.pfnCallback = ME_ReadFromRTFString;
1623   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1624 }
1625
1626
1627 static int
1628 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1629 {
1630   const int nLen = lstrlenW(text);
1631   const int nTextLen = ME_GetTextLength(editor);
1632   int nStart, nEnd;
1633   int nMin, nMax;
1634   ME_DisplayItem *item;
1635   ME_DisplayItem *para;
1636   WCHAR wLastChar = ' ';
1637
1638   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1639         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1640
1641   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1642     FIXME("Flags 0x%08x not implemented\n",
1643         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1644
1645   nMin = chrg->cpMin;
1646   if (chrg->cpMax == -1)
1647     nMax = nTextLen;
1648   else
1649     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1650
1651   /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1652   if (editor->bEmulateVersion10 && nMax == nTextLen)
1653   {
1654     flags |= FR_DOWN;
1655   }
1656
1657   /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1658   if (editor->bEmulateVersion10 && nMax < nMin)
1659   {
1660     if (chrgText)
1661     {
1662       chrgText->cpMin = -1;
1663       chrgText->cpMax = -1;
1664     }
1665     return -1;
1666   }
1667
1668   /* when searching up, if cpMin < cpMax, then instead of searching
1669    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1670    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1671    * case, it is always bigger than cpMin.
1672    */
1673   if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1674   {
1675     int nSwap = nMax;
1676
1677     nMax = nMin > nTextLen ? nTextLen : nMin;
1678     if (nMin < nSwap || chrg->cpMax == -1)
1679       nMin = 0;
1680     else
1681       nMin = nSwap;
1682   }
1683
1684   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1685   {
1686     if (chrgText)
1687       chrgText->cpMin = chrgText->cpMax = -1;
1688     return -1;
1689   }
1690
1691   if (flags & FR_DOWN) /* Forward search */
1692   {
1693     /* If possible, find the character before where the search starts */
1694     if ((flags & FR_WHOLEWORD) && nMin)
1695     {
1696       ME_RunOfsFromCharOfs(editor, nMin - 1, NULL, &item, &nStart);
1697       wLastChar = item->member.run.strText->szData[nStart];
1698     }
1699
1700     ME_RunOfsFromCharOfs(editor, nMin, &para, &item, &nStart);
1701
1702     while (item
1703            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1704     {
1705       ME_DisplayItem *pCurItem = item;
1706       int nCurStart = nStart;
1707       int nMatched = 0;
1708     
1709       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1710       {
1711         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1712           break;
1713
1714         nMatched++;
1715         if (nMatched == nLen)
1716         {
1717           ME_DisplayItem *pNextItem = pCurItem;
1718           int nNextStart = nCurStart;
1719           WCHAR wNextChar;
1720
1721           /* Check to see if next character is a whitespace */
1722           if (flags & FR_WHOLEWORD)
1723           {
1724             if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1725             {
1726               pNextItem = ME_FindItemFwd(pCurItem, diRun);
1727               nNextStart = -nMatched;
1728             }
1729
1730             if (pNextItem)
1731               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1732             else
1733               wNextChar = ' ';
1734
1735             if (isalnumW(wNextChar))
1736               break;
1737           }
1738
1739           nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1740           if (chrgText)
1741           {
1742             chrgText->cpMin = nStart;
1743             chrgText->cpMax = nStart + nLen;
1744           }
1745           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1746           return nStart;
1747         }
1748         if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1749         {
1750           pCurItem = ME_FindItemFwd(pCurItem, diRun);
1751           nCurStart = -nMatched;
1752         }
1753       }
1754       if (pCurItem)
1755         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1756       else
1757         wLastChar = ' ';
1758
1759       nStart++;
1760       if (nStart == item->member.run.strText->nLen)
1761       {
1762         item = ME_FindItemFwd(item, diRun);
1763         para = ME_GetParagraph(item);
1764         nStart = 0;
1765       }
1766     }
1767   }
1768   else /* Backward search */
1769   {
1770     /* If possible, find the character after where the search ends */
1771     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1772     {
1773       ME_RunOfsFromCharOfs(editor, nMax + 1, NULL, &item, &nEnd);
1774       wLastChar = item->member.run.strText->szData[nEnd];
1775     }
1776
1777     ME_RunOfsFromCharOfs(editor, nMax, &para, &item, &nEnd);
1778
1779     while (item
1780            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1781     {
1782       ME_DisplayItem *pCurItem = item;
1783       int nCurEnd = nEnd;
1784       int nMatched = 0;
1785
1786       if (nCurEnd == 0)
1787       {
1788         pCurItem = ME_FindItemBack(pCurItem, diRun);
1789         nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1790       }
1791
1792       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1793       {
1794         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1795           break;
1796
1797         nMatched++;
1798         if (nMatched == nLen)
1799         {
1800           ME_DisplayItem *pPrevItem = pCurItem;
1801           int nPrevEnd = nCurEnd;
1802           WCHAR wPrevChar;
1803
1804           /* Check to see if previous character is a whitespace */
1805           if (flags & FR_WHOLEWORD)
1806           {
1807             if (nPrevEnd - nMatched == 0)
1808             {
1809               pPrevItem = ME_FindItemBack(pCurItem, diRun);
1810               if (pPrevItem)
1811                 nPrevEnd = pPrevItem->member.run.strText->nLen + nMatched;
1812             }
1813
1814             if (pPrevItem)
1815               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1816             else
1817               wPrevChar = ' ';
1818
1819             if (isalnumW(wPrevChar))
1820               break;
1821           }
1822
1823           nStart = ME_GetParagraph(pCurItem)->member.para.nCharOfs
1824                    + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1825           if (chrgText)
1826           {
1827             chrgText->cpMin = nStart;
1828             chrgText->cpMax = nStart + nLen;
1829           }
1830           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1831           return nStart;
1832         }
1833         if (nCurEnd - nMatched == 0)
1834         {
1835           pCurItem = ME_FindItemBack(pCurItem, diRun);
1836           /* Don't care about pCurItem becoming NULL here; it's already taken
1837            * care of in the exterior loop condition */
1838           nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1839         }
1840       }
1841       if (pCurItem)
1842         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1843       else
1844         wLastChar = ' ';
1845
1846       nEnd--;
1847       if (nEnd < 0)
1848       {
1849         item = ME_FindItemBack(item, diRun);
1850         para = ME_GetParagraph(item);
1851         nEnd = item->member.run.strText->nLen;
1852       }
1853     }
1854   }
1855   TRACE("not found\n");
1856   if (chrgText)
1857     chrgText->cpMin = chrgText->cpMax = -1;
1858   return -1;
1859 }
1860
1861 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1862 {
1863     int nStart, nCount; /* in chars */
1864
1865     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1866       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1867
1868     if (ex->flags & GT_SELECTION)
1869     {
1870       ME_GetSelection(editor, &nStart, &nCount);
1871       nCount -= nStart;
1872     }
1873     else
1874     {
1875       nStart = 0;
1876       nCount = 0x7fffffff;
1877     }
1878     if (ex->codepage == 1200)
1879     {
1880       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
1881       return ME_GetTextW(editor, (LPWSTR)pText, nStart, nCount, ex->flags & GT_USECRLF);
1882     }
1883     else
1884     {
1885       /* potentially each char may be a CR, why calculate the exact value with O(N) when
1886         we can just take a bigger buffer? :)
1887         The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1888         occurs only in richedit 2.0 mode, in which line breaks have only one CR
1889        */
1890       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1891       LPWSTR buffer;
1892       DWORD buflen = ex->cb;
1893       LRESULT rc;
1894       DWORD flags = 0;
1895
1896       nCount = min(nCount, ex->cb - 1);
1897       buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
1898
1899       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
1900       rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1,
1901                                (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1902       if (rc) rc--; /* do not count 0 terminator */
1903
1904       heap_free(buffer);
1905       return rc;
1906     }
1907 }
1908
1909 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1910                            int start, int nLen, BOOL unicode)
1911 {
1912     if (unicode) {
1913       return ME_GetTextW(editor, strText, start, nLen, 0);
1914     } else {
1915       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1916       int nChars = ME_GetTextW(editor, p, start, nLen, 0);
1917       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1918                           nLen+1, NULL, NULL);
1919       FREE_OBJ(p);
1920       return nChars;
1921     }
1922 }
1923
1924 typedef struct tagME_GlobalDestStruct
1925 {
1926   HGLOBAL hData;
1927   int nLength;
1928 } ME_GlobalDestStruct;
1929
1930 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1931 {
1932   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1933   int i;
1934   WORD *pSrc, *pDest;
1935
1936   cb = cb >> 1;
1937   pDest = (WORD *)lpBuff;
1938   pSrc = GlobalLock(pData->hData);
1939   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1940     pDest[i] = pSrc[pData->nLength+i];
1941   }
1942   pData->nLength += i;
1943   *pcb = 2*i;
1944   GlobalUnlock(pData->hData);
1945   return 0;
1946 }
1947
1948 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1949 {
1950   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1951   int i;
1952   BYTE *pSrc, *pDest;
1953
1954   pDest = lpBuff;
1955   pSrc = GlobalLock(pData->hData);
1956   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1957     pDest[i] = pSrc[pData->nLength+i];
1958   }
1959   pData->nLength += i;
1960   *pcb = i;
1961   GlobalUnlock(pData->hData);
1962   return 0;
1963 }
1964
1965 static BOOL ME_Paste(ME_TextEditor *editor)
1966 {
1967   DWORD dwFormat = 0;
1968   EDITSTREAM es;
1969   ME_GlobalDestStruct gds;
1970   UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1971   UINT cf = 0;
1972
1973   if (IsClipboardFormatAvailable(nRTFFormat))
1974     cf = nRTFFormat, dwFormat = SF_RTF;
1975   else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1976     cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1977   else
1978     return FALSE;
1979
1980   if (!OpenClipboard(editor->hWnd))
1981     return FALSE;
1982   gds.hData = GetClipboardData(cf);
1983   gds.nLength = 0;
1984   es.dwCookie = (DWORD_PTR)&gds;
1985   es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1986   ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
1987
1988   CloseClipboard();
1989   return TRUE;
1990 }
1991
1992 static BOOL ME_Copy(ME_TextEditor *editor, CHARRANGE *range)
1993 {
1994   LPDATAOBJECT dataObj = NULL;
1995   HRESULT hr = S_OK;
1996
1997   if (editor->cPasswordMask)
1998     return FALSE; /* Copying or Cutting masked text isn't allowed */
1999
2000   if(editor->lpOleCallback)
2001     hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, range, RECO_COPY, &dataObj);
2002   if(FAILED(hr) || !dataObj)
2003     hr = ME_GetDataObject(editor, range, &dataObj);
2004   if(SUCCEEDED(hr)) {
2005     hr = OleSetClipboard(dataObj);
2006     IDataObject_Release(dataObj);
2007   }
2008   return SUCCEEDED(hr) != 0;
2009 }
2010
2011 /* helper to send a msg filter notification */
2012 static BOOL
2013 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2014 {
2015     MSGFILTER msgf;
2016
2017     if (!editor->hWnd) return FALSE;
2018     msgf.nmhdr.hwndFrom = editor->hWnd;
2019     msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2020     msgf.nmhdr.code = EN_MSGFILTER;
2021     msgf.msg = msg;
2022     msgf.wParam = *wParam;
2023     msgf.lParam = *lParam;
2024     if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2025         return FALSE;
2026     *wParam = msgf.wParam;
2027     *lParam = msgf.lParam;
2028     msgf.wParam = *wParam;
2029
2030     return TRUE;
2031 }
2032
2033 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2034 {
2035   ME_DisplayItem *startPara, *endPara;
2036   ME_DisplayItem *prev_para;
2037   int from, to;
2038
2039   if (!editor->AutoURLDetect_bEnable) return;
2040
2041   ME_GetSelection(editor, &from, &to);
2042
2043   /* Find paragraph previous to the one that contains start cursor */
2044   ME_RunOfsFromCharOfs(editor, from, &startPara, NULL, NULL);
2045   prev_para = startPara->member.para.prev_para;
2046   if (prev_para->type == diParagraph) startPara = prev_para;
2047
2048   /* Find paragraph that contains end cursor */
2049   ME_RunOfsFromCharOfs(editor, to, &endPara, NULL, NULL);
2050   endPara = endPara->member.para.next_para;
2051
2052   ME_UpdateLinkAttribute(editor,
2053                          startPara->member.para.nCharOfs,
2054                          endPara->member.para.nCharOfs);
2055 }
2056
2057 static BOOL
2058 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2059 {
2060   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2061   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2062
2063   if (editor->bMouseCaptured)
2064       return FALSE;
2065   if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2066       editor->nSelectionType = stPosition;
2067
2068   switch (nKey)
2069   {
2070     case VK_LEFT:
2071     case VK_RIGHT:
2072     case VK_HOME:
2073     case VK_END:
2074         editor->nUDArrowX = -1;
2075         /* fall through */
2076     case VK_UP:
2077     case VK_DOWN:
2078     case VK_PRIOR:
2079     case VK_NEXT:
2080       ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2081       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2082       return TRUE;
2083     case VK_BACK:
2084     case VK_DELETE:
2085       editor->nUDArrowX = -1;
2086       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2087       if (editor->styleFlags & ES_READONLY)
2088         return FALSE;
2089       if (ME_IsSelection(editor))
2090       {
2091         ME_DeleteSelection(editor);
2092         ME_CommitUndo(editor);
2093       }
2094       else if (nKey == VK_DELETE)
2095       {
2096         /* Delete stops group typing.
2097          * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2098         ME_DeleteTextAtCursor(editor, 1, 1);
2099         ME_CommitUndo(editor);
2100       }
2101       else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2102       {
2103         BOOL bDeletionSucceeded;
2104         /* Backspace can be grouped for a single undo */
2105         ME_ContinueCoalescingTransaction(editor);
2106         bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2107         if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2108           /* Deletion was prevented so the cursor is moved back to where it was.
2109            * (e.g. this happens when trying to delete cell boundaries)
2110            */
2111           ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2112         }
2113         ME_CommitCoalescingUndo(editor);
2114       }
2115       else
2116         return TRUE;
2117       ME_MoveCursorFromTableRowStartParagraph(editor);
2118       ME_UpdateSelectionLinkAttribute(editor);
2119       ME_UpdateRepaint(editor);
2120       ME_SendRequestResize(editor, FALSE);
2121       return TRUE;
2122     case VK_RETURN:
2123       if (editor->styleFlags & ES_MULTILINE)
2124       {
2125         ME_Cursor cursor = editor->pCursors[0];
2126         ME_DisplayItem *para = cursor.pPara;
2127         int from, to;
2128         const WCHAR endl = '\r';
2129         ME_Style *style;
2130
2131         if (editor->styleFlags & ES_READONLY) {
2132           MessageBeep(MB_ICONERROR);
2133           return TRUE;
2134         }
2135
2136         ME_GetSelection(editor, &from, &to);
2137         if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2138         {
2139           if (!editor->bEmulateVersion10) { /* v4.1 */
2140             if (para->member.para.nFlags & MEPF_ROWEND) {
2141               /* Add a new table row after this row. */
2142               para = ME_AppendTableRow(editor, para);
2143               para = para->member.para.next_para;
2144               editor->pCursors[0].pPara = para;
2145               editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2146               editor->pCursors[0].nOffset = 0;
2147               editor->pCursors[1] = editor->pCursors[0];
2148               ME_CommitUndo(editor);
2149               ME_CheckTablesForCorruption(editor);
2150               ME_UpdateRepaint(editor);
2151               return TRUE;
2152             }
2153             else if (para == editor->pCursors[1].pPara &&
2154                      cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2155                      para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2156                      !para->member.para.prev_para->member.para.nCharOfs)
2157             {
2158               /* Insert a newline before the table. */
2159               para = para->member.para.prev_para;
2160               para->member.para.nFlags &= ~MEPF_ROWSTART;
2161               editor->pCursors[0].pPara = para;
2162               editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2163               editor->pCursors[1] = editor->pCursors[0];
2164               ME_InsertTextFromCursor(editor, 0, &endl, 1,
2165                                       editor->pCursors[0].pRun->member.run.style);
2166               para = editor->pBuffer->pFirst->member.para.next_para;
2167               ME_SetDefaultParaFormat(para->member.para.pFmt);
2168               para->member.para.nFlags = MEPF_REWRAP;
2169               editor->pCursors[0].pPara = para;
2170               editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2171               editor->pCursors[1] = editor->pCursors[0];
2172               para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2173               ME_CommitCoalescingUndo(editor);
2174               ME_CheckTablesForCorruption(editor);
2175               ME_UpdateRepaint(editor);
2176               return TRUE;
2177             }
2178           } else { /* v1.0 - 3.0 */
2179             ME_DisplayItem *para = cursor.pPara;
2180             if (ME_IsInTable(para))
2181             {
2182               if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2183               {
2184                 if (from == to) {
2185                   ME_ContinueCoalescingTransaction(editor);
2186                   para = ME_AppendTableRow(editor, para);
2187                   editor->pCursors[0].pPara = para;
2188                   editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2189                   editor->pCursors[0].nOffset = 0;
2190                   editor->pCursors[1] = editor->pCursors[0];
2191                   ME_CommitCoalescingUndo(editor);
2192                   ME_UpdateRepaint(editor);
2193                   return TRUE;
2194                 }
2195               } else {
2196                 ME_ContinueCoalescingTransaction(editor);
2197                 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2198                     !ME_IsInTable(para->member.para.prev_para))
2199                 {
2200                   /* Insert newline before table */
2201                   cursor.pRun = ME_FindItemBack(para, diRun);
2202                   if (cursor.pRun) {
2203                     editor->pCursors[0].pRun = cursor.pRun;
2204                     editor->pCursors[0].pPara = para->member.para.prev_para;
2205                   }
2206                   editor->pCursors[0].nOffset = 0;
2207                   editor->pCursors[1] = editor->pCursors[0];
2208                   ME_InsertTextFromCursor(editor, 0, &endl, 1,
2209                                           editor->pCursors[0].pRun->member.run.style);
2210                 } else {
2211                   editor->pCursors[1] = editor->pCursors[0];
2212                   para = ME_AppendTableRow(editor, para);
2213                   editor->pCursors[0].pPara = para;
2214                   editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2215                   editor->pCursors[0].nOffset = 0;
2216                   editor->pCursors[1] = editor->pCursors[0];
2217                 }
2218                 ME_CommitCoalescingUndo(editor);
2219                 ME_UpdateRepaint(editor);
2220                 return TRUE;
2221               }
2222             }
2223           }
2224
2225           style = ME_GetInsertStyle(editor, 0);
2226           ME_SaveTempStyle(editor);
2227           ME_ContinueCoalescingTransaction(editor);
2228           if (shift_is_down)
2229             ME_InsertEndRowFromCursor(editor, 0);
2230           else
2231             ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2232           ME_ReleaseStyle(style);
2233           ME_CommitCoalescingUndo(editor);
2234           SetCursor(NULL);
2235
2236           ME_UpdateSelectionLinkAttribute(editor);
2237           ME_UpdateRepaint(editor);
2238         }
2239         return TRUE;
2240       }
2241       break;
2242     case 'A':
2243       if (ctrl_is_down)
2244       {
2245         ME_SetSelection(editor, 0, -1);
2246         return TRUE;
2247       }
2248       break;
2249     case 'V':
2250       if (ctrl_is_down)
2251         return ME_Paste(editor);
2252       break;
2253     case 'C':
2254     case 'X':
2255       if (ctrl_is_down)
2256       {
2257         CHARRANGE range;
2258         BOOL result;
2259
2260         ME_GetSelection(editor, &range.cpMin, &range.cpMax);
2261         result = ME_Copy(editor, &range);
2262         if (result && nKey == 'X')
2263         {
2264           ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
2265           ME_CommitUndo(editor);
2266           ME_UpdateRepaint(editor);
2267         }
2268         return result;
2269       }
2270       break;
2271     case 'Z':
2272       if (ctrl_is_down)
2273       {
2274         ME_Undo(editor);
2275         return TRUE;
2276       }
2277       break;
2278     case 'Y':
2279       if (ctrl_is_down)
2280       {
2281         ME_Redo(editor);
2282         return TRUE;
2283       }
2284       break;
2285
2286     default:
2287       if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2288           editor->nUDArrowX = -1;
2289       if (ctrl_is_down)
2290       {
2291         if (nKey == 'W')
2292         {
2293           CHARFORMAT2W chf;
2294           char buf[2048];
2295           chf.cbSize = sizeof(chf);
2296           
2297           ME_GetSelectionCharFormat(editor, &chf);
2298           ME_DumpStyleToBuf(&chf, buf);
2299           MessageBoxA(NULL, buf, "Style dump", MB_OK);
2300         }
2301         if (nKey == 'Q')
2302         {
2303           ME_CheckCharOffsets(editor);
2304         }
2305       }
2306   }
2307   return FALSE;
2308 }
2309
2310 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2311                        LPARAM flags, BOOL unicode)
2312 {
2313   WCHAR wstr;
2314
2315   if (editor->bMouseCaptured)
2316     return 0;
2317
2318   if (unicode)
2319       wstr = (WCHAR)charCode;
2320   else
2321   {
2322       CHAR charA = charCode;
2323       MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2324   }
2325
2326   if (editor->styleFlags & ES_READONLY) {
2327     MessageBeep(MB_ICONERROR);
2328     return 0; /* FIXME really 0 ? */
2329   }
2330
2331   if ((unsigned)wstr >= ' ' || wstr == '\t')
2332   {
2333     ME_Cursor cursor = editor->pCursors[0];
2334     ME_DisplayItem *para = cursor.pPara;
2335     int from, to;
2336     BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2337     ME_GetSelection(editor, &from, &to);
2338     if (wstr == '\t' &&
2339         /* v4.1 allows tabs to be inserted with ctrl key down */
2340         !(ctrl_is_down && !editor->bEmulateVersion10))
2341     {
2342       ME_DisplayItem *para;
2343       BOOL bSelectedRow = FALSE;
2344
2345       para = cursor.pPara;
2346       if (ME_IsSelection(editor) &&
2347           cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2348           to == ME_GetCursorOfs(editor, 0) &&
2349           para->member.para.prev_para->type == diParagraph)
2350       {
2351         para = para->member.para.prev_para;
2352         bSelectedRow = TRUE;
2353       }
2354       if (ME_IsInTable(para))
2355       {
2356         ME_TabPressedInTable(editor, bSelectedRow);
2357         ME_CommitUndo(editor);
2358         return 0;
2359       }
2360     } else if (!editor->bEmulateVersion10) { /* v4.1 */
2361       if (para->member.para.nFlags & MEPF_ROWEND) {
2362         if (from == to) {
2363           para = para->member.para.next_para;
2364           if (para->member.para.nFlags & MEPF_ROWSTART)
2365             para = para->member.para.next_para;
2366           editor->pCursors[0].pPara = para;
2367           editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2368           editor->pCursors[0].nOffset = 0;
2369           editor->pCursors[1] = editor->pCursors[0];
2370         }
2371       }
2372     } else { /* v1.0 - 3.0 */
2373       if (ME_IsInTable(cursor.pRun) &&
2374           cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2375           from == to)
2376       {
2377         /* Text should not be inserted at the end of the table. */
2378         MessageBeep(-1);
2379         return 0;
2380       }
2381     }
2382     /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2383     /* WM_CHAR is restricted to nTextLimit */
2384     if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2385     {
2386       ME_Style *style = ME_GetInsertStyle(editor, 0);
2387       ME_SaveTempStyle(editor);
2388       ME_ContinueCoalescingTransaction(editor);
2389       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2390       ME_ReleaseStyle(style);
2391       ME_CommitCoalescingUndo(editor);
2392       ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2393     }
2394
2395     ME_UpdateSelectionLinkAttribute(editor);
2396     ME_UpdateRepaint(editor);
2397   }
2398   return 0;
2399 }
2400
2401 /* Process the message and calculate the new click count.
2402  *
2403  * returns: The click count if it is mouse down event, else returns 0. */
2404 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2405                                   LPARAM lParam)
2406 {
2407     static int clickNum = 0;
2408     if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2409         return 0;
2410
2411     if ((msg == WM_LBUTTONDBLCLK) ||
2412         (msg == WM_RBUTTONDBLCLK) ||
2413         (msg == WM_MBUTTONDBLCLK) ||
2414         (msg == WM_XBUTTONDBLCLK))
2415     {
2416         msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2417     }
2418
2419     if ((msg == WM_LBUTTONDOWN) ||
2420         (msg == WM_RBUTTONDOWN) ||
2421         (msg == WM_MBUTTONDOWN) ||
2422         (msg == WM_XBUTTONDOWN))
2423     {
2424         static MSG prevClickMsg;
2425         MSG clickMsg;
2426         /* Compare the editor instead of the hwnd so that the this
2427          * can still be done for windowless richedit controls. */
2428         clickMsg.hwnd = (HWND)editor;
2429         clickMsg.message = msg;
2430         clickMsg.wParam = wParam;
2431         clickMsg.lParam = lParam;
2432         clickMsg.time = GetMessageTime();
2433         clickMsg.pt.x = (short)LOWORD(lParam);
2434         clickMsg.pt.y = (short)HIWORD(lParam);
2435         if ((clickNum != 0) &&
2436             (clickMsg.message == prevClickMsg.message) &&
2437             (clickMsg.hwnd == prevClickMsg.hwnd) &&
2438             (clickMsg.wParam == prevClickMsg.wParam) &&
2439             (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2440             (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2441             (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2442         {
2443             clickNum++;
2444         } else {
2445             clickNum = 1;
2446         }
2447         prevClickMsg = clickMsg;
2448     } else {
2449         return 0;
2450     }
2451     return clickNum;
2452 }
2453
2454 static BOOL ME_SetCursor(ME_TextEditor *editor)
2455 {
2456   POINT pt;
2457   BOOL isExact;
2458   int offset;
2459   SCROLLBARINFO sbi;
2460   DWORD messagePos = GetMessagePos();
2461   pt.x = (short)LOWORD(messagePos);
2462   pt.y = (short)HIWORD(messagePos);
2463
2464   if (editor->hWnd)
2465   {
2466     sbi.cbSize = sizeof(sbi);
2467     GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2468     if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2469         PtInRect(&sbi.rcScrollBar, pt))
2470     {
2471         ITextHost_TxSetCursor(editor->texthost,
2472                               LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2473         return TRUE;
2474     }
2475     sbi.cbSize = sizeof(sbi);
2476     GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2477     if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2478         PtInRect(&sbi.rcScrollBar, pt))
2479     {
2480         ITextHost_TxSetCursor(editor->texthost,
2481                               LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2482         return TRUE;
2483     }
2484   }
2485   ITextHost_TxScreenToClient(editor->texthost, &pt);
2486
2487   if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2488       ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2489       return TRUE;
2490   }
2491   if (!editor->bEmulateVersion10 /* v4.1 */ &&
2492       pt.y < editor->rcFormat.top &&
2493       pt.x < editor->rcFormat.left)
2494   {
2495       ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2496       return TRUE;
2497   }
2498   if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2499   {
2500       if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2501           ITextHost_TxSetCursor(editor->texthost,
2502                                 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2503       else /* v4.1 */
2504           ITextHost_TxSetCursor(editor->texthost,
2505                                 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2506       return TRUE;
2507   }
2508   if (pt.x < editor->rcFormat.left)
2509   {
2510       ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2511       return TRUE;
2512   }
2513   offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
2514   if (isExact)
2515   {
2516       ME_Cursor cursor;
2517       ME_Run *run;
2518
2519       ME_CursorFromCharOfs(editor, offset, &cursor);
2520       run = &cursor.pRun->member.run;
2521       if (run->style->fmt.dwMask & CFM_LINK &&
2522           run->style->fmt.dwEffects & CFE_LINK)
2523       {
2524           ITextHost_TxSetCursor(editor->texthost,
2525                                 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2526                                 FALSE);
2527           return TRUE;
2528       }
2529
2530       if (ME_IsSelection(editor))
2531       {
2532           int selStart, selEnd;
2533           ME_GetSelection(editor, &selStart, &selEnd);
2534           if (selStart <= offset && selEnd >= offset) {
2535               ITextHost_TxSetCursor(editor->texthost,
2536                                     LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2537                                     FALSE);
2538               return TRUE;
2539           }
2540       }
2541   }
2542   ITextHost_TxSetCursor(editor->texthost,
2543                         LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2544   return TRUE;
2545 }
2546
2547 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2548 {
2549   ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2550   editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2551   editor->rcFormat.left += 1 + editor->selofs;
2552   editor->rcFormat.right -= 1;
2553 }
2554
2555 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2556 {
2557   CHARRANGE selrange;
2558   HMENU menu;
2559   int seltype = 0;
2560   if(!editor->lpOleCallback || !editor->hWnd)
2561     return FALSE;
2562   ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
2563   if(selrange.cpMin == selrange.cpMax)
2564     seltype |= SEL_EMPTY;
2565   else
2566   {
2567     /* FIXME: Handle objects */
2568     seltype |= SEL_TEXT;
2569     if(selrange.cpMax-selrange.cpMin > 1)
2570       seltype |= SEL_MULTICHAR;
2571   }
2572   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2573   {
2574     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
2575     DestroyMenu(menu);
2576   }
2577   return TRUE;
2578 }
2579
2580 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2581 {
2582   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2583   int i;
2584   DWORD props;
2585   LONG selbarwidth;
2586
2587   ed->hWnd = NULL;
2588   ed->texthost = texthost;
2589   ed->bEmulateVersion10 = bEmulateVersion10;
2590   ITextHost_TxGetPropertyBits(texthost,
2591                               (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2592                                TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2593                                TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2594                                TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2595                                TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2596                               &props);
2597   ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2598   ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2599                      ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2600   ed->pBuffer = ME_MakeText();
2601   ed->nZoomNumerator = ed->nZoomDenominator = 0;
2602   ME_MakeFirstParagraph(ed);
2603   /* The four cursors are for:
2604    * 0 - The position where the caret is shown
2605    * 1 - The anchored end of the selection (for normal selection)
2606    * 2 & 3 - The anchored start and end respectively for word, line,
2607    * or paragraph selection.
2608    */
2609   ed->nCursors = 4;
2610   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2611   ed->pCursors[0].pPara = ed->pBuffer->pFirst->member.para.next_para;
2612   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pCursors[0].pPara, diRun);
2613   ed->pCursors[0].nOffset = 0;
2614   ed->pCursors[1] = ed->pCursors[0];
2615   ed->pCursors[2] = ed->pCursors[0];
2616   ed->pCursors[3] = ed->pCursors[1];
2617   ed->nLastTotalLength = ed->nTotalLength = 0;
2618   ed->nLastTotalWidth = ed->nTotalWidth = 0;
2619   ed->nUDArrowX = -1;
2620   ed->nSequence = 0;
2621   ed->rgbBackColor = -1;
2622   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2623   ed->bCaretAtEnd = FALSE;
2624   ed->nEventMask = 0;
2625   ed->nModifyStep = 0;
2626   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2627   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2628   ed->nUndoStackSize = 0;
2629   ed->nUndoLimit = STACK_SIZE_DEFAULT;
2630   ed->nUndoMode = umAddToUndo;
2631   ed->nParagraphs = 1;
2632   ed->nLastSelStart = ed->nLastSelEnd = 0;
2633   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
2634   ed->nAvailWidth = 0; /* wrap to client area */
2635   ed->bHideSelection = FALSE;
2636   ed->pfnWordBreak = NULL;
2637   ed->lpOleCallback = NULL;
2638   ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2639   ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2640   ed->AutoURLDetect_bEnable = FALSE;
2641   ed->bHaveFocus = FALSE;
2642   ed->bMouseCaptured = FALSE;
2643   for (i=0; i<HFONT_CACHE_SIZE; i++)
2644   {
2645     ed->pFontCache[i].nRefs = 0;
2646     ed->pFontCache[i].nAge = 0;
2647     ed->pFontCache[i].hFont = NULL;
2648   }
2649
2650   ME_CheckCharOffsets(ed);
2651   ed->bDefaultFormatRect = TRUE;
2652   ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2653   if (selbarwidth) {
2654     /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2655     ed->selofs = SELECTIONBAR_WIDTH;
2656     ed->styleFlags |= ES_SELECTIONBAR;
2657   } else {
2658     ed->selofs = 0;
2659   }
2660   ed->nSelectionType = stPosition;
2661
2662   ed->cPasswordMask = 0;
2663   if (props & TXTBIT_USEPASSWORD)
2664     ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2665
2666   if (props & TXTBIT_AUTOWORDSEL)
2667     ed->styleFlags |= ECO_AUTOWORDSELECTION;
2668   if (props & TXTBIT_MULTILINE) {
2669     ed->styleFlags |= ES_MULTILINE;
2670     ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2671   } else {
2672     ed->bWordWrap = FALSE;
2673   }
2674   if (props & TXTBIT_READONLY)
2675     ed->styleFlags |= ES_READONLY;
2676   if (!(props & TXTBIT_HIDESELECTION))
2677     ed->styleFlags |= ES_NOHIDESEL;
2678   if (props & TXTBIT_SAVESELECTION)
2679     ed->styleFlags |= ES_SAVESEL;
2680   if (props & TXTBIT_VERTICAL)
2681     ed->styleFlags |= ES_VERTICAL;
2682   if (props & TXTBIT_DISABLEDRAG)
2683     ed->styleFlags |= ES_NOOLEDRAGDROP;
2684
2685   ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2686
2687   /* Default scrollbar information */
2688   ed->vert_si.cbSize = sizeof(SCROLLINFO);
2689   ed->vert_si.nMin = 0;
2690   ed->vert_si.nMax = 0;
2691   ed->vert_si.nPage = 0;
2692   ed->vert_si.nPos = 0;
2693
2694   ed->horz_si.cbSize = sizeof(SCROLLINFO);
2695   ed->horz_si.nMin = 0;
2696   ed->horz_si.nMax = 0;
2697   ed->horz_si.nPage = 0;
2698   ed->horz_si.nPos = 0;
2699
2700   OleInitialize(NULL);
2701
2702   return ed;
2703 }
2704
2705 static void ME_DestroyEditor(ME_TextEditor *editor)
2706 {
2707   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2708   ME_DisplayItem *p = pFirst, *pNext = NULL;
2709   int i;
2710
2711   ME_ClearTempStyle(editor);
2712   ME_EmptyUndoStack(editor);
2713   while(p) {
2714     pNext = p->next;
2715     ME_DestroyDisplayItem(p);
2716     p = pNext;
2717   }
2718   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2719   for (i=0; i<HFONT_CACHE_SIZE; i++)
2720   {
2721     if (editor->pFontCache[i].hFont)
2722       DeleteObject(editor->pFontCache[i].hFont);
2723   }
2724   if (editor->rgbBackColor != -1)
2725     DeleteObject(editor->hbrBackground);
2726   if(editor->lpOleCallback)
2727     IUnknown_Release(editor->lpOleCallback);
2728   IUnknown_Release(editor->texthost);
2729   OleUninitialize();
2730
2731   FREE_OBJ(editor->pBuffer);
2732   FREE_OBJ(editor->pCursors);
2733
2734   FREE_OBJ(editor);
2735 }
2736
2737 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2738 {
2739     TRACE("\n");
2740     switch (fdwReason)
2741     {
2742     case DLL_PROCESS_ATTACH:
2743       DisableThreadLibraryCalls(hinstDLL);
2744       me_heap = HeapCreate (0, 0x10000, 0);
2745       if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2746       hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2747       LookupInit();
2748       break;
2749
2750     case DLL_PROCESS_DETACH:
2751       UnregisterClassW(RichEdit20W, 0);
2752       UnregisterClassW(RichEdit50W, 0);
2753       UnregisterClassA("RichEdit20A", 0);
2754       UnregisterClassA("RichEdit50A", 0);
2755       if (ME_ListBoxRegistered)
2756           UnregisterClassW(REListBox20W, 0);
2757       if (ME_ComboBoxRegistered)
2758           UnregisterClassW(REComboBox20W, 0);
2759       LookupCleanup();
2760       HeapDestroy (me_heap);
2761       me_heap = NULL;
2762       break;
2763     }
2764     return TRUE;
2765 }
2766
2767
2768 static const char * const edit_messages[] = {
2769   "EM_GETSEL",
2770   "EM_SETSEL",
2771   "EM_GETRECT",
2772   "EM_SETRECT",
2773   "EM_SETRECTNP",
2774   "EM_SCROLL",
2775   "EM_LINESCROLL",
2776   "EM_SCROLLCARET",
2777   "EM_GETMODIFY",
2778   "EM_SETMODIFY",
2779   "EM_GETLINECOUNT",
2780   "EM_LINEINDEX",
2781   "EM_SETHANDLE",
2782   "EM_GETHANDLE",
2783   "EM_GETTHUMB",
2784   "EM_UNKNOWN_BF",
2785   "EM_UNKNOWN_C0",
2786   "EM_LINELENGTH",
2787   "EM_REPLACESEL",
2788   "EM_UNKNOWN_C3",
2789   "EM_GETLINE",
2790   "EM_LIMITTEXT",
2791   "EM_CANUNDO",
2792   "EM_UNDO",
2793   "EM_FMTLINES",
2794   "EM_LINEFROMCHAR",
2795   "EM_UNKNOWN_CA",
2796   "EM_SETTABSTOPS",
2797   "EM_SETPASSWORDCHAR",
2798   "EM_EMPTYUNDOBUFFER",
2799   "EM_GETFIRSTVISIBLELINE",
2800   "EM_SETREADONLY",
2801   "EM_SETWORDBREAKPROC",
2802   "EM_GETWORDBREAKPROC",
2803   "EM_GETPASSWORDCHAR",
2804   "EM_SETMARGINS",
2805   "EM_GETMARGINS",
2806   "EM_GETLIMITTEXT",
2807   "EM_POSFROMCHAR",
2808   "EM_CHARFROMPOS",
2809   "EM_SETIMESTATUS",
2810   "EM_GETIMESTATUS"
2811 };
2812
2813 static const char * const richedit_messages[] = {
2814   "EM_CANPASTE",
2815   "EM_DISPLAYBAND",
2816   "EM_EXGETSEL",
2817   "EM_EXLIMITTEXT",
2818   "EM_EXLINEFROMCHAR",
2819   "EM_EXSETSEL",
2820   "EM_FINDTEXT",
2821   "EM_FORMATRANGE",
2822   "EM_GETCHARFORMAT",
2823   "EM_GETEVENTMASK",
2824   "EM_GETOLEINTERFACE",
2825   "EM_GETPARAFORMAT",
2826   "EM_GETSELTEXT",
2827   "EM_HIDESELECTION", 
2828   "EM_PASTESPECIAL",
2829   "EM_REQUESTRESIZE",
2830   "EM_SELECTIONTYPE",
2831   "EM_SETBKGNDCOLOR",
2832   "EM_SETCHARFORMAT",
2833   "EM_SETEVENTMASK",
2834   "EM_SETOLECALLBACK",
2835   "EM_SETPARAFORMAT",
2836   "EM_SETTARGETDEVICE",
2837   "EM_STREAMIN",
2838   "EM_STREAMOUT",
2839   "EM_GETTEXTRANGE",
2840   "EM_FINDWORDBREAK",
2841   "EM_SETOPTIONS",
2842   "EM_GETOPTIONS",
2843   "EM_FINDTEXTEX",
2844   "EM_GETWORDBREAKPROCEX",
2845   "EM_SETWORDBREAKPROCEX",
2846   "EM_SETUNDOLIMIT",
2847   "EM_UNKNOWN_USER_83",
2848   "EM_REDO",
2849   "EM_CANREDO",
2850   "EM_GETUNDONAME",
2851   "EM_GETREDONAME",
2852   "EM_STOPGROUPTYPING",
2853   "EM_SETTEXTMODE",
2854   "EM_GETTEXTMODE",
2855   "EM_AUTOURLDETECT",
2856   "EM_GETAUTOURLDETECT",
2857   "EM_SETPALETTE",
2858   "EM_GETTEXTEX",
2859   "EM_GETTEXTLENGTHEX",
2860   "EM_SHOWSCROLLBAR",
2861   "EM_SETTEXTEX",
2862   "EM_UNKNOWN_USER_98",
2863   "EM_UNKNOWN_USER_99",
2864   "EM_SETPUNCTUATION",
2865   "EM_GETPUNCTUATION",
2866   "EM_SETWORDWRAPMODE",
2867   "EM_GETWORDWRAPMODE",
2868   "EM_SETIMECOLOR",
2869   "EM_GETIMECOLOR",
2870   "EM_SETIMEOPTIONS",
2871   "EM_GETIMEOPTIONS",
2872   "EM_CONVPOSITION",
2873   "EM_UNKNOWN_USER_109",
2874   "EM_UNKNOWN_USER_110",
2875   "EM_UNKNOWN_USER_111",
2876   "EM_UNKNOWN_USER_112",
2877   "EM_UNKNOWN_USER_113",
2878   "EM_UNKNOWN_USER_114",
2879   "EM_UNKNOWN_USER_115",
2880   "EM_UNKNOWN_USER_116",
2881   "EM_UNKNOWN_USER_117",
2882   "EM_UNKNOWN_USER_118",
2883   "EM_UNKNOWN_USER_119",
2884   "EM_SETLANGOPTIONS",
2885   "EM_GETLANGOPTIONS",
2886   "EM_GETIMECOMPMODE",
2887   "EM_FINDTEXTW",
2888   "EM_FINDTEXTEXW",
2889   "EM_RECONVERSION",
2890   "EM_SETIMEMODEBIAS",
2891   "EM_GETIMEMODEBIAS"
2892 };
2893
2894 static const char *
2895 get_msg_name(UINT msg)
2896 {
2897   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2898     return edit_messages[msg - EM_GETSEL];
2899   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2900     return richedit_messages[msg - EM_CANPASTE];
2901   return "";
2902 }
2903
2904 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2905 {
2906   int x,y;
2907   ME_DisplayItem *para, *run;
2908   BOOL isExact;
2909   int nCharOfs; /* The start of the clicked text. Absolute character offset */
2910
2911   ENLINK info;
2912   x = (short)LOWORD(lParam);
2913   y = (short)HIWORD(lParam);
2914   nCharOfs = ME_CharFromPos(editor, x, y, &isExact);
2915   if (!isExact) return;
2916
2917   ME_RunOfsFromCharOfs(editor, nCharOfs, &para, &run, NULL);
2918
2919   if ((run->member.run.style->fmt.dwMask & CFM_LINK)
2920     && (run->member.run.style->fmt.dwEffects & CFE_LINK))
2921   { /* The clicked run has CFE_LINK set */
2922     info.nmhdr.hwndFrom = editor->hWnd;
2923     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2924     info.nmhdr.code = EN_LINK;
2925     info.msg = msg;
2926     info.wParam = wParam;
2927     info.lParam = lParam;
2928     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor, para, run, 0);
2929     info.chrg.cpMax = info.chrg.cpMin + run->member.run.strText->nLen;
2930     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
2931   }
2932 }
2933
2934 #define UNSUPPORTED_MSG(e) \
2935   case e:                  \
2936     FIXME(#e ": stub\n");  \
2937     *phresult = S_FALSE;   \
2938     return 0;
2939
2940 /* Handle messages for windowless and windoweded richedit controls.
2941  *
2942  * The LRESULT that is returned is a return value for window procs,
2943  * and the phresult parameter is the COM return code needed by the
2944  * text services interface. */
2945 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2946                          LPARAM lParam, BOOL unicode, HRESULT* phresult)
2947 {
2948   *phresult = S_OK;
2949
2950   switch(msg) {
2951
2952   UNSUPPORTED_MSG(EM_DISPLAYBAND)
2953   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2954   UNSUPPORTED_MSG(EM_FMTLINES)
2955   UNSUPPORTED_MSG(EM_FORMATRANGE)
2956   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2957   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2958   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2959   UNSUPPORTED_MSG(EM_GETIMESTATUS)
2960   UNSUPPORTED_MSG(EM_SETIMESTATUS)
2961   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2962   UNSUPPORTED_MSG(EM_GETREDONAME)
2963   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2964   UNSUPPORTED_MSG(EM_GETUNDONAME)
2965   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2966   UNSUPPORTED_MSG(EM_PASTESPECIAL)
2967   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2968   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2969   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2970   UNSUPPORTED_MSG(EM_SETFONTSIZE)
2971   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2972   UNSUPPORTED_MSG(EM_SETMARGINS)
2973   UNSUPPORTED_MSG(EM_SETPALETTE)
2974   UNSUPPORTED_MSG(EM_SETTABSTOPS)
2975   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2976   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2977   UNSUPPORTED_MSG(WM_STYLECHANGING)
2978   UNSUPPORTED_MSG(WM_STYLECHANGED)
2979
2980 /* Messages specific to Richedit controls */
2981
2982   case EM_STREAMIN:
2983    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2984   case EM_STREAMOUT:
2985    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2986   case WM_GETDLGCODE:
2987   {
2988     UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
2989     if (editor->styleFlags & ES_MULTILINE)
2990       code |= DLGC_WANTMESSAGE;
2991     return code;
2992   }
2993   case EM_EMPTYUNDOBUFFER:
2994     ME_EmptyUndoStack(editor);
2995     return 0;
2996   case EM_GETSEL:
2997   {
2998     /* Note: wParam/lParam can be NULL */
2999     UINT from, to;
3000     PUINT pfrom = wParam ? (PUINT)wParam : &from;
3001     PUINT pto = lParam ? (PUINT)lParam : &to;
3002     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
3003     if ((*pfrom|*pto) & 0xFFFF0000)
3004       return -1;
3005     return MAKELONG(*pfrom,*pto);
3006   }
3007   case EM_EXGETSEL:
3008   {
3009     CHARRANGE *pRange = (CHARRANGE *)lParam;
3010     ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
3011     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3012     return 0;
3013   }
3014   case EM_SETUNDOLIMIT:
3015   {
3016     if ((int)wParam < 0)
3017       editor->nUndoLimit = STACK_SIZE_DEFAULT;
3018     else
3019       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3020     /* Setting a max stack size keeps wine from getting killed 
3021       for hogging memory. Windows allocates all this memory at once, so
3022       no program would realistically set a value above our maximum. */
3023     return editor->nUndoLimit;
3024   }
3025   case EM_CANUNDO:
3026     return editor->pUndoStack != NULL;
3027   case EM_CANREDO:
3028     return editor->pRedoStack != NULL;
3029   case WM_UNDO: /* FIXME: actually not the same */
3030   case EM_UNDO:
3031     return ME_Undo(editor);
3032   case EM_REDO:
3033     return ME_Redo(editor);
3034   case EM_GETOPTIONS:
3035   {
3036     /* these flags are equivalent to the ES_* counterparts */
3037     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3038                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3039     DWORD settings = editor->styleFlags & mask;
3040
3041     return settings;
3042   }
3043   case EM_SETOPTIONS:
3044   {
3045     /* these flags are equivalent to ES_* counterparts, except for
3046      * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3047      * but is still stored in editor->styleFlags. */
3048     const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3049                        ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3050                        ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3051     DWORD settings = mask & editor->styleFlags;
3052     DWORD oldSettings = settings;
3053     DWORD changedSettings;
3054
3055     switch(wParam)
3056     {
3057       case ECOOP_SET:
3058         settings = lParam;
3059         break;
3060       case ECOOP_OR:
3061         settings |= lParam;
3062         break;
3063       case ECOOP_AND:
3064         settings &= lParam;
3065         break;
3066       case ECOOP_XOR:
3067         settings ^= lParam;
3068     }
3069     changedSettings = oldSettings ^ settings;
3070
3071     if (changedSettings) {
3072       editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3073
3074       if (changedSettings & ECO_SELECTIONBAR)
3075       {
3076         ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3077         if (settings & ECO_SELECTIONBAR) {
3078           assert(!editor->selofs);
3079           editor->selofs = SELECTIONBAR_WIDTH;
3080           editor->rcFormat.left += editor->selofs;
3081         } else {
3082           editor->rcFormat.left -= editor->selofs;
3083           editor->selofs = 0;
3084         }
3085         ME_RewrapRepaint(editor);
3086       }
3087
3088       if (changedSettings & settings & ECO_VERTICAL)
3089         FIXME("ECO_VERTICAL not implemented yet!\n");
3090       if (changedSettings & settings & ECO_AUTOHSCROLL)
3091         FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3092       if (changedSettings & settings & ECO_AUTOVSCROLL)
3093         FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3094       if (changedSettings & settings & ECO_NOHIDESEL)
3095         FIXME("ECO_NOHIDESEL not implemented yet!\n");
3096       if (changedSettings & settings & ECO_WANTRETURN)
3097         FIXME("ECO_WANTRETURN not implemented yet!\n");
3098       if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3099         FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3100     }
3101
3102     return settings;
3103   }
3104   case EM_SETSEL:
3105   {
3106     ME_InvalidateSelection(editor);
3107     ME_SetSelection(editor, wParam, lParam);
3108     ME_InvalidateSelection(editor);
3109     ITextHost_TxShowCaret(editor->texthost, FALSE);
3110     ME_ShowCaret(editor);
3111     ME_SendSelChange(editor);
3112     return 0;
3113   }
3114   case EM_SETSCROLLPOS:
3115   {
3116     POINT *point = (POINT *)lParam;
3117     ME_ScrollAbs(editor, point->x, point->y);
3118     return 0;
3119   }
3120   case EM_AUTOURLDETECT:
3121   {
3122     if (wParam==1 || wParam ==0)
3123     {
3124         editor->AutoURLDetect_bEnable = (BOOL)wParam;
3125         return 0;
3126     }
3127     return E_INVALIDARG;
3128   }
3129   case EM_GETAUTOURLDETECT:
3130   {
3131     return editor->AutoURLDetect_bEnable;
3132   }
3133   case EM_EXSETSEL:
3134   {
3135     int end;
3136     CHARRANGE range = *(CHARRANGE *)lParam;
3137
3138     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3139
3140     ME_InvalidateSelection(editor);
3141     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3142     ME_InvalidateSelection(editor);
3143     ITextHost_TxShowCaret(editor->texthost, FALSE);
3144     ME_ShowCaret(editor);
3145     ME_SendSelChange(editor);
3146
3147     return end;
3148   }
3149   case EM_SHOWSCROLLBAR:
3150   {
3151     DWORD flags;
3152
3153     switch (wParam)
3154     {
3155       case SB_HORZ:
3156         flags = WS_HSCROLL;
3157         break;
3158       case SB_VERT:
3159         flags = WS_VSCROLL;
3160         break;
3161       case SB_BOTH:
3162         flags = WS_HSCROLL|WS_VSCROLL;
3163         break;
3164       default:
3165         return 0;
3166     }
3167
3168     if (lParam) {
3169       editor->styleFlags |= flags;
3170       if (flags & WS_HSCROLL)
3171         ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3172                           editor->nTotalWidth > editor->sizeWindow.cx);
3173       if (flags & WS_VSCROLL)
3174         ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3175                           editor->nTotalLength > editor->sizeWindow.cy);
3176     } else {
3177       editor->styleFlags &= ~flags;
3178       ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3179     }
3180     return 0;
3181   }
3182   case EM_SETTEXTEX:
3183   {
3184     LPWSTR wszText;
3185     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3186     size_t len = 0;
3187     int from, to;
3188     ME_Style *style;
3189     BOOL bRtf, bUnicode, bSelection;
3190     int oldModify = editor->nModifyStep;
3191
3192     if (!pStruct) return 0;
3193
3194     /* If we detect ascii rtf at the start of the string,
3195      * we know it isn't unicode. */
3196     bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3197                          !strncmp((char *)lParam, "{\\urtf}", 6)));
3198     bUnicode = !bRtf && pStruct->codepage == 1200;
3199
3200     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3201           bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3202           pStruct->flags, pStruct->codepage);
3203
3204     bSelection = (pStruct->flags & ST_SELECTION) != 0;
3205     if (bSelection) {
3206       ME_GetSelection(editor, &from, &to);
3207       style = ME_GetSelectionInsertStyle(editor);
3208       ME_InternalDeleteText(editor, from, to - from, FALSE);
3209     } else {
3210       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
3211       style = editor->pBuffer->pDefaultStyle;
3212     }
3213
3214     if (bRtf) {
3215       ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3216       if (bSelection) {
3217         /* FIXME: The length returned is doesn't include the rtf control
3218          * characters, only the actual text. */
3219         len = lParam ? strlen((char *)lParam) : 0;
3220       }
3221     } else {
3222       /* FIXME: make use of pStruct->codepage in the to unicode translation */
3223       wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3224       len = wszText ? lstrlenW(wszText) : 0;
3225       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3226     }
3227
3228     if (bSelection) {
3229       ME_ReleaseStyle(style);
3230       ME_UpdateSelectionLinkAttribute(editor);
3231     } else {
3232       len = 1;
3233       ME_UpdateLinkAttribute(editor, 0, -1);
3234     }
3235     ME_CommitUndo(editor);
3236     if (!(pStruct->flags & ST_KEEPUNDO))
3237     {
3238       editor->nModifyStep = oldModify;
3239       ME_EmptyUndoStack(editor);
3240     }
3241     ME_UpdateRepaint(editor);
3242     return len;
3243   }
3244   case EM_SETBKGNDCOLOR:
3245   {
3246     LRESULT lColor;
3247     if (editor->rgbBackColor != -1) {
3248       DeleteObject(editor->hbrBackground);
3249       lColor = editor->rgbBackColor;
3250     }
3251     else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3252
3253     if (wParam)
3254     {
3255       editor->rgbBackColor = -1;
3256       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3257     }
3258     else
3259     {
3260       editor->rgbBackColor = lParam;
3261       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3262     }
3263     ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3264     ITextHost_TxViewChange(editor->texthost, TRUE);
3265     return lColor;
3266   }
3267   case EM_GETMODIFY:
3268     return editor->nModifyStep == 0 ? 0 : -1;
3269   case EM_SETMODIFY:
3270   {
3271     if (wParam)
3272       editor->nModifyStep = 1;
3273     else
3274       editor->nModifyStep = 0;
3275     
3276     return 0;
3277   }
3278   case EM_SETREADONLY:
3279   {
3280     if (wParam)
3281       editor->styleFlags |= ES_READONLY;
3282     else
3283       editor->styleFlags &= ~ES_READONLY;
3284     return 0;
3285   }
3286   case EM_SETEVENTMASK:
3287   {
3288     DWORD nOldMask = editor->nEventMask;
3289     
3290     editor->nEventMask = lParam;
3291     return nOldMask;
3292   }
3293   case EM_GETEVENTMASK:
3294     return editor->nEventMask;
3295   case EM_SETCHARFORMAT:
3296   {
3297     CHARFORMAT2W buf, *p;
3298     BOOL bRepaint = TRUE;
3299     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3300     if (p == NULL) return 0;
3301     if (!wParam)
3302       ME_SetDefaultCharFormat(editor, p);
3303     else if (wParam == (SCF_WORD | SCF_SELECTION)) {
3304       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3305       return 0;
3306     } else if (wParam == SCF_ALL) {
3307       if (editor->mode & TM_PLAINTEXT)
3308         ME_SetDefaultCharFormat(editor, p);
3309       else {
3310         ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
3311         editor->nModifyStep = 1;
3312       }
3313     } else if (editor->mode & TM_PLAINTEXT) {
3314       return 0;
3315     } else {
3316       int from, to;
3317       ME_GetSelection(editor, &from, &to);
3318       bRepaint = (from != to);
3319       ME_SetSelectionCharFormat(editor, p);
3320       if (from != to) editor->nModifyStep = 1;
3321     }
3322     ME_CommitUndo(editor);
3323     if (bRepaint)
3324     {
3325       ME_WrapMarkedParagraphs(editor);
3326       ME_UpdateScrollBar(editor);
3327       ME_Repaint(editor);
3328     }
3329     return 1;
3330   }
3331   case EM_GETCHARFORMAT:
3332   {
3333     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3334     if (dst->cbSize != sizeof(CHARFORMATA) &&
3335         dst->cbSize != sizeof(CHARFORMATW) &&
3336         dst->cbSize != sizeof(CHARFORMAT2A) &&
3337         dst->cbSize != sizeof(CHARFORMAT2W))
3338       return 0;
3339     tmp.cbSize = sizeof(tmp);
3340     if (!wParam)
3341       ME_GetDefaultCharFormat(editor, &tmp);
3342     else
3343       ME_GetSelectionCharFormat(editor, &tmp);
3344     ME_CopyToCFAny(dst, &tmp);
3345     return tmp.dwMask;
3346   }
3347   case EM_SETPARAFORMAT:
3348   {
3349     BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3350     ME_WrapMarkedParagraphs(editor);
3351     ME_UpdateScrollBar(editor);
3352     ME_Repaint(editor);
3353     ME_CommitUndo(editor);
3354     return result;
3355   }
3356   case EM_GETPARAFORMAT:
3357     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3358     return ((PARAFORMAT2 *)lParam)->dwMask;
3359   case EM_GETFIRSTVISIBLELINE:
3360   {
3361     ME_DisplayItem *p = editor->pBuffer->pFirst;
3362     int y = editor->vert_si.nPos;
3363     int ypara = 0;
3364     int count = 0;
3365     int ystart, yend;
3366     while(p) {
3367       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3368       if (p->type == diTextEnd)
3369         break;
3370       if (p->type == diParagraph) {
3371         ypara = p->member.para.pt.y;
3372         continue;
3373       }
3374       ystart = ypara + p->member.row.pt.y;
3375       yend = ystart + p->member.row.nHeight;
3376       if (y < yend) {
3377         break;
3378       }
3379       count++;
3380     }
3381     return count;
3382   }
3383   case EM_HIDESELECTION:
3384   {
3385      editor->bHideSelection = (wParam != 0);
3386      ME_InvalidateSelection(editor);
3387      return 0;
3388   }
3389   case EM_LINESCROLL:
3390   {
3391     if (!(editor->styleFlags & ES_MULTILINE))
3392       return FALSE;
3393     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3394     return TRUE;
3395   }
3396   case WM_CLEAR:
3397   {
3398     int from, to;
3399     ME_GetSelection(editor, &from, &to);
3400     ME_InternalDeleteText(editor, from, to-from, FALSE);
3401     ME_CommitUndo(editor);
3402     ME_UpdateRepaint(editor);
3403     return 0;
3404   }
3405   case EM_REPLACESEL:
3406   {
3407     int from, to;
3408     ME_Style *style;
3409     LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3410     size_t len = wszText ? lstrlenW(wszText) : 0;
3411     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3412
3413     ME_GetSelection(editor, &from, &to);
3414     style = ME_GetSelectionInsertStyle(editor);
3415     ME_InternalDeleteText(editor, from, to-from, FALSE);
3416     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3417     ME_ReleaseStyle(style);
3418     /* drop temporary style if line end */
3419     /*
3420      * FIXME question: does abc\n mean: put abc,
3421      * clear temp style, put \n? (would require a change)
3422      */
3423     if (len>0 && wszText[len-1] == '\n')
3424       ME_ClearTempStyle(editor);
3425     ME_EndToUnicode(unicode, wszText);
3426     ME_CommitUndo(editor);
3427     ME_UpdateSelectionLinkAttribute(editor);
3428     if (!wParam)
3429       ME_EmptyUndoStack(editor);
3430     ME_UpdateRepaint(editor);
3431     return len;
3432   }
3433   case EM_SCROLLCARET:
3434     ME_EnsureVisible(editor, &editor->pCursors[0]);
3435     return 0;
3436   case WM_SETFONT:
3437   {
3438     LOGFONTW lf;
3439     CHARFORMAT2W fmt;
3440     HDC hDC;
3441     BOOL bRepaint = LOWORD(lParam);
3442
3443     if (!wParam)
3444       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
3445     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3446     hDC = ITextHost_TxGetDC(editor->texthost);
3447     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
3448     ITextHost_TxReleaseDC(editor->texthost, hDC);
3449     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
3450     ME_SetDefaultCharFormat(editor, &fmt);
3451
3452     ME_CommitUndo(editor);
3453     ME_MarkAllForWrapping(editor);
3454     ME_WrapMarkedParagraphs(editor);
3455     ME_UpdateScrollBar(editor);
3456     if (bRepaint)
3457       ME_Repaint(editor);
3458     return 0;
3459   }
3460   case WM_SETTEXT:
3461   {
3462     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
3463     if (lParam)
3464     {
3465       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3466       if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
3467       {
3468         /* Undocumented: WM_SETTEXT supports RTF text */
3469         ME_StreamInRTFString(editor, 0, (char *)lParam);
3470       }
3471       else
3472       {
3473         LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3474         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3475         if (lstrlenW(wszText) > 0)
3476         {
3477           int len = -1;
3478
3479           /* uses default style! */
3480           if (!(editor->styleFlags & ES_MULTILINE))
3481           {
3482             WCHAR * p;
3483
3484             p = wszText;
3485             while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3486             len = p - wszText;
3487           }
3488           ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3489         }
3490         ME_EndToUnicode(unicode, wszText);
3491       }
3492     }
3493     else
3494       TRACE("WM_SETTEXT - NULL\n");
3495     ME_UpdateLinkAttribute(editor, 0, -1);
3496     ME_SetSelection(editor, 0, 0);
3497     editor->nModifyStep = 0;
3498     ME_CommitUndo(editor);
3499     ME_EmptyUndoStack(editor);
3500     ME_UpdateRepaint(editor);
3501     return 1;
3502   }
3503   case EM_CANPASTE:
3504   {
3505     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3506     if (IsClipboardFormatAvailable(nRTFFormat))
3507       return TRUE;
3508     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3509       return TRUE;
3510     return FALSE;
3511   }
3512   case WM_PASTE:
3513     ME_Paste(editor);
3514     return 0;
3515   case WM_CUT:
3516   case WM_COPY:
3517   {
3518     CHARRANGE range;
3519     ME_GetSelection(editor, &range.cpMin, &range.cpMax);
3520
3521     if (ME_Copy(editor, &range) && msg == WM_CUT)
3522     {
3523       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
3524       ME_CommitUndo(editor);
3525       ME_UpdateRepaint(editor);
3526     }
3527     return 0;
3528   }
3529   case WM_GETTEXTLENGTH:
3530   {
3531     GETTEXTLENGTHEX how;
3532
3533     /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3534     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3535     how.codepage = unicode ? 1200 : CP_ACP;
3536     return ME_GetTextLengthEx(editor, &how);
3537   }
3538   case EM_GETTEXTLENGTHEX:
3539     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3540   case WM_GETTEXT:
3541   {
3542     GETTEXTEX ex;
3543     LRESULT rc;
3544     LPSTR bufferA = NULL;
3545     LPWSTR bufferW = NULL;
3546
3547     if (unicode)
3548         bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
3549     else
3550         bufferA = heap_alloc(wParam + 2);
3551
3552     ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3553     ex.flags = GT_USECRLF;
3554     ex.codepage = unicode ? 1200 : CP_ACP;
3555     ex.lpDefaultChar = NULL;
3556     ex.lpUsedDefChar = NULL;
3557
3558     rc = ME_GetTextEx(editor, &ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA);
3559
3560     if (unicode)
3561     {
3562         memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
3563         if (strlenW(bufferW) >= wParam) rc = 0;
3564     }
3565     else
3566     {
3567         memcpy((LPSTR)lParam, bufferA, wParam);
3568         if (strlen(bufferA) >= wParam) rc = 0;
3569     }
3570     heap_free(bufferA);
3571     heap_free(bufferW);
3572     return rc;
3573   }
3574   case EM_GETTEXTEX:
3575     return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3576   case EM_GETSELTEXT:
3577   {
3578     int from, to;
3579     ME_GetSelection(editor, &from, &to);
3580     return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3581                            to - from, unicode);
3582   }
3583   case EM_GETSCROLLPOS:
3584   {
3585     POINT *point = (POINT *)lParam;
3586     point->x = editor->horz_si.nPos;
3587     point->y = editor->vert_si.nPos;
3588     return 1;
3589   }
3590   case EM_GETTEXTRANGE:
3591   {
3592     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3593     int start = rng->chrg.cpMin;
3594     int end = rng->chrg.cpMax;
3595     int textlength = ME_GetTextLength(editor);
3596     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
3597       rng->chrg.cpMin, rng->chrg.cpMax, unicode,
3598       editor->bEmulateVersion10, ME_GetTextLength(editor));
3599     if (start < 0) return 0;
3600     if ((start == 0 && end == -1) || end > textlength)
3601       end = textlength;
3602     if (start >= end) return 0;
3603     return ME_GetTextRange(editor, rng->lpstrText, start, end - start, unicode);
3604   }
3605   case EM_GETLINE:
3606   {
3607     ME_DisplayItem *run;
3608     const unsigned int nMaxChars = *(WORD *) lParam;
3609     unsigned int nCharsLeft = nMaxChars;
3610     char *dest = (char *) lParam;
3611     BOOL wroteNull = FALSE;
3612
3613     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3614           unicode ? "Unicode" : "Ansi");
3615
3616     run = ME_FindRowWithNumber(editor, wParam);
3617     if (run == NULL)
3618       return 0;
3619
3620     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3621            && run->type == diRun)
3622     {
3623       unsigned int nCopy;
3624       ME_String *strText;
3625
3626       strText = run->member.run.strText;
3627       nCopy = min(nCharsLeft, strText->nLen);
3628
3629       if (unicode)
3630         memcpy(dest, strText->szData, nCopy * sizeof(WCHAR));
3631       else
3632         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3633                                     nCharsLeft, NULL, NULL);
3634       dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3635       nCharsLeft -= nCopy;
3636     }
3637
3638     /* append line termination, space allowing */
3639     if (nCharsLeft > 0)
3640     {
3641       if (unicode)
3642         *((WCHAR *)dest) = '\0';
3643       else
3644         *dest = '\0';
3645       nCharsLeft--;
3646       wroteNull = TRUE;
3647     }
3648
3649     TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3650     return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3651   }
3652   case EM_GETLINECOUNT:
3653   {
3654     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3655     int nRows = 0;
3656
3657     ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3658
3659     while (item != editor->pBuffer->pLast)
3660     {
3661       assert(item->type == diParagraph);
3662       prev_para = ME_FindItemBack(item, diRun);
3663       if (prev_para) {
3664         assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3665       }
3666       nRows += item->member.para.nRows;
3667       item = item->member.para.next_para;
3668     }
3669     last_para = ME_FindItemBack(item, diRun);
3670     assert(last_para);
3671     assert(last_para->member.run.nFlags & MERF_ENDPARA);
3672     if (editor->bEmulateVersion10 && prev_para &&
3673         last_para->member.run.nCharOfs == 0 &&
3674         prev_para->member.run.strText->nLen == 1 &&
3675         prev_para->member.run.strText->szData[0] == '\r')
3676     {
3677       /* In 1.0 emulation, the last solitary \r at the very end of the text
3678          (if one exists) is NOT a line break.
3679          FIXME: this is an ugly hack. This should have a more regular model. */
3680       nRows--;
3681     }
3682
3683     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3684     return max(1, nRows);
3685   }
3686   case EM_LINEFROMCHAR:
3687   {
3688     if (wParam == -1)
3689       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
3690     else
3691       return ME_RowNumberFromCharOfs(editor, wParam);
3692   }
3693   case EM_EXLINEFROMCHAR:
3694   {
3695     if (lParam == -1)
3696       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
3697     else    
3698       return ME_RowNumberFromCharOfs(editor, lParam);
3699   }
3700   case EM_LINEINDEX:
3701   {
3702     ME_DisplayItem *item, *para;
3703     int nCharOfs;
3704     
3705     if (wParam == -1)
3706       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3707     else
3708       item = ME_FindRowWithNumber(editor, wParam);
3709     if (!item)
3710       return -1;
3711     para = ME_GetParagraph(item);
3712     item = ME_FindItemFwd(item, diRun);
3713     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3714     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3715     return nCharOfs;
3716   }
3717   case EM_LINELENGTH:
3718   {
3719     ME_DisplayItem *item, *item_end;
3720     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3721     ME_DisplayItem *para, *run;
3722
3723     if (wParam > ME_GetTextLength(editor))
3724       return 0;
3725     if (wParam == -1)
3726     {
3727       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3728       return 0;
3729     }
3730     ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3731     item = ME_RowStart(run);
3732     nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3733     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3734     if (item_end->type == diStartRow) {
3735       nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3736     } else {
3737       ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3738       assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3739       nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.strText->nLen;
3740     }
3741     nChars = nNextLineOfs - nThisLineOfs;
3742     TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3743     return nChars;
3744   }
3745   case EM_EXLIMITTEXT:
3746   {
3747     if ((int)lParam < 0)
3748      return 0;
3749     if (lParam == 0)
3750       editor->nTextLimit = 65536;
3751     else
3752       editor->nTextLimit = (int) lParam;
3753     return 0;
3754   }
3755   case EM_LIMITTEXT:
3756   {
3757     if (wParam == 0)
3758       editor->nTextLimit = 65536;
3759     else
3760       editor->nTextLimit = (int) wParam;
3761     return 0;
3762   }
3763   case EM_GETLIMITTEXT:
3764   {
3765     return editor->nTextLimit;
3766   }
3767   case EM_FINDTEXT:
3768   {
3769     FINDTEXTA *ft = (FINDTEXTA *)lParam;
3770     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3771     WCHAR *tmp;
3772     LRESULT r;
3773
3774     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3775       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3776     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3777     FREE_OBJ( tmp );
3778     return r;
3779   }
3780   case EM_FINDTEXTEX:
3781   {
3782     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3783     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3784     WCHAR *tmp;
3785     LRESULT r;
3786
3787     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3788       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3789     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3790     FREE_OBJ( tmp );
3791     return r;
3792   }
3793   case EM_FINDTEXTW:
3794   {
3795     FINDTEXTW *ft = (FINDTEXTW *)lParam;
3796     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3797   }
3798   case EM_FINDTEXTEXW:
3799   {
3800     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3801     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3802   }
3803   case EM_GETZOOM:
3804     if (!wParam || !lParam)
3805       return FALSE;
3806     *(int *)wParam = editor->nZoomNumerator;
3807     *(int *)lParam = editor->nZoomDenominator;
3808     return TRUE;
3809   case EM_SETZOOM:
3810     return ME_SetZoom(editor, wParam, lParam);
3811   case EM_CHARFROMPOS:
3812     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3813   case EM_POSFROMCHAR:
3814   {
3815     ME_DisplayItem *pPara, *pRun;
3816     int nCharOfs, nOffset, nLength;
3817     POINTL pt = {0,0};
3818
3819     nCharOfs = wParam;
3820     /* detect which API version we're dealing with */
3821     if (wParam >= 0x40000)
3822         nCharOfs = lParam;
3823     nLength = ME_GetTextLength(editor);
3824     nCharOfs = min(nCharOfs, nLength);
3825     nCharOfs = max(nCharOfs, 0);
3826
3827     ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3828     assert(pRun->type == diRun);
3829     pt.y = pRun->member.run.pt.y;
3830     pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3831     pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3832     pt.x += editor->rcFormat.left;
3833
3834     pt.x -= editor->horz_si.nPos;
3835     pt.y -= editor->vert_si.nPos;
3836
3837     if (wParam >= 0x40000) {
3838         *(POINTL *)wParam = pt;
3839     }
3840     return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3841   }
3842   case WM_CREATE:
3843   {
3844     SCROLLINFO si;
3845
3846     ME_SetDefaultFormatRect(editor);
3847
3848     si.cbSize = sizeof(si);
3849     si.fMask = SIF_PAGE | SIF_RANGE;
3850     if (editor->styleFlags & ES_DISABLENOSCROLL)
3851       si.fMask |= SIF_DISABLENOSCROLL;
3852     si.nMax = (si.fMask & SIF_DISABLENOSCROLL) ? 1 : 0;
3853     si.nMin = 0;
3854     si.nPage = 0;
3855     if (editor->hWnd) {
3856       SetScrollInfo(editor->hWnd, SB_VERT, &si, TRUE);
3857       SetScrollInfo(editor->hWnd, SB_HORZ, &si, TRUE);
3858     } else {
3859       ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, si.nMin, si.nMax, TRUE);
3860       ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, si.nMin, si.nMax, TRUE);
3861     }
3862
3863     ME_CommitUndo(editor);
3864     ME_WrapMarkedParagraphs(editor);
3865     ME_MoveCaret(editor);
3866     return 0;
3867   }
3868   case WM_DESTROY:
3869     ME_DestroyEditor(editor);
3870     return 0;
3871   case WM_SETCURSOR:
3872   {
3873     return ME_SetCursor(editor);
3874   }
3875   case WM_LBUTTONDBLCLK:
3876   case WM_LBUTTONDOWN:
3877   {
3878     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3879     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3880         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3881       return 0;
3882     ITextHost_TxSetFocus(editor->texthost);
3883     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3884                    ME_CalculateClickCount(editor, msg, wParam, lParam));
3885     ITextHost_TxSetCapture(editor->texthost, TRUE);
3886     editor->bMouseCaptured = TRUE;
3887     ME_LinkNotify(editor,msg,wParam,lParam);
3888     if (!ME_SetCursor(editor)) goto do_default;
3889     break;
3890   }
3891   case WM_MOUSEMOVE:
3892     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3893         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3894       return 0;
3895     if (editor->bMouseCaptured)
3896       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3897     ME_LinkNotify(editor,msg,wParam,lParam);
3898     /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3899     if (editor->bMouseCaptured)
3900         ME_SetCursor(editor);
3901     break;
3902   case WM_LBUTTONUP:
3903     if (editor->bMouseCaptured) {
3904       ITextHost_TxSetCapture(editor->texthost, FALSE);
3905       editor->bMouseCaptured = FALSE;
3906     }
3907     if (editor->nSelectionType == stDocument)
3908       editor->nSelectionType = stPosition;
3909     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3910         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3911       return 0;
3912     else
3913     {
3914       ME_SetCursor(editor);
3915       ME_LinkNotify(editor,msg,wParam,lParam);
3916     }
3917     break;
3918   case WM_RBUTTONUP:
3919   case WM_RBUTTONDOWN:
3920     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3921     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3922         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3923       return 0;
3924     goto do_default;
3925   case WM_CONTEXTMENU:
3926     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3927       goto do_default;
3928     break;
3929   case WM_SETFOCUS:
3930     editor->bHaveFocus = TRUE;
3931     ME_ShowCaret(editor);
3932     ME_SendOldNotify(editor, EN_SETFOCUS);
3933     return 0;
3934   case WM_KILLFOCUS:
3935     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3936     editor->bHaveFocus = FALSE;
3937     ME_HideCaret(editor);
3938     ME_SendOldNotify(editor, EN_KILLFOCUS);
3939     return 0;
3940   case WM_COMMAND:
3941     TRACE("editor wnd command = %d\n", LOWORD(wParam));
3942     return 0;
3943   case WM_KEYUP:
3944     if ((editor->nEventMask & ENM_KEYEVENTS) &&
3945         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3946       return 0;
3947     goto do_default;
3948   case WM_KEYDOWN:
3949     if ((editor->nEventMask & ENM_KEYEVENTS) &&
3950         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3951       return 0;
3952     if (ME_KeyDown(editor, LOWORD(wParam)))
3953       return 0;
3954     goto do_default;
3955   case WM_CHAR:
3956     return ME_Char(editor, wParam, lParam, unicode);
3957   case WM_UNICHAR:
3958     if (unicode)
3959     {
3960         if(wParam == UNICODE_NOCHAR) return TRUE;
3961         if(wParam <= 0x000fffff)
3962         {
3963             if(wParam > 0xffff) /* convert to surrogates */
3964             {
3965                 wParam -= 0x10000;
3966                 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
3967                 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
3968             } else {
3969               ME_Char(editor, wParam, 0, TRUE);
3970             }
3971         }
3972         return 0;
3973     }
3974     break;
3975   case EM_STOPGROUPTYPING:
3976     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3977     return 0;
3978   case WM_HSCROLL:
3979   {
3980     const int scrollUnit = 7;
3981
3982     switch(LOWORD(wParam))
3983     {
3984       case SB_LEFT:
3985         ME_ScrollAbs(editor, 0, 0);
3986         break;
3987       case SB_RIGHT:
3988         ME_ScrollAbs(editor,
3989                      editor->horz_si.nMax - (int)editor->horz_si.nPage,
3990                      editor->vert_si.nMax - (int)editor->vert_si.nPage);
3991         break;
3992       case SB_LINELEFT:
3993         ME_ScrollLeft(editor, scrollUnit);
3994         break;
3995       case SB_LINERIGHT:
3996         ME_ScrollRight(editor, scrollUnit);
3997         break;
3998       case SB_PAGELEFT:
3999         ME_ScrollLeft(editor, editor->sizeWindow.cx);
4000         break;
4001       case SB_PAGERIGHT:
4002         ME_ScrollRight(editor, editor->sizeWindow.cx);
4003         break;
4004       case SB_THUMBTRACK:
4005       case SB_THUMBPOSITION:
4006       {
4007         SCROLLINFO sbi;
4008         sbi.cbSize = sizeof(sbi);
4009         sbi.fMask = SIF_TRACKPOS;
4010         /* Try to get 32-bit track position value. */
4011         if (!GetScrollInfo(editor->hWnd, SB_HORZ, &sbi))
4012           /* GetScrollInfo failed, settle for 16-bit value in wParam. */
4013           sbi.nTrackPos = HIWORD(wParam);
4014
4015         ME_HScrollAbs(editor, sbi.nTrackPos);
4016         break;
4017       }
4018     }
4019     break;
4020   }
4021   case EM_SCROLL: /* fall through */
4022   case WM_VSCROLL:
4023   {
4024     int origNPos;
4025     int lineHeight;
4026
4027     origNPos = editor->vert_si.nPos;
4028     lineHeight = 24;
4029
4030     if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4031       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4032     if (lineHeight <= 0) lineHeight = 24;
4033
4034     switch(LOWORD(wParam))
4035     {
4036       case SB_TOP:
4037         ME_ScrollAbs(editor, 0, 0);
4038         break;
4039       case SB_BOTTOM:
4040         ME_ScrollAbs(editor,
4041                      editor->horz_si.nMax - (int)editor->horz_si.nPage,
4042                      editor->vert_si.nMax - (int)editor->vert_si.nPage);
4043         break;
4044       case SB_LINEUP:
4045         ME_ScrollUp(editor,lineHeight);
4046         break;
4047       case SB_LINEDOWN:
4048         ME_ScrollDown(editor,lineHeight);
4049         break;
4050       case SB_PAGEUP:
4051         ME_ScrollUp(editor,editor->sizeWindow.cy);
4052         break;
4053       case SB_PAGEDOWN:
4054         ME_ScrollDown(editor,editor->sizeWindow.cy);
4055         break;
4056       case SB_THUMBTRACK:
4057       case SB_THUMBPOSITION:
4058       {
4059         SCROLLINFO sbi;
4060         sbi.cbSize = sizeof(sbi);
4061         sbi.fMask = SIF_TRACKPOS;
4062         /* Try to get 32-bit track position value. */
4063         if (!GetScrollInfo(editor->hWnd, SB_VERT, &sbi))
4064           /* GetScrollInfo failed, settle for 16-bit value in wParam. */
4065           sbi.nTrackPos = HIWORD(wParam);
4066
4067         ME_VScrollAbs(editor, sbi.nTrackPos);
4068         break;
4069       }
4070     }
4071     if (msg == EM_SCROLL)
4072       return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4073     break;
4074   }
4075   case WM_MOUSEWHEEL:
4076   {
4077     int gcWheelDelta;
4078     UINT pulScrollLines;
4079     BOOL ctrl_is_down;
4080
4081     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4082         !ME_FilterEvent(editor, msg, &wParam, &lParam))
4083       return 0;
4084
4085     ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4086
4087     gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4088
4089     if (abs(gcWheelDelta) >= WHEEL_DELTA)
4090     {
4091       if (ctrl_is_down) {
4092         int numerator;
4093         if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4094         {
4095           numerator = 100;
4096         } else {
4097           numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4098         }
4099         numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4100         if (numerator >= 10 && numerator <= 500)
4101           ME_SetZoom(editor, numerator, 100);
4102       } else {
4103         SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4104         /* FIXME follow the original */
4105         if (pulScrollLines)
4106           ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4107       }
4108     }
4109     break;
4110   }
4111   case EM_GETRECT:
4112   {
4113     *((RECT *)lParam) = editor->rcFormat;
4114     if (editor->bDefaultFormatRect)
4115       ((RECT *)lParam)->left -= editor->selofs;
4116     return 0;
4117   }
4118   case EM_SETRECT:
4119   case EM_SETRECTNP:
4120   {
4121     if (lParam)
4122     {
4123       int border = 0;
4124       RECT clientRect;
4125       RECT *rc = (RECT *)lParam;
4126
4127       border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4128       ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4129       if (wParam == 0)
4130       {
4131         editor->rcFormat.top = max(0, rc->top - border);
4132         editor->rcFormat.left = max(0, rc->left - border);
4133         editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4134         editor->rcFormat.right = min(clientRect.right, rc->right + border);
4135       } else if (wParam == 1) {
4136         /* MSDN incorrectly says a wParam value of 1 causes the
4137          * lParam rect to be used as a relative offset,
4138          * however, the tests show it just prevents min/max bound
4139          * checking. */
4140         editor->rcFormat.top = rc->top - border;
4141         editor->rcFormat.left = rc->left - border;
4142         editor->rcFormat.bottom = rc->bottom;
4143         editor->rcFormat.right = rc->right + border;
4144       } else {
4145         return 0;
4146       }
4147       editor->bDefaultFormatRect = FALSE;
4148     }
4149     else
4150     {
4151       ME_SetDefaultFormatRect(editor);
4152       editor->bDefaultFormatRect = TRUE;
4153     }
4154     ME_MarkAllForWrapping(editor);
4155     ME_WrapMarkedParagraphs(editor);
4156     ME_UpdateScrollBar(editor);
4157     if (msg != EM_SETRECTNP)
4158       ME_Repaint(editor);
4159     return 0;
4160   }
4161   case EM_REQUESTRESIZE:
4162     ME_SendRequestResize(editor, TRUE);
4163     return 0;
4164   case WM_SETREDRAW:
4165     goto do_default;
4166   case WM_SIZE:
4167   {
4168     RECT clientRect;
4169
4170     ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4171     if (editor->bDefaultFormatRect) {
4172       ME_SetDefaultFormatRect(editor);
4173     } else {
4174       editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4175       editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4176     }
4177     editor->prevClientRect = clientRect;
4178     ME_RewrapRepaint(editor);
4179     goto do_default;
4180   }
4181   /* IME messages to make richedit controls IME aware */
4182   case WM_IME_SETCONTEXT:
4183   case WM_IME_CONTROL:
4184   case WM_IME_SELECT:
4185   case WM_IME_COMPOSITIONFULL:
4186     return 0;
4187   case WM_IME_STARTCOMPOSITION:
4188   {
4189     editor->imeStartIndex=ME_GetCursorOfs(editor,0);
4190     ME_DeleteSelection(editor);
4191     ME_CommitUndo(editor);
4192     ME_UpdateRepaint(editor);
4193     return 0;
4194   }
4195   case WM_IME_COMPOSITION:
4196   {
4197     HIMC hIMC;
4198
4199     ME_Style *style = ME_GetInsertStyle(editor, 0);
4200     hIMC = ITextHost_TxImmGetContext(editor->texthost);
4201     ME_DeleteSelection(editor);
4202     ME_CommitUndo(editor);
4203     ME_SaveTempStyle(editor);
4204     if (lParam & GCS_RESULTSTR)
4205     {
4206         LPWSTR lpCompStr = NULL;
4207         DWORD dwBufLen;
4208
4209         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
4210         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4211         ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
4212         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4213         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4214     }
4215     else if (lParam & GCS_COMPSTR)
4216     {
4217         LPWSTR lpCompStr = NULL;
4218         DWORD dwBufLen;
4219
4220         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
4221         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4222         ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
4223         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4224
4225         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4226         ME_SetSelection(editor,editor->imeStartIndex,
4227                         editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4228     }
4229     ME_ReleaseStyle(style);
4230     ME_UpdateRepaint(editor);
4231     return 0;
4232   }
4233   case WM_IME_ENDCOMPOSITION:
4234   {
4235     ME_DeleteSelection(editor);
4236     editor->imeStartIndex=-1;
4237     return 0;
4238   }
4239   case EM_GETOLEINTERFACE:
4240   {
4241     LPVOID *ppvObj = (LPVOID*) lParam;
4242     return CreateIRichEditOle(editor, ppvObj);
4243   }
4244   case EM_GETPASSWORDCHAR:
4245   {
4246     return editor->cPasswordMask;
4247   }
4248   case EM_SETOLECALLBACK:
4249     if(editor->lpOleCallback)
4250       IUnknown_Release(editor->lpOleCallback);
4251     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
4252     if(editor->lpOleCallback)
4253       IUnknown_AddRef(editor->lpOleCallback);
4254     return TRUE;
4255   case EM_GETWORDBREAKPROC:
4256     return (LRESULT)editor->pfnWordBreak;
4257   case EM_SETWORDBREAKPROC:
4258   {
4259     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4260
4261     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4262     return (LRESULT)pfnOld;
4263   }
4264   case EM_GETTEXTMODE:
4265     return editor->mode;
4266   case EM_SETTEXTMODE:
4267   {
4268     LRESULT ret;
4269     int mask = 0;
4270     int changes = 0;
4271     GETTEXTLENGTHEX how;
4272
4273     /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
4274     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
4275     how.codepage = unicode ? 1200 : CP_ACP;
4276     ret = ME_GetTextLengthEx(editor, &how);
4277     if (!ret)
4278     {
4279       /*Check for valid wParam*/
4280       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
4281           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
4282           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
4283         return 1;
4284       else
4285       {
4286         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4287         {
4288           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
4289           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
4290         }
4291         /*FIXME: Currently no support for undo level and code page options*/ 
4292         editor->mode = (editor->mode & (~mask)) | changes;
4293         return 0;
4294       }
4295     }
4296     return ret;
4297   }
4298   case EM_SETPASSWORDCHAR:
4299   {
4300     editor->cPasswordMask = wParam;
4301     ME_RewrapRepaint(editor);
4302     return 0;
4303   }
4304   case EM_SETTARGETDEVICE:
4305     if (wParam == 0)
4306     {
4307       BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4308       if (editor->nAvailWidth || editor->bWordWrap != new)
4309       {
4310         editor->bWordWrap = new;
4311         editor->nAvailWidth = 0; /* wrap to client area */
4312         ME_RewrapRepaint(editor);
4313       }
4314     } else {
4315       int width = max(0, lParam);
4316       if ((editor->styleFlags & ES_MULTILINE) &&
4317           (!editor->bWordWrap || editor->nAvailWidth != width))
4318       {
4319         editor->nAvailWidth = width;
4320         editor->bWordWrap = TRUE;
4321         ME_RewrapRepaint(editor);
4322       }
4323       FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4324     }
4325     return TRUE;
4326   default:
4327   do_default:
4328     *phresult = S_FALSE;
4329     break;
4330   }
4331   return 0L;
4332 }
4333
4334 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4335                                       LPARAM lParam, BOOL unicode)
4336 {
4337   ME_TextEditor *editor;
4338   HRESULT hresult;
4339   LRESULT lresult = 0;
4340
4341   TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4342         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4343
4344   editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4345   if (!editor)
4346   {
4347     if (msg == WM_NCCREATE)
4348     {
4349       CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4350       ITextHost *texthost;
4351
4352       TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4353       texthost = ME_CreateTextHost(hWnd, FALSE);
4354       return texthost != NULL;
4355     }
4356     else if (msg != WM_NCDESTROY)
4357     {
4358       ERR("called with invalid hWnd %p - application bug?\n", hWnd);
4359       return 0;
4360     }
4361   }
4362
4363   switch (msg)
4364   {
4365     case WM_PAINT:
4366     {
4367       HDC hDC;
4368       RECT rc;
4369       PAINTSTRUCT ps;
4370
4371       hDC = BeginPaint(editor->hWnd, &ps);
4372       /* Erase area outside of the formatting rectangle */
4373       if (ps.rcPaint.top < editor->rcFormat.top)
4374       {
4375         rc = ps.rcPaint;
4376         rc.bottom = editor->rcFormat.top;
4377         FillRect(hDC, &rc, editor->hbrBackground);
4378         ps.rcPaint.top = editor->rcFormat.top;
4379       }
4380       if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4381         rc = ps.rcPaint;
4382         rc.top = editor->rcFormat.bottom;
4383         FillRect(hDC, &rc, editor->hbrBackground);
4384         ps.rcPaint.bottom = editor->rcFormat.bottom;
4385       }
4386       if (ps.rcPaint.left < editor->rcFormat.left) {
4387         rc = ps.rcPaint;
4388         rc.right = editor->rcFormat.left;
4389         FillRect(hDC, &rc, editor->hbrBackground);
4390         ps.rcPaint.left = editor->rcFormat.left;
4391       }
4392       if (ps.rcPaint.right > editor->rcFormat.right) {
4393         rc = ps.rcPaint;
4394         rc.left = editor->rcFormat.right;
4395         FillRect(hDC, &rc, editor->hbrBackground);
4396         ps.rcPaint.right = editor->rcFormat.right;
4397       }
4398
4399       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
4400       EndPaint(editor->hWnd, &ps);
4401       return 0;
4402     }
4403     case WM_ERASEBKGND:
4404     {
4405       HDC hDC = (HDC)wParam;
4406       RECT rc;
4407
4408       if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4409         FillRect(hDC, &rc, editor->hbrBackground);
4410       return 1;
4411     }
4412     case EM_SETOPTIONS:
4413     {
4414       DWORD dwStyle;
4415       const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4416                          ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4417                          ECO_SELECTIONBAR;
4418       lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4419       dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4420       dwStyle = (dwStyle & ~mask) | (lresult & mask);
4421       SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4422       return lresult;
4423     }
4424     case EM_SETREADONLY:
4425     {
4426       DWORD dwStyle;
4427       lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4428       dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4429       dwStyle &= ~ES_READONLY;
4430       if (wParam)
4431         dwStyle |= ES_READONLY;
4432       SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4433       return lresult;
4434     }
4435     default:
4436       lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4437   }
4438
4439   if (hresult == S_FALSE)
4440     lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4441
4442   TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4443         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4444
4445   return lresult;
4446 }
4447
4448 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4449 {
4450     BOOL unicode = TRUE;
4451
4452     /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4453     if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4454         unicode = FALSE;
4455
4456     return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4457 }
4458
4459 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4460 {
4461     return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4462 }
4463
4464 /******************************************************************
4465  *        RichEditANSIWndProc (RICHED20.10)
4466  */
4467 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4468 {
4469     return RichEditWndProcA(hWnd, msg, wParam, lParam);
4470 }
4471
4472 /******************************************************************
4473  *        RichEdit10ANSIWndProc (RICHED20.9)
4474  */
4475 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4476 {
4477   if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4478   {
4479     ITextHost *texthost;
4480     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4481
4482     TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4483     texthost = ME_CreateTextHost(hWnd, TRUE);
4484     return texthost != NULL;
4485   }
4486   return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4487 }
4488
4489 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4490 {
4491   ITextHost_TxNotify(editor->texthost, nCode, NULL);
4492 }
4493
4494 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
4495 {
4496   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
4497   int i = 0;
4498   
4499   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
4500     item = item->member.para.next_para;
4501   if (!item)
4502     return 0;
4503   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
4504     item = item->member.para.next_para;
4505     i++;
4506   }
4507   return i;
4508 }
4509
4510
4511 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart,
4512                 int nChars, int bCRLF)
4513 {
4514   ME_DisplayItem *pRun;
4515   int nOffset, nWritten = 0;
4516   WCHAR *pStart = buffer;
4517
4518   ME_RunOfsFromCharOfs(editor, nStart, NULL, &pRun, &nOffset);
4519
4520   /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4521   if (editor->bEmulateVersion10) bCRLF = 0;
4522
4523   while (nChars && pRun)
4524   {
4525     int nLen;
4526
4527     if (pRun->member.run.nFlags & MERF_ENDCELL &&
4528         pRun->member.run.nFlags & MERF_ENDPARA)
4529     {
4530       *buffer = '\t';
4531       nLen = 1;
4532     } else if (pRun->member.run.nFlags & MERF_ENDPARA) {
4533       if (!ME_FindItemFwd(pRun, diRun)) {
4534         /* No '\r' is appended to the last paragraph. */
4535         nLen = 0;
4536       } else if (bCRLF && nChars == 1) {
4537         nLen = 0;
4538         nChars = 0;
4539       } else {
4540         WCHAR cr_lf[] = {'\r', '\n', 0};
4541         WCHAR *szData;
4542
4543         if (bCRLF)
4544         {
4545           nLen = 2;
4546           szData = cr_lf;
4547         } else {
4548           nLen = pRun->member.run.strText->nLen;
4549           szData = pRun->member.run.strText->szData;
4550         }
4551         nLen = min(nChars, nLen - nOffset);
4552         CopyMemory(buffer, szData + nOffset, sizeof(WCHAR) * nLen);
4553       }
4554     } else {
4555       nLen = min(nChars, pRun->member.run.strText->nLen - nOffset);
4556       CopyMemory(buffer, pRun->member.run.strText->szData + nOffset,
4557                  sizeof(WCHAR) * nLen);
4558     }
4559     nChars -= nLen;
4560     nWritten += nLen;
4561     buffer += nLen;
4562     nOffset = 0;
4563
4564     pRun = ME_FindItemFwd(pRun, diRun);
4565   }
4566   *buffer = 0;
4567   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4568   return nWritten;
4569 }
4570
4571 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4572 {
4573   WNDCLASSW wcW;
4574   WNDCLASSA wcA;
4575   
4576   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4577   wcW.lpfnWndProc = RichEditWndProcW;
4578   wcW.cbClsExtra = 0;
4579   wcW.cbWndExtra = sizeof(ME_TextEditor *);
4580   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4581   wcW.hIcon = NULL;
4582   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4583   wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4584   wcW.lpszMenuName = NULL;
4585
4586   if (is_version_nt())
4587   {
4588     wcW.lpszClassName = RichEdit20W;
4589     if (!RegisterClassW(&wcW)) return FALSE;
4590     wcW.lpszClassName = RichEdit50W;
4591     if (!RegisterClassW(&wcW)) return FALSE;
4592   }
4593   else
4594   {
4595     /* WNDCLASSA/W have the same layout */
4596     wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4597     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4598     wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4599     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4600   }
4601
4602   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4603   wcA.lpfnWndProc = RichEditWndProcA;
4604   wcA.cbClsExtra = 0;
4605   wcA.cbWndExtra = sizeof(ME_TextEditor *);
4606   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4607   wcA.hIcon = NULL;
4608   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4609   wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4610   wcA.lpszMenuName = NULL;
4611   wcA.lpszClassName = "RichEdit20A";
4612   if (!RegisterClassA(&wcA)) return FALSE;
4613   wcA.lpszClassName = "RichEdit50A";
4614   if (!RegisterClassA(&wcA)) return FALSE;
4615
4616   return TRUE;
4617 }
4618
4619 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4620   /* FIXME: Not implemented */
4621   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4622         hWnd, msg, get_msg_name(msg), wParam, lParam);
4623   return DefWindowProcW(hWnd, msg, wParam, lParam);
4624 }
4625
4626 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4627   /* FIXME: Not implemented */
4628   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4629         hWnd, msg, get_msg_name(msg), wParam, lParam);
4630   return DefWindowProcW(hWnd, msg, wParam, lParam);
4631 }
4632
4633 /******************************************************************
4634  *        REExtendedRegisterClass (RICHED20.8)
4635  *
4636  * FIXME undocumented
4637  * Need to check for errors and implement controls and callbacks 
4638  */
4639 LRESULT WINAPI REExtendedRegisterClass(void)
4640 {
4641   WNDCLASSW wcW;
4642   UINT result;
4643
4644   FIXME("semi stub\n");
4645
4646   wcW.cbClsExtra = 0;
4647   wcW.cbWndExtra = 4;
4648   wcW.hInstance = NULL;
4649   wcW.hIcon = NULL;
4650   wcW.hCursor = NULL;
4651   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4652   wcW.lpszMenuName = NULL;
4653
4654   if (!ME_ListBoxRegistered)
4655   {
4656       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4657       wcW.lpfnWndProc = REListWndProc;
4658       wcW.lpszClassName = REListBox20W;
4659       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4660   }
4661
4662   if (!ME_ComboBoxRegistered)
4663   {
4664       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4665       wcW.lpfnWndProc = REComboWndProc;
4666       wcW.lpszClassName = REComboBox20W;
4667       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
4668   }
4669
4670   result = 0;
4671   if (ME_ListBoxRegistered)
4672       result += 1;
4673   if (ME_ComboBoxRegistered)
4674       result += 2;
4675
4676   return result;
4677 }
4678
4679 static BOOL isurlspecial(WCHAR c)
4680 {
4681   static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4682   return strchrW( special_chars, c ) != NULL;
4683 }
4684
4685 /**
4686  * This proc takes a selection, and scans it forward in order to select the span
4687  * of a possible URL candidate. A possible URL candidate must start with isalnum
4688  * or one of the following special characters: *|/\+%#@ and must consist entirely
4689  * of the characters allowed to start the URL, plus : (colon) which may occur
4690  * at most once, and not at either end.
4691  *
4692  * sel_max == -1 indicates scan to end of text.
4693  */
4694 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
4695         int * candidate_min, int * candidate_max)
4696 {
4697   ME_DisplayItem * item;
4698   ME_DisplayItem * para;
4699   int nStart;
4700   BOOL foundColon = FALSE;
4701   WCHAR lastAcceptedChar = '\0';
4702
4703   TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
4704
4705   *candidate_min = *candidate_max = -1;
4706   ME_RunOfsFromCharOfs(editor, sel_min, &para, &item, &nStart);
4707   TRACE("nStart = %d\n", nStart);
4708   if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4709   while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
4710   {
4711     ME_DisplayItem * next_item;
4712
4713     if (!(item->member.run.nFlags & MERF_ENDPARA)) {
4714       /* Find start of candidate */
4715       if (*candidate_min == -1) {
4716         while (nStart < item->member.run.strText->nLen &&
4717                 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4718                   isurlspecial(item->member.run.strText->szData[nStart]))) {
4719           nStart++;
4720         }
4721         if (nStart < item->member.run.strText->nLen &&
4722                 (isalnumW(item->member.run.strText->szData[nStart]) ||
4723                  isurlspecial(item->member.run.strText->szData[nStart]))) {
4724           *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4725           lastAcceptedChar = item->member.run.strText->szData[nStart];
4726           nStart++;
4727         }
4728       }
4729
4730       /* Find end of candidate */
4731       if (*candidate_min >= 0) {
4732         while (nStart < item->member.run.strText->nLen &&
4733                 (isalnumW(item->member.run.strText->szData[nStart]) ||
4734                  isurlspecial(item->member.run.strText->szData[nStart]) ||
4735                  (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
4736           if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
4737           lastAcceptedChar = item->member.run.strText->szData[nStart];
4738           nStart++;
4739         }
4740         if (nStart < item->member.run.strText->nLen &&
4741                 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4742                  isurlspecial(item->member.run.strText->szData[nStart]) )) {
4743           *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4744           nStart++;
4745           if (lastAcceptedChar == ':') (*candidate_max)--;
4746           return TRUE;
4747         }
4748       }
4749     } else {
4750       /* End of paragraph: skip it if before candidate span, or terminates
4751          current active span */
4752       if (*candidate_min >= 0) {
4753         *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
4754         if (lastAcceptedChar == ':') (*candidate_max)--;
4755         return TRUE;
4756       }
4757     }
4758
4759     /* Reaching this point means no span was found, so get next span */
4760     next_item = ME_FindItemFwd(item, diRun);
4761     if (!next_item) {
4762       if (*candidate_min >= 0) {
4763         /* There are no further runs, so take end of text as end of candidate */
4764         *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4765         if (lastAcceptedChar == ':') (*candidate_max)--;
4766         return TRUE;
4767       }
4768     }
4769     item = next_item;
4770     para = ME_GetParagraph(item);
4771     nStart = 0;
4772   }
4773
4774   if (item) {
4775     if (*candidate_min >= 0) {
4776       /* There are no further runs, so take end of text as end of candidate */
4777       *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4778       if (lastAcceptedChar == ':') (*candidate_max)--;
4779       return TRUE;
4780     }
4781   }
4782   return FALSE;
4783 }
4784
4785 /**
4786  * This proc evaluates the selection and returns TRUE if it can be considered an URL
4787  */
4788 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
4789 {
4790   struct prefix_s {
4791     const char *text;
4792     int length;
4793   } prefixes[12] = {
4794     /* Code below depends on these being in decreasing length order! */
4795     {"prospero:", 10},
4796     {"telnet:", 8},
4797     {"gopher:", 8},
4798     {"mailto:", 8},
4799     {"https:", 7},
4800     {"file:", 6},
4801     {"news:", 6},
4802     {"wais:", 6},
4803     {"nntp:", 6},
4804     {"http:", 5},
4805     {"www.", 5},
4806     {"ftp:", 5},
4807   };
4808   LPWSTR bufferW = NULL;
4809   WCHAR bufW[32];
4810   unsigned int i;
4811
4812   if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4813   assert(sel_min <= sel_max);
4814   for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
4815   {
4816     if (sel_max - sel_min < prefixes[i].length) continue;
4817     if (bufferW == NULL) {
4818       bufferW = heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
4819     }
4820     ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, lstrlenA(prefixes[i].text)), 0);
4821     MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
4822     if (!lstrcmpW(bufW, bufferW))
4823     {
4824       heap_free(bufferW);
4825       return TRUE;
4826     }
4827   }
4828   heap_free(bufferW);
4829   return FALSE;
4830 }
4831
4832 /**
4833  * This proc walks through the indicated selection and evaluates whether each
4834  * section identified by ME_FindNextURLCandidate and in-between sections have
4835  * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4836  * not what it is supposed to be, this proc sets or unsets it as appropriate.
4837  *
4838  * Returns TRUE if at least one section was modified.
4839  */
4840 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
4841 {
4842   BOOL modified = FALSE;
4843   int cMin, cMax;
4844
4845   if (!editor->AutoURLDetect_bEnable) return FALSE;
4846
4847   if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4848   do
4849   {
4850     int beforeURL[2];
4851     int inURL[2];
4852     CHARFORMAT2W link;
4853
4854     if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4855     {
4856       /* Section before candidate is not an URL */
4857       beforeURL[0] = sel_min;
4858       beforeURL[1] = cMin;
4859
4860       if (ME_IsCandidateAnURL(editor, cMin, cMax))
4861       {
4862         inURL[0] = cMin; inURL[1] = cMax;
4863       }
4864       else
4865       {
4866         beforeURL[1] = cMax;
4867         inURL[0] = inURL[1] = -1;
4868       }
4869       sel_min = cMax;
4870     }
4871     else
4872     {
4873       /* No more candidates until end of selection */
4874       beforeURL[0] = sel_min;
4875       beforeURL[1] = sel_max;
4876       inURL[0] = inURL[1] = -1;
4877       sel_min = sel_max;
4878     }
4879
4880     if (beforeURL[0] < beforeURL[1])
4881     {
4882       /* CFE_LINK effect should be consistently unset */
4883       link.cbSize = sizeof(link);
4884       ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4885       if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4886       {
4887         /* CFE_LINK must be unset from this range */
4888         memset(&link, 0, sizeof(CHARFORMAT2W));
4889         link.cbSize = sizeof(link);
4890         link.dwMask = CFM_LINK;
4891         link.dwEffects = 0;
4892         ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4893         modified = TRUE;
4894       }
4895     }
4896     if (inURL[0] < inURL[1])
4897     {
4898       /* CFE_LINK effect should be consistently set */
4899       link.cbSize = sizeof(link);
4900       ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
4901       if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4902       {
4903         /* CFE_LINK must be set on this range */
4904         memset(&link, 0, sizeof(CHARFORMAT2W));
4905         link.cbSize = sizeof(link);
4906         link.dwMask = CFM_LINK;
4907         link.dwEffects = CFE_LINK;
4908         ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
4909         modified = TRUE;
4910       }
4911     }
4912   } while (sel_min < sel_max);
4913   return modified;
4914 }