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