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