Fix some gcc 4.0 warnings.
[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 < STREAMIN_BUFFER_SIZE)
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   }
397 }
398
399 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
400    the same tags mean different things in different contexts */
401 static void ME_RTFParAttrHook(RTF_Info *info)
402 {
403   PARAFORMAT2 fmt;
404   fmt.cbSize = sizeof(fmt);
405   fmt.dwMask = 0;
406   
407   switch(info->rtfMinor)
408   {
409   case rtfParDef: /* I'm not 100% sure what does it do, but I guess it restores default paragraph attributes */
410     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
411     fmt.wAlignment = PFA_LEFT;
412     fmt.cTabCount = 0;
413     fmt.dxOffset = fmt.dxStartIndent = 0;
414     break;
415   case rtfFirstIndent:
416     ME_GetSelectionParaFormat(info->editor, &fmt);
417     fmt.dwMask = PFM_STARTINDENT;
418     fmt.dxStartIndent = info->rtfParam + fmt.dxOffset;
419     break;
420   case rtfLeftIndent:
421   {
422     int first, left;
423     ME_GetSelectionParaFormat(info->editor, &fmt);
424     first = fmt.dxStartIndent;
425     left = info->rtfParam;
426     fmt.dwMask = PFM_STARTINDENT|PFM_OFFSET;
427     fmt.dxStartIndent = first + left;
428     fmt.dxOffset = -first;
429     break;
430   }
431   case rtfRightIndent:
432     fmt.dwMask = PFM_RIGHTINDENT;
433     fmt.dxRightIndent = info->rtfParam;
434     break;
435   case rtfQuadLeft:
436   case rtfQuadJust:
437     fmt.dwMask = PFM_ALIGNMENT;
438     fmt.wAlignment = PFA_LEFT;
439     break;
440   case rtfQuadRight:
441     fmt.dwMask = PFM_ALIGNMENT;
442     fmt.wAlignment = PFA_RIGHT;
443     break;
444   case rtfQuadCenter:
445     fmt.dwMask = PFM_ALIGNMENT;
446     fmt.wAlignment = PFA_CENTER;
447     break;
448   case rtfTabPos:
449     ME_GetSelectionParaFormat(info->editor, &fmt);
450     if (!(fmt.dwMask & PFM_TABSTOPS))
451     {
452       fmt.dwMask |= PFM_TABSTOPS;
453       fmt.cTabCount = 0;
454     }
455     if (fmt.cTabCount < MAX_TAB_STOPS)
456       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
457     break;
458   }  
459   if (fmt.dwMask) {
460     RTFFlushOutputBuffer(info);
461     /* FIXME too slow ? how come ?*/
462     ME_SetSelectionParaFormat(info->editor, &fmt);
463   }
464 }
465
466 static void ME_RTFReadHook(RTF_Info *info) {
467   switch(info->rtfClass)
468   {
469     case rtfGroup:
470       switch(info->rtfMajor)
471       {
472         case rtfBeginGroup:
473           if (info->stackTop < maxStack) {
474             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
475             info->stack[info->stackTop].codePage = info->codePage;
476             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
477           }
478           info->stackTop++;
479           break;
480         case rtfEndGroup:
481         {
482           ME_Style *s;
483           RTFFlushOutputBuffer(info);
484           info->stackTop--;
485           /* FIXME too slow ? how come ? */
486           s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
487           ME_ReleaseStyle(info->style);
488           info->style = s;
489           info->codePage = info->stack[info->stackTop].codePage;
490           info->unicodeLength = info->stack[info->stackTop].unicodeLength;
491           break;
492         }
493       }
494       break;
495     case rtfControl:
496       switch(info->rtfMajor)
497       {
498         case rtfCharAttr:
499           ME_RTFCharAttrHook(info);
500           break;
501         case rtfParAttr:
502           ME_RTFParAttrHook(info);
503           break;
504       }
505       break;
506   }
507 }
508
509 void
510 ME_StreamInFill(ME_InStream *stream)
511 {
512   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
513                                                                 stream->buffer,
514                                                                 sizeof(stream->buffer),
515                                                                 &stream->dwSize);
516   stream->dwUsed = 0;
517 }
518
519 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
520 {
521   RTF_Info parser;
522   ME_Style *style;
523   int from, to, to2, nUndoMode;
524   ME_UndoItem *pUI;
525   int nEventMask = editor->nEventMask;
526   ME_InStream inStream;
527
528   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
529   editor->nEventMask = 0;
530   
531   ME_GetSelection(editor, &from, &to);
532   if (format & SFF_SELECTION) {
533     style = ME_GetSelectionInsertStyle(editor);
534
535     ME_InternalDeleteText(editor, from, to-from);
536   }
537   else {
538     style = editor->pBuffer->pDefaultStyle;
539     ME_AddRefStyle(style);
540     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
541     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
542     from = to = 0;
543     ME_ClearTempStyle(editor);
544     /* FIXME restore default paragraph formatting ! */
545   }
546   
547   nUndoMode = editor->nUndoMode;
548   editor->nUndoMode = umIgnore;
549
550   inStream.editstream = stream;
551   inStream.editstream->dwError = 0;
552   inStream.dwSize = 0;
553   inStream.dwUsed = 0;
554
555   if (format & SF_RTF)
556   {
557     /* Check if it's really RTF, and if it is not, use plain text */
558     ME_StreamInFill(&inStream);
559     if (!inStream.editstream->dwError)
560     {
561       if (strncmp(inStream.buffer, "{\\rtf1", 6) && strncmp(inStream.buffer, "{\\urtf", 6))
562       {
563         format &= ~SF_RTF;
564         format |= SF_TEXT;
565       }
566     }
567   }
568
569   if (!inStream.editstream->dwError)
570   {
571     if (format & SF_RTF) {
572       /* setup the RTF parser */
573       memset(&parser, 0, sizeof parser);
574       RTFSetEditStream(&parser, &inStream);
575       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
576       parser.hwndEdit = editor->hWnd;
577       parser.editor = editor;
578       parser.style = style;
579       WriterInit(&parser);
580       RTFInit(&parser);
581       RTFSetReadHook(&parser, ME_RTFReadHook);
582       BeginFile(&parser);
583   
584       /* do the parsing */
585       RTFRead(&parser);
586       RTFFlushOutputBuffer(&parser);
587       RTFDestroy(&parser);
588
589       style = parser.style;
590     }
591     else if (format & SF_TEXT)
592       ME_StreamInText(editor, format, &inStream, style);
593     else
594       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
595     ME_GetSelection(editor, &to, &to2);
596     /* put the cursor at the top */
597     if (!(format & SFF_SELECTION))
598       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
599     else
600     {
601       /* FIXME where to put cursor now ? */
602     }
603   }
604   
605   editor->nUndoMode = nUndoMode;
606   pUI = ME_AddUndoItem(editor, diUndoDeleteRun, NULL);
607   TRACE("from %d to %d\n", from, to);
608   if (pUI && from < to)
609   {
610     pUI->nStart = from;
611     pUI->nLen = to-from;
612   }
613   ME_CommitUndo(editor);
614   ME_ReleaseStyle(style); 
615   editor->nEventMask = nEventMask;
616   if (editor->bRedraw)
617   {
618     InvalidateRect(editor->hWnd, NULL, TRUE);
619     ME_UpdateRepaint(editor);
620   }
621   if (!(format & SFF_SELECTION)) {
622     ME_ClearTempStyle(editor);
623   }
624   ME_MoveCaret(editor);
625   ME_SendSelChange(editor);
626
627   return 0;
628 }
629
630
631 ME_DisplayItem *
632 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
633 {
634   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
635   
636   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
637     item = ME_FindItemFwd(item, diParagraph);
638
639   if (!item)
640     return item;
641
642   nOffset -= item->member.para.nCharOfs;
643   if (nItemType == diParagraph) {
644     if (nItemOffset)
645       *nItemOffset = nOffset;
646     return item;
647   }
648   
649   do {
650     item = ME_FindItemFwd(item, diRun);
651   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
652   if (item) {
653     nOffset -= item->member.run.nCharOfs;
654     if (nItemOffset)
655       *nItemOffset = nOffset;
656   }
657   return item;
658 }
659
660
661 static int
662 ME_FindText(ME_TextEditor *editor, DWORD flags, CHARRANGE *chrg, WCHAR *text, CHARRANGE *chrgText)
663 {
664   int nStart = chrg->cpMin;
665   int nLen = lstrlenW(text);
666   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
667   ME_DisplayItem *para;
668   
669   if (!item)
670     return -1;
671
672   if (!nLen)
673   {
674     if (chrgText)
675       chrgText->cpMin = chrgText->cpMax = chrg->cpMin;
676     return chrg->cpMin;
677   }
678  
679   if (!(flags & FR_DOWN))
680     FIXME("Backward search not implemented\n");
681   if (!(flags & FR_MATCHCASE))
682     FIXME("Case-insensitive search not implemented\n");
683   if (flags & ~(FR_DOWN | FR_MATCHCASE))
684     FIXME("Flags 0x%08lx not implemented\n", flags & ~(FR_DOWN | FR_MATCHCASE));
685   
686   para = ME_GetParagraph(item);
687   while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen < chrg->cpMax)
688   {
689     ME_DisplayItem *pCurItem = item;
690     int nCurStart = nStart;
691     int nMatched = 0;
692     
693     while (pCurItem->member.run.strText->szData[nCurStart + nMatched] == text[nMatched])
694     {
695       nMatched++;
696       if (nMatched == nLen)
697       {
698         nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
699         if (chrgText)
700         {
701           chrgText->cpMin = nStart;
702           chrgText->cpMax = nStart + nLen;
703         }
704         return nStart;
705       }
706       if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
707       {
708         pCurItem = ME_FindItemFwd(pCurItem, diRun);
709         nCurStart = -nMatched;
710       }
711     }
712     nStart++;
713     if (nStart == ME_StrLen(item->member.run.strText))
714     {
715       item = ME_FindItemFwd(item, diRun);
716       para = ME_GetParagraph(item);
717       nStart = 0;
718     }
719   }
720   return -1;
721 }
722
723
724 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
725   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
726   HDC hDC;
727   int i;
728   ed->hWnd = hWnd;
729   ed->bEmulateVersion10 = FALSE;
730   ed->pBuffer = ME_MakeText();
731   hDC = GetDC(hWnd);
732   ME_MakeFirstParagraph(hDC, ed->pBuffer);
733   ReleaseDC(hWnd, hDC);
734   ed->bCaretShown = FALSE;
735   ed->nCursors = 3;
736   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
737   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
738   ed->pCursors[0].nOffset = 0;
739   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
740   ed->pCursors[1].nOffset = 0;
741   ed->nLastTotalLength = ed->nTotalLength = 0;
742   ed->nUDArrowX = -1;
743   ed->nSequence = 0;
744   ed->rgbBackColor = -1;
745   ed->bCaretAtEnd = FALSE;
746   ed->nEventMask = 0;
747   ed->nModifyStep = 0;
748   ed->pUndoStack = ed->pRedoStack = NULL;
749   ed->nUndoMode = umAddToUndo;
750   ed->nParagraphs = 1;
751   ed->nLastSelStart = ed->nLastSelEnd = 0;
752   ed->nScrollPosY = 0;
753   ed->nZoomNumerator = ed->nZoomDenominator = 0;
754   ed->bRedraw = TRUE;
755   GetClientRect(hWnd, &ed->rcFormat);
756   for (i=0; i<HFONT_CACHE_SIZE; i++)
757   {
758     ed->pFontCache[i].nRefs = 0;
759     ed->pFontCache[i].nAge = 0;
760     ed->pFontCache[i].hFont = NULL;
761   }
762   ME_CheckCharOffsets(ed);
763   return ed;
764 }
765
766 typedef struct tagME_GlobalDestStruct
767 {
768   HGLOBAL hData;
769   int nLength;
770 } ME_GlobalDestStruct;
771
772 static DWORD CALLBACK ME_AppendToHGLOBAL(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
773 {
774   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
775   int nMaxSize;
776   BYTE *pDest;
777   
778   nMaxSize = GlobalSize(pData->hData);
779   if (pData->nLength+cb+1 >= cb)
780   {
781     /* round up to 2^17 */
782     int nNewSize = (((nMaxSize+cb+1)|0x1FFFF)+1) & 0xFFFE0000;
783     pData->hData = GlobalReAlloc(pData->hData, nNewSize, 0);
784   }
785   pDest = (BYTE *)GlobalLock(pData->hData);
786   memcpy(pDest + pData->nLength, lpBuff, cb);
787   pData->nLength += cb;
788   pDest[pData->nLength] = '\0';
789   GlobalUnlock(pData->hData);
790   *pcb = cb;
791   
792   return 0;
793 }
794
795 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
796 {
797   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
798   int i;
799   WORD *pSrc, *pDest;
800   
801   cb = cb >> 1;
802   pDest = (WORD *)lpBuff;
803   pSrc = (WORD *)GlobalLock(pData->hData);
804   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
805     pDest[i] = pSrc[pData->nLength+i];
806   }    
807   pData->nLength += i;
808   *pcb = 2*i;
809   GlobalUnlock(pData->hData);
810   return 0;
811 }
812
813 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
814 {
815   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
816   int i;
817   BYTE *pSrc, *pDest;
818   
819   pDest = lpBuff;
820   pSrc = (BYTE *)GlobalLock(pData->hData);
821   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
822     pDest[i] = pSrc[pData->nLength+i];
823   }    
824   pData->nLength += i;
825   *pcb = i;
826   GlobalUnlock(pData->hData);
827   return 0;
828 }
829
830
831 void ME_DestroyEditor(ME_TextEditor *editor)
832 {
833   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
834   ME_DisplayItem *p = pFirst, *pNext = NULL;
835   int i;
836   
837   ME_ClearTempStyle(editor);
838   ME_EmptyUndoStack(editor);
839   while(p) {
840     pNext = p->next;
841     ME_DestroyDisplayItem(p);    
842     p = pNext;
843   }
844   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
845   for (i=0; i<HFONT_CACHE_SIZE; i++)
846   {
847     if (editor->pFontCache[i].hFont)
848       DeleteObject(editor->pFontCache[i].hFont);
849   }
850     
851   FREE_OBJ(editor);
852 }
853
854 static WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
855 static WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
856
857 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
858 {
859     TRACE("\n");
860     switch (fdwReason)
861     {
862     case DLL_PROCESS_ATTACH:
863       DisableThreadLibraryCalls(hinstDLL);
864       me_heap = HeapCreate (0, 0x10000, 0);
865       ME_RegisterEditorClass(hinstDLL);
866       break;
867
868     case DLL_PROCESS_DETACH:
869       UnregisterClassW(wszClassName, 0);
870       UnregisterClassW(wszClassName50, 0);
871       UnregisterClassA("RichEdit20A", 0);
872       UnregisterClassA("RichEdit50A", 0);
873       HeapDestroy (me_heap);
874       me_heap = NULL;
875       break;
876     }
877     return TRUE;
878 }
879
880
881 #define UNSUPPORTED_MSG(e) \
882   case e: \
883     FIXME(#e ": stub\n"); \
884     return DefWindowProcW(hWnd, msg, wParam, lParam);
885
886 static const char * const edit_messages[] = {
887   "EM_GETSEL",
888   "EM_SETSEL",
889   "EM_GETRECT",
890   "EM_SETRECT",
891   "EM_SETRECTNP",
892   "EM_SCROLL",
893   "EM_LINESCROLL",
894   "EM_SCROLLCARET",
895   "EM_GETMODIFY",
896   "EM_SETMODIFY",
897   "EM_GETLINECOUNT",
898   "EM_LINEINDEX",
899   "EM_SETHANDLE",
900   "EM_GETHANDLE",
901   "EM_GETTHUMB",
902   "EM_UNKNOWN_BF",
903   "EM_UNKNOWN_C0",
904   "EM_LINELENGTH",
905   "EM_REPLACESEL",
906   "EM_UNKNOWN_C3",
907   "EM_GETLINE",
908   "EM_LIMITTEXT",
909   "EM_CANUNDO",
910   "EM_UNDO",
911   "EM_FMTLINES",
912   "EM_LINEFROMCHAR",
913   "EM_UNKNOWN_CA",
914   "EM_SETTABSTOPS",
915   "EM_SETPASSWORDCHAR",
916   "EM_EMPTYUNDOBUFFER",
917   "EM_GETFIRSTVISIBLELINE",
918   "EM_SETREADONLY",
919   "EM_SETWORDBREAKPROC",
920   "EM_GETWORDBREAKPROC",
921   "EM_GETPASSWORDCHAR",
922   "EM_SETMARGINS",
923   "EM_GETMARGINS",
924   "EM_GETLIMITTEXT",
925   "EM_POSFROMCHAR",
926   "EM_CHARFROMPOS"
927 };
928
929 static const char * const richedit_messages[] = {
930   "EM_CANPASTE",
931   "EM_DISPLAYBAND",
932   "EM_EXGETSEL",
933   "EM_EXLIMITTEXT",
934   "EM_EXLINEFROMCHAR",
935   "EM_EXSETSEL",
936   "EM_FINDTEXT",
937   "EM_FORMATRANGE",
938   "EM_GETCHARFORMAT",
939   "EM_GETEVENTMASK",
940   "EM_GETOLEINTERFACE",
941   "EM_GETPARAFORMAT",
942   "EM_GETSELTEXT",
943   "EM_HIDESELECTION",
944   "EM_PASTESPECIAL",
945   "EM_REQUESTRESIZE",
946   "EM_SELECTIONTYPE",
947   "EM_SETBKGNDCOLOR",
948   "EM_SETCHARFORMAT",
949   "EM_SETEVENTMASK",
950   "EM_SETOLECALLBACK",
951   "EM_SETPARAFORMAT",
952   "EM_SETTARGETDEVICE",
953   "EM_STREAMIN",
954   "EM_STREAMOUT",
955   "EM_GETTEXTRANGE",
956   "EM_FINDWORDBREAK",
957   "EM_SETOPTIONS",
958   "EM_GETOPTIONS",
959   "EM_FINDTEXTEX",
960   "EM_GETWORDBREAKPROCEX",
961   "EM_SETWORDBREAKPROCEX",
962   "EM_SETUNDOLIMIT",
963   "EM_UNKNOWN_USER_83",
964   "EM_REDO",
965   "EM_CANREDO",
966   "EM_GETUNDONAME",
967   "EM_GETREDONAME",
968   "EM_STOPGROUPTYPING",
969   "EM_SETTEXTMODE",
970   "EM_GETTEXTMODE",
971   "EM_AUTOURLDETECT",
972   "EM_GETAUTOURLDETECT",
973   "EM_SETPALETTE",
974   "EM_GETTEXTEX",
975   "EM_GETTEXTLENGTHEX",
976   "EM_SHOWSCROLLBAR",
977   "EM_SETTEXTEX",
978   "EM_UNKNOWN_USER_98",
979   "EM_UNKNOWN_USER_99",
980   "EM_SETPUNCTUATION",
981   "EM_GETPUNCTUATION",
982   "EM_SETWORDWRAPMODE",
983   "EM_GETWORDWRAPMODE",
984   "EM_SETIMECOLOR",
985   "EM_GETIMECOLOR",
986   "EM_SETIMEOPTIONS",
987   "EM_GETIMEOPTIONS",
988   "EM_CONVPOSITION",
989   "EM_UNKNOWN_USER_109",
990   "EM_UNKNOWN_USER_110",
991   "EM_UNKNOWN_USER_111",
992   "EM_UNKNOWN_USER_112",
993   "EM_UNKNOWN_USER_113",
994   "EM_UNKNOWN_USER_114",
995   "EM_UNKNOWN_USER_115",
996   "EM_UNKNOWN_USER_116",
997   "EM_UNKNOWN_USER_117",
998   "EM_UNKNOWN_USER_118",
999   "EM_UNKNOWN_USER_119",
1000   "EM_SETLANGOPTIONS",
1001   "EM_GETLANGOPTIONS",
1002   "EM_GETIMECOMPMODE",
1003   "EM_FINDTEXTW",
1004   "EM_FINDTEXTEXW",
1005   "EM_RECONVERSION",
1006   "EM_SETIMEMODEBIAS",
1007   "EM_GETIMEMODEBIAS"
1008 };
1009
1010 static const char *
1011 get_msg_name(UINT msg)
1012 {
1013   if (msg >= EM_GETSEL && msg <= EM_SETLIMITTEXT)
1014     return edit_messages[msg - EM_GETSEL];
1015   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1016     return richedit_messages[msg - EM_CANPASTE];
1017   return "";
1018 }
1019
1020 /******************************************************************
1021  *        RichEditANSIWndProc (RICHED20.10)
1022  */
1023 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
1024   SCROLLINFO si;
1025   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
1026   
1027   TRACE("hWnd %p msg %d (%s) %08x %08lx\n",
1028         hWnd, msg, get_msg_name(msg), wParam, lParam);
1029   
1030   switch(msg) {
1031   
1032   UNSUPPORTED_MSG(EM_AUTOURLDETECT)
1033   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1034   UNSUPPORTED_MSG(EM_EXLIMITTEXT)
1035   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1036   UNSUPPORTED_MSG(EM_FMTLINES)
1037   UNSUPPORTED_MSG(EM_FORMATRANGE)
1038   UNSUPPORTED_MSG(EM_GETAUTOURLDETECT)
1039   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1040   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1041   UNSUPPORTED_MSG(EM_GETFIRSTVISIBLELINE)
1042   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1043   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1044   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1045   UNSUPPORTED_MSG(EM_GETLIMITTEXT)
1046   UNSUPPORTED_MSG(EM_GETLINE)
1047   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1048   UNSUPPORTED_MSG(EM_GETOPTIONS)
1049   UNSUPPORTED_MSG(EM_GETPASSWORDCHAR)
1050   UNSUPPORTED_MSG(EM_GETREDONAME)
1051   UNSUPPORTED_MSG(EM_GETSCROLLPOS)
1052   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1053   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1054   UNSUPPORTED_MSG(EM_GETUNDONAME)
1055   UNSUPPORTED_MSG(EM_GETWORDBREAKPROC)
1056   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1057   UNSUPPORTED_MSG(EM_HIDESELECTION)
1058   UNSUPPORTED_MSG(EM_LIMITTEXT) /* also known as EM_SETLIMITTEXT */
1059   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1060 /*  UNSUPPORTED_MSG(EM_POSFROMCHARS) missing in Wine headers */
1061   UNSUPPORTED_MSG(EM_REQUESTRESIZE)
1062   UNSUPPORTED_MSG(EM_SCROLL)
1063   UNSUPPORTED_MSG(EM_SCROLLCARET)
1064   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1065   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1066   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1067   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1068   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1069   UNSUPPORTED_MSG(EM_SETOLECALLBACK)
1070   UNSUPPORTED_MSG(EM_SETOPTIONS)
1071   UNSUPPORTED_MSG(EM_SETPALETTE)
1072   UNSUPPORTED_MSG(EM_SETPASSWORDCHAR)
1073   UNSUPPORTED_MSG(EM_SETSCROLLPOS)
1074   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1075   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1076   UNSUPPORTED_MSG(EM_SETTEXTMODE)
1077   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1078   UNSUPPORTED_MSG(EM_SETUNDOLIMIT)
1079   UNSUPPORTED_MSG(EM_SETWORDBREAKPROC)
1080   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1081   UNSUPPORTED_MSG(EM_SHOWSCROLLBAR)
1082   UNSUPPORTED_MSG(WM_SETFONT)
1083   UNSUPPORTED_MSG(WM_STYLECHANGING)
1084   UNSUPPORTED_MSG(WM_STYLECHANGED)
1085 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1086     
1087 /* Messages specific to Richedit controls */
1088   
1089   case EM_STREAMIN:
1090    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1091   case EM_STREAMOUT:
1092    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1093   case WM_GETDLGCODE:
1094   {
1095     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1096     if (GetWindowLongW(hWnd, GWL_STYLE)&ES_WANTRETURN)
1097       code |= 0; /* FIXME what can we do here ? ask for messages and censor them ? */
1098     return code;
1099   }
1100   case WM_NCCREATE:
1101   {
1102     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1103     TRACE("WM_NCCREATE: style 0x%08lx\n", pcs->style);
1104     editor = ME_MakeEditor(hWnd);
1105     SetWindowLongW(hWnd, 0, (long)editor);
1106     pcs = 0; /* ignore */
1107     return TRUE;
1108   }
1109   case EM_EMPTYUNDOBUFFER:
1110     ME_EmptyUndoStack(editor);
1111     return 0;
1112   case EM_GETSEL:
1113   {
1114     /* Note: wParam/lParam can be NULL */
1115     UINT from, to;
1116     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1117     PUINT pto = lParam ? (PUINT)lParam : &to;
1118     ME_GetSelection(editor, pfrom, pto);
1119     if ((*pfrom|*pto) & 0xFFFF0000)
1120       return -1;
1121     return MAKELONG(*pfrom,*pto);
1122   }
1123   case EM_EXGETSEL:
1124   {
1125     CHARRANGE *pRange = (CHARRANGE *)lParam;
1126     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1127     TRACE("EM_EXGETSEL = (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1128     return 0;
1129   }
1130   case EM_CANUNDO:
1131     return editor->pUndoStack != NULL;
1132   case EM_CANREDO:
1133     return editor->pRedoStack != NULL;
1134   case WM_UNDO: /* FIXME: actually not the same */
1135   case EM_UNDO:
1136     ME_Undo(editor);
1137     return 0;
1138   case EM_REDO:
1139     ME_Redo(editor);
1140     return 0;
1141   case EM_SETSEL:
1142   {
1143     ME_SetSelection(editor, wParam, lParam);
1144     ME_Repaint(editor);
1145     ME_SendSelChange(editor);
1146     return 0;
1147   }
1148   case EM_EXSETSEL:
1149   {
1150     CHARRANGE *pRange = (CHARRANGE *)lParam;
1151     TRACE("EM_EXSETSEL (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1152     ME_SetSelection(editor, pRange->cpMin, pRange->cpMax);
1153     /* FIXME optimize */
1154     ME_Repaint(editor);
1155     ME_SendSelChange(editor);
1156     return 0;
1157   }
1158   case EM_SETTEXTEX:
1159   {
1160     LPWSTR wszText = (LPWSTR)lParam;
1161     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1162     size_t len = lstrlenW(wszText);
1163     int from, to;
1164     ME_Style *style;
1165     TRACE("EM_SETTEXEX - %s, flags %d, cp %d\n", debugstr_w(wszText), (int)pStruct->flags, pStruct->codepage);
1166     if (pStruct->codepage != 1200) {
1167       FIXME("EM_SETTEXTEX only supports unicode right now!\n"); 
1168       return 0;
1169     }
1170     /* FIXME: this should support RTF strings too, according to MSDN */
1171     if (pStruct->flags & ST_SELECTION) {
1172       ME_GetSelection(editor, &from, &to);
1173       style = ME_GetSelectionInsertStyle(editor);
1174       ME_InternalDeleteText(editor, from, to - from);
1175       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1176       ME_ReleaseStyle(style);
1177     }
1178     else {
1179       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1180       ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1181       len = 1;
1182     }
1183     ME_CommitUndo(editor);
1184     if (!(pStruct->flags & ST_KEEPUNDO))
1185       ME_EmptyUndoStack(editor);
1186     ME_UpdateRepaint(editor);
1187     return len;
1188   }
1189   case EM_SETBKGNDCOLOR:
1190   {
1191     LRESULT lColor = ME_GetBackColor(editor);
1192     if (wParam)
1193       editor->rgbBackColor = -1;
1194     else
1195       editor->rgbBackColor = lParam;
1196     if (editor->bRedraw)
1197     {
1198       InvalidateRect(hWnd, NULL, TRUE);
1199       UpdateWindow(hWnd);
1200     }
1201     return lColor;
1202   }
1203   case EM_GETMODIFY:
1204     return editor->nModifyStep == 0 ? 0 : 1;
1205   case EM_SETMODIFY:
1206   {
1207     if (wParam)
1208       editor->nModifyStep = 0x80000000;
1209     else
1210       editor->nModifyStep = 0;
1211     
1212     return 0;
1213   }
1214   case EM_SETREADONLY:
1215   {
1216     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1217     if (wParam)
1218       nStyle |= ES_READONLY;
1219     else
1220       nStyle &= ~ES_READONLY;
1221     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1222     ME_Repaint(editor);
1223     return 0;
1224   }
1225   case EM_SETEVENTMASK:
1226     editor->nEventMask = lParam;
1227     return 0;
1228   case EM_GETEVENTMASK:
1229     return editor->nEventMask;
1230   case EM_SETCHARFORMAT:
1231   {
1232     CHARFORMAT2W buf, *p;
1233     BOOL bRepaint = TRUE;
1234     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1235     if (!wParam)
1236       ME_SetDefaultCharFormat(editor, p);
1237     else if (wParam == (SCF_WORD | SCF_SELECTION))
1238       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1239     else if (wParam == SCF_ALL)
1240       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1241     else {
1242       int from, to;
1243       ME_GetSelection(editor, &from, &to);
1244       bRepaint = (from != to);
1245       ME_SetSelectionCharFormat(editor, p);
1246     }
1247     ME_CommitUndo(editor);
1248     if (bRepaint)
1249       ME_UpdateRepaint(editor);
1250     return 0;
1251   }
1252   case EM_GETCHARFORMAT:
1253   {
1254     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1255     if (dst->cbSize != sizeof(CHARFORMATA) &&
1256         dst->cbSize != sizeof(CHARFORMATW) &&
1257         dst->cbSize != sizeof(CHARFORMAT2A) &&
1258         dst->cbSize != sizeof(CHARFORMAT2W))
1259       return 0;
1260     tmp.cbSize = sizeof(tmp);
1261     if (!wParam)
1262       ME_GetDefaultCharFormat(editor, &tmp);
1263     else
1264       ME_GetSelectionCharFormat(editor, &tmp);
1265     ME_CopyToCFAny(dst, &tmp);
1266     return tmp.dwMask;
1267   }
1268   case EM_SETPARAFORMAT:
1269     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1270     ME_UpdateRepaint(editor);
1271     ME_CommitUndo(editor);
1272     return 0;
1273   case EM_GETPARAFORMAT:
1274     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1275     return 0;
1276   case EM_LINESCROLL:
1277   {
1278     int nPos = editor->nScrollPosY, nEnd= editor->nTotalLength - editor->sizeWindow.cy;
1279     nPos += 8 * lParam; /* FIXME follow the original */
1280     if (nPos>=nEnd)
1281       nPos = nEnd;
1282     if (nPos<0)
1283       nPos = 0;
1284     if (nPos != editor->nScrollPosY) {
1285       if (editor->bRedraw)
1286       {
1287         ScrollWindow(hWnd, 0, editor->nScrollPosY-nPos, NULL, NULL);
1288         SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1289         UpdateWindow(hWnd);
1290       }
1291       editor->nScrollPosY = nPos;
1292     }
1293     return TRUE; /* Should return false if a single line richedit control */
1294   }
1295   case WM_CLEAR:
1296   {
1297     int from, to;
1298     ME_GetSelection(editor, &from, &to);
1299     ME_InternalDeleteText(editor, from, to-from);
1300     ME_CommitUndo(editor);
1301     ME_UpdateRepaint(editor);
1302     return 0;
1303   }
1304   case EM_REPLACESEL:
1305   {
1306     int from, to;
1307     ME_Style *style;
1308     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1309     size_t len = lstrlenW(wszText);
1310     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1311     
1312     ME_GetSelection(editor, &from, &to);
1313     style = ME_GetSelectionInsertStyle(editor);
1314     ME_InternalDeleteText(editor, from, to-from);
1315     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1316     ME_ReleaseStyle(style);
1317     ME_EndToUnicode(hWnd, wszText);
1318     /* drop temporary style if line end */
1319     /* FIXME question: does abc\n mean: put abc, clear temp style, put \n? (would require a change) */  
1320     if (len>0 && wszText[len-1] == '\n')
1321       ME_ClearTempStyle(editor);
1322       
1323     ME_CommitUndo(editor);
1324     if (!wParam)
1325       ME_EmptyUndoStack(editor);
1326     ME_UpdateRepaint(editor);
1327     return 0;
1328   }
1329   case WM_SETTEXT:
1330   {
1331     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1332     if (lParam)
1333     {
1334       LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1335       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1336       TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1337       if (lstrlenW(wszText) > 0)
1338       {
1339         /* uses default style! */
1340         ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1341       }
1342       ME_EndToUnicode(hWnd, wszText);
1343     }
1344     else
1345       TRACE("WM_SETTEXT - NULL\n");
1346     ME_CommitUndo(editor);
1347     ME_EmptyUndoStack(editor);
1348     ME_UpdateRepaint(editor);
1349     return 0;
1350   }
1351   case EM_CANPASTE:
1352   {
1353     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1354     if (IsClipboardFormatAvailable(nRTFFormat))
1355       return TRUE;
1356     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1357       return TRUE;
1358     return FALSE;
1359   }
1360   case WM_PASTE:
1361   {    
1362     DWORD dwFormat = 0;
1363     EDITSTREAM es;
1364     ME_GlobalDestStruct gds;
1365     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1366     UINT cf = 0;
1367
1368     if (IsClipboardFormatAvailable(nRTFFormat))
1369       cf = nRTFFormat, dwFormat = SF_RTF;
1370     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1371       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1372     else
1373       return 0;
1374
1375     if (!OpenClipboard(hWnd))
1376       return 0;
1377     gds.hData = GetClipboardData(cf);
1378     gds.nLength = 0;
1379     es.dwCookie = (DWORD)&gds;
1380     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1381     SendMessageW(hWnd, EM_STREAMIN, dwFormat|SFF_SELECTION, (LPARAM)&es);
1382     
1383     CloseClipboard();
1384     return 0;
1385   }
1386   case WM_CUT:
1387   case WM_COPY:
1388   {
1389     int from, to, pars;
1390     WCHAR *data;
1391     HANDLE hData;
1392     EDITSTREAM es;
1393     ME_GlobalDestStruct gds;
1394     
1395     if (!OpenClipboard(hWnd))
1396       return 0;
1397       
1398     EmptyClipboard();
1399     ME_GetSelection(editor, &from, &to);
1400     pars = ME_CountParagraphsBetween(editor, from, to);
1401     hData = GlobalAlloc(GMEM_MOVEABLE, sizeof(WCHAR)*(to-from+pars+1));
1402     data = (WCHAR *)GlobalLock(hData);
1403     ME_GetTextW(editor, data, from, to-from, TRUE);
1404     GlobalUnlock(hData);
1405
1406     gds.hData = GlobalAlloc(GMEM_MOVEABLE, 0);
1407     gds.nLength = 0;
1408     es.dwCookie = (DWORD)&gds;
1409     es.pfnCallback = ME_AppendToHGLOBAL;
1410     SendMessageW(hWnd, EM_STREAMOUT, SFF_SELECTION|SF_RTF, (LPARAM)&es);
1411     GlobalReAlloc(gds.hData, gds.nLength+1, 0);
1412     
1413     SetClipboardData(CF_UNICODETEXT, hData);    
1414     SetClipboardData(RegisterClipboardFormatA("Rich Text Format"), gds.hData);
1415     
1416     CloseClipboard();
1417     if (msg == WM_CUT)
1418     {
1419       ME_InternalDeleteText(editor, from, to-from);
1420       ME_CommitUndo(editor);
1421       ME_UpdateRepaint(editor);
1422     }
1423     return 0;
1424   }
1425   case WM_GETTEXTLENGTH:
1426     return ME_GetTextLength(editor);
1427   case EM_GETTEXTLENGTHEX:
1428     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
1429   case WM_GETTEXT:
1430   {
1431     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1432     tr.chrg.cpMin = 0;
1433     tr.chrg.cpMax = wParam-1;
1434     tr.lpstrText = (WCHAR *)lParam;
1435     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1436   }
1437   case EM_GETTEXTEX:
1438   {
1439     GETTEXTEX *ex = (GETTEXTEX*)wParam;
1440     int nStart, nCount;
1441
1442     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1443       FIXME("GETTEXTEX flags 0x%08lx not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1444
1445     if (ex->flags & GT_SELECTION)
1446     {
1447       ME_GetSelection(editor, &nStart, &nCount);
1448       nCount -= nStart;
1449       nCount = min(nCount, ex->cb - 1);
1450     }
1451     else
1452     {
1453       nStart = 0;
1454       nCount = ex->cb - 1;
1455     }
1456     if (ex->codepage == 1200 || IsWindowUnicode(hWnd))
1457     {
1458       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
1459       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
1460     }
1461     else
1462     {
1463         LPWSTR buffer = HeapAlloc(GetProcessHeap(), 0, (nCount + 1) * sizeof(WCHAR));
1464         DWORD buflen = ex->cb;
1465         LRESULT rc;
1466         DWORD flags = 0;
1467
1468         buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
1469         rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
1470
1471         HeapFree(GetProcessHeap(),0,buffer);
1472         return rc;
1473     }
1474   }
1475   case EM_GETSELTEXT:
1476   {
1477     int from, to;
1478     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1479     ME_GetSelection(editor, &from, &to);
1480     tr.chrg.cpMin = from;
1481     tr.chrg.cpMax = to;
1482     tr.lpstrText = (WCHAR *)lParam;
1483     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1484   }
1485   case EM_GETTEXTRANGE:
1486   {
1487     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
1488     if (IsWindowUnicode(hWnd))
1489       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
1490     else
1491     {
1492       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
1493       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1494       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
1495       /* FIXME this is a potential security hole (buffer overrun) 
1496          if you know more about wchar->mbyte conversion please explain
1497       */
1498       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
1499       FREE_OBJ(p);
1500       return nChars;
1501     }
1502   }
1503   case EM_GETLINECOUNT:
1504   {
1505     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
1506     int nRows = 0;
1507
1508     while (item != editor->pBuffer->pLast)
1509     {
1510       assert(item->type == diParagraph);
1511       nRows += item->member.para.nRows;
1512       item = item->member.para.next_para;
1513     }
1514     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
1515     return max(1, nRows);
1516   }
1517   case EM_LINEFROMCHAR:
1518   {
1519     if (wParam == -1)
1520       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
1521     else
1522       return ME_RowNumberFromCharOfs(editor, wParam);
1523   }
1524   case EM_EXLINEFROMCHAR:
1525   {
1526     return ME_RowNumberFromCharOfs(editor, lParam);
1527   }
1528   case EM_LINEINDEX:
1529   {
1530     ME_DisplayItem *item, *para;
1531     int nCharOfs;
1532     
1533     if (wParam == -1)
1534       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
1535     else
1536       item = ME_FindRowWithNumber(editor, wParam);
1537     if (!item)
1538       return -1;
1539     para = ME_GetParagraph(item);
1540     item = ME_FindItemFwd(item, diRun);
1541     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
1542     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
1543     return nCharOfs;
1544   }
1545   case EM_LINELENGTH:
1546   {
1547     ME_DisplayItem *item, *item_end;
1548     int nChars = 0;
1549     
1550     if (wParam > ME_GetTextLength(editor))
1551       return 0;
1552     if (wParam == -1)
1553     {
1554       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
1555       return 0;
1556     }
1557     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
1558     item = ME_RowStart(item);
1559     item_end = ME_RowEnd(item);
1560     if (!item_end)
1561     {
1562       /* Empty buffer, no runs */
1563       nChars = 0;
1564     }
1565     else
1566     {
1567       nChars = ME_CharOfsFromRunOfs(editor, item_end, ME_StrLen(item_end->member.run.strText));
1568       nChars -= ME_CharOfsFromRunOfs(editor, item, 0);
1569     }
1570     TRACE("EM_LINELENGTH(%d)==%d\n",wParam, nChars);
1571     return nChars;
1572   }
1573   case EM_FINDTEXT:
1574   {
1575     FINDTEXTA *ft = (FINDTEXTA *)lParam;
1576     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
1577     WCHAR *tmp;
1578     
1579     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1580       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
1581     return ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
1582   }
1583   case EM_FINDTEXTEX:
1584   {
1585     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
1586     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
1587     WCHAR *tmp;
1588     
1589     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1590       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
1591     return ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
1592   }
1593   case EM_FINDTEXTW:
1594   {
1595     FINDTEXTW *ft = (FINDTEXTW *)lParam;
1596     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
1597   }
1598   case EM_FINDTEXTEXW:
1599   {
1600     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
1601     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
1602   }
1603   case EM_GETZOOM:
1604     if (!wParam || !lParam)
1605       return FALSE;
1606     *(int *)wParam = editor->nZoomNumerator;
1607     *(int *)lParam = editor->nZoomDenominator;
1608     return TRUE;
1609   case EM_SETZOOM:
1610     return ME_SetZoom(editor, wParam, lParam);
1611   case EM_CHARFROMPOS:
1612     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
1613   case WM_CREATE:
1614     ME_CommitUndo(editor);
1615     ME_WrapMarkedParagraphs(editor);
1616     ME_MoveCaret(editor);
1617     return 0;
1618   case WM_DESTROY:
1619     ME_DestroyEditor(editor);
1620     SetWindowLongW(hWnd, 0, 0);
1621     return 0;
1622   case WM_LBUTTONDOWN:
1623     SetFocus(hWnd);
1624     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1625     SetCapture(hWnd);
1626     break;
1627   case WM_MOUSEMOVE:
1628     if (GetCapture() == hWnd)
1629       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1630     break;
1631   case WM_LBUTTONUP:
1632     if (GetCapture() == hWnd)
1633       ReleaseCapture();
1634     break;
1635   case WM_PAINT:
1636     if (editor->bRedraw)
1637     {
1638       HDC hDC;
1639       PAINTSTRUCT ps;
1640
1641       hDC = BeginPaint(hWnd, &ps);
1642       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
1643       EndPaint(hWnd, &ps);
1644     }
1645     break;
1646   case WM_SETFOCUS:
1647     ME_ShowCaret(editor);
1648     ME_SendOldNotify(editor, EN_SETFOCUS);
1649     return 0;
1650   case WM_KILLFOCUS:
1651     ME_HideCaret(editor);
1652     ME_SendOldNotify(editor, EN_KILLFOCUS);
1653     return 0;
1654   case WM_ERASEBKGND:
1655   {
1656     if (editor->bRedraw)
1657     {
1658       HDC hDC = (HDC)wParam;
1659       RECT rc;
1660       COLORREF rgbBG = ME_GetBackColor(editor);
1661       if (GetUpdateRect(hWnd,&rc,TRUE))
1662       {
1663         HBRUSH hbr = CreateSolidBrush(rgbBG);
1664         FillRect(hDC, &rc, hbr);
1665         DeleteObject(hbr);
1666       }
1667     }
1668     return 1;
1669   }
1670   case WM_COMMAND:
1671     TRACE("editor wnd command = %d\n", LOWORD(wParam));
1672     return 0;
1673   case WM_KEYDOWN:
1674     if (ME_ArrowKey(editor, LOWORD(wParam), GetKeyState(VK_CONTROL)<0)) {
1675       ME_CommitUndo(editor);
1676       ME_EnsureVisible(editor, editor->pCursors[0].pRun);
1677       HideCaret(hWnd);
1678       ME_MoveCaret(editor);
1679       ShowCaret(hWnd);
1680       return 0;
1681     }
1682     if (GetKeyState(VK_CONTROL)<0)
1683     {
1684       if (LOWORD(wParam)=='W')
1685       {
1686         CHARFORMAT2W chf;
1687         char buf[2048];
1688         ME_GetSelectionCharFormat(editor, &chf);
1689         ME_DumpStyleToBuf(&chf, buf);
1690         MessageBoxA(NULL, buf, "Style dump", MB_OK);
1691       }
1692       if (LOWORD(wParam)=='Q')
1693       {
1694         ME_CheckCharOffsets(editor);
1695       }
1696     }
1697     goto do_default;
1698   case WM_CHAR: 
1699   {
1700     WCHAR wstr = LOWORD(wParam);
1701
1702     switch (wstr)
1703     {
1704     case 3: /* Ctrl-C */
1705       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
1706       return 0;
1707     }
1708     
1709     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
1710       MessageBeep(MB_ICONERROR);
1711       return 0; /* FIXME really 0 ? */
1712     }
1713
1714     switch (wstr)
1715     {
1716     case 1: /* Ctrl-A */
1717       ME_SetSelection(editor, 0, -1);
1718       return 0;
1719     case 22: /* Ctrl-V */
1720       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
1721       return 0;
1722     case 24: /* Ctrl-X */
1723       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
1724       return 0;
1725     case 25: /* Ctrl-Y */
1726       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
1727       return 0;
1728     case 26: /* Ctrl-Z */
1729       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
1730       return 0;
1731     }
1732     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
1733       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
1734       ME_Style *style = ME_GetInsertStyle(editor, 0);
1735       ME_SaveTempStyle(editor);
1736       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
1737       ME_ReleaseStyle(style);
1738       ME_CommitUndo(editor);
1739       ME_UpdateRepaint(editor);
1740     }
1741     return 0;
1742   }
1743   case WM_VSCROLL: 
1744   {
1745     int nPos = editor->nScrollPosY;
1746     si.cbSize = sizeof(SCROLLINFO);
1747     si.fMask = SIF_PAGE|SIF_POS|SIF_RANGE|SIF_TRACKPOS;
1748     GetScrollInfo(hWnd, SB_VERT, &si);
1749     switch(LOWORD(wParam)) {
1750     case SB_LINEUP:
1751       nPos -= 24; /* FIXME follow the original */
1752       if (nPos<0) nPos = 0;
1753       break;
1754     case SB_LINEDOWN:
1755     {
1756       int nEnd = editor->nTotalLength - editor->sizeWindow.cy;
1757       nPos += 24; /* FIXME follow the original */
1758       if (nPos>=nEnd) nPos = nEnd;
1759       break;
1760     }
1761     case SB_PAGEUP:
1762       nPos -= editor->sizeWindow.cy;
1763       if (nPos<0) nPos = 0;
1764       break;
1765     case SB_PAGEDOWN:
1766       nPos += editor->sizeWindow.cy;
1767       if (nPos>=editor->nTotalLength) nPos = editor->nTotalLength-1;
1768       break;
1769     case SB_THUMBTRACK:
1770     case SB_THUMBPOSITION:
1771       nPos = si.nTrackPos;
1772       break;
1773     }
1774     if (nPos != editor->nScrollPosY) {
1775       if (editor->bRedraw)
1776       {
1777         ScrollWindow(hWnd, 0, editor->nScrollPosY-nPos, NULL, NULL);
1778         SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1779         UpdateWindow(hWnd);
1780       }
1781       editor->nScrollPosY = nPos;
1782     }
1783     break;
1784   }
1785   case WM_MOUSEWHEEL:
1786   {
1787     int gcWheelDelta = 0, nPos = editor->nScrollPosY, nEnd = editor->nTotalLength - editor->sizeWindow.cy; 
1788     UINT pulScrollLines;
1789     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
1790     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
1791     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
1792       nPos += pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8; /* FIXME follow the original */
1793     if (nPos>=nEnd)
1794       nPos = nEnd;
1795     if (nPos<0)
1796       nPos = 0;
1797     if (nPos != editor->nScrollPosY) {
1798       if (editor->bRedraw)
1799       {
1800         ScrollWindow(hWnd, 0, editor->nScrollPosY-nPos, NULL, NULL);
1801         SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1802         UpdateWindow(hWnd);
1803       }
1804       editor->nScrollPosY = nPos;
1805     }
1806     break;
1807   }
1808   case EM_GETRECT:
1809   {
1810     *((RECT *)lParam) = editor->rcFormat;
1811     return 0;
1812   }
1813   case EM_SETRECT:
1814   case EM_SETRECTNP:
1815   {
1816     if (lParam)
1817     {
1818       RECT *rc = (RECT *)lParam;
1819       
1820       if (wParam)
1821       {
1822         editor->rcFormat.left += rc->left;
1823         editor->rcFormat.top += rc->top;
1824         editor->rcFormat.right += rc->right;
1825         editor->rcFormat.bottom += rc->bottom;
1826       }
1827       else
1828       {
1829         editor->rcFormat = *rc;
1830       }
1831     }
1832     else
1833     {
1834       GetClientRect(hWnd, &editor->rcFormat);
1835     }
1836     if (msg != EM_SETRECTNP)
1837       ME_RewrapRepaint(editor);
1838     return 0;
1839   }
1840   case WM_SETREDRAW:
1841     editor->bRedraw = wParam;
1842     return 0;
1843   case WM_SIZE:
1844   {
1845     GetClientRect(hWnd, &editor->rcFormat);
1846     ME_RewrapRepaint(editor);
1847     return DefWindowProcW(hWnd, msg, wParam, lParam);
1848   }
1849   case EM_GETOLEINTERFACE:
1850   {
1851     LPVOID *ppvObj = (LPVOID*) lParam;
1852     FIXME("EM_GETOLEINTERFACE %p: stub\n", ppvObj);
1853     return CreateIRichEditOle(ppvObj);
1854   }
1855   default:
1856   do_default:
1857     return DefWindowProcW(hWnd, msg, wParam, lParam);
1858   }
1859   return 0L;
1860 }
1861
1862
1863 /******************************************************************
1864  *        RichEdit10ANSIWndProc (RICHED20.9)
1865  */
1866 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1867 {
1868   LRESULT result;
1869   
1870   /* FIXME: this is NOT the same as 2.0 version */
1871   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
1872   if (msg == WM_NCCREATE)
1873   {
1874     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
1875     
1876     editor->bEmulateVersion10 = TRUE;
1877     editor->pBuffer->pLast->member.para.nCharOfs = 2;
1878   }
1879   return result;
1880 }
1881
1882 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
1883 {
1884   HWND hWnd = editor->hWnd;
1885   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
1886 }
1887
1888 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
1889 {
1890   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1891   int i = 0;
1892   
1893   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
1894     item = item->member.para.next_para;
1895   if (!item)
1896     return 0;
1897   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
1898     item = item->member.para.next_para;
1899     i++;
1900   }
1901   return i;
1902 }
1903
1904
1905 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
1906 {
1907   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1908   int nWritten = 0;
1909   
1910   if (!item) {
1911     *buffer = L'\0';
1912     return 0;
1913   }
1914   assert(item);    
1915   
1916   if (nStart)
1917   {
1918     int nLen = ME_StrLen(item->member.run.strText) - nStart;
1919     if (nLen > nChars)
1920       nLen = nChars;
1921     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
1922     nChars -= nLen;
1923     nWritten += nLen;
1924     if (!nChars)
1925       return nWritten;
1926     buffer += nLen;
1927     nStart = 0;
1928     item = ME_FindItemFwd(item, diRun);
1929   }
1930   
1931   while(nChars && item)
1932   {
1933     int nLen = ME_StrLen(item->member.run.strText);
1934     if (nLen > nChars)
1935       nLen = nChars;
1936       
1937     if (item->member.run.nFlags & MERF_ENDPARA)
1938     {
1939       *buffer++ = '\r';
1940       if (bCRLF)
1941       {
1942         *buffer = '\n';
1943         nWritten++;
1944       }
1945       assert(nLen == 1);
1946     }
1947     else      
1948       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
1949     nChars -= nLen;
1950     nWritten += nLen;
1951     buffer += nLen;    
1952       
1953     if (!nChars)
1954     {
1955       *buffer = L'\0';
1956       return nWritten;
1957     }
1958     item = ME_FindItemFwd(item, diRun);
1959   }
1960   *buffer = L'\0';
1961   return nWritten;  
1962 }
1963
1964 void ME_RegisterEditorClass(HINSTANCE hInstance)
1965 {
1966   BOOL bResult;
1967   WNDCLASSW wcW;
1968   WNDCLASSA wcA;
1969   
1970   wcW.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
1971   wcW.lpfnWndProc = RichEditANSIWndProc;
1972   wcW.cbClsExtra = 0;
1973   wcW.cbWndExtra = 4;
1974   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
1975   wcW.hIcon = NULL;
1976   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
1977   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
1978   wcW.lpszMenuName = NULL;
1979   wcW.lpszClassName = wszClassName;
1980   bResult = RegisterClassW(&wcW);  
1981   assert(bResult);
1982   wcW.lpszClassName = wszClassName50;
1983   bResult = RegisterClassW(&wcW);  
1984   assert(bResult);
1985
1986   wcA.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
1987   wcA.lpfnWndProc = RichEditANSIWndProc;
1988   wcA.cbClsExtra = 0;
1989   wcA.cbWndExtra = 4;
1990   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
1991   wcA.hIcon = NULL;
1992   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
1993   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
1994   wcA.lpszMenuName = NULL;
1995   wcA.lpszClassName = "RichEdit20A";
1996   bResult = RegisterClassA(&wcA);  
1997   assert(bResult);
1998   wcA.lpszClassName = "RichEdit50A";
1999   bResult = RegisterClassA(&wcA);  
2000   assert(bResult);
2001 }
2002 /******************************************************************
2003  *        CreateTextServices (RICHED20.4)
2004  *
2005  * FIXME should be ITextHost instead of void*
2006  */
2007 HRESULT WINAPI CreateTextServices(IUnknown *punkOuter, void *pITextHost,
2008     IUnknown **ppUnk)
2009 {
2010   FIXME("stub\n");
2011   /* FIXME should support aggregation */
2012   if (punkOuter)
2013     return CLASS_E_NOAGGREGATION;
2014     
2015   return E_FAIL; /* E_NOTIMPL isn't allowed by MSDN */
2016 }
2017
2018 /******************************************************************
2019  *        REExtendedRegisterClass (RICHED20.8)
2020  *
2021  * FIXME undocumented
2022  */
2023 void WINAPI REExtendedRegisterClass(void)
2024 {
2025   FIXME("stub\n");
2026 }