Fixed another case of misunderstanding MSDN wrt StreamInProc, causing
[wine] / dlls / riched20 / editor.c
1 /*
2  * RichEdit - functions dealing with editor object
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /* 
22   API implementation status:
23   
24   Messages (ANSI versions not done yet)
25   - EM_AUTOURLDETECT 2.0
26   + EM_CANPASTE
27   + EM_CANREDO 2.0
28   + EM_CANUNDO
29   + EM_CHARFROMPOS
30   - EM_DISPLAYBAND
31   + EM_EMPTYUNDOBUFFER
32   + EM_EXGETSEL
33   - EM_EXLIMITTEXT
34   + EM_EXLINEFROMCHAR
35   + EM_EXSETSEL
36   + EM_FINDTEXT (only FR_DOWN flag implemented)
37   + EM_FINDTEXTEX (only FR_DOWN flag implemented)
38   - EM_FINDWORDBREAK
39   - EM_FMTLINES
40   - EM_FORMATRANGE
41   - EM_GETAUTOURLDETECT 2.0
42   - EM_GETBIDIOPTIONS 3.0
43   - EM_GETCHARFORMAT (partly done)
44   - EM_GETEDITSTYLE
45   + EM_GETEVENTMASK
46   - EM_GETFIRSTVISIBLELINE
47   - EM_GETIMECOLOR 1.0asian
48   - EM_GETIMECOMPMODE 2.0
49   - EM_GETIMEOPTIONS 1.0asian
50   - EM_GETIMESTATUS
51   - EM_GETLANGOPTIONS 2.0
52   - EM_GETLIMITTEXT
53   - EM_GETLINE        
54   + EM_GETLINECOUNT   returns number of rows, not of paragraphs
55   + EM_GETMODIFY
56   - EM_GETOLEINTERFACE
57   - EM_GETOPTIONS
58   + EM_GETPARAFORMAT
59   - EM_GETPASSWORDCHAR 2.0
60   - EM_GETPUNCTUATION 1.0asian
61   + EM_GETRECT
62   - EM_GETREDONAME 2.0
63   + EM_GETSEL
64   + EM_GETSELTEXT (ANSI&Unicode)
65   - EM_GETSCROLLPOS 3.0
66 ! - EM_GETTHUMB
67   - EM_GETTEXTEX 2.0
68   + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
69   - EM_GETTEXTMODE 2.0
70 ? + EM_GETTEXTRANGE (ANSI&Unicode)
71   - EM_GETTYPOGRAPHYOPTIONS 3.0
72   - EM_GETUNDONAME
73   - EM_GETWORDBREAKPROC
74   - EM_GETWORDBREAKPROCEX
75   - EM_GETWORDWRAPMODE 1.0asian
76   + EM_GETZOOM 3.0
77   - EM_HIDESELECTION
78   - EM_LIMITTEXT
79   + EM_LINEFROMCHAR
80   + EM_LINEINDEX
81   + EM_LINELENGTH
82   + EM_LINESCROLL
83   - EM_PASTESPECIAL
84   - EM_POSFROMCHARS
85   + EM_REDO 2.0
86   - EM_REQUESTRESIZE
87   + EM_REPLACESEL (proper style?) ANSI&Unicode
88   - EM_SCROLL
89   - EM_SCROLLCARET
90   - EM_SELECTIONTYPE
91   - EM_SETBIDIOPTIONS 3.0
92   + EM_SETBKGNDCOLOR
93   - EM_SETCHARFORMAT (partly done, no ANSI)
94   - EM_SETEDITSTYLE
95   + EM_SETEVENTMASK (few notifications supported)
96   - EM_SETFONTSIZE
97   - EM_SETIMECOLOR 1.0asian
98   - EM_SETIMEOPTIONS 1.0asian
99   - EM_SETLANGOPTIONS 2.0
100   - EM_SETLIMITTEXT
101   + EM_SETMODIFY (not sure if implementation is correct)
102   - EM_SETOLECALLBACK
103   - EM_SETOPTIONS
104   - EM_SETPALETTE 2.0
105   + EM_SETPARAFORMAT
106   - EM_SETPASSWORDCHAR 2.0
107   - EM_SETPUNCTUATION 1.0asian
108   + EM_SETREADONLY no beep on modification attempt
109   + EM_SETRECT
110   + EM_SETRECTNP (EM_SETRECT without repainting)
111   + EM_SETSEL
112   - EM_SETSCROLLPOS 3.0
113   - EM_SETTABSTOPS 3.0
114   - EM_SETTARGETDEVICE
115   + EM_SETTEXTEX 3.0 (unicode only, no rich text insertion handling, proper style?)
116   - EM_SETTEXTMODE 2.0
117   - EM_SETTYPOGRAPHYOPTIONS 3.0
118   - EM_SETUNDOLIMIT 2.0
119   - EM_SETWORDBREAKPROC
120   - EM_SETWORDBREAKPROCEX
121   - EM_SETWORDWRAPMODE 1.0asian
122   + EM_SETZOOM 3.0
123   - EM_SHOWSCROLLBAR 2.0
124   - EM_STOPGROUPTYPING 2.0
125   + EM_STREAMIN
126   + EM_STREAMOUT
127   + EM_UNDO
128   + WM_CHAR
129   + WM_CLEAR
130   + WM_COPY
131   + WM_CUT
132   + WM_GETDLGCODE (the current implementation is incomplete)
133   + WM_GETTEXT (ANSI&Unicode)
134   + WM_GETTEXTLENGTH (ANSI version sucks)
135   + WM_PASTE
136   - WM_SETFONT
137   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
138   - WM_STYLECHANGING
139   - WM_STYLECHANGED (things like read-only flag)
140   - WM_UNICHAR
141   
142   Notifications
143   
144   * EN_CHANGE (sent from the wrong place)
145   - EN_CORRECTTEXT
146   - EN_DROPFILES
147   - EN_ERRSPACE
148   - EN_HSCROLL
149   - EN_IMECHANGE
150   + EN_KILLFOCUS
151   - EN_LINK
152   - EN_MAXTEXT
153   - EN_MSGFILTER
154   - EN_OLEOPFAILED
155   - EN_PROTECTED
156   - EN_REQUESTRESIZE
157   - EN_SAVECLIPBOARD
158   + EN_SELCHANGE 
159   + EN_SETFOCUS
160   - EN_STOPNOUNDO
161   * EN_UPDATE (sent from the wrong place)
162   - EN_VSCROLL
163   
164   Styles
165   
166   - ES_AUTOHSCROLL
167   - ES_AUTOVSCROLL
168   - ES_CENTER
169   - ES_DISABLENOSCROLL (scrollbar is always visible)
170   - ES_EX_NOCALLOLEINIT
171   - ES_LEFT
172   - ES_MULTILINE (currently single line controls aren't supported)
173   - ES_NOIME
174   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
175   - ES_RIGHT
176   - ES_SAVESEL
177   - ES_SELFIME
178   - ES_SUNKEN
179   - ES_VERTICAL
180   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
181   - WS_SETFONT
182   - WS_HSCROLL
183   - WS_VSCROLL
184 */
185
186 /*
187  * RICHED20 TODO (incomplete):
188  *
189  * - messages/styles/notifications listed above 
190  * - Undo coalescing 
191  * - add remaining CHARFORMAT/PARAFORMAT fields
192  * - right/center align should strip spaces from the beginning
193  * - more advanced navigation (Ctrl-arrows)
194  * - tabs
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  *
212  * Bugs that are probably fixed, but not so easy to verify:
213  * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
214  * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
215  * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
216  * - caret shouldn't be displayed when selection isn't empty
217  * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
218  * - undo for setting default format (done, might be buggy)
219  * - styles might be not released properly (looks like they work like charm, but who knows?
220  *
221  */
222
223 #include "editor.h"
224 #include "commdlg.h"
225 #include "ole2.h"
226 #include "richole.h"
227 #include "winreg.h"
228 #define NO_SHLWAPI_STREAM 
229 #include "shlwapi.h"
230
231 #include "rtf.h"
232  
233 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
234
235 int me_debug = 0;
236 HANDLE me_heap = NULL;
237
238 static ME_TextBuffer *ME_MakeText(void) {
239   
240   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
241
242   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
243   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
244   
245   p1->prev = NULL;
246   p1->next = p2;
247   p2->prev = p1;
248   p2->next = NULL;
249   p1->member.para.next_para = p2;
250   p2->member.para.prev_para = p1;
251   p2->member.para.nCharOfs = 0;  
252   
253   buf->pFirst = p1;
254   buf->pLast = p2;
255   buf->pCharStyle = NULL;
256   
257   return buf;
258 }
259
260
261 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
262 {
263   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
264   WCHAR *pText;
265   
266   TRACE("%08lx %p\n", dwFormat, stream);
267   
268   do {
269     long nWideChars = 0;
270
271     if (!stream->dwSize)
272     {
273       ME_StreamInFill(stream);
274       if (stream->editstream->dwError)
275         break;
276       if (!stream->dwSize)
277         break;
278     }
279       
280     if (!(dwFormat & SF_UNICODE))
281     {
282       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
283       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
284       pText = wszText;
285     }
286     else
287     {
288       nWideChars = stream->dwSize >> 1;
289       pText = (WCHAR *)stream->buffer;
290     }
291     
292     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
293     if (stream->dwSize == 0)
294       break;
295     stream->dwSize = 0;
296   } while(1);
297   ME_CommitUndo(editor);
298   ME_Repaint(editor);
299   return 0;
300 }
301
302 static void ME_RTFCharAttrHook(RTF_Info *info)
303 {
304   CHARFORMAT2W fmt;
305   fmt.cbSize = sizeof(fmt);
306   fmt.dwMask = 0;
307   
308   switch(info->rtfMinor)
309   {
310     case rtfPlain:
311       /* FIXME add more flags once they're implemented */
312       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
313       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
314       fmt.yHeight = 12*20; /* 12pt */
315       fmt.wWeight = 400;
316       break;
317     case rtfBold:
318       fmt.dwMask = CFM_BOLD;
319       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
320       break;
321     case rtfItalic:
322       fmt.dwMask = CFM_ITALIC;
323       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
324       break;
325     case rtfUnderline:
326       fmt.dwMask = CFM_UNDERLINE;
327       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
328       fmt.bUnderlineType = CFU_CF1UNDERLINE;
329       break;
330     case rtfNoUnderline:
331       fmt.dwMask = CFM_UNDERLINE;
332       fmt.dwEffects = 0;
333       break;
334     case rtfStrikeThru:
335       fmt.dwMask = CFM_STRIKEOUT;
336       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
337       break;
338     case rtfSubScript:
339     case rtfSuperScript:
340     case rtfSubScrShrink:
341     case rtfSuperScrShrink:
342     case rtfNoSuperSub:
343       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
344       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
345       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
346       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
347       break;
348     case rtfBackColor:
349       fmt.dwMask = CFM_BACKCOLOR;
350       fmt.dwEffects = 0;
351       if (info->rtfParam == 0)
352         fmt.dwEffects = CFE_AUTOBACKCOLOR;
353       else if (info->rtfParam != rtfNoParam)
354       {
355         RTFColor *c = RTFGetColor(info, info->rtfParam);
356         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
357       }
358       break;
359     case rtfForeColor:
360       fmt.dwMask = CFM_COLOR;
361       fmt.dwEffects = 0;
362       if (info->rtfParam == 0)
363         fmt.dwEffects = CFE_AUTOCOLOR;
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 rtfFontNum:
371       if (info->rtfParam != rtfNoParam)
372       {
373         RTFFont *f = RTFGetFont(info, info->rtfParam);
374         if (f)
375         {
376           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
377           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
378           fmt.bCharSet = f->rtfFCharSet;
379           fmt.dwMask = CFM_FACE | CFM_CHARSET;
380         }
381       }
382       break;
383     case rtfFontSize:
384       fmt.dwMask = CFM_SIZE;
385       if (info->rtfParam != rtfNoParam)
386         fmt.yHeight = info->rtfParam*10;
387       break;
388   }
389   if (fmt.dwMask) {
390     ME_Style *style2;
391     RTFFlushOutputBuffer(info);
392     /* FIXME too slow ? how come ? */
393     style2 = ME_ApplyStyle(info->style, &fmt);
394     ME_ReleaseStyle(info->style);
395     info->style = style2;
396     info->styleChanged = TRUE;
397   }
398 }
399
400 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
401    the same tags mean different things in different contexts */
402 static void ME_RTFParAttrHook(RTF_Info *info)
403 {
404   PARAFORMAT2 fmt;
405   fmt.cbSize = sizeof(fmt);
406   fmt.dwMask = 0;
407   
408   switch(info->rtfMinor)
409   {
410   case rtfParDef: /* I'm not 100% sure what does it do, but I guess it restores default paragraph attributes */
411     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
412     fmt.wAlignment = PFA_LEFT;
413     fmt.cTabCount = 0;
414     fmt.dxOffset = fmt.dxStartIndent = 0;
415     break;
416   case rtfFirstIndent:
417     ME_GetSelectionParaFormat(info->editor, &fmt);
418     fmt.dwMask = PFM_STARTINDENT;
419     fmt.dxStartIndent = info->rtfParam + fmt.dxOffset;
420     break;
421   case rtfLeftIndent:
422   {
423     int first, left;
424     ME_GetSelectionParaFormat(info->editor, &fmt);
425     first = fmt.dxStartIndent;
426     left = info->rtfParam;
427     fmt.dwMask = PFM_STARTINDENT|PFM_OFFSET;
428     fmt.dxStartIndent = first + left;
429     fmt.dxOffset = -first;
430     break;
431   }
432   case rtfRightIndent:
433     fmt.dwMask = PFM_RIGHTINDENT;
434     fmt.dxRightIndent = info->rtfParam;
435     break;
436   case rtfQuadLeft:
437   case rtfQuadJust:
438     fmt.dwMask = PFM_ALIGNMENT;
439     fmt.wAlignment = PFA_LEFT;
440     break;
441   case rtfQuadRight:
442     fmt.dwMask = PFM_ALIGNMENT;
443     fmt.wAlignment = PFA_RIGHT;
444     break;
445   case rtfQuadCenter:
446     fmt.dwMask = PFM_ALIGNMENT;
447     fmt.wAlignment = PFA_CENTER;
448     break;
449   case rtfTabPos:
450     ME_GetSelectionParaFormat(info->editor, &fmt);
451     if (!(fmt.dwMask & PFM_TABSTOPS))
452     {
453       fmt.dwMask |= PFM_TABSTOPS;
454       fmt.cTabCount = 0;
455     }
456     if (fmt.cTabCount < MAX_TAB_STOPS)
457       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
458     break;
459   }  
460   if (fmt.dwMask) {
461     RTFFlushOutputBuffer(info);
462     /* FIXME too slow ? how come ?*/
463     ME_SetSelectionParaFormat(info->editor, &fmt);
464   }
465 }
466
467 static void ME_RTFReadHook(RTF_Info *info) {
468   switch(info->rtfClass)
469   {
470     case rtfGroup:
471       switch(info->rtfMajor)
472       {
473         case rtfBeginGroup:
474           if (info->stackTop < maxStack) {
475             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
476             info->stack[info->stackTop].codePage = info->codePage;
477             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
478           }
479           info->stackTop++;
480           info->styleChanged = FALSE;
481           break;
482         case rtfEndGroup:
483         {
484           ME_Style *s;
485           RTFFlushOutputBuffer(info);
486           info->stackTop--;
487           if (info->styleChanged)
488           {
489             /* FIXME too slow ? how come ? */
490             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
491             ME_ReleaseStyle(info->style);
492             info->style = s;
493             info->codePage = info->stack[info->stackTop].codePage;
494             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
495           }
496           break;
497         }
498       }
499       break;
500     case rtfControl:
501       switch(info->rtfMajor)
502       {
503         case rtfCharAttr:
504           ME_RTFCharAttrHook(info);
505           break;
506         case rtfParAttr:
507           ME_RTFParAttrHook(info);
508           break;
509       }
510       break;
511   }
512 }
513
514 void
515 ME_StreamInFill(ME_InStream *stream)
516 {
517   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
518                                                                 (BYTE *)stream->buffer,
519                                                                 sizeof(stream->buffer),
520                                                                 (LONG *)&stream->dwSize);
521   stream->dwUsed = 0;
522 }
523
524 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
525 {
526   RTF_Info parser;
527   ME_Style *style;
528   int from, to, to2, nUndoMode;
529   ME_UndoItem *pUI;
530   int nEventMask = editor->nEventMask;
531   ME_InStream inStream;
532
533   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
534   editor->nEventMask = 0;
535   
536   ME_GetSelection(editor, &from, &to);
537   if (format & SFF_SELECTION) {
538     style = ME_GetSelectionInsertStyle(editor);
539
540     ME_InternalDeleteText(editor, from, to-from);
541   }
542   else {
543     style = editor->pBuffer->pDefaultStyle;
544     ME_AddRefStyle(style);
545     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
546     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
547     from = to = 0;
548     ME_ClearTempStyle(editor);
549     /* FIXME restore default paragraph formatting ! */
550   }
551   
552   nUndoMode = editor->nUndoMode;
553   editor->nUndoMode = umIgnore;
554
555   inStream.editstream = stream;
556   inStream.editstream->dwError = 0;
557   inStream.dwSize = 0;
558   inStream.dwUsed = 0;
559
560   if (format & SF_RTF)
561   {
562     /* Check if it's really RTF, and if it is not, use plain text */
563     ME_StreamInFill(&inStream);
564     if (!inStream.editstream->dwError)
565     {
566       if (strncmp(inStream.buffer, "{\\rtf1", 6) && strncmp(inStream.buffer, "{\\urtf", 6))
567       {
568         format &= ~SF_RTF;
569         format |= SF_TEXT;
570       }
571     }
572   }
573
574   if (!inStream.editstream->dwError)
575   {
576     if (format & SF_RTF) {
577       /* setup the RTF parser */
578       memset(&parser, 0, sizeof parser);
579       RTFSetEditStream(&parser, &inStream);
580       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
581       parser.hwndEdit = editor->hWnd;
582       parser.editor = editor;
583       parser.style = style;
584       WriterInit(&parser);
585       RTFInit(&parser);
586       RTFSetReadHook(&parser, ME_RTFReadHook);
587       BeginFile(&parser);
588   
589       /* do the parsing */
590       RTFRead(&parser);
591       RTFFlushOutputBuffer(&parser);
592       RTFDestroy(&parser);
593
594       style = parser.style;
595     }
596     else if (format & SF_TEXT)
597       ME_StreamInText(editor, format, &inStream, style);
598     else
599       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
600     ME_GetSelection(editor, &to, &to2);
601     /* put the cursor at the top */
602     if (!(format & SFF_SELECTION))
603       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
604     else
605     {
606       /* FIXME where to put cursor now ? */
607     }
608   }
609   
610   editor->nUndoMode = nUndoMode;
611   pUI = ME_AddUndoItem(editor, diUndoDeleteRun, NULL);
612   TRACE("from %d to %d\n", from, to);
613   if (pUI && from < to)
614   {
615     pUI->nStart = from;
616     pUI->nLen = to-from;
617   }
618   ME_CommitUndo(editor);
619   ME_ReleaseStyle(style); 
620   editor->nEventMask = nEventMask;
621   if (editor->bRedraw)
622   {
623     InvalidateRect(editor->hWnd, NULL, TRUE);
624     ME_UpdateRepaint(editor);
625   }
626   if (!(format & SFF_SELECTION)) {
627     ME_ClearTempStyle(editor);
628   }
629   ME_MoveCaret(editor);
630   ME_SendSelChange(editor);
631
632   return 0;
633 }
634
635
636 ME_DisplayItem *
637 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
638 {
639   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
640   
641   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
642     item = ME_FindItemFwd(item, diParagraph);
643
644   if (!item)
645     return item;
646
647   nOffset -= item->member.para.nCharOfs;
648   if (nItemType == diParagraph) {
649     if (nItemOffset)
650       *nItemOffset = nOffset;
651     return item;
652   }
653   
654   do {
655     item = ME_FindItemFwd(item, diRun);
656   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
657   if (item) {
658     nOffset -= item->member.run.nCharOfs;
659     if (nItemOffset)
660       *nItemOffset = nOffset;
661   }
662   return item;
663 }
664
665
666 static int
667 ME_FindText(ME_TextEditor *editor, DWORD flags, CHARRANGE *chrg, WCHAR *text, CHARRANGE *chrgText)
668 {
669   int nStart, nEnd;
670   int nLen = lstrlenW(text);
671   int nMin, nMax;
672   ME_DisplayItem *item;
673   ME_DisplayItem *para;
674
675   TRACE("flags==0x%08lx, chrg->cpMin==%ld, chrg->cpMax==%ld text==%s\n",
676         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
677   
678   if (!(flags & FR_MATCHCASE))
679     FIXME("Case-insensitive search not implemented\n");
680   if (flags & ~(FR_DOWN | FR_MATCHCASE))
681     FIXME("Flags 0x%08lx not implemented\n", flags & ~(FR_DOWN | FR_MATCHCASE));
682
683   if (chrg->cpMax == -1)
684   {
685     nMin = chrg->cpMin;
686     nMax = ME_GetTextLength(editor);
687   }
688   else
689   {
690     nMin = min(chrg->cpMin, chrg->cpMax);
691     nMax = max(chrg->cpMin, chrg->cpMax);
692   }
693   
694   if (!nLen)
695   {
696     if (chrgText)
697       chrgText->cpMin = chrgText->cpMax = ((flags & FR_DOWN) ? nMin : nMax);
698     return chrgText->cpMin;
699   }
700  
701   if (flags & FR_DOWN) /* Forward search */
702   {
703     nStart = nMin;
704     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
705     if (!item)
706       return -1;
707
708     para = ME_GetParagraph(item);
709     while (item
710            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen < nMax)
711     {
712       ME_DisplayItem *pCurItem = item;
713       int nCurStart = nStart;
714       int nMatched = 0;
715     
716       while (pCurItem && pCurItem->member.run.strText->szData[nCurStart + nMatched] == text[nMatched])
717       {
718         nMatched++;
719         if (nMatched == nLen)
720         {
721           nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
722           if (chrgText)
723           {
724             chrgText->cpMin = nStart;
725             chrgText->cpMax = nStart + nLen;
726           }
727           TRACE("found at %d-%d\n", nStart, nStart + nLen);
728           return nStart;
729         }
730         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
731         {
732           pCurItem = ME_FindItemFwd(pCurItem, diRun);
733           para = ME_GetParagraph(pCurItem);
734           nCurStart = -nMatched;
735         }
736       }
737       nStart++;
738       if (nStart == ME_StrLen(item->member.run.strText))
739       {
740         item = ME_FindItemFwd(item, diRun);
741         para = ME_GetParagraph(item);
742         nStart = 0;
743       }
744     }
745   }
746   else /* Backward search */
747   {
748     nEnd = nMax;
749     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
750     if (!item)
751       return -1;
752     
753     para = ME_GetParagraph(item);
754     
755     while (item
756            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
757     {
758       ME_DisplayItem *pCurItem = item;
759       int nCurEnd = nEnd;
760       int nMatched = 0;
761       
762       while (pCurItem && pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1] == text[nLen - nMatched - 1])
763       {
764         nMatched++;
765         if (nMatched == nLen)
766         {
767           nStart = para->member.para.nCharOfs + item->member.run.nCharOfs + nCurEnd - nMatched;
768           if (chrgText)
769           {
770             chrgText->cpMin = nStart;
771             chrgText->cpMax = nStart + nLen;
772           }
773           TRACE("found at %d-%d\n", nStart, nStart + nLen);
774           return nStart;
775         }
776         if (nCurEnd - nMatched == 0)
777         {
778           pCurItem = ME_FindItemBack(pCurItem, diRun);
779           para = ME_GetParagraph(pCurItem);
780           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
781         }
782       }
783       nEnd--;
784       if (nEnd < 0)
785       {
786         item = ME_FindItemBack(item, diRun);
787         para = ME_GetParagraph(item);
788         nEnd = ME_StrLen(item->member.run.strText);
789       }
790     }
791   }
792   TRACE("not found\n");
793   return -1;
794 }
795
796
797 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
798   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
799   HDC hDC;
800   int i;
801   ed->hWnd = hWnd;
802   ed->bEmulateVersion10 = FALSE;
803   ed->pBuffer = ME_MakeText();
804   hDC = GetDC(hWnd);
805   ME_MakeFirstParagraph(hDC, ed->pBuffer);
806   ReleaseDC(hWnd, hDC);
807   ed->bCaretShown = FALSE;
808   ed->nCursors = 3;
809   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
810   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
811   ed->pCursors[0].nOffset = 0;
812   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
813   ed->pCursors[1].nOffset = 0;
814   ed->nLastTotalLength = ed->nTotalLength = 0;
815   ed->nUDArrowX = -1;
816   ed->nSequence = 0;
817   ed->rgbBackColor = -1;
818   ed->bCaretAtEnd = FALSE;
819   ed->nEventMask = 0;
820   ed->nModifyStep = 0;
821   ed->pUndoStack = ed->pRedoStack = NULL;
822   ed->nUndoMode = umAddToUndo;
823   ed->nParagraphs = 1;
824   ed->nLastSelStart = ed->nLastSelEnd = 0;
825   ed->nScrollPosY = 0;
826   ed->nZoomNumerator = ed->nZoomDenominator = 0;
827   ed->bRedraw = TRUE;
828   GetClientRect(hWnd, &ed->rcFormat);
829   for (i=0; i<HFONT_CACHE_SIZE; i++)
830   {
831     ed->pFontCache[i].nRefs = 0;
832     ed->pFontCache[i].nAge = 0;
833     ed->pFontCache[i].hFont = NULL;
834   }
835   ME_CheckCharOffsets(ed);
836   return ed;
837 }
838
839 typedef struct tagME_GlobalDestStruct
840 {
841   HGLOBAL hData;
842   int nLength;
843 } ME_GlobalDestStruct;
844
845 static DWORD CALLBACK ME_AppendToHGLOBAL(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
846 {
847   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
848   int nMaxSize;
849   BYTE *pDest;
850   
851   nMaxSize = GlobalSize(pData->hData);
852   if (pData->nLength+cb+1 >= cb)
853   {
854     /* round up to 2^17 */
855     int nNewSize = (((nMaxSize+cb+1)|0x1FFFF)+1) & 0xFFFE0000;
856     pData->hData = GlobalReAlloc(pData->hData, nNewSize, 0);
857   }
858   pDest = (BYTE *)GlobalLock(pData->hData);
859   memcpy(pDest + pData->nLength, lpBuff, cb);
860   pData->nLength += cb;
861   pDest[pData->nLength] = '\0';
862   GlobalUnlock(pData->hData);
863   *pcb = cb;
864   
865   return 0;
866 }
867
868 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
869 {
870   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
871   int i;
872   WORD *pSrc, *pDest;
873   
874   cb = cb >> 1;
875   pDest = (WORD *)lpBuff;
876   pSrc = (WORD *)GlobalLock(pData->hData);
877   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
878     pDest[i] = pSrc[pData->nLength+i];
879   }    
880   pData->nLength += i;
881   *pcb = 2*i;
882   GlobalUnlock(pData->hData);
883   return 0;
884 }
885
886 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
887 {
888   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
889   int i;
890   BYTE *pSrc, *pDest;
891   
892   pDest = lpBuff;
893   pSrc = (BYTE *)GlobalLock(pData->hData);
894   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
895     pDest[i] = pSrc[pData->nLength+i];
896   }    
897   pData->nLength += i;
898   *pcb = i;
899   GlobalUnlock(pData->hData);
900   return 0;
901 }
902
903
904 void ME_DestroyEditor(ME_TextEditor *editor)
905 {
906   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
907   ME_DisplayItem *p = pFirst, *pNext = NULL;
908   int i;
909   
910   ME_ClearTempStyle(editor);
911   ME_EmptyUndoStack(editor);
912   while(p) {
913     pNext = p->next;
914     ME_DestroyDisplayItem(p);    
915     p = pNext;
916   }
917   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
918   for (i=0; i<HFONT_CACHE_SIZE; i++)
919   {
920     if (editor->pFontCache[i].hFont)
921       DeleteObject(editor->pFontCache[i].hFont);
922   }
923     
924   FREE_OBJ(editor);
925 }
926
927 static WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
928 static WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
929
930 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
931 {
932     TRACE("\n");
933     switch (fdwReason)
934     {
935     case DLL_PROCESS_ATTACH:
936       DisableThreadLibraryCalls(hinstDLL);
937       me_heap = HeapCreate (0, 0x10000, 0);
938       ME_RegisterEditorClass(hinstDLL);
939       break;
940
941     case DLL_PROCESS_DETACH:
942       UnregisterClassW(wszClassName, 0);
943       UnregisterClassW(wszClassName50, 0);
944       UnregisterClassA("RichEdit20A", 0);
945       UnregisterClassA("RichEdit50A", 0);
946       HeapDestroy (me_heap);
947       me_heap = NULL;
948       break;
949     }
950     return TRUE;
951 }
952
953
954 #define UNSUPPORTED_MSG(e) \
955   case e: \
956     FIXME(#e ": stub\n"); \
957     return DefWindowProcW(hWnd, msg, wParam, lParam);
958
959 static const char * const edit_messages[] = {
960   "EM_GETSEL",
961   "EM_SETSEL",
962   "EM_GETRECT",
963   "EM_SETRECT",
964   "EM_SETRECTNP",
965   "EM_SCROLL",
966   "EM_LINESCROLL",
967   "EM_SCROLLCARET",
968   "EM_GETMODIFY",
969   "EM_SETMODIFY",
970   "EM_GETLINECOUNT",
971   "EM_LINEINDEX",
972   "EM_SETHANDLE",
973   "EM_GETHANDLE",
974   "EM_GETTHUMB",
975   "EM_UNKNOWN_BF",
976   "EM_UNKNOWN_C0",
977   "EM_LINELENGTH",
978   "EM_REPLACESEL",
979   "EM_UNKNOWN_C3",
980   "EM_GETLINE",
981   "EM_LIMITTEXT",
982   "EM_CANUNDO",
983   "EM_UNDO",
984   "EM_FMTLINES",
985   "EM_LINEFROMCHAR",
986   "EM_UNKNOWN_CA",
987   "EM_SETTABSTOPS",
988   "EM_SETPASSWORDCHAR",
989   "EM_EMPTYUNDOBUFFER",
990   "EM_GETFIRSTVISIBLELINE",
991   "EM_SETREADONLY",
992   "EM_SETWORDBREAKPROC",
993   "EM_GETWORDBREAKPROC",
994   "EM_GETPASSWORDCHAR",
995   "EM_SETMARGINS",
996   "EM_GETMARGINS",
997   "EM_GETLIMITTEXT",
998   "EM_POSFROMCHAR",
999   "EM_CHARFROMPOS"
1000 };
1001
1002 static const char * const richedit_messages[] = {
1003   "EM_CANPASTE",
1004   "EM_DISPLAYBAND",
1005   "EM_EXGETSEL",
1006   "EM_EXLIMITTEXT",
1007   "EM_EXLINEFROMCHAR",
1008   "EM_EXSETSEL",
1009   "EM_FINDTEXT",
1010   "EM_FORMATRANGE",
1011   "EM_GETCHARFORMAT",
1012   "EM_GETEVENTMASK",
1013   "EM_GETOLEINTERFACE",
1014   "EM_GETPARAFORMAT",
1015   "EM_GETSELTEXT",
1016   "EM_HIDESELECTION",
1017   "EM_PASTESPECIAL",
1018   "EM_REQUESTRESIZE",
1019   "EM_SELECTIONTYPE",
1020   "EM_SETBKGNDCOLOR",
1021   "EM_SETCHARFORMAT",
1022   "EM_SETEVENTMASK",
1023   "EM_SETOLECALLBACK",
1024   "EM_SETPARAFORMAT",
1025   "EM_SETTARGETDEVICE",
1026   "EM_STREAMIN",
1027   "EM_STREAMOUT",
1028   "EM_GETTEXTRANGE",
1029   "EM_FINDWORDBREAK",
1030   "EM_SETOPTIONS",
1031   "EM_GETOPTIONS",
1032   "EM_FINDTEXTEX",
1033   "EM_GETWORDBREAKPROCEX",
1034   "EM_SETWORDBREAKPROCEX",
1035   "EM_SETUNDOLIMIT",
1036   "EM_UNKNOWN_USER_83",
1037   "EM_REDO",
1038   "EM_CANREDO",
1039   "EM_GETUNDONAME",
1040   "EM_GETREDONAME",
1041   "EM_STOPGROUPTYPING",
1042   "EM_SETTEXTMODE",
1043   "EM_GETTEXTMODE",
1044   "EM_AUTOURLDETECT",
1045   "EM_GETAUTOURLDETECT",
1046   "EM_SETPALETTE",
1047   "EM_GETTEXTEX",
1048   "EM_GETTEXTLENGTHEX",
1049   "EM_SHOWSCROLLBAR",
1050   "EM_SETTEXTEX",
1051   "EM_UNKNOWN_USER_98",
1052   "EM_UNKNOWN_USER_99",
1053   "EM_SETPUNCTUATION",
1054   "EM_GETPUNCTUATION",
1055   "EM_SETWORDWRAPMODE",
1056   "EM_GETWORDWRAPMODE",
1057   "EM_SETIMECOLOR",
1058   "EM_GETIMECOLOR",
1059   "EM_SETIMEOPTIONS",
1060   "EM_GETIMEOPTIONS",
1061   "EM_CONVPOSITION",
1062   "EM_UNKNOWN_USER_109",
1063   "EM_UNKNOWN_USER_110",
1064   "EM_UNKNOWN_USER_111",
1065   "EM_UNKNOWN_USER_112",
1066   "EM_UNKNOWN_USER_113",
1067   "EM_UNKNOWN_USER_114",
1068   "EM_UNKNOWN_USER_115",
1069   "EM_UNKNOWN_USER_116",
1070   "EM_UNKNOWN_USER_117",
1071   "EM_UNKNOWN_USER_118",
1072   "EM_UNKNOWN_USER_119",
1073   "EM_SETLANGOPTIONS",
1074   "EM_GETLANGOPTIONS",
1075   "EM_GETIMECOMPMODE",
1076   "EM_FINDTEXTW",
1077   "EM_FINDTEXTEXW",
1078   "EM_RECONVERSION",
1079   "EM_SETIMEMODEBIAS",
1080   "EM_GETIMEMODEBIAS"
1081 };
1082
1083 static const char *
1084 get_msg_name(UINT msg)
1085 {
1086   if (msg >= EM_GETSEL && msg <= EM_SETLIMITTEXT)
1087     return edit_messages[msg - EM_GETSEL];
1088   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1089     return richedit_messages[msg - EM_CANPASTE];
1090   return "";
1091 }
1092
1093 /******************************************************************
1094  *        RichEditANSIWndProc (RICHED20.10)
1095  */
1096 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
1097   SCROLLINFO si;
1098   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
1099   
1100   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
1101         hWnd, msg, get_msg_name(msg), wParam, lParam);
1102   
1103   switch(msg) {
1104   
1105   UNSUPPORTED_MSG(EM_AUTOURLDETECT)
1106   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1107   UNSUPPORTED_MSG(EM_EXLIMITTEXT)
1108   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1109   UNSUPPORTED_MSG(EM_FMTLINES)
1110   UNSUPPORTED_MSG(EM_FORMATRANGE)
1111   UNSUPPORTED_MSG(EM_GETAUTOURLDETECT)
1112   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1113   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1114   UNSUPPORTED_MSG(EM_GETFIRSTVISIBLELINE)
1115   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1116   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1117   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1118   UNSUPPORTED_MSG(EM_GETLIMITTEXT)
1119   UNSUPPORTED_MSG(EM_GETLINE)
1120   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1121   UNSUPPORTED_MSG(EM_GETOPTIONS)
1122   UNSUPPORTED_MSG(EM_GETPASSWORDCHAR)
1123   UNSUPPORTED_MSG(EM_GETREDONAME)
1124   UNSUPPORTED_MSG(EM_GETSCROLLPOS)
1125   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1126   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1127   UNSUPPORTED_MSG(EM_GETUNDONAME)
1128   UNSUPPORTED_MSG(EM_GETWORDBREAKPROC)
1129   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1130   UNSUPPORTED_MSG(EM_HIDESELECTION)
1131   UNSUPPORTED_MSG(EM_LIMITTEXT) /* also known as EM_SETLIMITTEXT */
1132   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1133 /*  UNSUPPORTED_MSG(EM_POSFROMCHARS) missing in Wine headers */
1134   UNSUPPORTED_MSG(EM_REQUESTRESIZE)
1135   UNSUPPORTED_MSG(EM_SCROLL)
1136   UNSUPPORTED_MSG(EM_SCROLLCARET)
1137   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1138   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1139   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1140   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1141   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1142   UNSUPPORTED_MSG(EM_SETOLECALLBACK)
1143   UNSUPPORTED_MSG(EM_SETOPTIONS)
1144   UNSUPPORTED_MSG(EM_SETPALETTE)
1145   UNSUPPORTED_MSG(EM_SETPASSWORDCHAR)
1146   UNSUPPORTED_MSG(EM_SETSCROLLPOS)
1147   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1148   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1149   UNSUPPORTED_MSG(EM_SETTEXTMODE)
1150   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1151   UNSUPPORTED_MSG(EM_SETUNDOLIMIT)
1152   UNSUPPORTED_MSG(EM_SETWORDBREAKPROC)
1153   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1154   UNSUPPORTED_MSG(EM_SHOWSCROLLBAR)
1155   UNSUPPORTED_MSG(WM_SETFONT)
1156   UNSUPPORTED_MSG(WM_STYLECHANGING)
1157   UNSUPPORTED_MSG(WM_STYLECHANGED)
1158 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1159     
1160 /* Messages specific to Richedit controls */
1161   
1162   case EM_STREAMIN:
1163    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1164   case EM_STREAMOUT:
1165    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1166   case WM_GETDLGCODE:
1167   {
1168     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1169     if (GetWindowLongW(hWnd, GWL_STYLE)&ES_WANTRETURN)
1170       code |= 0; /* FIXME what can we do here ? ask for messages and censor them ? */
1171     return code;
1172   }
1173   case WM_NCCREATE:
1174   {
1175     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1176     TRACE("WM_NCCREATE: style 0x%08lx\n", pcs->style);
1177     editor = ME_MakeEditor(hWnd);
1178     SetWindowLongW(hWnd, 0, (long)editor);
1179     pcs = 0; /* ignore */
1180     return TRUE;
1181   }
1182   case EM_EMPTYUNDOBUFFER:
1183     ME_EmptyUndoStack(editor);
1184     return 0;
1185   case EM_GETSEL:
1186   {
1187     /* Note: wParam/lParam can be NULL */
1188     UINT from, to;
1189     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1190     PUINT pto = lParam ? (PUINT)lParam : &to;
1191     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1192     if ((*pfrom|*pto) & 0xFFFF0000)
1193       return -1;
1194     return MAKELONG(*pfrom,*pto);
1195   }
1196   case EM_EXGETSEL:
1197   {
1198     CHARRANGE *pRange = (CHARRANGE *)lParam;
1199     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1200     TRACE("EM_EXGETSEL = (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1201     return 0;
1202   }
1203   case EM_CANUNDO:
1204     return editor->pUndoStack != NULL;
1205   case EM_CANREDO:
1206     return editor->pRedoStack != NULL;
1207   case WM_UNDO: /* FIXME: actually not the same */
1208   case EM_UNDO:
1209     ME_Undo(editor);
1210     return 0;
1211   case EM_REDO:
1212     ME_Redo(editor);
1213     return 0;
1214   case EM_SETSEL:
1215   {
1216     ME_SetSelection(editor, wParam, lParam);
1217     ME_Repaint(editor);
1218     ME_SendSelChange(editor);
1219     return 0;
1220   }
1221   case EM_EXSETSEL:
1222   {
1223     CHARRANGE *pRange = (CHARRANGE *)lParam;
1224     TRACE("EM_EXSETSEL (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1225     ME_SetSelection(editor, pRange->cpMin, pRange->cpMax);
1226     /* FIXME optimize */
1227     ME_Repaint(editor);
1228     ME_SendSelChange(editor);
1229     return 0;
1230   }
1231   case EM_SETTEXTEX:
1232   {
1233     LPWSTR wszText = (LPWSTR)lParam;
1234     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1235     size_t len = lstrlenW(wszText);
1236     int from, to;
1237     ME_Style *style;
1238     TRACE("EM_SETTEXEX - %s, flags %d, cp %d\n", debugstr_w(wszText), (int)pStruct->flags, pStruct->codepage);
1239     if (pStruct->codepage != 1200) {
1240       FIXME("EM_SETTEXTEX only supports unicode right now!\n"); 
1241       return 0;
1242     }
1243     /* FIXME: this should support RTF strings too, according to MSDN */
1244     if (pStruct->flags & ST_SELECTION) {
1245       ME_GetSelection(editor, &from, &to);
1246       style = ME_GetSelectionInsertStyle(editor);
1247       ME_InternalDeleteText(editor, from, to - from);
1248       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1249       ME_ReleaseStyle(style);
1250     }
1251     else {
1252       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1253       ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1254       len = 1;
1255     }
1256     ME_CommitUndo(editor);
1257     if (!(pStruct->flags & ST_KEEPUNDO))
1258       ME_EmptyUndoStack(editor);
1259     ME_UpdateRepaint(editor);
1260     return len;
1261   }
1262   case EM_SETBKGNDCOLOR:
1263   {
1264     LRESULT lColor = ME_GetBackColor(editor);
1265     if (wParam)
1266       editor->rgbBackColor = -1;
1267     else
1268       editor->rgbBackColor = lParam;
1269     if (editor->bRedraw)
1270     {
1271       InvalidateRect(hWnd, NULL, TRUE);
1272       UpdateWindow(hWnd);
1273     }
1274     return lColor;
1275   }
1276   case EM_GETMODIFY:
1277     return editor->nModifyStep == 0 ? 0 : 1;
1278   case EM_SETMODIFY:
1279   {
1280     if (wParam)
1281       editor->nModifyStep = 0x80000000;
1282     else
1283       editor->nModifyStep = 0;
1284     
1285     return 0;
1286   }
1287   case EM_SETREADONLY:
1288   {
1289     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1290     if (wParam)
1291       nStyle |= ES_READONLY;
1292     else
1293       nStyle &= ~ES_READONLY;
1294     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1295     ME_Repaint(editor);
1296     return 0;
1297   }
1298   case EM_SETEVENTMASK:
1299   {
1300     DWORD nOldMask = editor->nEventMask;
1301     
1302     editor->nEventMask = lParam;
1303     return nOldMask;
1304   }
1305   case EM_GETEVENTMASK:
1306     return editor->nEventMask;
1307   case EM_SETCHARFORMAT:
1308   {
1309     CHARFORMAT2W buf, *p;
1310     BOOL bRepaint = TRUE;
1311     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1312     if (!wParam)
1313       ME_SetDefaultCharFormat(editor, p);
1314     else if (wParam == (SCF_WORD | SCF_SELECTION))
1315       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1316     else if (wParam == SCF_ALL)
1317       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1318     else {
1319       int from, to;
1320       ME_GetSelection(editor, &from, &to);
1321       bRepaint = (from != to);
1322       ME_SetSelectionCharFormat(editor, p);
1323     }
1324     ME_CommitUndo(editor);
1325     if (bRepaint)
1326       ME_UpdateRepaint(editor);
1327     return 0;
1328   }
1329   case EM_GETCHARFORMAT:
1330   {
1331     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1332     if (dst->cbSize != sizeof(CHARFORMATA) &&
1333         dst->cbSize != sizeof(CHARFORMATW) &&
1334         dst->cbSize != sizeof(CHARFORMAT2A) &&
1335         dst->cbSize != sizeof(CHARFORMAT2W))
1336       return 0;
1337     tmp.cbSize = sizeof(tmp);
1338     if (!wParam)
1339       ME_GetDefaultCharFormat(editor, &tmp);
1340     else
1341       ME_GetSelectionCharFormat(editor, &tmp);
1342     ME_CopyToCFAny(dst, &tmp);
1343     return tmp.dwMask;
1344   }
1345   case EM_SETPARAFORMAT:
1346     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1347     ME_UpdateRepaint(editor);
1348     ME_CommitUndo(editor);
1349     return 0;
1350   case EM_GETPARAFORMAT:
1351     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1352     return 0;
1353   case EM_LINESCROLL:
1354   {
1355     int nPos = editor->nScrollPosY, nEnd= editor->nTotalLength - editor->sizeWindow.cy;
1356     nPos += 8 * lParam; /* FIXME follow the original */
1357     if (nPos>=nEnd)
1358       nPos = nEnd;
1359     if (nPos<0)
1360       nPos = 0;
1361     if (nPos != editor->nScrollPosY) {
1362       int dy = editor->nScrollPosY - nPos;
1363       editor->nScrollPosY = nPos;
1364       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1365       if (editor->bRedraw)
1366       {
1367         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1368         UpdateWindow(hWnd);
1369       }
1370     }
1371     return TRUE; /* Should return false if a single line richedit control */
1372   }
1373   case WM_CLEAR:
1374   {
1375     int from, to;
1376     ME_GetSelection(editor, &from, &to);
1377     ME_InternalDeleteText(editor, from, to-from);
1378     ME_CommitUndo(editor);
1379     ME_UpdateRepaint(editor);
1380     return 0;
1381   }
1382   case EM_REPLACESEL:
1383   {
1384     int from, to;
1385     ME_Style *style;
1386     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1387     size_t len = lstrlenW(wszText);
1388     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1389     
1390     ME_GetSelection(editor, &from, &to);
1391     style = ME_GetSelectionInsertStyle(editor);
1392     ME_InternalDeleteText(editor, from, to-from);
1393     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1394     ME_ReleaseStyle(style);
1395     ME_EndToUnicode(hWnd, wszText);
1396     /* drop temporary style if line end */
1397     /* FIXME question: does abc\n mean: put abc, clear temp style, put \n? (would require a change) */  
1398     if (len>0 && wszText[len-1] == '\n')
1399       ME_ClearTempStyle(editor);
1400       
1401     ME_CommitUndo(editor);
1402     if (!wParam)
1403       ME_EmptyUndoStack(editor);
1404     ME_UpdateRepaint(editor);
1405     return 0;
1406   }
1407   case WM_SETTEXT:
1408   {
1409     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1410     if (lParam)
1411     {
1412       LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1413       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1414       TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1415       if (lstrlenW(wszText) > 0)
1416       {
1417         /* uses default style! */
1418         ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1419       }
1420       ME_EndToUnicode(hWnd, wszText);
1421     }
1422     else
1423       TRACE("WM_SETTEXT - NULL\n");
1424     ME_CommitUndo(editor);
1425     ME_EmptyUndoStack(editor);
1426     ME_UpdateRepaint(editor);
1427     return 0;
1428   }
1429   case EM_CANPASTE:
1430   {
1431     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1432     if (IsClipboardFormatAvailable(nRTFFormat))
1433       return TRUE;
1434     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1435       return TRUE;
1436     return FALSE;
1437   }
1438   case WM_PASTE:
1439   {    
1440     DWORD dwFormat = 0;
1441     EDITSTREAM es;
1442     ME_GlobalDestStruct gds;
1443     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1444     UINT cf = 0;
1445
1446     if (IsClipboardFormatAvailable(nRTFFormat))
1447       cf = nRTFFormat, dwFormat = SF_RTF;
1448     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1449       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1450     else
1451       return 0;
1452
1453     if (!OpenClipboard(hWnd))
1454       return 0;
1455     gds.hData = GetClipboardData(cf);
1456     gds.nLength = 0;
1457     es.dwCookie = (DWORD)&gds;
1458     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1459     SendMessageW(hWnd, EM_STREAMIN, dwFormat|SFF_SELECTION, (LPARAM)&es);
1460     
1461     CloseClipboard();
1462     return 0;
1463   }
1464   case WM_CUT:
1465   case WM_COPY:
1466   {
1467     int from, to, pars;
1468     WCHAR *data;
1469     HANDLE hData;
1470     EDITSTREAM es;
1471     ME_GlobalDestStruct gds;
1472     
1473     if (!OpenClipboard(hWnd))
1474       return 0;
1475       
1476     EmptyClipboard();
1477     ME_GetSelection(editor, &from, &to);
1478     pars = ME_CountParagraphsBetween(editor, from, to);
1479     hData = GlobalAlloc(GMEM_MOVEABLE, sizeof(WCHAR)*(to-from+pars+1));
1480     data = (WCHAR *)GlobalLock(hData);
1481     ME_GetTextW(editor, data, from, to-from, TRUE);
1482     GlobalUnlock(hData);
1483
1484     gds.hData = GlobalAlloc(GMEM_MOVEABLE, 0);
1485     gds.nLength = 0;
1486     es.dwCookie = (DWORD)&gds;
1487     es.pfnCallback = ME_AppendToHGLOBAL;
1488     SendMessageW(hWnd, EM_STREAMOUT, SFF_SELECTION|SF_RTF, (LPARAM)&es);
1489     GlobalReAlloc(gds.hData, gds.nLength+1, 0);
1490     
1491     SetClipboardData(CF_UNICODETEXT, hData);    
1492     SetClipboardData(RegisterClipboardFormatA("Rich Text Format"), gds.hData);
1493     
1494     CloseClipboard();
1495     if (msg == WM_CUT)
1496     {
1497       ME_InternalDeleteText(editor, from, to-from);
1498       ME_CommitUndo(editor);
1499       ME_UpdateRepaint(editor);
1500     }
1501     return 0;
1502   }
1503   case WM_GETTEXTLENGTH:
1504     return ME_GetTextLength(editor);
1505   case EM_GETTEXTLENGTHEX:
1506     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
1507   case WM_GETTEXT:
1508   {
1509     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1510     tr.chrg.cpMin = 0;
1511     tr.chrg.cpMax = wParam-1;
1512     tr.lpstrText = (WCHAR *)lParam;
1513     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1514   }
1515   case EM_GETTEXTEX:
1516   {
1517     GETTEXTEX *ex = (GETTEXTEX*)wParam;
1518     int nStart, nCount;
1519
1520     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1521       FIXME("GETTEXTEX flags 0x%08lx not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1522
1523     if (ex->flags & GT_SELECTION)
1524     {
1525       ME_GetSelection(editor, &nStart, &nCount);
1526       nCount -= nStart;
1527       nCount = min(nCount, ex->cb - 1);
1528     }
1529     else
1530     {
1531       nStart = 0;
1532       nCount = ex->cb - 1;
1533     }
1534     if (ex->codepage == 1200 || IsWindowUnicode(hWnd))
1535     {
1536       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
1537       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
1538     }
1539     else
1540     {
1541         LPWSTR buffer = HeapAlloc(GetProcessHeap(), 0, (nCount + 1) * sizeof(WCHAR));
1542         DWORD buflen = ex->cb;
1543         LRESULT rc;
1544         DWORD flags = 0;
1545
1546         buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
1547         rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
1548
1549         HeapFree(GetProcessHeap(),0,buffer);
1550         return rc;
1551     }
1552   }
1553   case EM_GETSELTEXT:
1554   {
1555     int from, to;
1556     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1557     ME_GetSelection(editor, &from, &to);
1558     tr.chrg.cpMin = from;
1559     tr.chrg.cpMax = to;
1560     tr.lpstrText = (WCHAR *)lParam;
1561     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1562   }
1563   case EM_GETTEXTRANGE:
1564   {
1565     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
1566     if (IsWindowUnicode(hWnd))
1567       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
1568     else
1569     {
1570       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
1571       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1572       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
1573       /* FIXME this is a potential security hole (buffer overrun) 
1574          if you know more about wchar->mbyte conversion please explain
1575       */
1576       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
1577       FREE_OBJ(p);
1578       return nChars;
1579     }
1580   }
1581   case EM_GETLINECOUNT:
1582   {
1583     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
1584     int nRows = 0;
1585
1586     while (item != editor->pBuffer->pLast)
1587     {
1588       assert(item->type == diParagraph);
1589       nRows += item->member.para.nRows;
1590       item = item->member.para.next_para;
1591     }
1592     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
1593     return max(1, nRows);
1594   }
1595   case EM_LINEFROMCHAR:
1596   {
1597     if (wParam == -1)
1598       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
1599     else
1600       return ME_RowNumberFromCharOfs(editor, wParam);
1601   }
1602   case EM_EXLINEFROMCHAR:
1603   {
1604     return ME_RowNumberFromCharOfs(editor, lParam);
1605   }
1606   case EM_LINEINDEX:
1607   {
1608     ME_DisplayItem *item, *para;
1609     int nCharOfs;
1610     
1611     if (wParam == -1)
1612       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
1613     else
1614       item = ME_FindRowWithNumber(editor, wParam);
1615     if (!item)
1616       return -1;
1617     para = ME_GetParagraph(item);
1618     item = ME_FindItemFwd(item, diRun);
1619     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
1620     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
1621     return nCharOfs;
1622   }
1623   case EM_LINELENGTH:
1624   {
1625     ME_DisplayItem *item, *item_end;
1626     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
1627     
1628     if (wParam > ME_GetTextLength(editor))
1629       return 0;
1630     if (wParam == -1)
1631     {
1632       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
1633       return 0;
1634     }
1635     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
1636     item = ME_RowStart(item);
1637     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
1638     item_end = ME_FindItemFwd(item, diStartRow);
1639     if (item_end)
1640       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
1641     else
1642       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs-1;
1643     nChars = nNextLineOfs - nThisLineOfs;
1644     TRACE("EM_LINELENGTH(%d)==%d\n",wParam, nChars);
1645     return nChars;
1646   }
1647   case EM_FINDTEXT:
1648   {
1649     FINDTEXTA *ft = (FINDTEXTA *)lParam;
1650     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
1651     WCHAR *tmp;
1652     
1653     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1654       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
1655     return ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
1656   }
1657   case EM_FINDTEXTEX:
1658   {
1659     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
1660     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
1661     WCHAR *tmp;
1662     
1663     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1664       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
1665     return ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
1666   }
1667   case EM_FINDTEXTW:
1668   {
1669     FINDTEXTW *ft = (FINDTEXTW *)lParam;
1670     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
1671   }
1672   case EM_FINDTEXTEXW:
1673   {
1674     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
1675     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
1676   }
1677   case EM_GETZOOM:
1678     if (!wParam || !lParam)
1679       return FALSE;
1680     *(int *)wParam = editor->nZoomNumerator;
1681     *(int *)lParam = editor->nZoomDenominator;
1682     return TRUE;
1683   case EM_SETZOOM:
1684     return ME_SetZoom(editor, wParam, lParam);
1685   case EM_CHARFROMPOS:
1686     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
1687   case WM_CREATE:
1688     ME_CommitUndo(editor);
1689     ME_WrapMarkedParagraphs(editor);
1690     ME_MoveCaret(editor);
1691     return 0;
1692   case WM_DESTROY:
1693     ME_DestroyEditor(editor);
1694     SetWindowLongW(hWnd, 0, 0);
1695     return 0;
1696   case WM_LBUTTONDOWN:
1697     SetFocus(hWnd);
1698     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1699     SetCapture(hWnd);
1700     break;
1701   case WM_MOUSEMOVE:
1702     if (GetCapture() == hWnd)
1703       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1704     break;
1705   case WM_LBUTTONUP:
1706     if (GetCapture() == hWnd)
1707       ReleaseCapture();
1708     break;
1709   case WM_PAINT:
1710     if (editor->bRedraw)
1711     {
1712       HDC hDC;
1713       PAINTSTRUCT ps;
1714
1715       hDC = BeginPaint(hWnd, &ps);
1716       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
1717       EndPaint(hWnd, &ps);
1718     }
1719     break;
1720   case WM_SETFOCUS:
1721     ME_ShowCaret(editor);
1722     ME_SendOldNotify(editor, EN_SETFOCUS);
1723     return 0;
1724   case WM_KILLFOCUS:
1725     ME_HideCaret(editor);
1726     ME_SendOldNotify(editor, EN_KILLFOCUS);
1727     return 0;
1728   case WM_ERASEBKGND:
1729   {
1730     if (editor->bRedraw)
1731     {
1732       HDC hDC = (HDC)wParam;
1733       RECT rc;
1734       COLORREF rgbBG = ME_GetBackColor(editor);
1735       if (GetUpdateRect(hWnd,&rc,TRUE))
1736       {
1737         HBRUSH hbr = CreateSolidBrush(rgbBG);
1738         FillRect(hDC, &rc, hbr);
1739         DeleteObject(hbr);
1740       }
1741     }
1742     return 1;
1743   }
1744   case WM_COMMAND:
1745     TRACE("editor wnd command = %d\n", LOWORD(wParam));
1746     return 0;
1747   case WM_KEYDOWN:
1748     if (ME_ArrowKey(editor, LOWORD(wParam), GetKeyState(VK_CONTROL)<0)) {
1749       ME_CommitUndo(editor);
1750       ME_EnsureVisible(editor, editor->pCursors[0].pRun);
1751       HideCaret(hWnd);
1752       ME_MoveCaret(editor);
1753       ShowCaret(hWnd);
1754       return 0;
1755     }
1756     if (GetKeyState(VK_CONTROL)<0)
1757     {
1758       if (LOWORD(wParam)=='W')
1759       {
1760         CHARFORMAT2W chf;
1761         char buf[2048];
1762         ME_GetSelectionCharFormat(editor, &chf);
1763         ME_DumpStyleToBuf(&chf, buf);
1764         MessageBoxA(NULL, buf, "Style dump", MB_OK);
1765       }
1766       if (LOWORD(wParam)=='Q')
1767       {
1768         ME_CheckCharOffsets(editor);
1769       }
1770     }
1771     goto do_default;
1772   case WM_CHAR: 
1773   {
1774     WCHAR wstr = LOWORD(wParam);
1775
1776     switch (wstr)
1777     {
1778     case 3: /* Ctrl-C */
1779       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
1780       return 0;
1781     }
1782     
1783     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
1784       MessageBeep(MB_ICONERROR);
1785       return 0; /* FIXME really 0 ? */
1786     }
1787
1788     switch (wstr)
1789     {
1790     case 1: /* Ctrl-A */
1791       ME_SetSelection(editor, 0, -1);
1792       return 0;
1793     case 22: /* Ctrl-V */
1794       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
1795       return 0;
1796     case 24: /* Ctrl-X */
1797       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
1798       return 0;
1799     case 25: /* Ctrl-Y */
1800       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
1801       return 0;
1802     case 26: /* Ctrl-Z */
1803       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
1804       return 0;
1805     }
1806     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
1807       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
1808       ME_Style *style = ME_GetInsertStyle(editor, 0);
1809       ME_SaveTempStyle(editor);
1810       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
1811       ME_ReleaseStyle(style);
1812       ME_CommitUndo(editor);
1813       ME_UpdateRepaint(editor);
1814     }
1815     return 0;
1816   }
1817   case WM_VSCROLL: 
1818   {
1819     int nPos = editor->nScrollPosY;
1820     si.cbSize = sizeof(SCROLLINFO);
1821     si.fMask = SIF_PAGE|SIF_POS|SIF_RANGE|SIF_TRACKPOS;
1822     GetScrollInfo(hWnd, SB_VERT, &si);
1823     switch(LOWORD(wParam)) {
1824     case SB_LINEUP:
1825       nPos -= 24; /* FIXME follow the original */
1826       if (nPos<0) nPos = 0;
1827       break;
1828     case SB_LINEDOWN:
1829     {
1830       int nEnd = editor->nTotalLength - editor->sizeWindow.cy;
1831       nPos += 24; /* FIXME follow the original */
1832       if (nPos>=nEnd) nPos = nEnd;
1833       break;
1834     }
1835     case SB_PAGEUP:
1836       nPos -= editor->sizeWindow.cy;
1837       if (nPos<0) nPos = 0;
1838       break;
1839     case SB_PAGEDOWN:
1840       nPos += editor->sizeWindow.cy;
1841       if (nPos>=editor->nTotalLength) nPos = editor->nTotalLength-1;
1842       break;
1843     case SB_THUMBTRACK:
1844     case SB_THUMBPOSITION:
1845       nPos = si.nTrackPos;
1846       break;
1847     }
1848     if (nPos != editor->nScrollPosY) {
1849       int dy = editor->nScrollPosY - nPos;
1850       editor->nScrollPosY = nPos;
1851       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1852       if (editor->bRedraw)
1853       {
1854         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1855         UpdateWindow(hWnd);
1856       }
1857     }
1858     break;
1859   }
1860   case WM_MOUSEWHEEL:
1861   {
1862     int gcWheelDelta = 0, nPos = editor->nScrollPosY, nEnd = editor->nTotalLength - editor->sizeWindow.cy; 
1863     UINT pulScrollLines;
1864     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
1865     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
1866     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
1867       nPos += pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8; /* FIXME follow the original */
1868     if (nPos>=nEnd)
1869       nPos = nEnd;
1870     if (nPos<0)
1871       nPos = 0;
1872     if (nPos != editor->nScrollPosY) {
1873       int dy = editor->nScrollPosY - nPos;
1874       editor->nScrollPosY = nPos;
1875       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1876       if (editor->bRedraw)
1877       {
1878         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1879         UpdateWindow(hWnd);
1880       }
1881     }
1882     break;
1883   }
1884   case EM_GETRECT:
1885   {
1886     *((RECT *)lParam) = editor->rcFormat;
1887     return 0;
1888   }
1889   case EM_SETRECT:
1890   case EM_SETRECTNP:
1891   {
1892     if (lParam)
1893     {
1894       RECT *rc = (RECT *)lParam;
1895       
1896       if (wParam)
1897       {
1898         editor->rcFormat.left += rc->left;
1899         editor->rcFormat.top += rc->top;
1900         editor->rcFormat.right += rc->right;
1901         editor->rcFormat.bottom += rc->bottom;
1902       }
1903       else
1904       {
1905         editor->rcFormat = *rc;
1906       }
1907     }
1908     else
1909     {
1910       GetClientRect(hWnd, &editor->rcFormat);
1911     }
1912     if (msg != EM_SETRECTNP)
1913       ME_RewrapRepaint(editor);
1914     return 0;
1915   }
1916   case WM_SETREDRAW:
1917     editor->bRedraw = wParam;
1918     return 0;
1919   case WM_SIZE:
1920   {
1921     GetClientRect(hWnd, &editor->rcFormat);
1922     ME_RewrapRepaint(editor);
1923     return DefWindowProcW(hWnd, msg, wParam, lParam);
1924   }
1925   case EM_GETOLEINTERFACE:
1926   {
1927     LPVOID *ppvObj = (LPVOID*) lParam;
1928     FIXME("EM_GETOLEINTERFACE %p: stub\n", ppvObj);
1929     return CreateIRichEditOle(ppvObj);
1930   }
1931   default:
1932   do_default:
1933     return DefWindowProcW(hWnd, msg, wParam, lParam);
1934   }
1935   return 0L;
1936 }
1937
1938
1939 /******************************************************************
1940  *        RichEdit10ANSIWndProc (RICHED20.9)
1941  */
1942 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1943 {
1944   LRESULT result;
1945   
1946   /* FIXME: this is NOT the same as 2.0 version */
1947   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
1948   if (msg == WM_NCCREATE)
1949   {
1950     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
1951     
1952     editor->bEmulateVersion10 = TRUE;
1953     editor->pBuffer->pLast->member.para.nCharOfs = 2;
1954   }
1955   return result;
1956 }
1957
1958 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
1959 {
1960   HWND hWnd = editor->hWnd;
1961   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
1962 }
1963
1964 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
1965 {
1966   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1967   int i = 0;
1968   
1969   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
1970     item = item->member.para.next_para;
1971   if (!item)
1972     return 0;
1973   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
1974     item = item->member.para.next_para;
1975     i++;
1976   }
1977   return i;
1978 }
1979
1980
1981 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
1982 {
1983   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1984   int nWritten = 0;
1985   
1986   if (!item) {
1987     *buffer = L'\0';
1988     return 0;
1989   }
1990   assert(item);    
1991   
1992   if (nStart)
1993   {
1994     int nLen = ME_StrLen(item->member.run.strText) - nStart;
1995     if (nLen > nChars)
1996       nLen = nChars;
1997     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
1998     nChars -= nLen;
1999     nWritten += nLen;
2000     if (!nChars)
2001       return nWritten;
2002     buffer += nLen;
2003     nStart = 0;
2004     item = ME_FindItemFwd(item, diRun);
2005   }
2006   
2007   while(nChars && item)
2008   {
2009     int nLen = ME_StrLen(item->member.run.strText);
2010     if (nLen > nChars)
2011       nLen = nChars;
2012       
2013     if (item->member.run.nFlags & MERF_ENDPARA)
2014     {
2015       *buffer++ = '\r';
2016       if (bCRLF)
2017       {
2018         *buffer = '\n';
2019         nWritten++;
2020       }
2021       assert(nLen == 1);
2022     }
2023     else      
2024       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2025     nChars -= nLen;
2026     nWritten += nLen;
2027     buffer += nLen;    
2028       
2029     if (!nChars)
2030     {
2031       *buffer = L'\0';
2032       return nWritten;
2033     }
2034     item = ME_FindItemFwd(item, diRun);
2035   }
2036   *buffer = L'\0';
2037   return nWritten;  
2038 }
2039
2040 void ME_RegisterEditorClass(HINSTANCE hInstance)
2041 {
2042   BOOL bResult;
2043   WNDCLASSW wcW;
2044   WNDCLASSA wcA;
2045   
2046   wcW.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2047   wcW.lpfnWndProc = RichEditANSIWndProc;
2048   wcW.cbClsExtra = 0;
2049   wcW.cbWndExtra = 4;
2050   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2051   wcW.hIcon = NULL;
2052   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2053   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2054   wcW.lpszMenuName = NULL;
2055   wcW.lpszClassName = wszClassName;
2056   bResult = RegisterClassW(&wcW);  
2057   assert(bResult);
2058   wcW.lpszClassName = wszClassName50;
2059   bResult = RegisterClassW(&wcW);  
2060   assert(bResult);
2061
2062   wcA.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2063   wcA.lpfnWndProc = RichEditANSIWndProc;
2064   wcA.cbClsExtra = 0;
2065   wcA.cbWndExtra = 4;
2066   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
2067   wcA.hIcon = NULL;
2068   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2069   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2070   wcA.lpszMenuName = NULL;
2071   wcA.lpszClassName = "RichEdit20A";
2072   bResult = RegisterClassA(&wcA);  
2073   assert(bResult);
2074   wcA.lpszClassName = "RichEdit50A";
2075   bResult = RegisterClassA(&wcA);  
2076   assert(bResult);
2077 }
2078 /******************************************************************
2079  *        CreateTextServices (RICHED20.4)
2080  *
2081  * FIXME should be ITextHost instead of void*
2082  */
2083 HRESULT WINAPI CreateTextServices(IUnknown *punkOuter, void *pITextHost,
2084     IUnknown **ppUnk)
2085 {
2086   FIXME("stub\n");
2087   /* FIXME should support aggregation */
2088   if (punkOuter)
2089     return CLASS_E_NOAGGREGATION;
2090     
2091   return E_FAIL; /* E_NOTIMPL isn't allowed by MSDN */
2092 }
2093
2094 /******************************************************************
2095  *        REExtendedRegisterClass (RICHED20.8)
2096  *
2097  * FIXME undocumented
2098  */
2099 void WINAPI REExtendedRegisterClass(void)
2100 {
2101   FIXME("stub\n");
2102 }