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