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