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