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