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