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