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