riched20: Fix bugs in EM_SETOPTIONS.
[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  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 /* 
24   API implementation status:
25   
26   Messages (ANSI versions not done yet)
27   + EM_AUTOURLDETECT 2.0
28   + EM_CANPASTE
29   + EM_CANREDO 2.0
30   + EM_CANUNDO
31   + EM_CHARFROMPOS
32   - EM_DISPLAYBAND
33   + EM_EMPTYUNDOBUFFER
34   + EM_EXGETSEL
35   + EM_EXLIMITTEXT
36   + EM_EXLINEFROMCHAR
37   + EM_EXSETSEL
38   + EM_FINDTEXT (only FR_DOWN flag implemented)
39   + EM_FINDTEXTEX (only FR_DOWN flag implemented)
40   - EM_FINDWORDBREAK
41   - EM_FMTLINES
42   - EM_FORMATRANGE
43   + EM_GETAUTOURLDETECT 2.0
44   - EM_GETBIDIOPTIONS 3.0
45   - EM_GETCHARFORMAT (partly done)
46   - EM_GETEDITSTYLE
47   + EM_GETEVENTMASK
48   + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
49   - EM_GETIMECOLOR 1.0asian
50   - EM_GETIMECOMPMODE 2.0
51   - EM_GETIMEOPTIONS 1.0asian
52   - EM_GETIMESTATUS
53   - EM_GETLANGOPTIONS 2.0
54   + EM_GETLIMITTEXT
55   + EM_GETLINE
56   + EM_GETLINECOUNT   returns number of rows, not of paragraphs
57   + EM_GETMODIFY
58   - EM_GETOLEINTERFACE
59   + EM_GETOPTIONS
60   + EM_GETPARAFORMAT
61   + EM_GETPASSWORDCHAR 2.0
62   - EM_GETPUNCTUATION 1.0asian
63   + EM_GETRECT
64   - EM_GETREDONAME 2.0
65   + EM_GETSEL
66   + EM_GETSELTEXT (ANSI&Unicode)
67   + EM_GETSCROLLPOS 3.0 (only Y value valid)
68 ! - EM_GETTHUMB
69   + EM_GETTEXTEX 2.0
70   + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
71   - EM_GETTEXTMODE 2.0
72 ? + EM_GETTEXTRANGE (ANSI&Unicode)
73   - EM_GETTYPOGRAPHYOPTIONS 3.0
74   - EM_GETUNDONAME
75   + EM_GETWORDBREAKPROC
76   - EM_GETWORDBREAKPROCEX
77   - EM_GETWORDWRAPMODE 1.0asian
78   + EM_GETZOOM 3.0
79   + EM_HIDESELECTION
80   + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
81   + EM_LINEFROMCHAR
82   + EM_LINEINDEX
83   + EM_LINELENGTH
84   + EM_LINESCROLL
85   - EM_PASTESPECIAL
86   + EM_POSFROMCHAR
87   + EM_REDO 2.0
88   + EM_REQUESTRESIZE
89   + EM_REPLACESEL (proper style?) ANSI&Unicode
90   + EM_SCROLL
91   + EM_SCROLLCARET
92   - EM_SELECTIONTYPE
93   - EM_SETBIDIOPTIONS 3.0
94   + EM_SETBKGNDCOLOR
95   + EM_SETCHARFORMAT (partly done, no ANSI)
96   - EM_SETEDITSTYLE
97   + EM_SETEVENTMASK (few notifications supported)
98   - EM_SETFONTSIZE
99   - EM_SETIMECOLOR 1.0asian
100   - EM_SETIMEOPTIONS 1.0asian
101   - EM_SETLANGOPTIONS 2.0
102   - EM_SETLIMITTEXT
103   + EM_SETMODIFY (not sure if implementation is correct)
104   - EM_SETOLECALLBACK
105   + EM_SETOPTIONS (partially implemented)
106   - EM_SETPALETTE 2.0
107   + EM_SETPARAFORMAT
108   + EM_SETPASSWORDCHAR 2.0
109   - EM_SETPUNCTUATION 1.0asian
110   + EM_SETREADONLY no beep on modification attempt
111   + EM_SETRECT
112   + EM_SETRECTNP (EM_SETRECT without repainting)
113   + EM_SETSEL
114   + EM_SETSCROLLPOS 3.0
115   - EM_SETTABSTOPS 3.0
116   - EM_SETTARGETDEVICE
117   + EM_SETTEXTEX 3.0 (no rich text insertion handling, proper style?)
118   - EM_SETTEXTMODE 2.0
119   - EM_SETTYPOGRAPHYOPTIONS 3.0
120   + EM_SETUNDOLIMIT 2.0
121   + EM_SETWORDBREAKPROC (used only for word movement at the moment)
122   - EM_SETWORDBREAKPROCEX
123   - EM_SETWORDWRAPMODE 1.0asian
124   + EM_SETZOOM 3.0
125   + EM_SHOWSCROLLBAR 2.0
126   - EM_STOPGROUPTYPING 2.0
127   + EM_STREAMIN
128   + EM_STREAMOUT
129   + EM_UNDO
130   + WM_CHAR
131   + WM_CLEAR
132   + WM_COPY
133   + WM_CUT
134   + WM_GETDLGCODE (the current implementation is incomplete)
135   + WM_GETTEXT (ANSI&Unicode)
136   + WM_GETTEXTLENGTH (ANSI version sucks)
137   + WM_PASTE
138   + WM_SETFONT
139   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
140   - WM_STYLECHANGING
141   - WM_STYLECHANGED (things like read-only flag)
142   - WM_UNICHAR
143   
144   Notifications
145   
146   * EN_CHANGE (sent from the wrong place)
147   - EN_CORRECTTEXT
148   - EN_DROPFILES
149   - EN_ERRSPACE
150   - EN_HSCROLL
151   - EN_IMECHANGE
152   + EN_KILLFOCUS
153   - EN_LINK
154   - EN_MAXTEXT
155   - EN_MSGFILTER
156   - EN_OLEOPFAILED
157   - EN_PROTECTED
158   + EN_REQUESTRESIZE
159   - EN_SAVECLIPBOARD
160   + EN_SELCHANGE 
161   + EN_SETFOCUS
162   - EN_STOPNOUNDO
163   * EN_UPDATE (sent from the wrong place)
164   - EN_VSCROLL
165   
166   Styles
167   
168   - ES_AUTOHSCROLL
169   - ES_AUTOVSCROLL
170   - ES_CENTER
171   + ES_DISABLENOSCROLL (scrollbar is always visible)
172   - ES_EX_NOCALLOLEINIT
173   - ES_LEFT
174   - ES_MULTILINE (currently single line controls aren't supported)
175   - ES_NOIME
176   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
177   - ES_RIGHT
178   - ES_SAVESEL
179   - ES_SELFIME
180   - ES_SUNKEN
181   - ES_VERTICAL
182   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
183   - WS_SETFONT
184   - WS_HSCROLL
185   + WS_VSCROLL
186 */
187
188 /*
189  * RICHED20 TODO (incomplete):
190  *
191  * - messages/styles/notifications listed above 
192  * - Undo coalescing 
193  * - add remaining CHARFORMAT/PARAFORMAT fields
194  * - right/center align should strip spaces from the beginning
195  * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
196  * - COM interface (looks like a major pain in the TODO list)
197  * - calculate heights of pictures (half-done)
198  * - horizontal scrolling (not even started)
199  * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
200  * - find/replace
201  * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
202  * - italic caret with italic fonts
203  * - IME
204  * - most notifications aren't sent at all (the most important ones are)
205  * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
206  * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
207  * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
208  * - full justification
209  * - hyphenation
210  * - tables
211  * - ListBox & ComboBox not implemented
212  *
213  * Bugs that are probably fixed, but not so easy to verify:
214  * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
215  * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
216  * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
217  * - caret shouldn't be displayed when selection isn't empty
218  * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
219  * - undo for setting default format (done, might be buggy)
220  * - styles might be not released properly (looks like they work like charm, but who knows?
221  *
222  */
223
224 #include "editor.h"
225 #include "commdlg.h"
226 #include "winreg.h"
227 #define NO_SHLWAPI_STREAM 
228 #include "shlwapi.h"
229 #include "rtf.h"
230 #include "imm.h"
231 #include "res.h"
232
233 #define STACK_SIZE_DEFAULT  100
234 #define STACK_SIZE_MAX     1000
235
236 #define TEXT_LIMIT_DEFAULT 32767
237  
238 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
239
240 static BOOL ME_RegisterEditorClass(HINSTANCE);
241
242 static const WCHAR RichEdit20W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
243 static const WCHAR RichEdit50W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
244 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
245 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
246 static HCURSOR hLeft;
247 static HCURSOR hBeam;
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_UNDERLINE | 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 = 400;
339       break;
340     case rtfBold:
341       fmt.dwMask = CFM_BOLD;
342       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
343       break;
344     case rtfItalic:
345       fmt.dwMask = CFM_ITALIC;
346       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
347       break;
348     case rtfUnderline:
349       fmt.dwMask = CFM_UNDERLINE;
350       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
351       fmt.bUnderlineType = CFU_CF1UNDERLINE;
352       break;
353     case rtfNoUnderline:
354       fmt.dwMask = CFM_UNDERLINE;
355       fmt.dwEffects = 0;
356       break;
357     case rtfStrikeThru:
358       fmt.dwMask = CFM_STRIKEOUT;
359       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
360       break;
361     case rtfSubScript:
362     case rtfSuperScript:
363     case rtfSubScrShrink:
364     case rtfSuperScrShrink:
365     case rtfNoSuperSub:
366       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
367       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
368       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
369       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
370       break;
371     case rtfInvisible:
372       fmt.dwMask = CFM_HIDDEN;
373       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
374       break;
375     case rtfBackColor:
376       fmt.dwMask = CFM_BACKCOLOR;
377       fmt.dwEffects = 0;
378       if (info->rtfParam == 0)
379         fmt.dwEffects = CFE_AUTOBACKCOLOR;
380       else if (info->rtfParam != rtfNoParam)
381       {
382         RTFColor *c = RTFGetColor(info, info->rtfParam);
383         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
384       }
385       break;
386     case rtfForeColor:
387       fmt.dwMask = CFM_COLOR;
388       fmt.dwEffects = 0;
389       if (info->rtfParam == 0)
390         fmt.dwEffects = CFE_AUTOCOLOR;
391       else if (info->rtfParam != rtfNoParam)
392       {
393         RTFColor *c = RTFGetColor(info, info->rtfParam);
394         if (c)
395           fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
396         else
397           fmt.crTextColor = 0;
398       }
399       break;
400     case rtfFontNum:
401       if (info->rtfParam != rtfNoParam)
402       {
403         RTFFont *f = RTFGetFont(info, info->rtfParam);
404         if (f)
405         {
406           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
407           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
408           fmt.bCharSet = f->rtfFCharSet;
409           fmt.dwMask = CFM_FACE | CFM_CHARSET;
410         }
411       }
412       break;
413     case rtfFontSize:
414       fmt.dwMask = CFM_SIZE;
415       if (info->rtfParam != rtfNoParam)
416         fmt.yHeight = info->rtfParam*10;
417       break;
418   }
419   if (fmt.dwMask) {
420     ME_Style *style2;
421     RTFFlushOutputBuffer(info);
422     /* FIXME too slow ? how come ? */
423     style2 = ME_ApplyStyle(info->style, &fmt);
424     ME_ReleaseStyle(info->style);
425     info->style = style2;
426     info->styleChanged = TRUE;
427   }
428 }
429
430 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
431    the same tags mean different things in different contexts */
432 static void ME_RTFParAttrHook(RTF_Info *info)
433 {
434   PARAFORMAT2 fmt;
435   fmt.cbSize = sizeof(fmt);
436   fmt.dwMask = 0;
437   
438   switch(info->rtfMinor)
439   {
440   case rtfParDef: /* restores default paragraph attributes */
441     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
442     fmt.wAlignment = PFA_LEFT;
443     fmt.cTabCount = 0;
444     fmt.dxOffset = fmt.dxStartIndent = 0;
445     RTFFlushOutputBuffer(info);
446     ME_GetParagraph(info->editor->pCursors[0].pRun)->member.para.bTable = FALSE;
447     break;
448   case rtfInTable:
449   {
450     ME_DisplayItem *para;
451     
452     RTFFlushOutputBuffer(info);
453     para = ME_GetParagraph(info->editor->pCursors[0].pRun);
454     assert(para->member.para.pCells);
455     para->member.para.bTable = TRUE;
456     return;
457   }
458   case rtfFirstIndent:
459     ME_GetSelectionParaFormat(info->editor, &fmt);
460     fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
461     fmt.dxStartIndent += info->rtfParam + fmt.dxOffset;
462     fmt.dxOffset = -info->rtfParam;
463     break;
464   case rtfLeftIndent:
465     ME_GetSelectionParaFormat(info->editor, &fmt);
466     fmt.dwMask = PFM_STARTINDENT;
467     fmt.dxStartIndent = -fmt.dxOffset + info->rtfParam;
468     break;
469   case rtfRightIndent:
470     fmt.dwMask = PFM_RIGHTINDENT;
471     fmt.dxRightIndent = info->rtfParam;
472     break;
473   case rtfQuadLeft:
474   case rtfQuadJust:
475     fmt.dwMask = PFM_ALIGNMENT;
476     fmt.wAlignment = PFA_LEFT;
477     break;
478   case rtfQuadRight:
479     fmt.dwMask = PFM_ALIGNMENT;
480     fmt.wAlignment = PFA_RIGHT;
481     break;
482   case rtfQuadCenter:
483     fmt.dwMask = PFM_ALIGNMENT;
484     fmt.wAlignment = PFA_CENTER;
485     break;
486   case rtfTabPos:
487     ME_GetSelectionParaFormat(info->editor, &fmt);
488     if (!(fmt.dwMask & PFM_TABSTOPS))
489     {
490       fmt.dwMask |= PFM_TABSTOPS;
491       fmt.cTabCount = 0;
492     }
493     if (fmt.cTabCount < MAX_TAB_STOPS)
494       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
495     break;
496   }  
497   if (fmt.dwMask) {
498     RTFFlushOutputBuffer(info);
499     /* FIXME too slow ? how come ?*/
500     ME_SetSelectionParaFormat(info->editor, &fmt);
501   }
502 }
503
504 static void ME_RTFTblAttrHook(RTF_Info *info)
505 {
506   ME_DisplayItem *para;
507   
508   switch (info->rtfMinor)
509   {
510     case rtfRowDef:
511       RTFFlushOutputBuffer(info);
512       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
513       
514       /* Release possibly inherited cell definitions */
515       ME_DestroyTableCellList(para);
516       
517       para->member.para.pCells = ALLOC_OBJ(ME_TableCell);
518       para->member.para.pCells->nRightBoundary = 0;
519       para->member.para.pCells->next = NULL;
520       para->member.para.pLastCell = para->member.para.pCells;
521       break;
522     case rtfCellPos:
523       RTFFlushOutputBuffer(info);
524       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
525       
526       if (para->member.para.pLastCell->nRightBoundary)
527       {
528         ME_TableCell *pCell = ALLOC_OBJ(ME_TableCell);
529         
530         pCell->next = NULL;
531         para->member.para.pLastCell->next = pCell;
532         para->member.para.pLastCell = pCell;
533       }
534       para->member.para.pLastCell->nRightBoundary = info->rtfParam;
535       break;
536   }
537 }
538
539 static void ME_RTFReadHook(RTF_Info *info) {
540   switch(info->rtfClass)
541   {
542     case rtfGroup:
543       switch(info->rtfMajor)
544       {
545         case rtfBeginGroup:
546           if (info->stackTop < maxStack) {
547             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
548             info->stack[info->stackTop].codePage = info->codePage;
549             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
550           }
551           info->stackTop++;
552           info->styleChanged = FALSE;
553           break;
554         case rtfEndGroup:
555         {
556           ME_Style *s;
557           RTFFlushOutputBuffer(info);
558           if (info->stackTop<=1) {
559             info->rtfClass = rtfEOF;
560             return;
561           }
562           info->stackTop--;
563           assert(info->stackTop >= 0);
564           if (info->styleChanged)
565           {
566             /* FIXME too slow ? how come ? */
567             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
568             ME_ReleaseStyle(info->style);
569             info->style = s;
570             info->codePage = info->stack[info->stackTop].codePage;
571             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
572           }
573           break;
574         }
575       }
576       break;
577     case rtfControl:
578       switch(info->rtfMajor)
579       {
580         case rtfCharAttr:
581           ME_RTFCharAttrHook(info);
582           break;
583         case rtfParAttr:
584           ME_RTFParAttrHook(info);
585           break;
586         case rtfTblAttr:
587           ME_RTFTblAttrHook(info);
588           break;
589         case rtfSpecialChar:
590           if (info->rtfMinor == rtfCell)
591           {
592             RTFFlushOutputBuffer(info);
593             ME_InsertTableCellFromCursor(info->editor, 0);
594           }
595       }
596       break;
597   }
598 }
599
600 void
601 ME_StreamInFill(ME_InStream *stream)
602 {
603   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
604                                                                 (BYTE *)stream->buffer,
605                                                                 sizeof(stream->buffer),
606                                                                 (LONG *)&stream->dwSize);
607   stream->dwUsed = 0;
608 }
609
610 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
611 {
612   RTF_Info parser;
613   ME_Style *style;
614   int from, to, to2, nUndoMode;
615   int nEventMask = editor->nEventMask;
616   ME_InStream inStream;
617
618   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
619   editor->nEventMask = 0;
620   
621   ME_GetSelection(editor, &from, &to);
622   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
623     style = ME_GetSelectionInsertStyle(editor);
624
625     ME_InternalDeleteText(editor, from, to-from);
626   }
627   else {
628     style = editor->pBuffer->pDefaultStyle;
629     ME_AddRefStyle(style);
630     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
631     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
632     from = to = 0;
633     ME_ClearTempStyle(editor);
634     /* FIXME restore default paragraph formatting ! */
635   }
636
637
638   /* Back up undo mode to a local variable */
639   nUndoMode = editor->nUndoMode;
640
641   /* Only create an undo if SFF_SELECTION is set */
642   if (!(format & SFF_SELECTION))
643     editor->nUndoMode = umIgnore;
644
645   inStream.editstream = stream;
646   inStream.editstream->dwError = 0;
647   inStream.dwSize = 0;
648   inStream.dwUsed = 0;
649
650   if (format & SF_RTF)
651   {
652     /* Check if it's really RTF, and if it is not, use plain text */
653     ME_StreamInFill(&inStream);
654     if (!inStream.editstream->dwError)
655     {
656       if (strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
657       {
658         format &= ~SF_RTF;
659         format |= SF_TEXT;
660       }
661     }
662   }
663
664   if (!inStream.editstream->dwError)
665   {
666     if (format & SF_RTF) {
667       /* setup the RTF parser */
668       memset(&parser, 0, sizeof parser);
669       RTFSetEditStream(&parser, &inStream);
670       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
671       parser.hwndEdit = editor->hWnd;
672       parser.editor = editor;
673       parser.style = style;
674       WriterInit(&parser);
675       RTFInit(&parser);
676       RTFSetReadHook(&parser, ME_RTFReadHook);
677       BeginFile(&parser);
678   
679       /* do the parsing */
680       RTFRead(&parser);
681       RTFFlushOutputBuffer(&parser);
682       RTFDestroy(&parser);
683
684       style = parser.style;
685     }
686     else if (format & SF_TEXT)
687       ME_StreamInText(editor, format, &inStream, style);
688     else
689       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
690     ME_GetSelection(editor, &to, &to2);
691     /* put the cursor at the top */
692     if (!(format & SFF_SELECTION))
693       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
694   }
695
696   /* Restore saved undo mode */
697   editor->nUndoMode = nUndoMode;
698
699   /* even if we didn't add an undo, we need to commit anything on the stack */
700   ME_CommitUndo(editor);
701
702   /* If SFF_SELECTION isn't set, delete any undos from before we started too */
703   if (!(format & SFF_SELECTION))
704     ME_EmptyUndoStack(editor);
705
706   ME_ReleaseStyle(style);
707   editor->nEventMask = nEventMask;
708   if (editor->bRedraw)
709   {
710     ME_UpdateRepaint(editor);
711   }
712   if (!(format & SFF_SELECTION)) {
713     ME_ClearTempStyle(editor);
714   }
715   ME_MoveCaret(editor);
716   ME_SendSelChange(editor);
717   ME_SendRequestResize(editor, FALSE);
718
719   return 0;
720 }
721
722
723 typedef struct tagME_RTFStringStreamStruct
724 {
725   char *string;
726   int pos;
727   int length;
728 } ME_RTFStringStreamStruct;
729
730 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
731 {
732   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
733   int count;
734
735   count = min(cb, pStruct->length - pStruct->pos);
736   memmove(lpBuff, pStruct->string + pStruct->pos, count);
737   pStruct->pos += count;
738   *pcb = count;
739   return 0;
740 }
741
742 static void
743 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
744 {
745   EDITSTREAM es;
746   ME_RTFStringStreamStruct data;
747
748   data.string = string;
749   data.length = strlen(string);
750   data.pos = 0;
751   es.dwCookie = (DWORD)&data;
752   es.pfnCallback = ME_ReadFromRTFString;
753   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es);
754 }
755
756
757 ME_DisplayItem *
758 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
759 {
760   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
761   
762   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
763     item = ME_FindItemFwd(item, diParagraph);
764
765   if (!item)
766     return item;
767
768   nOffset -= item->member.para.nCharOfs;
769   if (nItemType == diParagraph) {
770     if (nItemOffset)
771       *nItemOffset = nOffset;
772     return item;
773   }
774   
775   do {
776     item = ME_FindItemFwd(item, diRun);
777   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
778   if (item) {
779     nOffset -= item->member.run.nCharOfs;
780     if (nItemOffset)
781       *nItemOffset = nOffset;
782   }
783   return item;
784 }
785
786
787 static int
788 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
789 {
790   const int nLen = lstrlenW(text);
791   const int nTextLen = ME_GetTextLength(editor);
792   int nStart, nEnd;
793   int nMin, nMax;
794   ME_DisplayItem *item;
795   ME_DisplayItem *para;
796   WCHAR wLastChar = ' ';
797
798   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
799         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
800   
801   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
802     FIXME("Flags 0x%08x not implemented\n",
803         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
804
805   nMin = chrg->cpMin;
806   if (chrg->cpMax == -1)
807     nMax = nTextLen;
808   else
809     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
810   
811   /* when searching up, if cpMin < cpMax, then instead of searching
812    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
813    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
814    * case, it is always bigger than cpMin.
815    */
816   if (!(flags & FR_DOWN))
817   {
818     int nSwap = nMax;
819
820     nMax = nMin > nTextLen ? nTextLen : nMin;
821     if (nMin < nSwap || chrg->cpMax == -1)
822       nMin = 0;
823     else
824       nMin = nSwap;
825   }
826
827   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
828   {
829     if (chrgText)
830       chrgText->cpMin = chrgText->cpMax = -1;
831     return -1;
832   }
833  
834   if (flags & FR_DOWN) /* Forward search */
835   {
836     /* If possible, find the character before where the search starts */
837     if ((flags & FR_WHOLEWORD) && nMin)
838     {
839       nStart = nMin - 1;
840       item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
841       if (!item)
842       {
843         if (chrgText)
844           chrgText->cpMin = chrgText->cpMax = -1;
845         return -1;
846       }
847       wLastChar = item->member.run.strText->szData[nStart];
848     }
849
850     nStart = nMin;
851     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
852     if (!item)
853     {
854       if (chrgText)
855         chrgText->cpMin = chrgText->cpMax = -1;
856       return -1;
857     }
858
859     para = ME_GetParagraph(item);
860     while (item
861            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
862     {
863       ME_DisplayItem *pCurItem = item;
864       int nCurStart = nStart;
865       int nMatched = 0;
866     
867       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
868       {
869         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
870           break;
871
872         nMatched++;
873         if (nMatched == nLen)
874         {
875           ME_DisplayItem *pNextItem = pCurItem;
876           int nNextStart = nCurStart;
877           WCHAR wNextChar;
878
879           /* Check to see if next character is a whitespace */
880           if (flags & FR_WHOLEWORD)
881           {
882             if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
883             {
884               pNextItem = ME_FindItemFwd(pCurItem, diRun);
885               nNextStart = -nMatched;
886             }
887
888             if (pNextItem)
889               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
890             else
891               wNextChar = ' ';
892
893             if (isalnumW(wNextChar))
894               break;
895           }
896
897           nStart += para->member.para.nCharOfs + pCurItem->member.run.nCharOfs;
898           if (chrgText)
899           {
900             chrgText->cpMin = nStart;
901             chrgText->cpMax = nStart + nLen;
902           }
903           TRACE("found at %d-%d\n", nStart, nStart + nLen);
904           return nStart;
905         }
906         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
907         {
908           pCurItem = ME_FindItemFwd(pCurItem, diRun);
909           para = ME_GetParagraph(pCurItem);
910           nCurStart = -nMatched;
911         }
912       }
913       if (pCurItem)
914         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
915       else
916         wLastChar = ' ';
917
918       nStart++;
919       if (nStart == ME_StrLen(item->member.run.strText))
920       {
921         item = ME_FindItemFwd(item, diRun);
922         para = ME_GetParagraph(item);
923         nStart = 0;
924       }
925     }
926   }
927   else /* Backward search */
928   {
929     /* If possible, find the character after where the search ends */
930     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
931     {
932       nEnd = nMax + 1;
933       item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
934       if (!item)
935       {
936         if (chrgText)
937           chrgText->cpMin = chrgText->cpMax = -1;
938         return -1;
939       }
940       wLastChar = item->member.run.strText->szData[nEnd];
941     }
942
943     nEnd = nMax;
944     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
945     if (!item)
946     {
947       if (chrgText)
948         chrgText->cpMin = chrgText->cpMax = -1;
949       return -1;
950     }
951     
952     para = ME_GetParagraph(item);
953     
954     while (item
955            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
956     {
957       ME_DisplayItem *pCurItem = item;
958       int nCurEnd = nEnd;
959       int nMatched = 0;
960       
961       if (nCurEnd - nMatched == 0)
962       {
963         pCurItem = ME_FindItemBack(pCurItem, diRun);
964         para = ME_GetParagraph(pCurItem);
965         nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
966       }
967       
968       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
969       {
970         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
971           break;
972
973         nMatched++;
974         if (nMatched == nLen)
975         {
976           ME_DisplayItem *pPrevItem = pCurItem;
977           int nPrevEnd = nCurEnd;
978           WCHAR wPrevChar;
979
980           /* Check to see if previous character is a whitespace */
981           if (flags & FR_WHOLEWORD)
982           {
983             if (nPrevEnd - nMatched == 0)
984             {
985               pPrevItem = ME_FindItemBack(pCurItem, diRun);
986               if (pPrevItem)
987                 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
988             }
989
990             if (pPrevItem)
991               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
992             else
993               wPrevChar = ' ';
994
995             if (isalnumW(wPrevChar))
996               break;
997           }
998
999           nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1000           if (chrgText)
1001           {
1002             chrgText->cpMin = nStart;
1003             chrgText->cpMax = nStart + nLen;
1004           }
1005           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1006           return nStart;
1007         }
1008         if (nCurEnd - nMatched == 0)
1009         {
1010           pCurItem = ME_FindItemBack(pCurItem, diRun);
1011           /* Don't care about pCurItem becoming NULL here; it's already taken
1012            * care of in the exterior loop condition */
1013           para = ME_GetParagraph(pCurItem);
1014           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1015         }
1016       }
1017       if (pCurItem)
1018         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1019       else
1020         wLastChar = ' ';
1021
1022       nEnd--;
1023       if (nEnd < 0)
1024       {
1025         item = ME_FindItemBack(item, diRun);
1026         para = ME_GetParagraph(item);
1027         nEnd = ME_StrLen(item->member.run.strText);
1028       }
1029     }
1030   }
1031   TRACE("not found\n");
1032   if (chrgText)
1033     chrgText->cpMin = chrgText->cpMax = -1;
1034   return -1;
1035 }
1036
1037
1038 static BOOL
1039 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1040 {
1041   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1042   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1043   
1044   switch (nKey)
1045   {
1046     case VK_LEFT:
1047     case VK_RIGHT:
1048     case VK_UP:
1049     case VK_DOWN:
1050     case VK_HOME:
1051     case VK_END:
1052     case VK_PRIOR:
1053     case VK_NEXT:
1054       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1055       return TRUE;
1056     case VK_BACK:
1057     case VK_DELETE:
1058       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1059       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1060         return FALSE;
1061       if (ME_IsSelection(editor))
1062         ME_DeleteSelection(editor);
1063       else if (nKey == VK_DELETE || ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1064         ME_DeleteTextAtCursor(editor, 1, 1);
1065       else
1066         return TRUE;
1067       ME_CommitUndo(editor);
1068       ME_UpdateRepaint(editor);
1069       ME_SendRequestResize(editor, FALSE);
1070       return TRUE;
1071
1072     default:
1073       if (ctrl_is_down)
1074       {
1075         if (nKey == 'W')
1076         {
1077           CHARFORMAT2W chf;
1078           char buf[2048];
1079           chf.cbSize = sizeof(chf);
1080           
1081           ME_GetSelectionCharFormat(editor, &chf);
1082           ME_DumpStyleToBuf(&chf, buf);
1083           MessageBoxA(NULL, buf, "Style dump", MB_OK);
1084         }
1085         if (nKey == 'Q')
1086         {
1087           ME_CheckCharOffsets(editor);
1088         }
1089       }
1090   }
1091   return FALSE;
1092 }
1093
1094 static void ME_SetCursor(ME_TextEditor *editor, int x)
1095 {
1096     if (x < editor->selofs || editor->linesel)
1097       SetCursor(hLeft);
1098     else
1099       SetCursor(hBeam);
1100 }
1101
1102 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1103 {
1104   CHARRANGE selrange;
1105   HMENU menu;
1106   int seltype = 0;
1107   if(!editor->lpOleCallback)
1108     return FALSE;
1109   ME_GetSelection(editor, (int *)&selrange.cpMin, (int *)&selrange.cpMax);
1110   if(selrange.cpMin == selrange.cpMax)
1111     seltype |= SEL_EMPTY;
1112   else
1113   {
1114     /* FIXME: Handle objects */
1115     seltype |= SEL_TEXT;
1116     if(selrange.cpMax-selrange.cpMin > 1)
1117       seltype |= SEL_MULTICHAR;
1118   }
1119   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1120   {
1121     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1122     DestroyMenu(menu);
1123   }
1124   return TRUE;
1125 }
1126
1127 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1128   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1129   HDC hDC;
1130   int i;
1131   ed->hWnd = hWnd;
1132   ed->bEmulateVersion10 = FALSE;
1133   ed->pBuffer = ME_MakeText();
1134   hDC = GetDC(hWnd);
1135   ME_MakeFirstParagraph(hDC, ed->pBuffer);
1136   ReleaseDC(hWnd, hDC);
1137   ed->bCaretShown = FALSE;
1138   ed->nCursors = 4;
1139   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1140   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1141   ed->pCursors[0].nOffset = 0;
1142   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1143   ed->pCursors[1].nOffset = 0;
1144   ed->nLastTotalLength = ed->nTotalLength = 0;
1145   ed->nHeight = 0;
1146   ed->nUDArrowX = -1;
1147   ed->nSequence = 0;
1148   ed->rgbBackColor = -1;
1149   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1150   ed->bCaretAtEnd = FALSE;
1151   ed->nEventMask = 0;
1152   ed->nModifyStep = 0;
1153   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1154   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1155   ed->nUndoStackSize = 0;
1156   ed->nUndoLimit = STACK_SIZE_DEFAULT;
1157   ed->nUndoMode = umAddToUndo;
1158   ed->nParagraphs = 1;
1159   ed->nLastSelStart = ed->nLastSelEnd = 0;
1160   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1161   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1162   ed->bRedraw = TRUE;
1163   ed->bHideSelection = FALSE;
1164   ed->nInvalidOfs = -1;
1165   ed->pfnWordBreak = NULL;
1166   ed->lpOleCallback = NULL;
1167   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1168   ed->AutoURLDetect_bEnable = FALSE;
1169   ed->bHaveFocus = FALSE;
1170   GetClientRect(hWnd, &ed->rcFormat);
1171   for (i=0; i<HFONT_CACHE_SIZE; i++)
1172   {
1173     ed->pFontCache[i].nRefs = 0;
1174     ed->pFontCache[i].nAge = 0;
1175     ed->pFontCache[i].hFont = NULL;
1176   }
1177   
1178   ME_CheckCharOffsets(ed);
1179   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
1180     ed->selofs = 16;
1181   else
1182     ed->selofs = 0;
1183   ed->linesel = 0;
1184
1185   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1186     ed->cPasswordMask = '*';
1187   else
1188     ed->cPasswordMask = 0;
1189   
1190   return ed;
1191 }
1192
1193 typedef struct tagME_GlobalDestStruct
1194 {
1195   HGLOBAL hData;
1196   int nLength;
1197 } ME_GlobalDestStruct;
1198
1199 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1200 {
1201   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1202   int i;
1203   WORD *pSrc, *pDest;
1204   
1205   cb = cb >> 1;
1206   pDest = (WORD *)lpBuff;
1207   pSrc = (WORD *)GlobalLock(pData->hData);
1208   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1209     pDest[i] = pSrc[pData->nLength+i];
1210   }    
1211   pData->nLength += i;
1212   *pcb = 2*i;
1213   GlobalUnlock(pData->hData);
1214   return 0;
1215 }
1216
1217 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1218 {
1219   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1220   int i;
1221   BYTE *pSrc, *pDest;
1222   
1223   pDest = lpBuff;
1224   pSrc = (BYTE *)GlobalLock(pData->hData);
1225   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1226     pDest[i] = pSrc[pData->nLength+i];
1227   }    
1228   pData->nLength += i;
1229   *pcb = i;
1230   GlobalUnlock(pData->hData);
1231   return 0;
1232 }
1233
1234
1235 void ME_DestroyEditor(ME_TextEditor *editor)
1236 {
1237   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1238   ME_DisplayItem *p = pFirst, *pNext = NULL;
1239   int i;
1240
1241   ME_ClearTempStyle(editor);
1242   ME_EmptyUndoStack(editor);
1243   while(p) {
1244     pNext = p->next;
1245     ME_DestroyDisplayItem(p);
1246     p = pNext;
1247   }
1248   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1249   for (i=0; i<HFONT_CACHE_SIZE; i++)
1250   {
1251     if (editor->pFontCache[i].hFont)
1252       DeleteObject(editor->pFontCache[i].hFont);
1253   }
1254   DeleteObject(editor->hbrBackground);
1255   if(editor->lpOleCallback)
1256     IUnknown_Release(editor->lpOleCallback);
1257
1258   FREE_OBJ(editor->pBuffer);
1259   FREE_OBJ(editor->pCursors);
1260
1261   FREE_OBJ(editor);
1262 }
1263
1264 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1265 {
1266     TRACE("\n");
1267     switch (fdwReason)
1268     {
1269     case DLL_PROCESS_ATTACH:
1270       DisableThreadLibraryCalls(hinstDLL);
1271       me_heap = HeapCreate (0, 0x10000, 0);
1272       if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
1273       hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
1274       hBeam = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
1275       LookupInit();
1276       break;
1277
1278     case DLL_PROCESS_DETACH:
1279       UnregisterClassW(RichEdit20W, 0);
1280       UnregisterClassW(RichEdit50W, 0);
1281       UnregisterClassA("RichEdit20A", 0);
1282       UnregisterClassA("RichEdit50A", 0);
1283       if (ME_ListBoxRegistered)
1284           UnregisterClassW(REListBox20W, 0);
1285       if (ME_ComboBoxRegistered)
1286           UnregisterClassW(REComboBox20W, 0);
1287       LookupCleanup();
1288       HeapDestroy (me_heap);
1289       me_heap = NULL;
1290       break;
1291     }
1292     return TRUE;
1293 }
1294
1295
1296 #define UNSUPPORTED_MSG(e) \
1297   case e: \
1298     FIXME(#e ": stub\n"); \
1299     return DefWindowProcW(hWnd, msg, wParam, lParam);
1300
1301 static const char * const edit_messages[] = {
1302   "EM_GETSEL",
1303   "EM_SETSEL",
1304   "EM_GETRECT",
1305   "EM_SETRECT",
1306   "EM_SETRECTNP",
1307   "EM_SCROLL",
1308   "EM_LINESCROLL",
1309   "EM_SCROLLCARET",
1310   "EM_GETMODIFY",
1311   "EM_SETMODIFY",
1312   "EM_GETLINECOUNT",
1313   "EM_LINEINDEX",
1314   "EM_SETHANDLE",
1315   "EM_GETHANDLE",
1316   "EM_GETTHUMB",
1317   "EM_UNKNOWN_BF",
1318   "EM_UNKNOWN_C0",
1319   "EM_LINELENGTH",
1320   "EM_REPLACESEL",
1321   "EM_UNKNOWN_C3",
1322   "EM_GETLINE",
1323   "EM_LIMITTEXT",
1324   "EM_CANUNDO",
1325   "EM_UNDO",
1326   "EM_FMTLINES",
1327   "EM_LINEFROMCHAR",
1328   "EM_UNKNOWN_CA",
1329   "EM_SETTABSTOPS",
1330   "EM_SETPASSWORDCHAR",
1331   "EM_EMPTYUNDOBUFFER",
1332   "EM_GETFIRSTVISIBLELINE",
1333   "EM_SETREADONLY",
1334   "EM_SETWORDBREAKPROC",
1335   "EM_GETWORDBREAKPROC",
1336   "EM_GETPASSWORDCHAR",
1337   "EM_SETMARGINS",
1338   "EM_GETMARGINS",
1339   "EM_GETLIMITTEXT",
1340   "EM_POSFROMCHAR",
1341   "EM_CHARFROMPOS"
1342 };
1343
1344 static const char * const richedit_messages[] = {
1345   "EM_CANPASTE",
1346   "EM_DISPLAYBAND",
1347   "EM_EXGETSEL",
1348   "EM_EXLIMITTEXT",
1349   "EM_EXLINEFROMCHAR",
1350   "EM_EXSETSEL",
1351   "EM_FINDTEXT",
1352   "EM_FORMATRANGE",
1353   "EM_GETCHARFORMAT",
1354   "EM_GETEVENTMASK",
1355   "EM_GETOLEINTERFACE",
1356   "EM_GETPARAFORMAT",
1357   "EM_GETSELTEXT",
1358   "EM_HIDESELECTION", 
1359   "EM_PASTESPECIAL",
1360   "EM_REQUESTRESIZE",
1361   "EM_SELECTIONTYPE",
1362   "EM_SETBKGNDCOLOR",
1363   "EM_SETCHARFORMAT",
1364   "EM_SETEVENTMASK",
1365   "EM_SETOLECALLBACK",
1366   "EM_SETPARAFORMAT",
1367   "EM_SETTARGETDEVICE",
1368   "EM_STREAMIN",
1369   "EM_STREAMOUT",
1370   "EM_GETTEXTRANGE",
1371   "EM_FINDWORDBREAK",
1372   "EM_SETOPTIONS",
1373   "EM_GETOPTIONS",
1374   "EM_FINDTEXTEX",
1375   "EM_GETWORDBREAKPROCEX",
1376   "EM_SETWORDBREAKPROCEX",
1377   "EM_SETUNDOLIMIT",
1378   "EM_UNKNOWN_USER_83",
1379   "EM_REDO",
1380   "EM_CANREDO",
1381   "EM_GETUNDONAME",
1382   "EM_GETREDONAME",
1383   "EM_STOPGROUPTYPING",
1384   "EM_SETTEXTMODE",
1385   "EM_GETTEXTMODE",
1386   "EM_AUTOURLDETECT",
1387   "EM_GETAUTOURLDETECT",
1388   "EM_SETPALETTE",
1389   "EM_GETTEXTEX",
1390   "EM_GETTEXTLENGTHEX",
1391   "EM_SHOWSCROLLBAR",
1392   "EM_SETTEXTEX",
1393   "EM_UNKNOWN_USER_98",
1394   "EM_UNKNOWN_USER_99",
1395   "EM_SETPUNCTUATION",
1396   "EM_GETPUNCTUATION",
1397   "EM_SETWORDWRAPMODE",
1398   "EM_GETWORDWRAPMODE",
1399   "EM_SETIMECOLOR",
1400   "EM_GETIMECOLOR",
1401   "EM_SETIMEOPTIONS",
1402   "EM_GETIMEOPTIONS",
1403   "EM_CONVPOSITION",
1404   "EM_UNKNOWN_USER_109",
1405   "EM_UNKNOWN_USER_110",
1406   "EM_UNKNOWN_USER_111",
1407   "EM_UNKNOWN_USER_112",
1408   "EM_UNKNOWN_USER_113",
1409   "EM_UNKNOWN_USER_114",
1410   "EM_UNKNOWN_USER_115",
1411   "EM_UNKNOWN_USER_116",
1412   "EM_UNKNOWN_USER_117",
1413   "EM_UNKNOWN_USER_118",
1414   "EM_UNKNOWN_USER_119",
1415   "EM_SETLANGOPTIONS",
1416   "EM_GETLANGOPTIONS",
1417   "EM_GETIMECOMPMODE",
1418   "EM_FINDTEXTW",
1419   "EM_FINDTEXTEXW",
1420   "EM_RECONVERSION",
1421   "EM_SETIMEMODEBIAS",
1422   "EM_GETIMEMODEBIAS"
1423 };
1424
1425 static const char *
1426 get_msg_name(UINT msg)
1427 {
1428   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
1429     return edit_messages[msg - EM_GETSEL];
1430   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1431     return richedit_messages[msg - EM_CANPASTE];
1432   return "";
1433 }
1434
1435 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
1436                                       LPARAM lParam, BOOL unicode)
1437 {
1438   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
1439   
1440   TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
1441         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
1442   
1443   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
1444     ERR("called with invalid hWnd %p - application bug?\n", hWnd);
1445     return 0; 
1446   }
1447
1448   switch(msg) {
1449   
1450   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1451   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1452   UNSUPPORTED_MSG(EM_FMTLINES)
1453   UNSUPPORTED_MSG(EM_FORMATRANGE)
1454   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1455   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1456   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1457   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1458   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1459   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1460   UNSUPPORTED_MSG(EM_GETREDONAME)
1461   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1462   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1463   UNSUPPORTED_MSG(EM_GETUNDONAME)
1464   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1465   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1466   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1467   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1468   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1469   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1470   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1471   UNSUPPORTED_MSG(EM_SETPALETTE)
1472   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1473   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1474   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1475   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1476   UNSUPPORTED_MSG(WM_STYLECHANGING)
1477   UNSUPPORTED_MSG(WM_STYLECHANGED)
1478 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1479     
1480 /* Messages specific to Richedit controls */
1481   
1482   case EM_STREAMIN:
1483    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1484   case EM_STREAMOUT:
1485    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1486   case WM_GETDLGCODE:
1487   {
1488     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1489     if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
1490     {
1491       int vk = (int)((LPMSG)lParam)->wParam;
1492       /* if style says we want return key */
1493       if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
1494       {
1495         code |= DLGC_WANTMESSAGE;
1496       }
1497       /* we always handle ctrl-tab */
1498       if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
1499       {
1500         code |= DLGC_WANTMESSAGE;
1501       }
1502     }
1503     return code;
1504   }
1505   case WM_NCCREATE:
1506   {
1507     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1508     TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
1509     editor = ME_MakeEditor(hWnd);
1510     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
1511     return TRUE;
1512   }
1513   case EM_EMPTYUNDOBUFFER:
1514     ME_EmptyUndoStack(editor);
1515     return 0;
1516   case EM_GETSEL:
1517   {
1518     /* Note: wParam/lParam can be NULL */
1519     UINT from, to;
1520     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1521     PUINT pto = lParam ? (PUINT)lParam : &to;
1522     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1523     if ((*pfrom|*pto) & 0xFFFF0000)
1524       return -1;
1525     return MAKELONG(*pfrom,*pto);
1526   }
1527   case EM_EXGETSEL:
1528   {
1529     CHARRANGE *pRange = (CHARRANGE *)lParam;
1530     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1531     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
1532     return 0;
1533   }
1534   case EM_SETUNDOLIMIT:
1535   {
1536     if ((int)wParam < 0)
1537       editor->nUndoLimit = STACK_SIZE_DEFAULT;
1538     else
1539       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
1540     /* Setting a max stack size keeps wine from getting killed 
1541       for hogging memory. Windows allocates all this memory at once, so
1542       no program would realistically set a value above our maximum. */
1543     return editor->nUndoLimit;
1544   }
1545   case EM_CANUNDO:
1546     return editor->pUndoStack != NULL;
1547   case EM_CANREDO:
1548     return editor->pRedoStack != NULL;
1549   case WM_UNDO: /* FIXME: actually not the same */
1550   case EM_UNDO:
1551     ME_Undo(editor);
1552     return 0;
1553   case EM_REDO:
1554     ME_Redo(editor);
1555     return 0;
1556   case EM_GETOPTIONS:
1557   {
1558     /* these flags are equivalent to the ES_* counterparts */
1559     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1560                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1561     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
1562
1563     return settings;
1564   }
1565   case EM_SETOPTIONS:
1566   {
1567     /* these flags are equivalent to ES_* counterparts                      
1568      * ECO_READONLY is already implemented in the code, only requires 
1569      * setting the bit to work                                        
1570      */
1571     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1572                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
1573     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
1574     DWORD settings = mask & raw;
1575
1576     switch(wParam)
1577     {
1578       case ECOOP_SET:
1579         settings = lParam;
1580         break;
1581       case ECOOP_OR:
1582         settings |= lParam;
1583         break;
1584       case ECOOP_AND:
1585         settings &= lParam;
1586         break;
1587       case ECOOP_XOR:
1588         settings ^= lParam;
1589     }
1590     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
1591
1592     if (settings & ECO_AUTOWORDSELECTION)
1593       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
1594     if (settings & ECO_SELECTIONBAR)
1595         editor->selofs = 16;
1596     else
1597         editor->selofs = 0;
1598     ME_WrapMarkedParagraphs(editor);
1599
1600     if (settings & ECO_VERTICAL)
1601       FIXME("ECO_VERTICAL not implemented yet!\n");
1602     if (settings & ECO_AUTOHSCROLL)
1603       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
1604     if (settings & ECO_AUTOVSCROLL)
1605       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
1606     if (settings & ECO_NOHIDESEL)
1607       FIXME("ECO_NOHIDESEL not implemented yet!\n");
1608     if (settings & ECO_WANTRETURN)
1609       FIXME("ECO_WANTRETURN not implemented yet!\n");
1610
1611     return settings;
1612   }
1613   case EM_SETSEL:
1614   {
1615     ME_InvalidateSelection(editor);
1616     ME_SetSelection(editor, wParam, lParam);
1617     ME_InvalidateSelection(editor);
1618     ME_SendSelChange(editor);
1619     return 0;
1620   }
1621   case EM_SETSCROLLPOS:
1622   {
1623     POINT *point = (POINT *)lParam;
1624     ME_ScrollAbs(editor, point->y);
1625     return 0;
1626   }
1627   case EM_AUTOURLDETECT:
1628   {
1629     if (wParam==1 || wParam ==0) 
1630     {
1631         editor->AutoURLDetect_bEnable = (BOOL)wParam;
1632         return 0;
1633     }
1634     return E_INVALIDARG;
1635   }
1636   case EM_GETAUTOURLDETECT:
1637   {
1638     return editor->AutoURLDetect_bEnable;
1639   }
1640   case EM_EXSETSEL:
1641   {
1642     int end;
1643     CHARRANGE range = *(CHARRANGE *)lParam;
1644
1645     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
1646
1647     ME_InvalidateSelection(editor);
1648     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
1649     ME_InvalidateSelection(editor);
1650     ME_SendSelChange(editor);
1651
1652     return end;
1653   }
1654   case EM_SHOWSCROLLBAR:
1655   {
1656     ShowScrollBar(editor->hWnd, wParam, lParam);
1657     return 0;
1658   }
1659   case EM_SETTEXTEX:
1660   {
1661     LPWSTR wszText;
1662     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1663     size_t len;
1664     int from, to;
1665     ME_Style *style;
1666     int oldModify = editor->nModifyStep;
1667
1668     if (!pStruct) return 0;
1669
1670     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
1671           pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
1672           pStruct->flags, pStruct->codepage);
1673
1674     /* FIXME: make use of pStruct->codepage in the to unicode translation */
1675     wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
1676     len = wszText ? lstrlenW(wszText) : 0;
1677
1678     /* FIXME: this should support RTF strings too, according to MSDN */
1679     if (pStruct->flags & ST_SELECTION) {
1680       ME_GetSelection(editor, &from, &to);
1681       style = ME_GetSelectionInsertStyle(editor);
1682       ME_InternalDeleteText(editor, from, to - from);
1683       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1684       ME_ReleaseStyle(style);
1685     }
1686     else {
1687       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1688       ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1689       len = 1;
1690     }
1691     ME_CommitUndo(editor);
1692     if (!(pStruct->flags & ST_KEEPUNDO))
1693     {
1694       editor->nModifyStep = oldModify;
1695       ME_EmptyUndoStack(editor);
1696     }
1697     ME_UpdateRepaint(editor);
1698     return len;
1699   }
1700   case EM_SETBKGNDCOLOR:
1701   {
1702     LRESULT lColor = ME_GetBackColor(editor);
1703     if (editor->rgbBackColor != -1)
1704       DeleteObject(editor->hbrBackground);
1705     if (wParam)
1706     {
1707       editor->rgbBackColor = -1;
1708       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1709     }
1710     else
1711     {
1712       editor->rgbBackColor = lParam;
1713       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
1714     }
1715     if (editor->bRedraw)
1716     {
1717       InvalidateRect(hWnd, NULL, TRUE);
1718       UpdateWindow(hWnd);
1719     }
1720     return lColor;
1721   }
1722   case EM_GETMODIFY:
1723     return editor->nModifyStep == 0 ? 0 : 1;
1724   case EM_SETMODIFY:
1725   {
1726     if (wParam)
1727       editor->nModifyStep = 1;
1728     else
1729       editor->nModifyStep = 0;
1730     
1731     return 0;
1732   }
1733   case EM_SETREADONLY:
1734   {
1735     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1736     if (wParam)
1737       nStyle |= ES_READONLY;
1738     else
1739       nStyle &= ~ES_READONLY;
1740     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1741     return 0;
1742   }
1743   case EM_SETEVENTMASK:
1744   {
1745     DWORD nOldMask = editor->nEventMask;
1746     
1747     editor->nEventMask = lParam;
1748     return nOldMask;
1749   }
1750   case EM_GETEVENTMASK:
1751     return editor->nEventMask;
1752   case EM_SETCHARFORMAT:
1753   {
1754     CHARFORMAT2W buf, *p;
1755     BOOL bRepaint = TRUE;
1756     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1757     if (p == NULL) return 0;
1758     if (!wParam)
1759       ME_SetDefaultCharFormat(editor, p);
1760     else if (wParam == (SCF_WORD | SCF_SELECTION)) {
1761       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1762       return 0;
1763     } else if (wParam == SCF_ALL) {
1764       if (editor->mode & TM_PLAINTEXT)
1765         ME_SetDefaultCharFormat(editor, p);
1766       else
1767         ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1768     } else if (editor->mode & TM_PLAINTEXT) {
1769       return 0;
1770     } else {
1771       int from, to;
1772       ME_GetSelection(editor, &from, &to);
1773       bRepaint = (from != to);
1774       ME_SetSelectionCharFormat(editor, p);
1775     }
1776     editor->nModifyStep = 1;
1777     ME_CommitUndo(editor);
1778     if (bRepaint)
1779       ME_RewrapRepaint(editor);
1780     return 1;
1781   }
1782   case EM_GETCHARFORMAT:
1783   {
1784     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1785     if (dst->cbSize != sizeof(CHARFORMATA) &&
1786         dst->cbSize != sizeof(CHARFORMATW) &&
1787         dst->cbSize != sizeof(CHARFORMAT2A) &&
1788         dst->cbSize != sizeof(CHARFORMAT2W))
1789       return 0;
1790     tmp.cbSize = sizeof(tmp);
1791     if (!wParam)
1792       ME_GetDefaultCharFormat(editor, &tmp);
1793     else
1794       ME_GetSelectionCharFormat(editor, &tmp);
1795     ME_CopyToCFAny(dst, &tmp);
1796     return tmp.dwMask;
1797   }
1798   case EM_SETPARAFORMAT:
1799     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1800     ME_RewrapRepaint(editor);
1801     ME_CommitUndo(editor);
1802     return 0;
1803   case EM_GETPARAFORMAT:
1804     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1805     return 0;
1806   case EM_GETFIRSTVISIBLELINE:
1807   {
1808     ME_DisplayItem *p = editor->pBuffer->pFirst;
1809     int y = ME_GetYScrollPos(editor);
1810     int ypara = 0;
1811     int count = 0;
1812     int ystart, yend;
1813     while(p) {
1814       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
1815       if (p->type == diTextEnd)
1816         break;
1817       if (p->type == diParagraph) {
1818         ypara = p->member.para.nYPos;
1819         continue;
1820       }
1821       ystart = ypara + p->member.row.nYPos;
1822       yend = ystart + p->member.row.nHeight;
1823       if (y < yend) {
1824         break;
1825       }
1826       count++;
1827     }
1828     return count;
1829   }
1830   case EM_HIDESELECTION:
1831   {
1832      editor->bHideSelection = (wParam != 0);
1833      ME_InvalidateSelection(editor);
1834      return 0;
1835   }
1836   case EM_LINESCROLL:
1837   {
1838     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
1839     return TRUE; /* Should return false if a single line richedit control */
1840   }
1841   case WM_CLEAR:
1842   {
1843     int from, to;
1844     ME_GetSelection(editor, &from, &to);
1845     ME_InternalDeleteText(editor, from, to-from);
1846     ME_CommitUndo(editor);
1847     ME_UpdateRepaint(editor);
1848     return 0;
1849   }
1850   case EM_REPLACESEL:
1851   {
1852     int from, to;
1853     ME_Style *style;
1854     LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
1855     size_t len = wszText ? lstrlenW(wszText) : 0;
1856     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1857
1858     ME_GetSelection(editor, &from, &to);
1859     style = ME_GetSelectionInsertStyle(editor);
1860     ME_InternalDeleteText(editor, from, to-from);
1861     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1862     ME_ReleaseStyle(style);
1863     /* drop temporary style if line end */
1864     /*
1865      * FIXME question: does abc\n mean: put abc,
1866      * clear temp style, put \n? (would require a change)
1867      */
1868     if (len>0 && wszText[len-1] == '\n')
1869       ME_ClearTempStyle(editor);
1870     ME_EndToUnicode(unicode, wszText);
1871     ME_CommitUndo(editor);
1872     if (!wParam)
1873       ME_EmptyUndoStack(editor);
1874     ME_UpdateRepaint(editor);
1875     return len;
1876   }
1877   case EM_SCROLLCARET:
1878   {
1879     int top, bottom; /* row's edges relative to document top */
1880     int nPos;
1881     ME_DisplayItem *para, *row;
1882     
1883     nPos = ME_GetYScrollPos(editor);
1884     row = ME_RowStart(editor->pCursors[0].pRun);
1885     para = ME_GetParagraph(row);
1886     top = para->member.para.nYPos + row->member.row.nYPos;
1887     bottom = top + row->member.row.nHeight;
1888     
1889     if (top < nPos) /* caret above window */
1890       ME_ScrollAbs(editor,  top);
1891     else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
1892       ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
1893     return 0;
1894   }
1895   case WM_SETFONT:
1896   {
1897     LOGFONTW lf;
1898     CHARFORMAT2W fmt;
1899     HDC hDC;
1900     BOOL bRepaint = LOWORD(lParam);
1901     
1902     if (!wParam)
1903       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
1904     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
1905     hDC = GetDC(hWnd);
1906     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
1907     ReleaseDC(hWnd, hDC);   
1908     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
1909     ME_SetDefaultCharFormat(editor, &fmt);
1910
1911     ME_CommitUndo(editor);
1912     if (bRepaint)
1913       ME_RewrapRepaint(editor);
1914     return 0;
1915   }
1916   case WM_SETTEXT:
1917   {
1918     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1919     if (lParam)
1920     {
1921       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1922       if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
1923       {
1924         /* Undocumented: WM_SETTEXT supports RTF text */
1925         ME_StreamInRTFString(editor, 0, (char *)lParam);
1926       }
1927       else
1928       {
1929         LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
1930         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1931         if (lstrlenW(wszText) > 0)
1932         {
1933           int len = -1;
1934
1935           /* uses default style! */
1936           if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
1937           {
1938             WCHAR * p;
1939
1940             p = wszText;
1941             while (*p != '\0' && *p != '\r' && *p != '\n') p++;
1942             len = p - wszText;
1943           }
1944           ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1945         }
1946         ME_EndToUnicode(unicode, wszText);
1947       }
1948     }
1949     else
1950       TRACE("WM_SETTEXT - NULL\n");
1951     ME_CommitUndo(editor);
1952     ME_EmptyUndoStack(editor);
1953     ME_SetSelection(editor, 0, 0);
1954     editor->nModifyStep = 0;
1955     ME_UpdateRepaint(editor);
1956     return 1;
1957   }
1958   case EM_CANPASTE:
1959   {
1960     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1961     if (IsClipboardFormatAvailable(nRTFFormat))
1962       return TRUE;
1963     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1964       return TRUE;
1965     return FALSE;
1966   }
1967   case WM_PASTE:
1968   {    
1969     DWORD dwFormat = 0;
1970     EDITSTREAM es;
1971     ME_GlobalDestStruct gds;
1972     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1973     UINT cf = 0;
1974
1975     if (IsClipboardFormatAvailable(nRTFFormat))
1976       cf = nRTFFormat, dwFormat = SF_RTF;
1977     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1978       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1979     else
1980       return 0;
1981
1982     if (!OpenClipboard(hWnd))
1983       return 0;
1984     gds.hData = GetClipboardData(cf);
1985     gds.nLength = 0;
1986     es.dwCookie = (DWORD)&gds;
1987     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1988     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es);
1989
1990     CloseClipboard();
1991     return 0;
1992   }
1993   case WM_CUT:
1994   case WM_COPY:
1995   {
1996     LPDATAOBJECT dataObj = NULL;
1997     CHARRANGE range;
1998     HRESULT hr = S_OK;
1999     
2000     if (editor->cPasswordMask)
2001       return 0; /* Copying or Cutting masked text isn't allowed */
2002     
2003     ME_GetSelection(editor, (int*)&range.cpMin, (int*)&range.cpMax);
2004     if(editor->lpOleCallback)
2005         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2006     if(FAILED(hr) || !dataObj)
2007         hr = ME_GetDataObject(editor, &range, &dataObj);
2008     if(SUCCEEDED(hr)) {
2009         hr = OleSetClipboard(dataObj);
2010         IDataObject_Release(dataObj);
2011     }
2012     if (SUCCEEDED(hr) && msg == WM_CUT)
2013     {
2014       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
2015       ME_CommitUndo(editor);
2016       ME_UpdateRepaint(editor);
2017     }
2018     return 0;
2019   }
2020   case WM_GETTEXTLENGTH:
2021   {
2022     GETTEXTLENGTHEX how;
2023
2024     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2025     how.codepage = unicode ? 1200 : CP_ACP;
2026     return ME_GetTextLengthEx(editor, &how);
2027   }
2028   case EM_GETTEXTLENGTHEX:
2029     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2030   case WM_GETTEXT:
2031   {
2032     GETTEXTEX ex;
2033     LRESULT rc;
2034     LPSTR bufferA = NULL;
2035     LPWSTR bufferW = NULL;
2036
2037     if (unicode)
2038         bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2039     else
2040         bufferA = heap_alloc(wParam + 2);
2041
2042     ex.cb = wParam + (unicode ? 2*sizeof(WCHAR) : 2);
2043     ex.flags = GT_USECRLF;
2044     ex.codepage = unicode ? 1200 : CP_ACP;
2045     ex.lpDefaultChar = NULL;
2046     ex.lpUsedDefaultChar = NULL;
2047     rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
2048
2049     if (unicode)
2050     {
2051         memcpy((LPWSTR)lParam, bufferW, wParam);
2052         if (lstrlenW(bufferW) >= wParam / sizeof(WCHAR)) rc = 0;
2053     }
2054     else
2055     {
2056         memcpy((LPSTR)lParam, bufferA, wParam);
2057         if (strlen(bufferA) >= wParam) rc = 0;
2058     }
2059     heap_free(bufferA);
2060     heap_free(bufferW);
2061     return rc;
2062   }
2063   case EM_GETTEXTEX:
2064   {
2065     GETTEXTEX *ex = (GETTEXTEX*)wParam;
2066     int nStart, nCount;
2067
2068     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2069       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2070
2071     if (ex->flags & GT_SELECTION)
2072     {
2073       ME_GetSelection(editor, &nStart, &nCount);
2074       nCount -= nStart;
2075       nCount = min(nCount, ex->cb - 1);
2076     }
2077     else
2078     {
2079       nStart = 0;
2080       nCount = ex->cb - 1;
2081     }
2082     if (ex->codepage == 1200)
2083     {
2084       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2085       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2086     }
2087     else
2088     {
2089       /* potentially each char may be a CR, why calculate the exact value with O(N) when
2090         we can just take a bigger buffer? :) */
2091       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2092       LPWSTR buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
2093       DWORD buflen = ex->cb;
2094       LRESULT rc;
2095       DWORD flags = 0;
2096
2097       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2098       rc = WideCharToMultiByte(ex->codepage, flags, buffer, -1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
2099       if (rc) rc--; /* do not count 0 terminator */
2100
2101       heap_free(buffer);
2102       return rc;
2103     }
2104   }
2105   case EM_GETSELTEXT:
2106   {
2107     int from, to;
2108     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2109     ME_GetSelection(editor, &from, &to);
2110     tr.chrg.cpMin = from;
2111     tr.chrg.cpMax = to;
2112     tr.lpstrText = (WCHAR *)lParam;
2113     return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
2114   }
2115   case EM_GETSCROLLPOS:
2116   {
2117       POINT *point = (POINT *)lParam;
2118       point->x = 0; /* FIXME side scrolling not implemented */
2119       point->y = ME_GetYScrollPos(editor);
2120       return 1;
2121   }
2122   case EM_GETTEXTRANGE:
2123   {
2124     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2125     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2126       rng->chrg.cpMin, rng->chrg.cpMax, unicode,
2127       editor->bEmulateVersion10, ME_GetTextLength(editor));
2128     if (unicode)
2129       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
2130     else
2131     {
2132       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2133       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2134       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
2135       /* FIXME this is a potential security hole (buffer overrun) 
2136          if you know more about wchar->mbyte conversion please explain
2137       */
2138       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2139       FREE_OBJ(p);
2140       return nChars;
2141     }
2142   }
2143   case EM_GETLINE:
2144   {
2145     ME_DisplayItem *run;
2146     const unsigned int nMaxChars = *(WORD *) lParam;
2147     unsigned int nEndChars, nCharsLeft = nMaxChars;
2148     char *dest = (char *) lParam;
2149     /* rich text editor 1.0 uses \r\n for line end, 2.0 uses just \r; 
2150     we need to know how if we have the extra \n or not */
2151     int nLF = editor->bEmulateVersion10;
2152
2153     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2154           unicode ? "Unicode" : "Ansi");
2155
2156     run = ME_FindRowWithNumber(editor, wParam);
2157     if (run == NULL)
2158       return 0;
2159
2160     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2161            && !(run->member.run.nFlags & MERF_ENDPARA))
2162     {
2163       unsigned int nCopy;
2164       ME_String *strText;
2165       if (run->type != diRun)
2166         break;
2167       strText = run->member.run.strText;
2168       nCopy = min(nCharsLeft, strText->nLen);
2169
2170       if (unicode)
2171         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2172       else
2173         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2174                                     nCharsLeft, NULL, NULL);
2175       dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
2176       nCharsLeft -= nCopy;
2177     }
2178
2179     /* append \r\0 (or \r\n\0 in 1.0), space allowing */
2180     nEndChars = min(nCharsLeft, 2 + nLF);
2181     nCharsLeft -= nEndChars;
2182     if (unicode)
2183     {
2184       const WCHAR src[] = {'\r', '\0'};
2185       const WCHAR src10[] = {'\r', '\n', '\0'};
2186       lstrcpynW((LPWSTR) dest, nLF ? src10 : src, nEndChars);
2187     }
2188     else
2189       lstrcpynA(dest, nLF ? "\r\n" : "\r", nEndChars);
2190
2191     TRACE("EM_GETLINE: got %u bytes\n", nMaxChars - nCharsLeft);
2192
2193     if (nEndChars == 2 + nLF)
2194       return nMaxChars - nCharsLeft - 1; /* don't count \0 */
2195     else
2196       return nMaxChars - nCharsLeft;
2197   }
2198   case EM_GETLINECOUNT:
2199   {
2200     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2201     int nRows = 0;
2202
2203     while (item != editor->pBuffer->pLast)
2204     {
2205       assert(item->type == diParagraph);
2206       nRows += item->member.para.nRows;
2207       item = item->member.para.next_para;
2208     }
2209     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2210     return max(1, nRows);
2211   }
2212   case EM_LINEFROMCHAR:
2213   {
2214     if (wParam == -1)
2215       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2216     else
2217       return ME_RowNumberFromCharOfs(editor, wParam);
2218   }
2219   case EM_EXLINEFROMCHAR:
2220   {
2221     if (lParam == -1)
2222       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2223     else    
2224       return ME_RowNumberFromCharOfs(editor, lParam);
2225   }
2226   case EM_LINEINDEX:
2227   {
2228     ME_DisplayItem *item, *para;
2229     int nCharOfs;
2230     
2231     if (wParam == -1)
2232       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2233     else
2234       item = ME_FindRowWithNumber(editor, wParam);
2235     if (!item)
2236       return -1;
2237     para = ME_GetParagraph(item);
2238     item = ME_FindItemFwd(item, diRun);
2239     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2240     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2241     return nCharOfs;
2242   }
2243   case EM_LINELENGTH:
2244   {
2245     ME_DisplayItem *item, *item_end;
2246     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2247     
2248     if (wParam > ME_GetTextLength(editor))
2249       return 0;
2250     if (wParam == -1)
2251     {
2252       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2253       return 0;
2254     }
2255     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2256     item = ME_RowStart(item);
2257     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2258     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2259     if (item_end->type == diStartRow)
2260       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2261     else
2262       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs
2263        - (editor->bEmulateVersion10?2:1);
2264     nChars = nNextLineOfs - nThisLineOfs;
2265     TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
2266     return nChars;
2267   }
2268   case EM_EXLIMITTEXT:
2269   {
2270     if ((int)lParam < 0)
2271      return 0;
2272     if (lParam == 0)
2273       editor->nTextLimit = 65536;
2274     else
2275       editor->nTextLimit = (int) lParam;
2276     return 0;
2277   }
2278   case EM_LIMITTEXT:
2279   {
2280     if (wParam == 0)
2281       editor->nTextLimit = 65536;
2282     else
2283       editor->nTextLimit = (int) wParam;
2284     return 0;
2285   }
2286   case EM_GETLIMITTEXT:
2287   {
2288     return editor->nTextLimit;
2289   }
2290   case EM_FINDTEXT:
2291   {
2292     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2293     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2294     WCHAR *tmp;
2295     LRESULT r;
2296
2297     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2298       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2299     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2300     FREE_OBJ( tmp );
2301     return r;
2302   }
2303   case EM_FINDTEXTEX:
2304   {
2305     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2306     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2307     WCHAR *tmp;
2308     LRESULT r;
2309
2310     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2311       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2312     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2313     FREE_OBJ( tmp );
2314     return r;
2315   }
2316   case EM_FINDTEXTW:
2317   {
2318     FINDTEXTW *ft = (FINDTEXTW *)lParam;
2319     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2320   }
2321   case EM_FINDTEXTEXW:
2322   {
2323     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2324     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2325   }
2326   case EM_GETZOOM:
2327     if (!wParam || !lParam)
2328       return FALSE;
2329     *(int *)wParam = editor->nZoomNumerator;
2330     *(int *)lParam = editor->nZoomDenominator;
2331     return TRUE;
2332   case EM_SETZOOM:
2333     return ME_SetZoom(editor, wParam, lParam);
2334   case EM_CHARFROMPOS:
2335     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2336   case EM_POSFROMCHAR:
2337   {
2338     ME_DisplayItem *pRun;
2339     int nCharOfs, nOffset, nLength;
2340     POINTL pt = {0,0};
2341     
2342     nCharOfs = wParam; 
2343     /* detect which API version we're dealing with */
2344     if (wParam >= 0x40000)
2345         nCharOfs = lParam;
2346     nLength = ME_GetTextLength(editor);
2347     
2348     if (nCharOfs < nLength) { 
2349         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2350         assert(pRun->type == diRun);
2351         pt.y = pRun->member.run.pt.y;
2352         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
2353         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
2354     } else {
2355         pt.x = 0;
2356         pt.y = editor->pBuffer->pLast->member.para.nYPos;
2357     }
2358     if (wParam >= 0x40000) {
2359         *(POINTL *)wParam = pt;
2360     }
2361     return MAKELONG( pt.x, pt.y );
2362   }
2363   case WM_CREATE:
2364     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
2365     { /* Squelch the default horizontal scrollbar it would make */
2366       ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
2367     }
2368     ME_CommitUndo(editor);
2369     ME_WrapMarkedParagraphs(editor);
2370     ME_MoveCaret(editor);
2371     return 0;
2372   case WM_DESTROY:
2373     ME_DestroyEditor(editor);
2374     SetWindowLongPtrW(hWnd, 0, 0);
2375     return 0;
2376   case WM_LBUTTONDOWN:
2377     SetFocus(hWnd);
2378     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2379     SetCapture(hWnd);
2380     ME_LinkNotify(editor,msg,wParam,lParam);
2381     ME_SetCursor(editor, LOWORD(lParam));
2382     break;
2383   case WM_MOUSEMOVE:
2384     if (GetCapture() == hWnd)
2385       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2386     ME_LinkNotify(editor,msg,wParam,lParam);
2387     ME_SetCursor(editor, LOWORD(lParam));
2388     break;
2389   case WM_LBUTTONUP:
2390     if (GetCapture() == hWnd)
2391       ReleaseCapture();
2392     editor->linesel = 0;
2393     ME_SetCursor(editor, LOWORD(lParam));
2394     ME_LinkNotify(editor,msg,wParam,lParam);
2395     break;
2396   case WM_LBUTTONDBLCLK:
2397     ME_LinkNotify(editor,msg,wParam,lParam);
2398     ME_SelectWord(editor);
2399     break;
2400   case WM_CONTEXTMENU:
2401     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
2402       goto do_default;
2403     break;
2404   case WM_PAINT:
2405     if (editor->bRedraw)
2406     {
2407       HDC hDC;
2408       PAINTSTRUCT ps;
2409
2410       hDC = BeginPaint(hWnd, &ps);
2411       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
2412       EndPaint(hWnd, &ps);
2413     }
2414     break;
2415   case WM_SETFOCUS:
2416     editor->bHaveFocus = TRUE;
2417     ME_ShowCaret(editor);
2418     ME_SendOldNotify(editor, EN_SETFOCUS);
2419     return 0;
2420   case WM_KILLFOCUS:
2421     ME_HideCaret(editor);
2422     editor->bHaveFocus = FALSE;
2423     ME_SendOldNotify(editor, EN_KILLFOCUS);
2424     return 0;
2425   case WM_ERASEBKGND:
2426   {
2427     if (editor->bRedraw)
2428     {
2429       HDC hDC = (HDC)wParam;
2430       RECT rc;
2431       if (GetUpdateRect(hWnd,&rc,TRUE))
2432       {
2433         FillRect(hDC, &rc, editor->hbrBackground);
2434       }
2435     }
2436     return 1;
2437   }
2438   case WM_COMMAND:
2439     TRACE("editor wnd command = %d\n", LOWORD(wParam));
2440     return 0;
2441   case WM_KEYDOWN:
2442     if (ME_KeyDown(editor, LOWORD(wParam)))
2443       return 0;
2444     goto do_default;
2445   case WM_CHAR: 
2446   {
2447     WCHAR wstr;
2448
2449     if (unicode)
2450         wstr = (WCHAR)wParam;
2451     else
2452     {
2453         CHAR charA = wParam;
2454         MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2455     }
2456     if (editor->AutoURLDetect_bEnable)
2457       ME_AutoURLDetect(editor, wstr);
2458         
2459     switch (wstr)
2460     {
2461     case 1: /* Ctrl-A */
2462       ME_SetSelection(editor, 0, -1);
2463       return 0;
2464     case 3: /* Ctrl-C */
2465       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
2466       return 0;
2467     }
2468     
2469     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
2470       MessageBeep(MB_ICONERROR);
2471       return 0; /* FIXME really 0 ? */
2472     }
2473
2474     switch (wstr)
2475     {
2476     case 22: /* Ctrl-V */
2477       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
2478       return 0;
2479     case 24: /* Ctrl-X */
2480       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
2481       return 0;
2482     case 25: /* Ctrl-Y */
2483       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
2484       return 0;
2485     case 26: /* Ctrl-Z */
2486       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
2487       return 0;
2488     }
2489     if (((unsigned)wstr)>=' '
2490         || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2491         || wstr=='\t') {
2492       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2493       /* WM_CHAR is restricted to nTextLimit */
2494       int from, to;
2495       ME_GetSelection(editor, &from, &to);
2496       if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2497       {
2498         ME_Style *style = ME_GetInsertStyle(editor, 0);
2499         ME_SaveTempStyle(editor);
2500         ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2501         ME_ReleaseStyle(style);
2502         ME_CommitUndo(editor);
2503       }
2504       ME_UpdateRepaint(editor);
2505     }
2506     return 0;
2507   }
2508   case EM_SCROLL: /* fall through */
2509   case WM_VSCROLL: 
2510   {
2511     int origNPos;
2512     int lineHeight;
2513     
2514     origNPos = ME_GetYScrollPos(editor);
2515     lineHeight = 24;
2516     
2517     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
2518       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2519     if (lineHeight <= 0) lineHeight = 24;
2520     
2521     switch(LOWORD(wParam)) 
2522     {
2523       case SB_LINEUP:
2524         ME_ScrollUp(editor,lineHeight);
2525         break;
2526       case SB_LINEDOWN:
2527         ME_ScrollDown(editor,lineHeight);
2528         break;
2529       case SB_PAGEUP:
2530         ME_ScrollUp(editor,editor->sizeWindow.cy);
2531         break;
2532       case SB_PAGEDOWN:
2533         ME_ScrollDown(editor,editor->sizeWindow.cy);
2534         break;
2535       case SB_THUMBTRACK:
2536       case SB_THUMBPOSITION:
2537         ME_ScrollAbs(editor,HIWORD(wParam));
2538         break;
2539     }
2540     if (msg == EM_SCROLL)
2541       return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
2542     break;
2543   }
2544   case WM_MOUSEWHEEL:
2545   {
2546     int gcWheelDelta;
2547     UINT pulScrollLines;
2548     
2549     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
2550     gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
2551     
2552     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
2553     {
2554       /* FIXME follow the original */
2555       ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8); 
2556     }
2557     break;
2558   }
2559   case EM_GETRECT:
2560   {
2561     *((RECT *)lParam) = editor->rcFormat;
2562     return 0;
2563   }
2564   case EM_SETRECT:
2565   case EM_SETRECTNP:
2566   {
2567     if (lParam)
2568     {
2569       RECT *rc = (RECT *)lParam;
2570       
2571       if (wParam)
2572       {
2573         editor->rcFormat.left += rc->left;
2574         editor->rcFormat.top += rc->top;
2575         editor->rcFormat.right += rc->right;
2576         editor->rcFormat.bottom += rc->bottom;
2577       }
2578       else
2579       {
2580         editor->rcFormat = *rc;
2581       }
2582     }
2583     else
2584     {
2585       GetClientRect(hWnd, &editor->rcFormat);
2586     }
2587     if (msg != EM_SETRECTNP)
2588       ME_RewrapRepaint(editor);
2589     return 0;
2590   }
2591   case EM_REQUESTRESIZE:
2592     ME_SendRequestResize(editor, TRUE);
2593     return 0;
2594   case WM_SETREDRAW:
2595     editor->bRedraw = wParam;
2596     return 0;
2597   case WM_SIZE:
2598   {
2599     GetClientRect(hWnd, &editor->rcFormat);
2600     ME_RewrapRepaint(editor);
2601     return DefWindowProcW(hWnd, msg, wParam, lParam);
2602   }
2603   /* IME messages to make richedit controls IME aware */
2604   case WM_IME_SETCONTEXT:
2605   case WM_IME_CONTROL:
2606   case WM_IME_SELECT:
2607   case WM_IME_COMPOSITIONFULL:
2608     return 0;
2609   case WM_IME_STARTCOMPOSITION:
2610   {
2611     editor->imeStartIndex=ME_GetCursorOfs(editor,0);
2612     ME_DeleteSelection(editor);
2613     ME_CommitUndo(editor);
2614     ME_UpdateRepaint(editor);
2615     return 0;
2616   }
2617   case WM_IME_COMPOSITION:
2618   {
2619     HIMC hIMC;
2620
2621     ME_Style *style = ME_GetInsertStyle(editor, 0);
2622     hIMC = ImmGetContext(hWnd);
2623     ME_DeleteSelection(editor);
2624     ME_CommitUndo(editor);
2625     ME_SaveTempStyle(editor);
2626     if (lParam & GCS_RESULTSTR)
2627     {
2628         LPWSTR lpCompStr = NULL;
2629         DWORD dwBufLen;
2630
2631         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2632         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
2633         ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
2634         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
2635         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
2636     }
2637     else if (lParam & GCS_COMPSTR)
2638     {
2639         LPWSTR lpCompStr = NULL;
2640         DWORD dwBufLen;
2641
2642         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
2643         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
2644         ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
2645         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
2646
2647         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
2648         ME_SetSelection(editor,editor->imeStartIndex,
2649                         editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
2650     }
2651     ME_ReleaseStyle(style);
2652     ME_UpdateRepaint(editor);
2653     return 0;
2654   }
2655   case WM_IME_ENDCOMPOSITION:
2656   {
2657     ME_DeleteSelection(editor);
2658     editor->imeStartIndex=-1;
2659     return 0;
2660   }
2661   case EM_GETOLEINTERFACE:
2662   {
2663     LPVOID *ppvObj = (LPVOID*) lParam;
2664     return CreateIRichEditOle(editor, ppvObj);
2665   }
2666   case EM_GETPASSWORDCHAR:
2667   {
2668     return editor->cPasswordMask;
2669   }
2670   case EM_SETOLECALLBACK:
2671     if(editor->lpOleCallback)
2672       IUnknown_Release(editor->lpOleCallback);
2673     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
2674     if(editor->lpOleCallback)
2675       IUnknown_AddRef(editor->lpOleCallback);
2676     return TRUE;
2677   case EM_GETWORDBREAKPROC:
2678     return (LRESULT)editor->pfnWordBreak;
2679   case EM_SETWORDBREAKPROC:
2680   {
2681     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
2682
2683     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
2684     return (LRESULT)pfnOld;
2685   }
2686   case EM_SETTEXTMODE:
2687   {
2688     LRESULT ret;
2689     int mask = 0;
2690     int changes = 0;
2691     ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
2692     if (!ret)
2693     {
2694       /*Check for valid wParam*/
2695       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
2696           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
2697           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
2698         return 1;
2699       else
2700       {
2701         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
2702         {
2703           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
2704           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
2705         }
2706         /*FIXME: Currently no support for undo level and code page options*/ 
2707         editor->mode = (editor->mode & (~mask)) | changes;
2708         return 0;
2709       }
2710     }
2711     return ret;
2712   }
2713   case EM_SETPASSWORDCHAR:
2714   {
2715     editor->cPasswordMask = wParam;
2716     ME_RewrapRepaint(editor);
2717     return 0;
2718   }
2719   default:
2720   do_default:
2721     return DefWindowProcW(hWnd, msg, wParam, lParam);
2722   }
2723   return 0L;
2724 }
2725
2726 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2727 {
2728     BOOL unicode = TRUE;
2729
2730     /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
2731     if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
2732         unicode = FALSE;
2733
2734     return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
2735 }
2736
2737 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2738 {
2739     return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
2740 }
2741
2742 /******************************************************************
2743  *        RichEditANSIWndProc (RICHED20.10)
2744  */
2745 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2746 {
2747     return RichEditWndProcA(hWnd, msg, wParam, lParam);
2748 }
2749
2750 /******************************************************************
2751  *        RichEdit10ANSIWndProc (RICHED20.9)
2752  */
2753 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2754 {
2755   LRESULT result;
2756   
2757   /* FIXME: this is NOT the same as 2.0 version */
2758   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
2759   if (msg == WM_NCCREATE)
2760   {
2761     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2762     
2763     editor->bEmulateVersion10 = TRUE;
2764     editor->pBuffer->pLast->member.para.nCharOfs = 2;
2765   }
2766   return result;
2767 }
2768
2769 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
2770 {
2771   HWND hWnd = editor->hWnd;
2772   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
2773 }
2774
2775 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2776 {
2777   int x,y;
2778   ME_Cursor tmpCursor;
2779   int nCharOfs; /* The start of the clicked text. Absolute character offset */
2780
2781   ME_Run *tmpRun;
2782
2783   ENLINK info;
2784   x = (short)LOWORD(lParam);
2785   y = (short)HIWORD(lParam);
2786   nCharOfs = ME_CharFromPos(editor, x, y);
2787   if (nCharOfs < 0) return;
2788
2789   ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
2790   tmpRun = &tmpCursor.pRun->member.run;
2791
2792   if ((tmpRun->style->fmt.dwMask & CFM_LINK)
2793     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
2794   { /* The clicked run has CFE_LINK set */
2795     info.nmhdr.hwndFrom = editor->hWnd;
2796     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2797     info.nmhdr.code = EN_LINK;
2798     info.msg = msg;
2799     info.wParam = wParam;
2800     info.lParam = lParam;
2801     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
2802     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
2803     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
2804   }  
2805 }
2806
2807 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
2808 {
2809   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
2810   int i = 0;
2811   
2812   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
2813     item = item->member.para.next_para;
2814   if (!item)
2815     return 0;
2816   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
2817     item = item->member.para.next_para;
2818     i++;
2819   }
2820   return i;
2821 }
2822
2823
2824 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
2825 {
2826   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
2827   int nWritten = 0;
2828   WCHAR *pStart = buffer;
2829   
2830   if (!item) {
2831     *buffer = 0;
2832     return 0;
2833   }
2834   
2835   if (nStart)
2836   {
2837     int nLen = ME_StrLen(item->member.run.strText) - nStart;
2838     if (nLen > nChars)
2839       nLen = nChars;
2840     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
2841     nChars -= nLen;
2842     nWritten += nLen;
2843     if (!nChars)
2844       return nWritten;
2845     buffer += nLen;
2846     nStart = 0;
2847     item = ME_FindItemFwd(item, diRun);
2848   }
2849   
2850   while(nChars && item)
2851   {
2852     int nLen = ME_StrLen(item->member.run.strText);
2853     if (nLen > nChars)
2854       nLen = nChars;
2855
2856     if (item->member.run.nFlags & MERF_ENDPARA)
2857     {
2858       if (!ME_FindItemFwd(item, diRun))
2859         /* No '\r' is appended to the last paragraph. */
2860         nLen = 0;
2861       else if (bCRLF && nChars == 1) {
2862         nLen = 0;
2863         nChars = 0;
2864       } else {
2865         *buffer = '\r';
2866         if (bCRLF)
2867         {
2868           *(++buffer) = '\n';
2869           nWritten++;
2870         }
2871         assert(nLen == 1);
2872         /* our end paragraph consists of 2 characters now */
2873         if (editor->bEmulateVersion10)
2874           nChars--;
2875       }
2876     }
2877     else
2878       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2879     nChars -= nLen;
2880     nWritten += nLen;
2881     buffer += nLen;    
2882       
2883     if (!nChars)
2884     {
2885       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2886       *buffer = 0;
2887       return nWritten;
2888     }
2889     item = ME_FindItemFwd(item, diRun);
2890   }
2891   *buffer = 0;
2892   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2893   return nWritten;  
2894 }
2895
2896 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
2897 {
2898   WNDCLASSW wcW;
2899   WNDCLASSA wcA;
2900   
2901   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2902   wcW.lpfnWndProc = RichEditWndProcW;
2903   wcW.cbClsExtra = 0;
2904   wcW.cbWndExtra = sizeof(ME_TextEditor *);
2905   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2906   wcW.hIcon = NULL;
2907   wcW.hCursor = hBeam;
2908   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2909   wcW.lpszMenuName = NULL;
2910
2911   if (is_version_nt())
2912   {
2913     wcW.lpszClassName = RichEdit20W;
2914     if (!RegisterClassW(&wcW)) return FALSE;
2915     wcW.lpszClassName = RichEdit50W;
2916     if (!RegisterClassW(&wcW)) return FALSE;
2917   }
2918   else
2919   {
2920     /* WNDCLASSA/W have the same layout */
2921     wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
2922     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
2923     wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
2924     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
2925   }
2926
2927   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2928   wcA.lpfnWndProc = RichEditWndProcA;
2929   wcA.cbClsExtra = 0;
2930   wcA.cbWndExtra = sizeof(ME_TextEditor *);
2931   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
2932   wcA.hIcon = NULL;
2933   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2934   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2935   wcA.lpszMenuName = NULL;
2936   wcA.lpszClassName = "RichEdit20A";
2937   if (!RegisterClassA(&wcA)) return FALSE;
2938   wcA.lpszClassName = "RichEdit50A";
2939   if (!RegisterClassA(&wcA)) return FALSE;
2940
2941   return TRUE;
2942 }
2943
2944 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2945   /* FIXME: Not implemented */
2946   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
2947         hWnd, msg, get_msg_name(msg), wParam, lParam);
2948   return DefWindowProcW(hWnd, msg, wParam, lParam);
2949 }
2950
2951 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2952   /* FIXME: Not implemented */
2953   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
2954         hWnd, msg, get_msg_name(msg), wParam, lParam);
2955   return DefWindowProcW(hWnd, msg, wParam, lParam);
2956 }
2957
2958 /******************************************************************
2959  *        REExtendedRegisterClass (RICHED20.8)
2960  *
2961  * FIXME undocumented
2962  * Need to check for errors and implement controls and callbacks 
2963  */
2964 LRESULT WINAPI REExtendedRegisterClass(void)
2965 {
2966   WNDCLASSW wcW;
2967   UINT result;
2968
2969   FIXME("semi stub\n");
2970
2971   wcW.cbClsExtra = 0;
2972   wcW.cbWndExtra = 4;
2973   wcW.hInstance = NULL;
2974   wcW.hIcon = NULL;
2975   wcW.hCursor = NULL;
2976   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
2977   wcW.lpszMenuName = NULL;
2978
2979   if (!ME_ListBoxRegistered)
2980   {
2981       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
2982       wcW.lpfnWndProc = REListWndProc;
2983       wcW.lpszClassName = REListBox20W;
2984       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
2985   }
2986
2987   if (!ME_ComboBoxRegistered)
2988   {
2989       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
2990       wcW.lpfnWndProc = REComboWndProc;
2991       wcW.lpszClassName = REComboBox20W;
2992       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
2993   }
2994
2995   result = 0;
2996   if (ME_ListBoxRegistered)
2997       result += 1;
2998   if (ME_ComboBoxRegistered)
2999       result += 2;
3000
3001   return result;
3002 }
3003
3004 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar) 
3005 {
3006   struct prefix_s {
3007     const char *text;
3008     int length;
3009   } prefixes[12] = {
3010     {"http:", 5},
3011     {"file:", 6},
3012     {"mailto:", 8},
3013     {"ftp:", 5},
3014     {"https:", 7},
3015     {"gopher:", 8},
3016     {"nntp:", 6},
3017     {"prospero:", 10},
3018     {"telnet:", 8},
3019     {"news:", 6},
3020     {"wais:", 6},
3021     {"www.", 5}
3022   };
3023   CHARRANGE ins_pt;
3024   int curf_ef, link_ef, def_ef;
3025   int cur_prefx, prefx_cnt;
3026   int sel_min, sel_max;
3027   int car_pos = 0;
3028   int text_pos=-1;
3029   int URLmin, URLmax = 0;
3030   CHARRANGE url;
3031   FINDTEXTA ft;
3032   CHARFORMAT2W cur_format;
3033   CHARFORMAT2W default_format;
3034   CHARFORMAT2W link;
3035   RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
3036   sel_min = ins_pt.cpMin;
3037   sel_max = ins_pt.cpMax;
3038   if (sel_min==sel_max) 
3039     car_pos = sel_min;
3040   if (sel_min!=sel_max)
3041     car_pos = ME_GetTextLength(editor)+1;   
3042   cur_format.cbSize = sizeof(cur_format);
3043   default_format.cbSize = sizeof(default_format);
3044   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
3045   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
3046   link.cbSize = sizeof(link);
3047   link.dwMask = CFM_LINK;
3048   link.dwEffects = CFE_LINK;
3049   curf_ef = cur_format.dwEffects & link.dwEffects;
3050   def_ef = default_format.dwEffects & link.dwEffects;
3051   link_ef = link.dwEffects & link.dwEffects;
3052   if (curf_ef == link_ef) 
3053   {
3054     if( curChar == '\n' || curChar=='\r' || curChar==' ') 
3055     {
3056       ME_SetSelection(editor, car_pos, car_pos);
3057       RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
3058       text_pos=-1;
3059       return 0;
3060     }
3061   }
3062   if (curf_ef == def_ef)
3063   {
3064     cur_prefx = 0;
3065     prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
3066     while (cur_prefx<=prefx_cnt) 
3067     {
3068       if (text_pos == -1) 
3069       {
3070         ft.lpstrText = prefixes[cur_prefx].text;
3071         URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
3072         URLmax=max(0, car_pos);
3073         if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
3074         {
3075         URLmax = ME_GetTextLength(editor)+1;
3076         }
3077         ft.chrg.cpMin = URLmin;
3078         ft.chrg.cpMax = URLmax;
3079         text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);   
3080         cur_prefx++;
3081       }
3082       if (text_pos != -1) 
3083       {
3084         url.cpMin=text_pos;
3085         url.cpMax=car_pos-1;
3086         ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
3087         ME_RewrapRepaint(editor);
3088         break;
3089       }
3090     }
3091   }
3092   return 0;
3093 }