user32: Use a finally handler to make sure capture is always released when exiting...
[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 (editor->bMouseCaptured)
2159       return FALSE;
2160   if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2161       editor->nSelectionType = stPosition;
2162
2163   switch (nKey)
2164   {
2165     case VK_LEFT:
2166     case VK_RIGHT:
2167     case VK_HOME:
2168     case VK_END:
2169         editor->nUDArrowX = -1;
2170         /* fall through */
2171     case VK_UP:
2172     case VK_DOWN:
2173     case VK_PRIOR:
2174     case VK_NEXT:
2175       ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2176       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2177       return TRUE;
2178     case VK_BACK:
2179     case VK_DELETE:
2180       editor->nUDArrowX = -1;
2181       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2182       if (editor->styleFlags & ES_READONLY)
2183         return FALSE;
2184       if (ME_IsSelection(editor))
2185       {
2186         ME_DeleteSelection(editor);
2187         ME_CommitUndo(editor);
2188       }
2189       else if (nKey == VK_DELETE)
2190       {
2191         /* Delete stops group typing.
2192          * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2193         ME_DeleteTextAtCursor(editor, 1, 1);
2194         ME_CommitUndo(editor);
2195       }
2196       else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2197       {
2198         BOOL bDeletionSucceeded;
2199         /* Backspace can be grouped for a single undo */
2200         ME_ContinueCoalescingTransaction(editor);
2201         bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2202         if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2203           /* Deletion was prevented so the cursor is moved back to where it was.
2204            * (e.g. this happens when trying to delete cell boundaries)
2205            */
2206           ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2207         }
2208         ME_CommitCoalescingUndo(editor);
2209       }
2210       else
2211         return TRUE;
2212       ME_MoveCursorFromTableRowStartParagraph(editor);
2213       ME_UpdateSelectionLinkAttribute(editor);
2214       ME_UpdateRepaint(editor);
2215       ME_SendRequestResize(editor, FALSE);
2216       return TRUE;
2217     case VK_RETURN:
2218       if (editor->styleFlags & ES_MULTILINE)
2219       {
2220         ME_Cursor cursor = editor->pCursors[0];
2221         ME_DisplayItem *para = ME_GetParagraph(cursor.pRun);
2222         int from, to;
2223         const WCHAR endl = '\r';
2224         ME_Style *style;
2225
2226         if (editor->styleFlags & ES_READONLY) {
2227           MessageBeep(MB_ICONERROR);
2228           return TRUE;
2229         }
2230
2231         ME_GetSelection(editor, &from, &to);
2232         if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2233         {
2234           if (!editor->bEmulateVersion10) { /* v4.1 */
2235             if (para->member.para.nFlags & MEPF_ROWEND) {
2236               /* Add a new table row after this row. */
2237               para = ME_AppendTableRow(editor, para);
2238               para = para->member.para.next_para;
2239               editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2240               editor->pCursors[0].nOffset = 0;
2241               editor->pCursors[1] = editor->pCursors[0];
2242               ME_CommitUndo(editor);
2243               ME_CheckTablesForCorruption(editor);
2244               ME_UpdateRepaint(editor);
2245               return TRUE;
2246             }
2247             else if (para == ME_GetParagraph(editor->pCursors[1].pRun) &&
2248                      cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2249                      para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2250                      !para->member.para.prev_para->member.para.nCharOfs)
2251             {
2252               /* Insert a newline before the table. */
2253               para = para->member.para.prev_para;
2254               para->member.para.nFlags &= ~MEPF_ROWSTART;
2255               editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2256               editor->pCursors[1] = editor->pCursors[0];
2257               ME_InsertTextFromCursor(editor, 0, &endl, 1,
2258                                       editor->pCursors[0].pRun->member.run.style);
2259               para = editor->pBuffer->pFirst->member.para.next_para;
2260               ME_SetDefaultParaFormat(para->member.para.pFmt);
2261               para->member.para.nFlags = MEPF_REWRAP;
2262               editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2263               editor->pCursors[1] = editor->pCursors[0];
2264               para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2265               ME_CommitCoalescingUndo(editor);
2266               ME_CheckTablesForCorruption(editor);
2267               ME_UpdateRepaint(editor);
2268               return TRUE;
2269             }
2270           } else { /* v1.0 - 3.0 */
2271             ME_DisplayItem *para = ME_GetParagraph(cursor.pRun);
2272             if (ME_IsInTable(para))
2273             {
2274               if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2275               {
2276                 if (from == to) {
2277                   ME_ContinueCoalescingTransaction(editor);
2278                   para = ME_AppendTableRow(editor, para);
2279                   editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2280                   editor->pCursors[0].nOffset = 0;
2281                   editor->pCursors[1] = editor->pCursors[0];
2282                   ME_CommitCoalescingUndo(editor);
2283                   ME_UpdateRepaint(editor);
2284                   return TRUE;
2285                 }
2286               } else {
2287                 ME_ContinueCoalescingTransaction(editor);
2288                 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2289                     !ME_IsInTable(para->member.para.prev_para))
2290                 {
2291                   /* Insert newline before table */
2292                   cursor.pRun = ME_FindItemBack(para, diRun);
2293                   if (cursor.pRun)
2294                     editor->pCursors[0].pRun = cursor.pRun;
2295                   editor->pCursors[0].nOffset = 0;
2296                   editor->pCursors[1] = editor->pCursors[0];
2297                   ME_InsertTextFromCursor(editor, 0, &endl, 1,
2298                                           editor->pCursors[0].pRun->member.run.style);
2299                 } else {
2300                   editor->pCursors[1] = editor->pCursors[0];
2301                   para = ME_AppendTableRow(editor, para);
2302                   editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2303                   editor->pCursors[0].nOffset = 0;
2304                   editor->pCursors[1] = editor->pCursors[0];
2305                 }
2306                 ME_CommitCoalescingUndo(editor);
2307                 ME_UpdateRepaint(editor);
2308                 return TRUE;
2309               }
2310             }
2311           }
2312
2313           style = ME_GetInsertStyle(editor, 0);
2314           ME_SaveTempStyle(editor);
2315           ME_ContinueCoalescingTransaction(editor);
2316           if (shift_is_down)
2317             ME_InsertEndRowFromCursor(editor, 0);
2318           else
2319             ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2320           ME_ReleaseStyle(style);
2321           ME_CommitCoalescingUndo(editor);
2322           SetCursor(NULL);
2323
2324           if (editor->AutoURLDetect_bEnable)
2325             ME_UpdateSelectionLinkAttribute(editor);
2326
2327           ME_UpdateRepaint(editor);
2328         }
2329         return TRUE;
2330       }
2331       break;
2332     case 'A':
2333       if (ctrl_is_down)
2334       {
2335         ME_SetSelection(editor, 0, -1);
2336         return TRUE;
2337       }
2338       break;
2339     case 'V':
2340       if (ctrl_is_down)
2341         return ME_Paste(editor);
2342       break;
2343     case 'C':
2344     case 'X':
2345       if (ctrl_is_down)
2346       {
2347         CHARRANGE range;
2348         BOOL result;
2349
2350         ME_GetSelection(editor, &range.cpMin, &range.cpMax);
2351         result = ME_Copy(editor, &range);
2352         if (result && nKey == 'X')
2353         {
2354           ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
2355           ME_CommitUndo(editor);
2356           ME_UpdateRepaint(editor);
2357         }
2358         return result;
2359       }
2360       break;
2361     case 'Z':
2362       if (ctrl_is_down)
2363       {
2364         ME_Undo(editor);
2365         return TRUE;
2366       }
2367       break;
2368     case 'Y':
2369       if (ctrl_is_down)
2370       {
2371         ME_Redo(editor);
2372         return TRUE;
2373       }
2374       break;
2375
2376     default:
2377       if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2378           editor->nUDArrowX = -1;
2379       if (ctrl_is_down)
2380       {
2381         if (nKey == 'W')
2382         {
2383           CHARFORMAT2W chf;
2384           char buf[2048];
2385           chf.cbSize = sizeof(chf);
2386           
2387           ME_GetSelectionCharFormat(editor, &chf);
2388           ME_DumpStyleToBuf(&chf, buf);
2389           MessageBoxA(NULL, buf, "Style dump", MB_OK);
2390         }
2391         if (nKey == 'Q')
2392         {
2393           ME_CheckCharOffsets(editor);
2394         }
2395       }
2396   }
2397   return FALSE;
2398 }
2399
2400 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2401                        LPARAM flags, BOOL unicode)
2402 {
2403   WCHAR wstr;
2404
2405   if (editor->bMouseCaptured)
2406     return 0;
2407
2408   if (unicode)
2409       wstr = (WCHAR)charCode;
2410   else
2411   {
2412       CHAR charA = charCode;
2413       MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2414   }
2415
2416   if (editor->styleFlags & ES_READONLY) {
2417     MessageBeep(MB_ICONERROR);
2418     return 0; /* FIXME really 0 ? */
2419   }
2420
2421   if ((unsigned)wstr >= ' ' || wstr == '\t')
2422   {
2423     ME_Cursor cursor = editor->pCursors[0];
2424     ME_DisplayItem *para = ME_GetParagraph(cursor.pRun);
2425     int from, to;
2426     BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2427     ME_GetSelection(editor, &from, &to);
2428     if (wstr == '\t' &&
2429         /* v4.1 allows tabs to be inserted with ctrl key down */
2430         !(ctrl_is_down && !editor->bEmulateVersion10))
2431     {
2432       ME_DisplayItem *para;
2433       BOOL bSelectedRow = FALSE;
2434
2435       para = ME_GetParagraph(cursor.pRun);
2436       if (ME_IsSelection(editor) &&
2437           cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2438           to == ME_GetCursorOfs(editor, 0) &&
2439           para->member.para.prev_para->type == diParagraph)
2440       {
2441         para = para->member.para.prev_para;
2442         bSelectedRow = TRUE;
2443       }
2444       if (ME_IsInTable(para))
2445       {
2446         ME_TabPressedInTable(editor, bSelectedRow);
2447         ME_CommitUndo(editor);
2448         return 0;
2449       }
2450     } else if (!editor->bEmulateVersion10) { /* v4.1 */
2451       if (para->member.para.nFlags & MEPF_ROWEND) {
2452         if (from == to) {
2453           para = para->member.para.next_para;
2454           if (para->member.para.nFlags & MEPF_ROWSTART)
2455             para = para->member.para.next_para;
2456           editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2457           editor->pCursors[0].nOffset = 0;
2458           editor->pCursors[1] = editor->pCursors[0];
2459         }
2460       }
2461     } else { /* v1.0 - 3.0 */
2462       if (ME_IsInTable(cursor.pRun) &&
2463           cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2464           from == to)
2465       {
2466         /* Text should not be inserted at the end of the table. */
2467         MessageBeep(-1);
2468         return 0;
2469       }
2470     }
2471     /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2472     /* WM_CHAR is restricted to nTextLimit */
2473     if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2474     {
2475       ME_Style *style = ME_GetInsertStyle(editor, 0);
2476       ME_SaveTempStyle(editor);
2477       ME_ContinueCoalescingTransaction(editor);
2478       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2479       ME_ReleaseStyle(style);
2480       ME_CommitCoalescingUndo(editor);
2481       ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2482     }
2483
2484     if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2485
2486     ME_UpdateRepaint(editor);
2487   }
2488   return 0;
2489 }
2490
2491 /* Process the message and calculate the new click count.
2492  *
2493  * returns: The click count if it is mouse down event, else returns 0. */
2494 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2495                                   LPARAM lParam)
2496 {
2497     static int clickNum = 0;
2498     if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2499         return 0;
2500
2501     if ((msg == WM_LBUTTONDBLCLK) ||
2502         (msg == WM_RBUTTONDBLCLK) ||
2503         (msg == WM_MBUTTONDBLCLK) ||
2504         (msg == WM_XBUTTONDBLCLK))
2505     {
2506         msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2507     }
2508
2509     if ((msg == WM_LBUTTONDOWN) ||
2510         (msg == WM_RBUTTONDOWN) ||
2511         (msg == WM_MBUTTONDOWN) ||
2512         (msg == WM_XBUTTONDOWN))
2513     {
2514         static MSG prevClickMsg;
2515         MSG clickMsg;
2516         /* Compare the editor instead of the hwnd so that the this
2517          * can still be done for windowless richedit controls. */
2518         clickMsg.hwnd = (HWND)editor;
2519         clickMsg.message = msg;
2520         clickMsg.wParam = wParam;
2521         clickMsg.lParam = lParam;
2522         clickMsg.time = GetMessageTime();
2523         clickMsg.pt.x = (short)LOWORD(lParam);
2524         clickMsg.pt.y = (short)HIWORD(lParam);
2525         if ((clickNum != 0) &&
2526             (clickMsg.message == prevClickMsg.message) &&
2527             (clickMsg.hwnd == prevClickMsg.hwnd) &&
2528             (clickMsg.wParam == prevClickMsg.wParam) &&
2529             (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2530             (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2531             (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2532         {
2533             clickNum++;
2534         } else {
2535             clickNum = 1;
2536         }
2537         prevClickMsg = clickMsg;
2538     } else {
2539         return 0;
2540     }
2541     return clickNum;
2542 }
2543
2544 static BOOL ME_SetCursor(ME_TextEditor *editor)
2545 {
2546   POINT pt;
2547   BOOL isExact;
2548   int offset;
2549   SCROLLBARINFO sbi;
2550   DWORD messagePos = GetMessagePos();
2551   pt.x = (short)LOWORD(messagePos);
2552   pt.y = (short)HIWORD(messagePos);
2553
2554   if (editor->hWnd)
2555   {
2556     sbi.cbSize = sizeof(sbi);
2557     GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2558     if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2559         PtInRect(&sbi.rcScrollBar, pt))
2560     {
2561         ITextHost_TxSetCursor(editor->texthost,
2562                               LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2563         return TRUE;
2564     }
2565     sbi.cbSize = sizeof(sbi);
2566     GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2567     if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2568         PtInRect(&sbi.rcScrollBar, pt))
2569     {
2570         ITextHost_TxSetCursor(editor->texthost,
2571                               LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2572         return TRUE;
2573     }
2574   }
2575   ITextHost_TxScreenToClient(editor->texthost, &pt);
2576
2577   if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2578       ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2579       return TRUE;
2580   }
2581   if (!editor->bEmulateVersion10 /* v4.1 */ &&
2582       pt.y < editor->rcFormat.top &&
2583       pt.x < editor->rcFormat.left)
2584   {
2585       ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2586       return TRUE;
2587   }
2588   if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2589   {
2590       if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2591           ITextHost_TxSetCursor(editor->texthost,
2592                                 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2593       else /* v4.1 */
2594           ITextHost_TxSetCursor(editor->texthost,
2595                                 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2596       return TRUE;
2597   }
2598   if (pt.x < editor->rcFormat.left)
2599   {
2600       ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2601       return TRUE;
2602   }
2603   offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
2604   if (isExact)
2605   {
2606       if (editor->AutoURLDetect_bEnable)
2607       {
2608           ME_Cursor cursor;
2609           ME_Run *run;
2610           ME_CursorFromCharOfs(editor, offset, &cursor);
2611           run = &cursor.pRun->member.run;
2612           if (editor->AutoURLDetect_bEnable &&
2613               run->style->fmt.dwMask & CFM_LINK &&
2614               run->style->fmt.dwEffects & CFE_LINK)
2615           {
2616               ITextHost_TxSetCursor(editor->texthost,
2617                                     LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2618                                     FALSE);
2619               return TRUE;
2620           }
2621       }
2622       if (ME_IsSelection(editor))
2623       {
2624           int selStart, selEnd;
2625           ME_GetSelection(editor, &selStart, &selEnd);
2626           if (selStart <= offset && selEnd >= offset) {
2627               ITextHost_TxSetCursor(editor->texthost,
2628                                     LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2629                                     FALSE);
2630               return TRUE;
2631           }
2632       }
2633   }
2634   ITextHost_TxSetCursor(editor->texthost,
2635                         LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2636   return TRUE;
2637 }
2638
2639 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2640 {
2641   ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2642   editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2643   editor->rcFormat.left += 1 + editor->selofs;
2644   editor->rcFormat.right -= 1;
2645 }
2646
2647 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2648 {
2649   CHARRANGE selrange;
2650   HMENU menu;
2651   int seltype = 0;
2652   if(!editor->lpOleCallback || !editor->hWnd)
2653     return FALSE;
2654   ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
2655   if(selrange.cpMin == selrange.cpMax)
2656     seltype |= SEL_EMPTY;
2657   else
2658   {
2659     /* FIXME: Handle objects */
2660     seltype |= SEL_TEXT;
2661     if(selrange.cpMax-selrange.cpMin > 1)
2662       seltype |= SEL_MULTICHAR;
2663   }
2664   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2665   {
2666     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
2667     DestroyMenu(menu);
2668   }
2669   return TRUE;
2670 }
2671
2672 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2673 {
2674   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2675   int i;
2676   DWORD props;
2677   LONG selbarwidth;
2678
2679   ed->hWnd = NULL;
2680   ed->texthost = texthost;
2681   ed->bEmulateVersion10 = bEmulateVersion10;
2682   ITextHost_TxGetPropertyBits(texthost,
2683                               (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2684                                TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2685                                TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2686                                TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2687                                TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2688                               &props);
2689   ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2690   ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2691                      ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2692   ed->pBuffer = ME_MakeText();
2693   ed->nZoomNumerator = ed->nZoomDenominator = 0;
2694   ME_MakeFirstParagraph(ed);
2695   /* The four cursors are for:
2696    * 0 - The position where the caret is shown
2697    * 1 - The anchored end of the selection (for normal selection)
2698    * 2 & 3 - The anchored start and end respectively for word, line,
2699    * or paragraph selection.
2700    */
2701   ed->nCursors = 4;
2702   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2703   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2704   ed->pCursors[0].nOffset = 0;
2705   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2706   ed->pCursors[1].nOffset = 0;
2707   ed->pCursors[2] = ed->pCursors[0];
2708   ed->pCursors[3] = ed->pCursors[1];
2709   ed->nLastTotalLength = ed->nTotalLength = 0;
2710   ed->nLastTotalWidth = ed->nTotalWidth = 0;
2711   ed->nUDArrowX = -1;
2712   ed->nSequence = 0;
2713   ed->rgbBackColor = -1;
2714   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2715   ed->bCaretAtEnd = FALSE;
2716   ed->nEventMask = 0;
2717   ed->nModifyStep = 0;
2718   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2719   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2720   ed->nUndoStackSize = 0;
2721   ed->nUndoLimit = STACK_SIZE_DEFAULT;
2722   ed->nUndoMode = umAddToUndo;
2723   ed->nParagraphs = 1;
2724   ed->nLastSelStart = ed->nLastSelEnd = 0;
2725   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
2726   ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2727   ed->bHideSelection = FALSE;
2728   ed->pfnWordBreak = NULL;
2729   ed->lpOleCallback = NULL;
2730   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2731   ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2732   ed->AutoURLDetect_bEnable = FALSE;
2733   ed->bHaveFocus = FALSE;
2734   ed->bMouseCaptured = FALSE;
2735   for (i=0; i<HFONT_CACHE_SIZE; i++)
2736   {
2737     ed->pFontCache[i].nRefs = 0;
2738     ed->pFontCache[i].nAge = 0;
2739     ed->pFontCache[i].hFont = NULL;
2740   }
2741
2742   ME_CheckCharOffsets(ed);
2743   ed->bDefaultFormatRect = TRUE;
2744   ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2745   /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2746   ed->selofs = selbarwidth ? SELECTIONBAR_WIDTH : 0;
2747   ed->nSelectionType = stPosition;
2748
2749   ed->cPasswordMask = 0;
2750   if (props & TXTBIT_USEPASSWORD)
2751     ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2752
2753   if (props & TXTBIT_AUTOWORDSEL)
2754     ed->styleFlags |= ECO_AUTOWORDSELECTION;
2755   if (props & TXTBIT_MULTILINE)
2756     ed->styleFlags |= ES_MULTILINE;
2757   if (props & TXTBIT_READONLY)
2758     ed->styleFlags |= ES_READONLY;
2759   if (!(props & TXTBIT_HIDESELECTION))
2760     ed->styleFlags |= ES_NOHIDESEL;
2761   if (props & TXTBIT_SAVESELECTION)
2762     ed->styleFlags |= ES_SAVESEL;
2763   if (props & TXTBIT_VERTICAL)
2764     ed->styleFlags |= ES_VERTICAL;
2765   if (props & TXTBIT_DISABLEDRAG)
2766     ed->styleFlags |= ES_NOOLEDRAGDROP;
2767
2768   ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2769
2770   /* Default scrollbar information */
2771   ed->vert_si.cbSize = sizeof(SCROLLINFO);
2772   ed->vert_si.nMin = 0;
2773   ed->vert_si.nMax = 0;
2774   ed->vert_si.nPage = 0;
2775   ed->vert_si.nPos = 0;
2776
2777   ed->horz_si.cbSize = sizeof(SCROLLINFO);
2778   ed->horz_si.nMin = 0;
2779   ed->horz_si.nMax = 0;
2780   ed->horz_si.nPage = 0;
2781   ed->horz_si.nPos = 0;
2782
2783   OleInitialize(NULL);
2784
2785   return ed;
2786 }
2787
2788 static void ME_DestroyEditor(ME_TextEditor *editor)
2789 {
2790   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2791   ME_DisplayItem *p = pFirst, *pNext = NULL;
2792   int i;
2793
2794   ME_ClearTempStyle(editor);
2795   ME_EmptyUndoStack(editor);
2796   while(p) {
2797     pNext = p->next;
2798     ME_DestroyDisplayItem(p);
2799     p = pNext;
2800   }
2801   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2802   for (i=0; i<HFONT_CACHE_SIZE; i++)
2803   {
2804     if (editor->pFontCache[i].hFont)
2805       DeleteObject(editor->pFontCache[i].hFont);
2806   }
2807   if (editor->rgbBackColor != -1)
2808     DeleteObject(editor->hbrBackground);
2809   if(editor->lpOleCallback)
2810     IUnknown_Release(editor->lpOleCallback);
2811   IUnknown_Release(editor->texthost);
2812   OleUninitialize();
2813
2814   FREE_OBJ(editor->pBuffer);
2815   FREE_OBJ(editor->pCursors);
2816
2817   FREE_OBJ(editor);
2818 }
2819
2820 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2821 {
2822     TRACE("\n");
2823     switch (fdwReason)
2824     {
2825     case DLL_PROCESS_ATTACH:
2826       DisableThreadLibraryCalls(hinstDLL);
2827       me_heap = HeapCreate (0, 0x10000, 0);
2828       if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2829       hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2830       LookupInit();
2831       break;
2832
2833     case DLL_PROCESS_DETACH:
2834       UnregisterClassW(RichEdit20W, 0);
2835       UnregisterClassW(RichEdit50W, 0);
2836       UnregisterClassA("RichEdit20A", 0);
2837       UnregisterClassA("RichEdit50A", 0);
2838       if (ME_ListBoxRegistered)
2839           UnregisterClassW(REListBox20W, 0);
2840       if (ME_ComboBoxRegistered)
2841           UnregisterClassW(REComboBox20W, 0);
2842       LookupCleanup();
2843       HeapDestroy (me_heap);
2844       me_heap = NULL;
2845       break;
2846     }
2847     return TRUE;
2848 }
2849
2850
2851 static const char * const edit_messages[] = {
2852   "EM_GETSEL",
2853   "EM_SETSEL",
2854   "EM_GETRECT",
2855   "EM_SETRECT",
2856   "EM_SETRECTNP",
2857   "EM_SCROLL",
2858   "EM_LINESCROLL",
2859   "EM_SCROLLCARET",
2860   "EM_GETMODIFY",
2861   "EM_SETMODIFY",
2862   "EM_GETLINECOUNT",
2863   "EM_LINEINDEX",
2864   "EM_SETHANDLE",
2865   "EM_GETHANDLE",
2866   "EM_GETTHUMB",
2867   "EM_UNKNOWN_BF",
2868   "EM_UNKNOWN_C0",
2869   "EM_LINELENGTH",
2870   "EM_REPLACESEL",
2871   "EM_UNKNOWN_C3",
2872   "EM_GETLINE",
2873   "EM_LIMITTEXT",
2874   "EM_CANUNDO",
2875   "EM_UNDO",
2876   "EM_FMTLINES",
2877   "EM_LINEFROMCHAR",
2878   "EM_UNKNOWN_CA",
2879   "EM_SETTABSTOPS",
2880   "EM_SETPASSWORDCHAR",
2881   "EM_EMPTYUNDOBUFFER",
2882   "EM_GETFIRSTVISIBLELINE",
2883   "EM_SETREADONLY",
2884   "EM_SETWORDBREAKPROC",
2885   "EM_GETWORDBREAKPROC",
2886   "EM_GETPASSWORDCHAR",
2887   "EM_SETMARGINS",
2888   "EM_GETMARGINS",
2889   "EM_GETLIMITTEXT",
2890   "EM_POSFROMCHAR",
2891   "EM_CHARFROMPOS",
2892   "EM_SETIMESTATUS",
2893   "EM_GETIMESTATUS"
2894 };
2895
2896 static const char * const richedit_messages[] = {
2897   "EM_CANPASTE",
2898   "EM_DISPLAYBAND",
2899   "EM_EXGETSEL",
2900   "EM_EXLIMITTEXT",
2901   "EM_EXLINEFROMCHAR",
2902   "EM_EXSETSEL",
2903   "EM_FINDTEXT",
2904   "EM_FORMATRANGE",
2905   "EM_GETCHARFORMAT",
2906   "EM_GETEVENTMASK",
2907   "EM_GETOLEINTERFACE",
2908   "EM_GETPARAFORMAT",
2909   "EM_GETSELTEXT",
2910   "EM_HIDESELECTION", 
2911   "EM_PASTESPECIAL",
2912   "EM_REQUESTRESIZE",
2913   "EM_SELECTIONTYPE",
2914   "EM_SETBKGNDCOLOR",
2915   "EM_SETCHARFORMAT",
2916   "EM_SETEVENTMASK",
2917   "EM_SETOLECALLBACK",
2918   "EM_SETPARAFORMAT",
2919   "EM_SETTARGETDEVICE",
2920   "EM_STREAMIN",
2921   "EM_STREAMOUT",
2922   "EM_GETTEXTRANGE",
2923   "EM_FINDWORDBREAK",
2924   "EM_SETOPTIONS",
2925   "EM_GETOPTIONS",
2926   "EM_FINDTEXTEX",
2927   "EM_GETWORDBREAKPROCEX",
2928   "EM_SETWORDBREAKPROCEX",
2929   "EM_SETUNDOLIMIT",
2930   "EM_UNKNOWN_USER_83",
2931   "EM_REDO",
2932   "EM_CANREDO",
2933   "EM_GETUNDONAME",
2934   "EM_GETREDONAME",
2935   "EM_STOPGROUPTYPING",
2936   "EM_SETTEXTMODE",
2937   "EM_GETTEXTMODE",
2938   "EM_AUTOURLDETECT",
2939   "EM_GETAUTOURLDETECT",
2940   "EM_SETPALETTE",
2941   "EM_GETTEXTEX",
2942   "EM_GETTEXTLENGTHEX",
2943   "EM_SHOWSCROLLBAR",
2944   "EM_SETTEXTEX",
2945   "EM_UNKNOWN_USER_98",
2946   "EM_UNKNOWN_USER_99",
2947   "EM_SETPUNCTUATION",
2948   "EM_GETPUNCTUATION",
2949   "EM_SETWORDWRAPMODE",
2950   "EM_GETWORDWRAPMODE",
2951   "EM_SETIMECOLOR",
2952   "EM_GETIMECOLOR",
2953   "EM_SETIMEOPTIONS",
2954   "EM_GETIMEOPTIONS",
2955   "EM_CONVPOSITION",
2956   "EM_UNKNOWN_USER_109",
2957   "EM_UNKNOWN_USER_110",
2958   "EM_UNKNOWN_USER_111",
2959   "EM_UNKNOWN_USER_112",
2960   "EM_UNKNOWN_USER_113",
2961   "EM_UNKNOWN_USER_114",
2962   "EM_UNKNOWN_USER_115",
2963   "EM_UNKNOWN_USER_116",
2964   "EM_UNKNOWN_USER_117",
2965   "EM_UNKNOWN_USER_118",
2966   "EM_UNKNOWN_USER_119",
2967   "EM_SETLANGOPTIONS",
2968   "EM_GETLANGOPTIONS",
2969   "EM_GETIMECOMPMODE",
2970   "EM_FINDTEXTW",
2971   "EM_FINDTEXTEXW",
2972   "EM_RECONVERSION",
2973   "EM_SETIMEMODEBIAS",
2974   "EM_GETIMEMODEBIAS"
2975 };
2976
2977 static const char *
2978 get_msg_name(UINT msg)
2979 {
2980   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2981     return edit_messages[msg - EM_GETSEL];
2982   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2983     return richedit_messages[msg - EM_CANPASTE];
2984   return "";
2985 }
2986
2987 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2988 {
2989   int x,y;
2990   ME_Cursor tmpCursor;
2991   BOOL isExact;
2992   int nCharOfs; /* The start of the clicked text. Absolute character offset */
2993
2994   ME_Run *tmpRun;
2995
2996   ENLINK info;
2997   x = (short)LOWORD(lParam);
2998   y = (short)HIWORD(lParam);
2999   nCharOfs = ME_CharFromPos(editor, x, y, &isExact);
3000   if (!isExact) return;
3001
3002   ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
3003   tmpRun = &tmpCursor.pRun->member.run;
3004
3005   if ((tmpRun->style->fmt.dwMask & CFM_LINK)
3006     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
3007   { /* The clicked run has CFE_LINK set */
3008     info.nmhdr.hwndFrom = editor->hWnd;
3009     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
3010     info.nmhdr.code = EN_LINK;
3011     info.msg = msg;
3012     info.wParam = wParam;
3013     info.lParam = lParam;
3014     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
3015     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
3016     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
3017   }
3018 }
3019
3020 #define UNSUPPORTED_MSG(e) \
3021   case e:                  \
3022     FIXME(#e ": stub\n");  \
3023     *phresult = S_FALSE;   \
3024     return 0;
3025
3026 /* Handle messages for windowless and windoweded richedit controls.
3027  *
3028  * The LRESULT that is returned is a return value for window procs,
3029  * and the phresult parameter is the COM return code needed by the
3030  * text services interface. */
3031 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3032                          LPARAM lParam, BOOL unicode, HRESULT* phresult)
3033 {
3034   *phresult = S_OK;
3035
3036   switch(msg) {
3037
3038   UNSUPPORTED_MSG(EM_DISPLAYBAND)
3039   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3040   UNSUPPORTED_MSG(EM_FMTLINES)
3041   UNSUPPORTED_MSG(EM_FORMATRANGE)
3042   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3043   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3044   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3045   UNSUPPORTED_MSG(EM_GETIMESTATUS)
3046   UNSUPPORTED_MSG(EM_SETIMESTATUS)
3047   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3048   UNSUPPORTED_MSG(EM_GETREDONAME)
3049   UNSUPPORTED_MSG(EM_GETTEXTMODE)
3050   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3051   UNSUPPORTED_MSG(EM_GETUNDONAME)
3052   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3053   UNSUPPORTED_MSG(EM_PASTESPECIAL)
3054   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3055   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3056   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3057   UNSUPPORTED_MSG(EM_SETFONTSIZE)
3058   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3059   UNSUPPORTED_MSG(EM_SETMARGINS)
3060   UNSUPPORTED_MSG(EM_SETPALETTE)
3061   UNSUPPORTED_MSG(EM_SETTABSTOPS)
3062   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3063   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3064   UNSUPPORTED_MSG(WM_STYLECHANGING)
3065   UNSUPPORTED_MSG(WM_STYLECHANGED)
3066
3067 /* Messages specific to Richedit controls */
3068
3069   case EM_STREAMIN:
3070    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3071   case EM_STREAMOUT:
3072    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3073   case WM_GETDLGCODE:
3074   {
3075     UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3076     if (editor->styleFlags & ES_MULTILINE)
3077       code |= DLGC_WANTMESSAGE;
3078     return code;
3079   }
3080   case EM_EMPTYUNDOBUFFER:
3081     ME_EmptyUndoStack(editor);
3082     return 0;
3083   case EM_GETSEL:
3084   {
3085     /* Note: wParam/lParam can be NULL */
3086     UINT from, to;
3087     PUINT pfrom = wParam ? (PUINT)wParam : &from;
3088     PUINT pto = lParam ? (PUINT)lParam : &to;
3089     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
3090     if ((*pfrom|*pto) & 0xFFFF0000)
3091       return -1;
3092     return MAKELONG(*pfrom,*pto);
3093   }
3094   case EM_EXGETSEL:
3095   {
3096     CHARRANGE *pRange = (CHARRANGE *)lParam;
3097     ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
3098     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3099     return 0;
3100   }
3101   case EM_SETUNDOLIMIT:
3102   {
3103     if ((int)wParam < 0)
3104       editor->nUndoLimit = STACK_SIZE_DEFAULT;
3105     else
3106       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3107     /* Setting a max stack size keeps wine from getting killed 
3108       for hogging memory. Windows allocates all this memory at once, so
3109       no program would realistically set a value above our maximum. */
3110     return editor->nUndoLimit;
3111   }
3112   case EM_CANUNDO:
3113     return editor->pUndoStack != NULL;
3114   case EM_CANREDO:
3115     return editor->pRedoStack != NULL;
3116   case WM_UNDO: /* FIXME: actually not the same */
3117   case EM_UNDO:
3118     return ME_Undo(editor);
3119   case EM_REDO:
3120     return ME_Redo(editor);
3121   case EM_GETOPTIONS:
3122   {
3123     /* these flags are equivalent to the ES_* counterparts */
3124     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3125                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3126     DWORD settings = editor->styleFlags & mask;
3127
3128     return settings;
3129   }
3130   case EM_SETOPTIONS:
3131   {
3132     /* these flags are equivalent to ES_* counterparts, except for
3133      * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3134      * but is still stored in editor->styleFlags. */
3135     const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3136                        ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3137                        ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3138     DWORD settings = mask & editor->styleFlags;
3139     DWORD oldSettings = settings;
3140     DWORD changedSettings;
3141
3142     switch(wParam)
3143     {
3144       case ECOOP_SET:
3145         settings = lParam;
3146         break;
3147       case ECOOP_OR:
3148         settings |= lParam;
3149         break;
3150       case ECOOP_AND:
3151         settings &= lParam;
3152         break;
3153       case ECOOP_XOR:
3154         settings ^= lParam;
3155     }
3156     changedSettings = oldSettings ^ settings;
3157
3158     if (oldSettings ^ settings) {
3159       editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3160
3161       if (settings & ECO_SELECTIONBAR) {
3162         editor->selofs = SELECTIONBAR_WIDTH;
3163         editor->rcFormat.left += SELECTIONBAR_WIDTH;
3164       } else {
3165         editor->selofs = 0;
3166         editor->rcFormat.left -= SELECTIONBAR_WIDTH;
3167       }
3168       ME_WrapMarkedParagraphs(editor);
3169     }
3170
3171     if (settings & ECO_VERTICAL)
3172       FIXME("ECO_VERTICAL not implemented yet!\n");
3173     if (settings & ECO_AUTOHSCROLL)
3174       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3175     if (settings & ECO_AUTOVSCROLL)
3176       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3177     if (settings & ECO_NOHIDESEL)
3178       FIXME("ECO_NOHIDESEL not implemented yet!\n");
3179     if (settings & ECO_WANTRETURN)
3180       FIXME("ECO_WANTRETURN not implemented yet!\n");
3181     if (settings & ECO_AUTOWORDSELECTION)
3182       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3183
3184     return settings;
3185   }
3186   case EM_SETSEL:
3187   {
3188     ME_InvalidateSelection(editor);
3189     ME_SetSelection(editor, wParam, lParam);
3190     ME_InvalidateSelection(editor);
3191     ITextHost_TxShowCaret(editor->texthost, FALSE);
3192     ME_ShowCaret(editor);
3193     ME_SendSelChange(editor);
3194     return 0;
3195   }
3196   case EM_SETSCROLLPOS:
3197   {
3198     POINT *point = (POINT *)lParam;
3199     ME_ScrollAbs(editor, point->x, point->y);
3200     return 0;
3201   }
3202   case EM_AUTOURLDETECT:
3203   {
3204     if (wParam==1 || wParam ==0)
3205     {
3206         editor->AutoURLDetect_bEnable = (BOOL)wParam;
3207         return 0;
3208     }
3209     return E_INVALIDARG;
3210   }
3211   case EM_GETAUTOURLDETECT:
3212   {
3213     return editor->AutoURLDetect_bEnable;
3214   }
3215   case EM_EXSETSEL:
3216   {
3217     int end;
3218     CHARRANGE range = *(CHARRANGE *)lParam;
3219
3220     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3221
3222     ME_InvalidateSelection(editor);
3223     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3224     ME_InvalidateSelection(editor);
3225     ITextHost_TxShowCaret(editor->texthost, FALSE);
3226     ME_ShowCaret(editor);
3227     ME_SendSelChange(editor);
3228
3229     return end;
3230   }
3231   case EM_SHOWSCROLLBAR:
3232   {
3233     ITextHost_TxShowScrollBar(editor->texthost, wParam, lParam);
3234     return 0;
3235   }
3236   case EM_SETTEXTEX:
3237   {
3238     LPWSTR wszText;
3239     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3240     size_t len = 0;
3241     int from, to;
3242     ME_Style *style;
3243     BOOL bRtf, bUnicode, bSelection;
3244     int oldModify = editor->nModifyStep;
3245
3246     if (!pStruct) return 0;
3247
3248     /* If we detect ascii rtf at the start of the string,
3249      * we know it isn't unicode. */
3250     bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3251                          !strncmp((char *)lParam, "{\\urtf}", 6)));
3252     bUnicode = !bRtf && pStruct->codepage == 1200;
3253
3254     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3255           bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3256           pStruct->flags, pStruct->codepage);
3257
3258     bSelection = (pStruct->flags & ST_SELECTION) != 0;
3259     if (bSelection) {
3260       ME_GetSelection(editor, &from, &to);
3261       style = ME_GetSelectionInsertStyle(editor);
3262       ME_InternalDeleteText(editor, from, to - from, FALSE);
3263     } else {
3264       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
3265       style = editor->pBuffer->pDefaultStyle;
3266     }
3267
3268     if (bRtf) {
3269       ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3270       if (bSelection) {
3271         /* FIXME: The length returned is doesn't include the rtf control
3272          * characters, only the actual text. */
3273         len = lParam ? strlen((char *)lParam) : 0;
3274       }
3275     } else {
3276       /* FIXME: make use of pStruct->codepage in the to unicode translation */
3277       wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3278       len = wszText ? lstrlenW(wszText) : 0;
3279       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3280     }
3281
3282     if (bSelection) {
3283       ME_ReleaseStyle(style);
3284       if (editor->AutoURLDetect_bEnable)
3285         ME_UpdateSelectionLinkAttribute(editor);
3286     } else {
3287       len = 1;
3288       if (editor->AutoURLDetect_bEnable)
3289         ME_UpdateLinkAttribute(editor, 0, -1);
3290     }
3291     ME_CommitUndo(editor);
3292     if (!(pStruct->flags & ST_KEEPUNDO))
3293     {
3294       editor->nModifyStep = oldModify;
3295       ME_EmptyUndoStack(editor);
3296     }
3297     ME_UpdateRepaint(editor);
3298     return len;
3299   }
3300   case EM_SETBKGNDCOLOR:
3301   {
3302     LRESULT lColor;
3303     if (editor->rgbBackColor != -1) {
3304       DeleteObject(editor->hbrBackground);
3305       lColor = editor->rgbBackColor;
3306     }
3307     else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3308
3309     if (wParam)
3310     {
3311       editor->rgbBackColor = -1;
3312       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3313     }
3314     else
3315     {
3316       editor->rgbBackColor = lParam;
3317       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3318     }
3319     ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3320     ITextHost_TxViewChange(editor->texthost, TRUE);
3321     return lColor;
3322   }
3323   case EM_GETMODIFY:
3324     return editor->nModifyStep == 0 ? 0 : -1;
3325   case EM_SETMODIFY:
3326   {
3327     if (wParam)
3328       editor->nModifyStep = 1;
3329     else
3330       editor->nModifyStep = 0;
3331     
3332     return 0;
3333   }
3334   case EM_SETREADONLY:
3335   {
3336     if (wParam)
3337       editor->styleFlags |= ES_READONLY;
3338     else
3339       editor->styleFlags &= ~ES_READONLY;
3340     return 0;
3341   }
3342   case EM_SETEVENTMASK:
3343   {
3344     DWORD nOldMask = editor->nEventMask;
3345     
3346     editor->nEventMask = lParam;
3347     return nOldMask;
3348   }
3349   case EM_GETEVENTMASK:
3350     return editor->nEventMask;
3351   case EM_SETCHARFORMAT:
3352   {
3353     CHARFORMAT2W buf, *p;
3354     BOOL bRepaint = TRUE;
3355     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3356     if (p == NULL) return 0;
3357     if (!wParam)
3358       ME_SetDefaultCharFormat(editor, p);
3359     else if (wParam == (SCF_WORD | SCF_SELECTION)) {
3360       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3361       return 0;
3362     } else if (wParam == SCF_ALL) {
3363       if (editor->mode & TM_PLAINTEXT)
3364         ME_SetDefaultCharFormat(editor, p);
3365       else {
3366         ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
3367         editor->nModifyStep = 1;
3368       }
3369     } else if (editor->mode & TM_PLAINTEXT) {
3370       return 0;
3371     } else {
3372       int from, to;
3373       ME_GetSelection(editor, &from, &to);
3374       bRepaint = (from != to);
3375       ME_SetSelectionCharFormat(editor, p);
3376       if (from != to) editor->nModifyStep = 1;
3377     }
3378     ME_CommitUndo(editor);
3379     if (bRepaint)
3380     {
3381       ME_WrapMarkedParagraphs(editor);
3382       ME_UpdateScrollBar(editor);
3383       ME_Repaint(editor);
3384     }
3385     return 1;
3386   }
3387   case EM_GETCHARFORMAT:
3388   {
3389     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3390     if (dst->cbSize != sizeof(CHARFORMATA) &&
3391         dst->cbSize != sizeof(CHARFORMATW) &&
3392         dst->cbSize != sizeof(CHARFORMAT2A) &&
3393         dst->cbSize != sizeof(CHARFORMAT2W))
3394       return 0;
3395     tmp.cbSize = sizeof(tmp);
3396     if (!wParam)
3397       ME_GetDefaultCharFormat(editor, &tmp);
3398     else
3399       ME_GetSelectionCharFormat(editor, &tmp);
3400     ME_CopyToCFAny(dst, &tmp);
3401     return tmp.dwMask;
3402   }
3403   case EM_SETPARAFORMAT:
3404   {
3405     BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3406     ME_WrapMarkedParagraphs(editor);
3407     ME_UpdateScrollBar(editor);
3408     ME_Repaint(editor);
3409     ME_CommitUndo(editor);
3410     return result;
3411   }
3412   case EM_GETPARAFORMAT:
3413     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3414     return ((PARAFORMAT2 *)lParam)->dwMask;
3415   case EM_GETFIRSTVISIBLELINE:
3416   {
3417     ME_DisplayItem *p = editor->pBuffer->pFirst;
3418     int y = editor->vert_si.nPos;
3419     int ypara = 0;
3420     int count = 0;
3421     int ystart, yend;
3422     while(p) {
3423       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3424       if (p->type == diTextEnd)
3425         break;
3426       if (p->type == diParagraph) {
3427         ypara = p->member.para.pt.y;
3428         continue;
3429       }
3430       ystart = ypara + p->member.row.pt.y;
3431       yend = ystart + p->member.row.nHeight;
3432       if (y < yend) {
3433         break;
3434       }
3435       count++;
3436     }
3437     return count;
3438   }
3439   case EM_HIDESELECTION:
3440   {
3441      editor->bHideSelection = (wParam != 0);
3442      ME_InvalidateSelection(editor);
3443      return 0;
3444   }
3445   case EM_LINESCROLL:
3446   {
3447     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3448     return TRUE; /* Should return false if a single line richedit control */
3449   }
3450   case WM_CLEAR:
3451   {
3452     int from, to;
3453     ME_GetSelection(editor, &from, &to);
3454     ME_InternalDeleteText(editor, from, to-from, FALSE);
3455     ME_CommitUndo(editor);
3456     ME_UpdateRepaint(editor);
3457     return 0;
3458   }
3459   case EM_REPLACESEL:
3460   {
3461     int from, to;
3462     ME_Style *style;
3463     LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3464     size_t len = wszText ? lstrlenW(wszText) : 0;
3465     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3466
3467     ME_GetSelection(editor, &from, &to);
3468     style = ME_GetSelectionInsertStyle(editor);
3469     ME_InternalDeleteText(editor, from, to-from, FALSE);
3470     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3471     ME_ReleaseStyle(style);
3472     /* drop temporary style if line end */
3473     /*
3474      * FIXME question: does abc\n mean: put abc,
3475      * clear temp style, put \n? (would require a change)
3476      */
3477     if (len>0 && wszText[len-1] == '\n')
3478       ME_ClearTempStyle(editor);
3479     ME_EndToUnicode(unicode, wszText);
3480     ME_CommitUndo(editor);
3481     if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3482     if (!wParam)
3483       ME_EmptyUndoStack(editor);
3484     ME_UpdateRepaint(editor);
3485     return len;
3486   }
3487   case EM_SCROLLCARET:
3488     ME_EnsureVisible(editor, &editor->pCursors[0]);
3489     return 0;
3490   case WM_SETFONT:
3491   {
3492     LOGFONTW lf;
3493     CHARFORMAT2W fmt;
3494     HDC hDC;
3495     BOOL bRepaint = LOWORD(lParam);
3496     
3497     if (!wParam)
3498       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
3499     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3500     hDC = ITextHost_TxGetDC(editor->texthost);
3501     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
3502     ITextHost_TxReleaseDC(editor->texthost, hDC);
3503     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
3504     ME_SetDefaultCharFormat(editor, &fmt);
3505
3506     ME_CommitUndo(editor);
3507     if (bRepaint)
3508       ME_RewrapRepaint(editor);
3509     return 0;
3510   }
3511   case WM_SETTEXT:
3512   {
3513     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
3514     if (lParam)
3515     {
3516       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3517       if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
3518       {
3519         /* Undocumented: WM_SETTEXT supports RTF text */
3520         ME_StreamInRTFString(editor, 0, (char *)lParam);
3521       }
3522       else
3523       {
3524         LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3525         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3526         if (lstrlenW(wszText) > 0)
3527         {
3528           int len = -1;
3529
3530           /* uses default style! */
3531           if (!(editor->styleFlags & ES_MULTILINE))
3532           {
3533             WCHAR * p;
3534
3535             p = wszText;
3536             while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3537             len = p - wszText;
3538           }
3539           ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3540         }
3541         ME_EndToUnicode(unicode, wszText);
3542       }
3543     }
3544     else
3545       TRACE("WM_SETTEXT - NULL\n");
3546     if (editor->AutoURLDetect_bEnable)
3547     {
3548       ME_UpdateLinkAttribute(editor, 0, -1);
3549     }
3550     ME_SetSelection(editor, 0, 0);
3551     editor->nModifyStep = 0;
3552     ME_CommitUndo(editor);
3553     ME_EmptyUndoStack(editor);
3554     ME_UpdateRepaint(editor);
3555     return 1;
3556   }
3557   case EM_CANPASTE:
3558   {
3559     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3560     if (IsClipboardFormatAvailable(nRTFFormat))
3561       return TRUE;
3562     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3563       return TRUE;
3564     return FALSE;
3565   }
3566   case WM_PASTE:
3567     ME_Paste(editor);
3568     return 0;
3569   case WM_CUT:
3570   case WM_COPY:
3571   {
3572     CHARRANGE range;
3573     ME_GetSelection(editor, &range.cpMin, &range.cpMax);
3574
3575     if (ME_Copy(editor, &range) && msg == WM_CUT)
3576     {
3577       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
3578       ME_CommitUndo(editor);
3579       ME_UpdateRepaint(editor);
3580     }
3581     return 0;
3582   }
3583   case WM_GETTEXTLENGTH:
3584   {
3585     GETTEXTLENGTHEX how;
3586
3587     /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3588     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3589     how.codepage = unicode ? 1200 : CP_ACP;
3590     return ME_GetTextLengthEx(editor, &how);
3591   }
3592   case EM_GETTEXTLENGTHEX:
3593     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3594   case WM_GETTEXT:
3595   {
3596     GETTEXTEX ex;
3597     LRESULT rc;
3598     LPSTR bufferA = NULL;
3599     LPWSTR bufferW = NULL;
3600
3601     if (unicode)
3602         bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
3603     else
3604         bufferA = heap_alloc(wParam + 2);
3605
3606     ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3607     ex.flags = GT_USECRLF;
3608     ex.codepage = unicode ? 1200 : CP_ACP;
3609     ex.lpDefaultChar = NULL;
3610     ex.lpUsedDefChar = NULL;
3611
3612     rc = ME_GetTextEx(editor, &ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA);
3613
3614     if (unicode)
3615     {
3616         memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
3617         if (strlenW(bufferW) >= wParam) rc = 0;
3618     }
3619     else
3620     {
3621         memcpy((LPSTR)lParam, bufferA, wParam);
3622         if (strlen(bufferA) >= wParam) rc = 0;
3623     }
3624     heap_free(bufferA);
3625     heap_free(bufferW);
3626     return rc;
3627   }
3628   case EM_GETTEXTEX:
3629     return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3630   case EM_GETSELTEXT:
3631   {
3632     int from, to;
3633     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
3634     ME_GetSelection(editor, &from, &to);
3635     tr.chrg.cpMin = from;
3636     tr.chrg.cpMax = to;
3637     tr.lpstrText = (WCHAR *)lParam;
3638     return ME_GetTextRange(editor, &tr, unicode);
3639   }
3640   case EM_GETSCROLLPOS:
3641   {
3642     POINT *point = (POINT *)lParam;
3643     point->x = editor->horz_si.nPos;
3644     point->y = editor->vert_si.nPos;
3645     return 1;
3646   }
3647   case EM_GETTEXTRANGE:
3648   {
3649     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3650     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
3651       rng->chrg.cpMin, rng->chrg.cpMax, unicode,
3652       editor->bEmulateVersion10, ME_GetTextLength(editor));
3653     return ME_GetTextRange(editor, rng, unicode);
3654   }
3655   case EM_GETLINE:
3656   {
3657     ME_DisplayItem *run;
3658     const unsigned int nMaxChars = *(WORD *) lParam;
3659     unsigned int nCharsLeft = nMaxChars;
3660     char *dest = (char *) lParam;
3661     BOOL wroteNull = FALSE;
3662
3663     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3664           unicode ? "Unicode" : "Ansi");
3665
3666     run = ME_FindRowWithNumber(editor, wParam);
3667     if (run == NULL)
3668       return 0;
3669
3670     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3671            && !(run->member.run.nFlags & MERF_ENDPARA))
3672     {
3673       unsigned int nCopy;
3674       ME_String *strText;
3675       if (run->type != diRun)
3676         break;
3677       strText = run->member.run.strText;
3678       nCopy = min(nCharsLeft, strText->nLen);
3679
3680       if (unicode)
3681         memcpy(dest, strText->szData, nCopy * sizeof(WCHAR));
3682       else
3683         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3684                                     nCharsLeft, NULL, NULL);
3685       dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3686       nCharsLeft -= nCopy;
3687     }
3688
3689     /* append line termination, space allowing */
3690     if (nCharsLeft > 0)
3691     {
3692       if (run && (run->member.run.nFlags & MERF_ENDPARA))
3693       {
3694         int i;
3695         /* Write as many \r as encoded in end-of-paragraph, space allowing */
3696         for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
3697         {
3698           *((WCHAR *)dest) = '\r';
3699           dest += unicode ? sizeof(WCHAR) : 1;
3700         }
3701         /* Write as many \n as encoded in end-of-paragraph, space allowing */
3702         for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
3703         {
3704           *((WCHAR *)dest) = '\n';
3705           dest += unicode ? sizeof(WCHAR) : 1;
3706         }
3707       }
3708       if (nCharsLeft > 0)
3709       {
3710         if (unicode)
3711           *((WCHAR *)dest) = '\0';
3712         else
3713           *dest = '\0';
3714         nCharsLeft--;
3715         wroteNull = TRUE;
3716       }
3717     }
3718
3719     TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3720     return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3721   }
3722   case EM_GETLINECOUNT:
3723   {
3724     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3725     int nRows = 0;
3726
3727     ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3728
3729     while (item != editor->pBuffer->pLast)
3730     {
3731       assert(item->type == diParagraph);
3732       prev_para = ME_FindItemBack(item, diRun);
3733       if (prev_para) {
3734         assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3735       }
3736       nRows += item->member.para.nRows;
3737       item = item->member.para.next_para;
3738     }
3739     last_para = ME_FindItemBack(item, diRun);
3740     assert(last_para);
3741     assert(last_para->member.run.nFlags & MERF_ENDPARA);
3742     if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
3743         && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
3744     {
3745       /* In 1.0 emulation, the last solitary \r at the very end of the text
3746          (if one exists) is NOT a line break.
3747          FIXME: this is an ugly hack. This should have a more regular model. */
3748       nRows--;
3749     }
3750
3751     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3752     return max(1, nRows);
3753   }
3754   case EM_LINEFROMCHAR:
3755   {
3756     if (wParam == -1)
3757       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
3758     else
3759       return ME_RowNumberFromCharOfs(editor, wParam);
3760   }
3761   case EM_EXLINEFROMCHAR:
3762   {
3763     if (lParam == -1)
3764       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
3765     else    
3766       return ME_RowNumberFromCharOfs(editor, lParam);
3767   }
3768   case EM_LINEINDEX:
3769   {
3770     ME_DisplayItem *item, *para;
3771     int nCharOfs;
3772     
3773     if (wParam == -1)
3774       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3775     else
3776       item = ME_FindRowWithNumber(editor, wParam);
3777     if (!item)
3778       return -1;
3779     para = ME_GetParagraph(item);
3780     item = ME_FindItemFwd(item, diRun);
3781     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3782     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3783     return nCharOfs;
3784   }
3785   case EM_LINELENGTH:
3786   {
3787     ME_DisplayItem *item, *item_end;
3788     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3789     
3790     if (wParam > ME_GetTextLength(editor))
3791       return 0;
3792     if (wParam == -1)
3793     {
3794       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3795       return 0;
3796     }
3797     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
3798     item = ME_RowStart(item);
3799     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
3800     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3801     if (item_end->type == diStartRow)
3802       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
3803     else
3804     {
3805       ME_DisplayItem *endPara;
3806
3807       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
3808       endPara = ME_FindItemFwd(item, diParagraphOrEnd);
3809       endPara = ME_FindItemBack(endPara, diRun);
3810       assert(endPara);
3811       assert(endPara->type == diRun);
3812       assert(endPara->member.run.nFlags & MERF_ENDPARA);
3813       nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
3814     }
3815     nChars = nNextLineOfs - nThisLineOfs;
3816     TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3817     return nChars;
3818   }
3819   case EM_EXLIMITTEXT:
3820   {
3821     if ((int)lParam < 0)
3822      return 0;
3823     if (lParam == 0)
3824       editor->nTextLimit = 65536;
3825     else
3826       editor->nTextLimit = (int) lParam;
3827     return 0;
3828   }
3829   case EM_LIMITTEXT:
3830   {
3831     if (wParam == 0)
3832       editor->nTextLimit = 65536;
3833     else
3834       editor->nTextLimit = (int) wParam;
3835     return 0;
3836   }
3837   case EM_GETLIMITTEXT:
3838   {
3839     return editor->nTextLimit;
3840   }
3841   case EM_FINDTEXT:
3842   {
3843     FINDTEXTA *ft = (FINDTEXTA *)lParam;
3844     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3845     WCHAR *tmp;
3846     LRESULT r;
3847
3848     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3849       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3850     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3851     FREE_OBJ( tmp );
3852     return r;
3853   }
3854   case EM_FINDTEXTEX:
3855   {
3856     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3857     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3858     WCHAR *tmp;
3859     LRESULT r;
3860
3861     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3862       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3863     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3864     FREE_OBJ( tmp );
3865     return r;
3866   }
3867   case EM_FINDTEXTW:
3868   {
3869     FINDTEXTW *ft = (FINDTEXTW *)lParam;
3870     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3871   }
3872   case EM_FINDTEXTEXW:
3873   {
3874     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3875     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3876   }
3877   case EM_GETZOOM:
3878     if (!wParam || !lParam)
3879       return FALSE;
3880     *(int *)wParam = editor->nZoomNumerator;
3881     *(int *)lParam = editor->nZoomDenominator;
3882     return TRUE;
3883   case EM_SETZOOM:
3884     return ME_SetZoom(editor, wParam, lParam);
3885   case EM_CHARFROMPOS:
3886     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3887   case EM_POSFROMCHAR:
3888   {
3889     ME_DisplayItem *pRun;
3890     int nCharOfs, nOffset, nLength;
3891     POINTL pt = {0,0};
3892
3893     nCharOfs = wParam;
3894     /* detect which API version we're dealing with */
3895     if (wParam >= 0x40000)
3896         nCharOfs = lParam;
3897     nLength = ME_GetTextLength(editor);
3898     nCharOfs = min(nCharOfs, nLength);
3899     nCharOfs = max(nCharOfs, 0);
3900
3901     ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
3902     assert(pRun->type == diRun);
3903     pt.y = pRun->member.run.pt.y;
3904     pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3905     pt.y += ME_GetParagraph(pRun)->member.para.pt.y + editor->rcFormat.top;
3906     pt.x += editor->rcFormat.left;
3907
3908     pt.x -= editor->horz_si.nPos;
3909     pt.y -= editor->vert_si.nPos;
3910
3911     if (wParam >= 0x40000) {
3912         *(POINTL *)wParam = pt;
3913     }
3914     return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3915   }
3916   case WM_CREATE:
3917   {
3918     SCROLLINFO si;
3919
3920     ME_SetDefaultFormatRect(editor);
3921
3922     si.cbSize = sizeof(si);
3923     si.fMask = SIF_PAGE | SIF_RANGE;
3924     if (editor->styleFlags & ES_DISABLENOSCROLL)
3925       si.fMask |= SIF_DISABLENOSCROLL;
3926     si.nMax = (si.fMask & SIF_DISABLENOSCROLL) ? 1 : 0;
3927     si.nMin = 0;
3928     si.nPage = 0;
3929     if (editor->hWnd) {
3930       SetScrollInfo(editor->hWnd, SB_VERT, &si, TRUE);
3931       SetScrollInfo(editor->hWnd, SB_HORZ, &si, TRUE);
3932     } else {
3933       ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, si.nMin, si.nMax, TRUE);
3934       ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, si.nMin, si.nMax, TRUE);
3935     }
3936
3937     ME_CommitUndo(editor);
3938     ME_WrapMarkedParagraphs(editor);
3939     ME_MoveCaret(editor);
3940     return 0;
3941   }
3942   case WM_DESTROY:
3943     ME_DestroyEditor(editor);
3944     return 0;
3945   case WM_SETCURSOR:
3946   {
3947     return ME_SetCursor(editor);
3948   }
3949   case WM_LBUTTONDBLCLK:
3950   case WM_LBUTTONDOWN:
3951   {
3952     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3953     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3954         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3955       return 0;
3956     ITextHost_TxSetFocus(editor->texthost);
3957     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3958                    ME_CalculateClickCount(editor, msg, wParam, lParam));
3959     ITextHost_TxSetCapture(editor->texthost, TRUE);
3960     editor->bMouseCaptured = TRUE;
3961     ME_LinkNotify(editor,msg,wParam,lParam);
3962     if (!ME_SetCursor(editor)) goto do_default;
3963     break;
3964   }
3965   case WM_MOUSEMOVE:
3966     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3967         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3968       return 0;
3969     if (editor->bMouseCaptured)
3970       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3971     ME_LinkNotify(editor,msg,wParam,lParam);
3972     /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3973     if (editor->bMouseCaptured)
3974         ME_SetCursor(editor);
3975     break;
3976   case WM_LBUTTONUP:
3977     if (editor->bMouseCaptured) {
3978       ITextHost_TxSetCapture(editor->texthost, FALSE);
3979       editor->bMouseCaptured = FALSE;
3980     }
3981     if (editor->nSelectionType == stDocument)
3982       editor->nSelectionType = stPosition;
3983     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3984         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3985       return 0;
3986     else
3987     {
3988       ME_SetCursor(editor);
3989       ME_LinkNotify(editor,msg,wParam,lParam);
3990     }
3991     break;
3992   case WM_RBUTTONUP:
3993   case WM_RBUTTONDOWN:
3994     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3995     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3996         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3997       return 0;
3998     goto do_default;
3999   case WM_CONTEXTMENU:
4000     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4001       goto do_default;
4002     break;
4003   case WM_SETFOCUS:
4004     editor->bHaveFocus = TRUE;
4005     ME_ShowCaret(editor);
4006     ME_SendOldNotify(editor, EN_SETFOCUS);
4007     return 0;
4008   case WM_KILLFOCUS:
4009     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4010     editor->bHaveFocus = FALSE;
4011     ME_HideCaret(editor);
4012     ME_SendOldNotify(editor, EN_KILLFOCUS);
4013     return 0;
4014   case WM_COMMAND:
4015     TRACE("editor wnd command = %d\n", LOWORD(wParam));
4016     return 0;
4017   case WM_KEYUP:
4018     if ((editor->nEventMask & ENM_KEYEVENTS) &&
4019         !ME_FilterEvent(editor, msg, &wParam, &lParam))
4020       return 0;
4021     goto do_default;
4022   case WM_KEYDOWN:
4023     if ((editor->nEventMask & ENM_KEYEVENTS) &&
4024         !ME_FilterEvent(editor, msg, &wParam, &lParam))
4025       return 0;
4026     if (ME_KeyDown(editor, LOWORD(wParam)))
4027       return 0;
4028     goto do_default;
4029   case WM_CHAR:
4030     return ME_Char(editor, wParam, lParam, unicode);
4031   case WM_UNICHAR:
4032     if (unicode)
4033     {
4034         if(wParam == UNICODE_NOCHAR) return TRUE;
4035         if(wParam <= 0x000fffff)
4036         {
4037             if(wParam > 0xffff) /* convert to surrogates */
4038             {
4039                 wParam -= 0x10000;
4040                 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4041                 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4042             } else {
4043               ME_Char(editor, wParam, 0, TRUE);
4044             }
4045         }
4046         return 0;
4047     }
4048     break;
4049   case EM_STOPGROUPTYPING:
4050     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4051     return 0;
4052   case WM_HSCROLL:
4053   {
4054     const int scrollUnit = 7;
4055
4056     switch(LOWORD(wParam))
4057     {
4058       case SB_LEFT:
4059         ME_ScrollAbs(editor, 0, 0);
4060         break;
4061       case SB_RIGHT:
4062         ME_ScrollAbs(editor,
4063                      editor->horz_si.nMax - (int)editor->horz_si.nPage,
4064                      editor->vert_si.nMax - (int)editor->vert_si.nPage);
4065         break;
4066       case SB_LINELEFT:
4067         ME_ScrollLeft(editor, scrollUnit);
4068         break;
4069       case SB_LINERIGHT:
4070         ME_ScrollRight(editor, scrollUnit);
4071         break;
4072       case SB_PAGELEFT:
4073         ME_ScrollLeft(editor, editor->sizeWindow.cx);
4074         break;
4075       case SB_PAGERIGHT:
4076         ME_ScrollRight(editor, editor->sizeWindow.cx);
4077         break;
4078       case SB_THUMBTRACK:
4079       case SB_THUMBPOSITION:
4080       {
4081         SCROLLINFO sbi;
4082         sbi.cbSize = sizeof(sbi);
4083         sbi.fMask = SIF_TRACKPOS;
4084         /* Try to get 32-bit track position value. */
4085         if (!GetScrollInfo(editor->hWnd, SB_HORZ, &sbi))
4086           /* GetScrollInfo failed, settle for 16-bit value in wParam. */
4087           sbi.nTrackPos = HIWORD(wParam);
4088
4089         ME_HScrollAbs(editor, sbi.nTrackPos);
4090         break;
4091       }
4092     }
4093     break;
4094   }
4095   case EM_SCROLL: /* fall through */
4096   case WM_VSCROLL:
4097   {
4098     int origNPos;
4099     int lineHeight;
4100
4101     origNPos = editor->vert_si.nPos;
4102     lineHeight = 24;
4103
4104     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
4105       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4106     if (lineHeight <= 0) lineHeight = 24;
4107
4108     switch(LOWORD(wParam))
4109     {
4110       case SB_TOP:
4111         ME_ScrollAbs(editor, 0, 0);
4112         break;
4113       case SB_BOTTOM:
4114         ME_ScrollAbs(editor,
4115                      editor->horz_si.nMax - (int)editor->horz_si.nPage,
4116                      editor->vert_si.nMax - (int)editor->vert_si.nPage);
4117         break;
4118       case SB_LINEUP:
4119         ME_ScrollUp(editor,lineHeight);
4120         break;
4121       case SB_LINEDOWN:
4122         ME_ScrollDown(editor,lineHeight);
4123         break;
4124       case SB_PAGEUP:
4125         ME_ScrollUp(editor,editor->sizeWindow.cy);
4126         break;
4127       case SB_PAGEDOWN:
4128         ME_ScrollDown(editor,editor->sizeWindow.cy);
4129         break;
4130       case SB_THUMBTRACK:
4131       case SB_THUMBPOSITION:
4132       {
4133         SCROLLINFO sbi;
4134         sbi.cbSize = sizeof(sbi);
4135         sbi.fMask = SIF_TRACKPOS;
4136         /* Try to get 32-bit track position value. */
4137         if (!GetScrollInfo(editor->hWnd, SB_VERT, &sbi))
4138           /* GetScrollInfo failed, settle for 16-bit value in wParam. */
4139           sbi.nTrackPos = HIWORD(wParam);
4140
4141         ME_VScrollAbs(editor, sbi.nTrackPos);
4142         break;
4143       }
4144     }
4145     if (msg == EM_SCROLL)
4146       return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4147     break;
4148   }
4149   case WM_MOUSEWHEEL:
4150   {
4151     int gcWheelDelta;
4152     UINT pulScrollLines;
4153     BOOL ctrl_is_down;
4154
4155     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4156         !ME_FilterEvent(editor, msg, &wParam, &lParam))
4157       return 0;
4158
4159     ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4160
4161     gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4162
4163     if (abs(gcWheelDelta) >= WHEEL_DELTA)
4164     {
4165       if (ctrl_is_down) {
4166         int numerator;
4167         if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4168         {
4169           numerator = 100;
4170         } else {
4171           numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4172         }
4173         numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4174         if (numerator >= 10 && numerator <= 500)
4175           ME_SetZoom(editor, numerator, 100);
4176       } else {
4177         SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4178         /* FIXME follow the original */
4179         if (pulScrollLines)
4180           ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4181       }
4182     }
4183     break;
4184   }
4185   case EM_GETRECT:
4186   {
4187     *((RECT *)lParam) = editor->rcFormat;
4188     if (editor->bDefaultFormatRect)
4189       ((RECT *)lParam)->left -= editor->selofs;
4190     return 0;
4191   }
4192   case EM_SETRECT:
4193   case EM_SETRECTNP:
4194   {
4195     if (lParam)
4196     {
4197       int border = 0;
4198       RECT clientRect;
4199       RECT *rc = (RECT *)lParam;
4200
4201       border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4202       ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4203       if (wParam == 0)
4204       {
4205         editor->rcFormat.top = max(0, rc->top - border);
4206         editor->rcFormat.left = max(0, rc->left - border);
4207         editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4208         editor->rcFormat.right = min(clientRect.right, rc->right + border);
4209       } else if (wParam == 1) {
4210         /* MSDN incorrectly says a wParam value of 1 causes the
4211          * lParam rect to be used as a relative offset,
4212          * however, the tests show it just prevents min/max bound
4213          * checking. */
4214         editor->rcFormat.top = rc->top - border;
4215         editor->rcFormat.left = rc->left - border;
4216         editor->rcFormat.bottom = rc->bottom;
4217         editor->rcFormat.right = rc->right + border;
4218       } else {
4219         return 0;
4220       }
4221       editor->bDefaultFormatRect = FALSE;
4222     }
4223     else
4224     {
4225       ME_SetDefaultFormatRect(editor);
4226       editor->bDefaultFormatRect = TRUE;
4227     }
4228     if (msg != EM_SETRECTNP)
4229       ME_RewrapRepaint(editor);
4230     return 0;
4231   }
4232   case EM_REQUESTRESIZE:
4233     ME_SendRequestResize(editor, TRUE);
4234     return 0;
4235   case WM_SETREDRAW:
4236     goto do_default;
4237   case WM_SIZE:
4238   {
4239     RECT clientRect;
4240
4241     ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4242     if (editor->bDefaultFormatRect) {
4243       ME_SetDefaultFormatRect(editor);
4244     } else {
4245       editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4246       editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4247     }
4248     editor->prevClientRect = clientRect;
4249     ME_RewrapRepaint(editor);
4250     goto do_default;
4251   }
4252   /* IME messages to make richedit controls IME aware */
4253   case WM_IME_SETCONTEXT:
4254   case WM_IME_CONTROL:
4255   case WM_IME_SELECT:
4256   case WM_IME_COMPOSITIONFULL:
4257     return 0;
4258   case WM_IME_STARTCOMPOSITION:
4259   {
4260     editor->imeStartIndex=ME_GetCursorOfs(editor,0);
4261     ME_DeleteSelection(editor);
4262     ME_CommitUndo(editor);
4263     ME_UpdateRepaint(editor);
4264     return 0;
4265   }
4266   case WM_IME_COMPOSITION:
4267   {
4268     HIMC hIMC;
4269
4270     ME_Style *style = ME_GetInsertStyle(editor, 0);
4271     hIMC = ITextHost_TxImmGetContext(editor->texthost);
4272     ME_DeleteSelection(editor);
4273     ME_CommitUndo(editor);
4274     ME_SaveTempStyle(editor);
4275     if (lParam & GCS_RESULTSTR)
4276     {
4277         LPWSTR lpCompStr = NULL;
4278         DWORD dwBufLen;
4279
4280         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
4281         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4282         ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
4283         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4284         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4285     }
4286     else if (lParam & GCS_COMPSTR)
4287     {
4288         LPWSTR lpCompStr = NULL;
4289         DWORD dwBufLen;
4290
4291         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
4292         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4293         ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
4294         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4295
4296         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4297         ME_SetSelection(editor,editor->imeStartIndex,
4298                         editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4299     }
4300     ME_ReleaseStyle(style);
4301     ME_UpdateRepaint(editor);
4302     return 0;
4303   }
4304   case WM_IME_ENDCOMPOSITION:
4305   {
4306     ME_DeleteSelection(editor);
4307     editor->imeStartIndex=-1;
4308     return 0;
4309   }
4310   case EM_GETOLEINTERFACE:
4311   {
4312     LPVOID *ppvObj = (LPVOID*) lParam;
4313     return CreateIRichEditOle(editor, ppvObj);
4314   }
4315   case EM_GETPASSWORDCHAR:
4316   {
4317     return editor->cPasswordMask;
4318   }
4319   case EM_SETOLECALLBACK:
4320     if(editor->lpOleCallback)
4321       IUnknown_Release(editor->lpOleCallback);
4322     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
4323     if(editor->lpOleCallback)
4324       IUnknown_AddRef(editor->lpOleCallback);
4325     return TRUE;
4326   case EM_GETWORDBREAKPROC:
4327     return (LRESULT)editor->pfnWordBreak;
4328   case EM_SETWORDBREAKPROC:
4329   {
4330     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4331
4332     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4333     return (LRESULT)pfnOld;
4334   }
4335   case EM_SETTEXTMODE:
4336   {
4337     LRESULT ret;
4338     int mask = 0;
4339     int changes = 0;
4340     GETTEXTLENGTHEX how;
4341
4342     /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
4343     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
4344     how.codepage = unicode ? 1200 : CP_ACP;
4345     ret = ME_GetTextLengthEx(editor, &how);
4346     if (!ret)
4347     {
4348       /*Check for valid wParam*/
4349       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
4350           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
4351           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
4352         return 1;
4353       else
4354       {
4355         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4356         {
4357           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
4358           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
4359         }
4360         /*FIXME: Currently no support for undo level and code page options*/ 
4361         editor->mode = (editor->mode & (~mask)) | changes;
4362         return 0;
4363       }
4364     }
4365     return ret;
4366   }
4367   case EM_SETPASSWORDCHAR:
4368   {
4369     editor->cPasswordMask = wParam;
4370     ME_RewrapRepaint(editor);
4371     return 0;
4372   }
4373   case EM_SETTARGETDEVICE:
4374     if (wParam == 0)
4375     {
4376       BOOL new = (lParam == 0);
4377       if (editor->bWordWrap != new)
4378       {
4379         editor->bWordWrap = new;
4380         ME_RewrapRepaint(editor);
4381       }
4382     }
4383     else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
4384     break;
4385   default:
4386   do_default:
4387     *phresult = S_FALSE;
4388     break;
4389   }
4390   return 0L;
4391 }
4392
4393 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4394                                       LPARAM lParam, BOOL unicode)
4395 {
4396   ME_TextEditor *editor;
4397   HRESULT hresult;
4398   LRESULT lresult = 0;
4399
4400   TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4401         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4402
4403   editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4404   if (!editor)
4405   {
4406     if (msg == WM_NCCREATE)
4407     {
4408       CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4409       ITextHost *texthost;
4410
4411       TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4412       texthost = ME_CreateTextHost(hWnd, FALSE);
4413       return texthost != NULL;
4414     }
4415     else if (msg != WM_NCDESTROY)
4416     {
4417       ERR("called with invalid hWnd %p - application bug?\n", hWnd);
4418       return 0;
4419     }
4420   }
4421
4422   switch (msg)
4423   {
4424     case WM_PAINT:
4425     {
4426       HDC hDC;
4427       RECT rc;
4428       PAINTSTRUCT ps;
4429
4430       hDC = BeginPaint(editor->hWnd, &ps);
4431       /* Erase area outside of the formatting rectangle */
4432       if (ps.rcPaint.top < editor->rcFormat.top)
4433       {
4434         rc = ps.rcPaint;
4435         rc.bottom = editor->rcFormat.top;
4436         FillRect(hDC, &rc, editor->hbrBackground);
4437         ps.rcPaint.top = editor->rcFormat.top;
4438       }
4439       if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4440         rc = ps.rcPaint;
4441         rc.top = editor->rcFormat.bottom;
4442         FillRect(hDC, &rc, editor->hbrBackground);
4443         ps.rcPaint.bottom = editor->rcFormat.bottom;
4444       }
4445       if (ps.rcPaint.left < editor->rcFormat.left) {
4446         rc = ps.rcPaint;
4447         rc.right = editor->rcFormat.left;
4448         FillRect(hDC, &rc, editor->hbrBackground);
4449         ps.rcPaint.left = editor->rcFormat.left;
4450       }
4451       if (ps.rcPaint.right > editor->rcFormat.right) {
4452         rc = ps.rcPaint;
4453         rc.left = editor->rcFormat.right;
4454         FillRect(hDC, &rc, editor->hbrBackground);
4455         ps.rcPaint.right = editor->rcFormat.right;
4456       }
4457
4458       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
4459       EndPaint(editor->hWnd, &ps);
4460       return 0;
4461     }
4462     case WM_ERASEBKGND:
4463     {
4464       HDC hDC = (HDC)wParam;
4465       RECT rc;
4466
4467       if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4468         FillRect(hDC, &rc, editor->hbrBackground);
4469       return 1;
4470     }
4471     case EM_SETOPTIONS:
4472     {
4473       DWORD dwStyle;
4474       const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4475                          ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4476                          ECO_SELECTIONBAR;
4477       lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4478       dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4479       dwStyle = (dwStyle & ~mask) | (lresult & mask);
4480       SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4481       return lresult;
4482     }
4483     case EM_SETREADONLY:
4484     {
4485       DWORD dwStyle;
4486       lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4487       dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4488       dwStyle &= ~ES_READONLY;
4489       if (wParam)
4490         dwStyle |= ES_READONLY;
4491       SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4492       return lresult;
4493     }
4494     default:
4495       lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4496   }
4497
4498   if (hresult == S_FALSE)
4499     lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4500
4501   TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4502         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4503
4504   return lresult;
4505 }
4506
4507 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4508 {
4509     BOOL unicode = TRUE;
4510
4511     /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4512     if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4513         unicode = FALSE;
4514
4515     return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4516 }
4517
4518 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4519 {
4520     return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4521 }
4522
4523 /******************************************************************
4524  *        RichEditANSIWndProc (RICHED20.10)
4525  */
4526 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4527 {
4528     return RichEditWndProcA(hWnd, msg, wParam, lParam);
4529 }
4530
4531 /******************************************************************
4532  *        RichEdit10ANSIWndProc (RICHED20.9)
4533  */
4534 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4535 {
4536   if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4537   {
4538     ITextHost *texthost;
4539     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4540
4541     TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4542     texthost = ME_CreateTextHost(hWnd, TRUE);
4543     return texthost != NULL;
4544   }
4545   return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4546 }
4547
4548 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4549 {
4550   ITextHost_TxNotify(editor->texthost, nCode, NULL);
4551 }
4552
4553 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
4554 {
4555   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
4556   int i = 0;
4557   
4558   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
4559     item = item->member.para.next_para;
4560   if (!item)
4561     return 0;
4562   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
4563     item = item->member.para.next_para;
4564     i++;
4565   }
4566   return i;
4567 }
4568
4569
4570 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
4571 {
4572   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
4573   int nWritten = 0;
4574   WCHAR *pStart = buffer;
4575   
4576   if (!item) {
4577     *buffer = 0;
4578     return 0;
4579   }
4580   
4581   /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4582   if (editor->bEmulateVersion10) bCRLF = 0;
4583
4584   if (nStart)
4585   {
4586     int nLen = ME_StrLen(item->member.run.strText) - nStart;
4587     if (nLen > nChars)
4588       nLen = nChars;
4589     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
4590     nChars -= nLen;
4591     nWritten += nLen;
4592     buffer += nLen;
4593     if (!nChars) {
4594       *buffer = 0;
4595       return nWritten;
4596     }
4597     nStart = 0;
4598     item = ME_FindItemFwd(item, diRun);
4599   }
4600   
4601   while(nChars && item)
4602   {
4603     int nLen = ME_StrLen(item->member.run.strText);
4604     if (item->member.run.nFlags & MERF_ENDPARA)
4605        nLen = item->member.run.nCR + item->member.run.nLF;
4606     if (nLen > nChars)
4607       nLen = nChars;
4608
4609     if (item->member.run.nFlags & MERF_ENDCELL &&
4610         item->member.run.nFlags & MERF_ENDPARA)
4611     {
4612       *buffer = '\t';
4613     }
4614     else if (item->member.run.nFlags & MERF_ENDPARA)
4615     {
4616       if (!ME_FindItemFwd(item, diRun))
4617         /* No '\r' is appended to the last paragraph. */
4618         nLen = 0;
4619       else if (bCRLF && nChars == 1) {
4620         nLen = 0;
4621         nChars = 0;
4622       } else {
4623         if (bCRLF)
4624         {
4625           /* richedit 2.0 case - actual line-break is \r but should report \r\n */
4626           if (ME_GetParagraph(item)->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND))
4627             assert(nLen == 2);
4628           else
4629             assert(nLen == 1);
4630           *buffer++ = '\r';
4631           *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
4632           if (nLen == 1)
4633             nWritten++;
4634           else
4635             buffer--;
4636         }
4637         else
4638         {
4639           int i, j;
4640
4641           /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
4642           i = 0;
4643           while (nChars - i > 0 && i < item->member.run.nCR)
4644           {
4645             buffer[i] = '\r'; i++;
4646           }
4647           j = 0;
4648           while (nChars - i - j > 0 && j < item->member.run.nLF)
4649           {
4650             buffer[i+j] = '\n'; j++;
4651           }
4652         }
4653       }
4654     }
4655     else
4656       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
4657     nChars -= nLen;
4658     nWritten += nLen;
4659     buffer += nLen;    
4660       
4661     if (!nChars)
4662     {
4663       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4664       *buffer = 0;
4665       return nWritten;
4666     }
4667     item = ME_FindItemFwd(item, diRun);
4668   }
4669   *buffer = 0;
4670   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4671   return nWritten;  
4672 }
4673
4674 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4675 {
4676   WNDCLASSW wcW;
4677   WNDCLASSA wcA;
4678   
4679   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4680   wcW.lpfnWndProc = RichEditWndProcW;
4681   wcW.cbClsExtra = 0;
4682   wcW.cbWndExtra = sizeof(ME_TextEditor *);
4683   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4684   wcW.hIcon = NULL;
4685   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4686   wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4687   wcW.lpszMenuName = NULL;
4688
4689   if (is_version_nt())
4690   {
4691     wcW.lpszClassName = RichEdit20W;
4692     if (!RegisterClassW(&wcW)) return FALSE;
4693     wcW.lpszClassName = RichEdit50W;
4694     if (!RegisterClassW(&wcW)) return FALSE;
4695   }
4696   else
4697   {
4698     /* WNDCLASSA/W have the same layout */
4699     wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4700     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4701     wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4702     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4703   }
4704
4705   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4706   wcA.lpfnWndProc = RichEditWndProcA;
4707   wcA.cbClsExtra = 0;
4708   wcA.cbWndExtra = sizeof(ME_TextEditor *);
4709   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4710   wcA.hIcon = NULL;
4711   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4712   wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4713   wcA.lpszMenuName = NULL;
4714   wcA.lpszClassName = "RichEdit20A";
4715   if (!RegisterClassA(&wcA)) return FALSE;
4716   wcA.lpszClassName = "RichEdit50A";
4717   if (!RegisterClassA(&wcA)) return FALSE;
4718
4719   return TRUE;
4720 }
4721
4722 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4723   /* FIXME: Not implemented */
4724   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4725         hWnd, msg, get_msg_name(msg), wParam, lParam);
4726   return DefWindowProcW(hWnd, msg, wParam, lParam);
4727 }
4728
4729 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4730   /* FIXME: Not implemented */
4731   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4732         hWnd, msg, get_msg_name(msg), wParam, lParam);
4733   return DefWindowProcW(hWnd, msg, wParam, lParam);
4734 }
4735
4736 /******************************************************************
4737  *        REExtendedRegisterClass (RICHED20.8)
4738  *
4739  * FIXME undocumented
4740  * Need to check for errors and implement controls and callbacks 
4741  */
4742 LRESULT WINAPI REExtendedRegisterClass(void)
4743 {
4744   WNDCLASSW wcW;
4745   UINT result;
4746
4747   FIXME("semi stub\n");
4748
4749   wcW.cbClsExtra = 0;
4750   wcW.cbWndExtra = 4;
4751   wcW.hInstance = NULL;
4752   wcW.hIcon = NULL;
4753   wcW.hCursor = NULL;
4754   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4755   wcW.lpszMenuName = NULL;
4756
4757   if (!ME_ListBoxRegistered)
4758   {
4759       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4760       wcW.lpfnWndProc = REListWndProc;
4761       wcW.lpszClassName = REListBox20W;
4762       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4763   }
4764
4765   if (!ME_ComboBoxRegistered)
4766   {
4767       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4768       wcW.lpfnWndProc = REComboWndProc;
4769       wcW.lpszClassName = REComboBox20W;
4770       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
4771   }
4772
4773   result = 0;
4774   if (ME_ListBoxRegistered)
4775       result += 1;
4776   if (ME_ComboBoxRegistered)
4777       result += 2;
4778
4779   return result;
4780 }
4781
4782 static BOOL isurlspecial(WCHAR c)
4783 {
4784   static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4785   return strchrW( special_chars, c ) != NULL;
4786 }
4787
4788 /**
4789  * This proc takes a selection, and scans it forward in order to select the span
4790  * of a possible URL candidate. A possible URL candidate must start with isalnum
4791  * or one of the following special characters: *|/\+%#@ and must consist entirely
4792  * of the characters allowed to start the URL, plus : (colon) which may occur
4793  * at most once, and not at either end.
4794  *
4795  * sel_max == -1 indicates scan to end of text.
4796  */
4797 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
4798         int * candidate_min, int * candidate_max)
4799 {
4800   ME_DisplayItem * item;
4801   ME_DisplayItem * para;
4802   int nStart;
4803   BOOL foundColon = FALSE;
4804   WCHAR lastAcceptedChar = '\0';
4805
4806   TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
4807
4808   *candidate_min = *candidate_max = -1;
4809   item = ME_FindItemAtOffset(editor, diRun, sel_min, &nStart);
4810   if (!item) return FALSE;
4811   TRACE("nStart = %d\n", nStart);
4812   para = ME_GetParagraph(item);
4813   if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4814   while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
4815   {
4816     ME_DisplayItem * next_item;
4817
4818     if (!(item->member.run.nFlags & MERF_ENDPARA)) {
4819       /* Find start of candidate */
4820       if (*candidate_min == -1) {
4821         while (nStart < ME_StrLen(item->member.run.strText) &&
4822                 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4823                   isurlspecial(item->member.run.strText->szData[nStart]))) {
4824           nStart++;
4825         }
4826         if (nStart < ME_StrLen(item->member.run.strText) &&
4827                 (isalnumW(item->member.run.strText->szData[nStart]) ||
4828                  isurlspecial(item->member.run.strText->szData[nStart]))) {
4829           *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4830           lastAcceptedChar = item->member.run.strText->szData[nStart];
4831           nStart++;
4832         }
4833       }
4834
4835       /* Find end of candidate */
4836       if (*candidate_min >= 0) {
4837         while (nStart < ME_StrLen(item->member.run.strText) &&
4838                 (isalnumW(item->member.run.strText->szData[nStart]) ||
4839                  isurlspecial(item->member.run.strText->szData[nStart]) ||
4840                  (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
4841           if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
4842           lastAcceptedChar = item->member.run.strText->szData[nStart];
4843           nStart++;
4844         }
4845         if (nStart < ME_StrLen(item->member.run.strText) &&
4846                 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4847                  isurlspecial(item->member.run.strText->szData[nStart]) )) {
4848           *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4849           nStart++;
4850           if (lastAcceptedChar == ':') (*candidate_max)--;
4851           return TRUE;
4852         }
4853       }
4854     } else {
4855       /* End of paragraph: skip it if before candidate span, or terminates
4856          current active span */
4857       if (*candidate_min >= 0) {
4858         *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
4859         if (lastAcceptedChar == ':') (*candidate_max)--;
4860         return TRUE;
4861       }
4862     }
4863
4864     /* Reaching this point means no span was found, so get next span */
4865     next_item = ME_FindItemFwd(item, diRun);
4866     if (!next_item) {
4867       if (*candidate_min >= 0) {
4868         /* There are no further runs, so take end of text as end of candidate */
4869         *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4870         if (lastAcceptedChar == ':') (*candidate_max)--;
4871         return TRUE;
4872       }
4873     }
4874     item = next_item;
4875     para = ME_GetParagraph(item);
4876     nStart = 0;
4877   }
4878
4879   if (item) {
4880     if (*candidate_min >= 0) {
4881       /* There are no further runs, so take end of text as end of candidate */
4882       *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4883       if (lastAcceptedChar == ':') (*candidate_max)--;
4884       return TRUE;
4885     }
4886   }
4887   return FALSE;
4888 }
4889
4890 /**
4891  * This proc evaluates the selection and returns TRUE if it can be considered an URL
4892  */
4893 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
4894 {
4895   struct prefix_s {
4896     const char *text;
4897     int length;
4898   } prefixes[12] = {
4899     /* Code below depends on these being in decreasing length order! */
4900     {"prospero:", 10},
4901     {"telnet:", 8},
4902     {"gopher:", 8},
4903     {"mailto:", 8},
4904     {"https:", 7},
4905     {"file:", 6},
4906     {"news:", 6},
4907     {"wais:", 6},
4908     {"nntp:", 6},
4909     {"http:", 5},
4910     {"www.", 5},
4911     {"ftp:", 5},
4912   };
4913   LPWSTR bufferW = NULL;
4914   WCHAR bufW[32];
4915   unsigned int i;
4916
4917   if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4918   assert(sel_min <= sel_max);
4919   for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
4920   {
4921     if (sel_max - sel_min < prefixes[i].length) continue;
4922     if (bufferW == NULL) {
4923       bufferW = heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
4924     }
4925     ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, lstrlenA(prefixes[i].text)), 0);
4926     MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
4927     if (!lstrcmpW(bufW, bufferW))
4928     {
4929       heap_free(bufferW);
4930       return TRUE;
4931     }
4932   }
4933   heap_free(bufferW);
4934   return FALSE;
4935 }
4936
4937 /**
4938  * This proc walks through the indicated selection and evaluates whether each
4939  * section identified by ME_FindNextURLCandidate and in-between sections have
4940  * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4941  * not what it is supposed to be, this proc sets or unsets it as appropriate.
4942  *
4943  * Returns TRUE if at least one section was modified.
4944  */
4945 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
4946 {
4947   BOOL modified = FALSE;
4948   int cMin, cMax;
4949
4950   if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4951   do
4952   {
4953     int beforeURL[2];
4954     int inURL[2];
4955     CHARFORMAT2W link;
4956
4957     if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4958     {
4959       /* Section before candidate is not an URL */
4960       beforeURL[0] = sel_min;
4961       beforeURL[1] = cMin;
4962
4963       if (ME_IsCandidateAnURL(editor, cMin, cMax))
4964       {
4965         inURL[0] = cMin; inURL[1] = cMax;
4966       }
4967       else
4968       {
4969         beforeURL[1] = cMax;
4970         inURL[0] = inURL[1] = -1;
4971       }
4972       sel_min = cMax;
4973     }
4974     else
4975     {
4976       /* No more candidates until end of selection */
4977       beforeURL[0] = sel_min;
4978       beforeURL[1] = sel_max;
4979       inURL[0] = inURL[1] = -1;
4980       sel_min = sel_max;
4981     }
4982
4983     if (beforeURL[0] < beforeURL[1])
4984     {
4985       /* CFE_LINK effect should be consistently unset */
4986       link.cbSize = sizeof(link);
4987       ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4988       if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4989       {
4990         /* CFE_LINK must be unset from this range */
4991         memset(&link, 0, sizeof(CHARFORMAT2W));
4992         link.cbSize = sizeof(link);
4993         link.dwMask = CFM_LINK;
4994         link.dwEffects = 0;
4995         ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4996         modified = TRUE;
4997       }
4998     }
4999     if (inURL[0] < inURL[1])
5000     {
5001       /* CFE_LINK effect should be consistently set */
5002       link.cbSize = sizeof(link);
5003       ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
5004       if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5005       {
5006         /* CFE_LINK must be set on this range */
5007         memset(&link, 0, sizeof(CHARFORMAT2W));
5008         link.cbSize = sizeof(link);
5009         link.dwMask = CFM_LINK;
5010         link.dwEffects = CFE_LINK;
5011         ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
5012         modified = TRUE;
5013       }
5014     }
5015   } while (sel_min < sel_max);
5016   return modified;
5017 }