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