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