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