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