dbghelp: Brought dbghelp.h a bit closer to PSDK definitions.
[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_Repaint(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     else
609     {
610       /* FIXME where to put cursor now ? */
611     }
612   }
613   
614   editor->nUndoMode = nUndoMode;
615   pUI = ME_AddUndoItem(editor, diUndoDeleteRun, NULL);
616   TRACE("from %d to %d\n", from, to);
617   if (pUI && from < to)
618   {
619     pUI->nStart = from;
620     pUI->nLen = to-from;
621   }
622   ME_CommitUndo(editor);
623   ME_ReleaseStyle(style); 
624   editor->nEventMask = nEventMask;
625   if (editor->bRedraw)
626   {
627     ME_UpdateRepaint(editor);
628   }
629   if (!(format & SFF_SELECTION)) {
630     ME_ClearTempStyle(editor);
631   }
632   ME_MoveCaret(editor);
633   ME_SendSelChange(editor);
634   ME_SendRequestResize(editor, FALSE);
635
636   return 0;
637 }
638
639
640 ME_DisplayItem *
641 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
642 {
643   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
644   
645   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
646     item = ME_FindItemFwd(item, diParagraph);
647
648   if (!item)
649     return item;
650
651   nOffset -= item->member.para.nCharOfs;
652   if (nItemType == diParagraph) {
653     if (nItemOffset)
654       *nItemOffset = nOffset;
655     return item;
656   }
657   
658   do {
659     item = ME_FindItemFwd(item, diRun);
660   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
661   if (item) {
662     nOffset -= item->member.run.nCharOfs;
663     if (nItemOffset)
664       *nItemOffset = nOffset;
665   }
666   return item;
667 }
668
669
670 static int
671 ME_FindText(ME_TextEditor *editor, DWORD flags, CHARRANGE *chrg, WCHAR *text, CHARRANGE *chrgText)
672 {
673   int nStart, nEnd;
674   int nLen = lstrlenW(text);
675   int nMin, nMax;
676   ME_DisplayItem *item;
677   ME_DisplayItem *para;
678
679   TRACE("flags==0x%08lx, chrg->cpMin==%ld, chrg->cpMax==%ld text==%s\n",
680         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
681   
682   if (!(flags & FR_MATCHCASE))
683     FIXME("Case-insensitive search not implemented\n");
684   if (flags & ~(FR_DOWN | FR_MATCHCASE))
685     FIXME("Flags 0x%08lx not implemented\n", flags & ~(FR_DOWN | FR_MATCHCASE));
686
687   if (chrg->cpMax == -1)
688   {
689     nMin = chrg->cpMin;
690     nMax = ME_GetTextLength(editor);
691   }
692   else
693   {
694     nMin = min(chrg->cpMin, chrg->cpMax);
695     nMax = max(chrg->cpMin, chrg->cpMax);
696   }
697   
698   if (!nLen)
699   {
700     if (chrgText)
701       chrgText->cpMin = chrgText->cpMax = ((flags & FR_DOWN) ? nMin : nMax);
702     return chrgText->cpMin;
703   }
704  
705   if (flags & FR_DOWN) /* Forward search */
706   {
707     nStart = nMin;
708     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
709     if (!item)
710       return -1;
711
712     para = ME_GetParagraph(item);
713     while (item
714            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen < nMax)
715     {
716       ME_DisplayItem *pCurItem = item;
717       int nCurStart = nStart;
718       int nMatched = 0;
719     
720       while (pCurItem && pCurItem->member.run.strText->szData[nCurStart + nMatched] == text[nMatched])
721       {
722         nMatched++;
723         if (nMatched == nLen)
724         {
725           nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
726           if (chrgText)
727           {
728             chrgText->cpMin = nStart;
729             chrgText->cpMax = nStart + nLen;
730           }
731           TRACE("found at %d-%d\n", nStart, nStart + nLen);
732           return nStart;
733         }
734         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
735         {
736           pCurItem = ME_FindItemFwd(pCurItem, diRun);
737           para = ME_GetParagraph(pCurItem);
738           nCurStart = -nMatched;
739         }
740       }
741       nStart++;
742       if (nStart == ME_StrLen(item->member.run.strText))
743       {
744         item = ME_FindItemFwd(item, diRun);
745         para = ME_GetParagraph(item);
746         nStart = 0;
747       }
748     }
749   }
750   else /* Backward search */
751   {
752     nEnd = nMax;
753     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
754     if (!item)
755       return -1;
756     
757     para = ME_GetParagraph(item);
758     
759     while (item
760            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
761     {
762       ME_DisplayItem *pCurItem = item;
763       int nCurEnd = nEnd;
764       int nMatched = 0;
765       
766       while (pCurItem && pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1] == text[nLen - nMatched - 1])
767       {
768         nMatched++;
769         if (nMatched == nLen)
770         {
771           nStart = para->member.para.nCharOfs + item->member.run.nCharOfs + nCurEnd - nMatched;
772           if (chrgText)
773           {
774             chrgText->cpMin = nStart;
775             chrgText->cpMax = nStart + nLen;
776           }
777           TRACE("found at %d-%d\n", nStart, nStart + nLen);
778           return nStart;
779         }
780         if (nCurEnd - nMatched == 0)
781         {
782           pCurItem = ME_FindItemBack(pCurItem, diRun);
783           para = ME_GetParagraph(pCurItem);
784           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
785         }
786       }
787       nEnd--;
788       if (nEnd < 0)
789       {
790         item = ME_FindItemBack(item, diRun);
791         para = ME_GetParagraph(item);
792         nEnd = ME_StrLen(item->member.run.strText);
793       }
794     }
795   }
796   TRACE("not found\n");
797   return -1;
798 }
799
800
801 static BOOL
802 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
803 {
804   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
805   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
806   
807   switch (nKey)
808   {
809     case VK_LEFT:
810     case VK_RIGHT:
811     case VK_UP:
812     case VK_DOWN:
813     case VK_HOME:
814     case VK_END:
815     case VK_PRIOR:
816     case VK_NEXT:
817       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
818       return TRUE;
819     case VK_BACK:
820     case VK_DELETE:
821       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
822       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
823         return FALSE;
824       if (ME_IsSelection(editor))
825         ME_DeleteSelection(editor);
826       else if (nKey == VK_DELETE || ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
827         ME_DeleteTextAtCursor(editor, 1, 1);
828       else
829         return TRUE;
830       ME_QueueInvalidateFromCursor(editor, 1);
831       ME_UpdateRepaint(editor);
832       ME_SendRequestResize(editor, FALSE);
833       return TRUE;
834
835     default:
836       if (ctrl_is_down)
837       {
838         if (nKey == 'W')
839         {
840           CHARFORMAT2W chf;
841           char buf[2048];
842           
843           ME_GetSelectionCharFormat(editor, &chf);
844           ME_DumpStyleToBuf(&chf, buf);
845           MessageBoxA(NULL, buf, "Style dump", MB_OK);
846         }
847         if (nKey == 'Q')
848         {
849           ME_CheckCharOffsets(editor);
850         }
851       }
852   }
853   return FALSE;
854 }
855
856
857 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
858   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
859   HDC hDC;
860   int i;
861   ed->hWnd = hWnd;
862   ed->bEmulateVersion10 = FALSE;
863   ed->pBuffer = ME_MakeText();
864   hDC = GetDC(hWnd);
865   ME_MakeFirstParagraph(hDC, ed->pBuffer);
866   ReleaseDC(hWnd, hDC);
867   ed->bCaretShown = FALSE;
868   ed->nCursors = 3;
869   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
870   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
871   ed->pCursors[0].nOffset = 0;
872   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
873   ed->pCursors[1].nOffset = 0;
874   ed->nLastTotalLength = ed->nTotalLength = 0;
875   ed->nUDArrowX = -1;
876   ed->nSequence = 0;
877   ed->rgbBackColor = -1;
878   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
879   ed->bCaretAtEnd = FALSE;
880   ed->nEventMask = 0;
881   ed->nModifyStep = 0;
882   ed->pUndoStack = ed->pRedoStack = NULL;
883   ed->nUndoMode = umAddToUndo;
884   ed->nParagraphs = 1;
885   ed->nLastSelStart = ed->nLastSelEnd = 0;
886   ed->nScrollPosY = 0;
887   ed->nZoomNumerator = ed->nZoomDenominator = 0;
888   ed->bRedraw = TRUE;
889   ed->nInvalidOfs = -1;
890   ed->pfnWordBreak = NULL;
891   GetClientRect(hWnd, &ed->rcFormat);
892   for (i=0; i<HFONT_CACHE_SIZE; i++)
893   {
894     ed->pFontCache[i].nRefs = 0;
895     ed->pFontCache[i].nAge = 0;
896     ed->pFontCache[i].hFont = NULL;
897   }
898   ME_CheckCharOffsets(ed);
899   return ed;
900 }
901
902 typedef struct tagME_GlobalDestStruct
903 {
904   HGLOBAL hData;
905   int nLength;
906 } ME_GlobalDestStruct;
907
908 static DWORD CALLBACK ME_AppendToHGLOBAL(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
909 {
910   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
911   int nMaxSize;
912   BYTE *pDest;
913   
914   nMaxSize = GlobalSize(pData->hData);
915   if (pData->nLength+cb+1 >= cb)
916   {
917     /* round up to 2^17 */
918     int nNewSize = (((nMaxSize+cb+1)|0x1FFFF)+1) & 0xFFFE0000;
919     pData->hData = GlobalReAlloc(pData->hData, nNewSize, 0);
920   }
921   pDest = (BYTE *)GlobalLock(pData->hData);
922   memcpy(pDest + pData->nLength, lpBuff, cb);
923   pData->nLength += cb;
924   pDest[pData->nLength] = '\0';
925   GlobalUnlock(pData->hData);
926   *pcb = cb;
927   
928   return 0;
929 }
930
931 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
932 {
933   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
934   int i;
935   WORD *pSrc, *pDest;
936   
937   cb = cb >> 1;
938   pDest = (WORD *)lpBuff;
939   pSrc = (WORD *)GlobalLock(pData->hData);
940   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
941     pDest[i] = pSrc[pData->nLength+i];
942   }    
943   pData->nLength += i;
944   *pcb = 2*i;
945   GlobalUnlock(pData->hData);
946   return 0;
947 }
948
949 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
950 {
951   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
952   int i;
953   BYTE *pSrc, *pDest;
954   
955   pDest = lpBuff;
956   pSrc = (BYTE *)GlobalLock(pData->hData);
957   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
958     pDest[i] = pSrc[pData->nLength+i];
959   }    
960   pData->nLength += i;
961   *pcb = i;
962   GlobalUnlock(pData->hData);
963   return 0;
964 }
965
966
967 void ME_DestroyEditor(ME_TextEditor *editor)
968 {
969   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
970   ME_DisplayItem *p = pFirst, *pNext = NULL;
971   int i;
972   
973   ME_ClearTempStyle(editor);
974   ME_EmptyUndoStack(editor);
975   while(p) {
976     pNext = p->next;
977     ME_DestroyDisplayItem(p);    
978     p = pNext;
979   }
980   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
981   for (i=0; i<HFONT_CACHE_SIZE; i++)
982   {
983     if (editor->pFontCache[i].hFont)
984       DeleteObject(editor->pFontCache[i].hFont);
985   }
986   DeleteObject(editor->hbrBackground);
987
988   FREE_OBJ(editor);
989 }
990
991 static WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
992 static WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
993 static WCHAR wszClassNameListBox[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
994 static WCHAR wszClassNameComboBox[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
995
996 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
997 {
998     TRACE("\n");
999     switch (fdwReason)
1000     {
1001     case DLL_PROCESS_ATTACH:
1002       DisableThreadLibraryCalls(hinstDLL);
1003       me_heap = HeapCreate (0, 0x10000, 0);
1004       ME_RegisterEditorClass(hinstDLL);
1005       break;
1006
1007     case DLL_PROCESS_DETACH:
1008       UnregisterClassW(wszClassName, 0);
1009       UnregisterClassW(wszClassName50, 0);
1010       UnregisterClassA("RichEdit20A", 0);
1011       UnregisterClassA("RichEdit50A", 0);
1012       if (ME_ListBoxRegistered)
1013           UnregisterClassW(wszClassNameListBox, 0);
1014       if (ME_ComboBoxRegistered)
1015           UnregisterClassW(wszClassNameComboBox, 0);
1016       HeapDestroy (me_heap);
1017       me_heap = NULL;
1018       break;
1019     }
1020     return TRUE;
1021 }
1022
1023
1024 #define UNSUPPORTED_MSG(e) \
1025   case e: \
1026     FIXME(#e ": stub\n"); \
1027     return DefWindowProcW(hWnd, msg, wParam, lParam);
1028
1029 static const char * const edit_messages[] = {
1030   "EM_GETSEL",
1031   "EM_SETSEL",
1032   "EM_GETRECT",
1033   "EM_SETRECT",
1034   "EM_SETRECTNP",
1035   "EM_SCROLL",
1036   "EM_LINESCROLL",
1037   "EM_SCROLLCARET",
1038   "EM_GETMODIFY",
1039   "EM_SETMODIFY",
1040   "EM_GETLINECOUNT",
1041   "EM_LINEINDEX",
1042   "EM_SETHANDLE",
1043   "EM_GETHANDLE",
1044   "EM_GETTHUMB",
1045   "EM_UNKNOWN_BF",
1046   "EM_UNKNOWN_C0",
1047   "EM_LINELENGTH",
1048   "EM_REPLACESEL",
1049   "EM_UNKNOWN_C3",
1050   "EM_GETLINE",
1051   "EM_LIMITTEXT",
1052   "EM_CANUNDO",
1053   "EM_UNDO",
1054   "EM_FMTLINES",
1055   "EM_LINEFROMCHAR",
1056   "EM_UNKNOWN_CA",
1057   "EM_SETTABSTOPS",
1058   "EM_SETPASSWORDCHAR",
1059   "EM_EMPTYUNDOBUFFER",
1060   "EM_GETFIRSTVISIBLELINE",
1061   "EM_SETREADONLY",
1062   "EM_SETWORDBREAKPROC",
1063   "EM_GETWORDBREAKPROC",
1064   "EM_GETPASSWORDCHAR",
1065   "EM_SETMARGINS",
1066   "EM_GETMARGINS",
1067   "EM_GETLIMITTEXT",
1068   "EM_POSFROMCHAR",
1069   "EM_CHARFROMPOS"
1070 };
1071
1072 static const char * const richedit_messages[] = {
1073   "EM_CANPASTE",
1074   "EM_DISPLAYBAND",
1075   "EM_EXGETSEL",
1076   "EM_EXLIMITTEXT",
1077   "EM_EXLINEFROMCHAR",
1078   "EM_EXSETSEL",
1079   "EM_FINDTEXT",
1080   "EM_FORMATRANGE",
1081   "EM_GETCHARFORMAT",
1082   "EM_GETEVENTMASK",
1083   "EM_GETOLEINTERFACE",
1084   "EM_GETPARAFORMAT",
1085   "EM_GETSELTEXT",
1086   "EM_HIDESELECTION",
1087   "EM_PASTESPECIAL",
1088   "EM_REQUESTRESIZE",
1089   "EM_SELECTIONTYPE",
1090   "EM_SETBKGNDCOLOR",
1091   "EM_SETCHARFORMAT",
1092   "EM_SETEVENTMASK",
1093   "EM_SETOLECALLBACK",
1094   "EM_SETPARAFORMAT",
1095   "EM_SETTARGETDEVICE",
1096   "EM_STREAMIN",
1097   "EM_STREAMOUT",
1098   "EM_GETTEXTRANGE",
1099   "EM_FINDWORDBREAK",
1100   "EM_SETOPTIONS",
1101   "EM_GETOPTIONS",
1102   "EM_FINDTEXTEX",
1103   "EM_GETWORDBREAKPROCEX",
1104   "EM_SETWORDBREAKPROCEX",
1105   "EM_SETUNDOLIMIT",
1106   "EM_UNKNOWN_USER_83",
1107   "EM_REDO",
1108   "EM_CANREDO",
1109   "EM_GETUNDONAME",
1110   "EM_GETREDONAME",
1111   "EM_STOPGROUPTYPING",
1112   "EM_SETTEXTMODE",
1113   "EM_GETTEXTMODE",
1114   "EM_AUTOURLDETECT",
1115   "EM_GETAUTOURLDETECT",
1116   "EM_SETPALETTE",
1117   "EM_GETTEXTEX",
1118   "EM_GETTEXTLENGTHEX",
1119   "EM_SHOWSCROLLBAR",
1120   "EM_SETTEXTEX",
1121   "EM_UNKNOWN_USER_98",
1122   "EM_UNKNOWN_USER_99",
1123   "EM_SETPUNCTUATION",
1124   "EM_GETPUNCTUATION",
1125   "EM_SETWORDWRAPMODE",
1126   "EM_GETWORDWRAPMODE",
1127   "EM_SETIMECOLOR",
1128   "EM_GETIMECOLOR",
1129   "EM_SETIMEOPTIONS",
1130   "EM_GETIMEOPTIONS",
1131   "EM_CONVPOSITION",
1132   "EM_UNKNOWN_USER_109",
1133   "EM_UNKNOWN_USER_110",
1134   "EM_UNKNOWN_USER_111",
1135   "EM_UNKNOWN_USER_112",
1136   "EM_UNKNOWN_USER_113",
1137   "EM_UNKNOWN_USER_114",
1138   "EM_UNKNOWN_USER_115",
1139   "EM_UNKNOWN_USER_116",
1140   "EM_UNKNOWN_USER_117",
1141   "EM_UNKNOWN_USER_118",
1142   "EM_UNKNOWN_USER_119",
1143   "EM_SETLANGOPTIONS",
1144   "EM_GETLANGOPTIONS",
1145   "EM_GETIMECOMPMODE",
1146   "EM_FINDTEXTW",
1147   "EM_FINDTEXTEXW",
1148   "EM_RECONVERSION",
1149   "EM_SETIMEMODEBIAS",
1150   "EM_GETIMEMODEBIAS"
1151 };
1152
1153 static const char *
1154 get_msg_name(UINT msg)
1155 {
1156   if (msg >= EM_GETSEL && msg <= EM_SETLIMITTEXT)
1157     return edit_messages[msg - EM_GETSEL];
1158   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1159     return richedit_messages[msg - EM_CANPASTE];
1160   return "";
1161 }
1162
1163 /******************************************************************
1164  *        RichEditANSIWndProc (RICHED20.10)
1165  */
1166 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
1167   SCROLLINFO si;
1168   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
1169   
1170   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
1171         hWnd, msg, get_msg_name(msg), wParam, lParam);
1172   
1173   switch(msg) {
1174   
1175   UNSUPPORTED_MSG(EM_AUTOURLDETECT)
1176   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1177   UNSUPPORTED_MSG(EM_EXLIMITTEXT)
1178   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1179   UNSUPPORTED_MSG(EM_FMTLINES)
1180   UNSUPPORTED_MSG(EM_FORMATRANGE)
1181   UNSUPPORTED_MSG(EM_GETAUTOURLDETECT)
1182   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1183   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1184   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1185   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1186   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1187   UNSUPPORTED_MSG(EM_GETLIMITTEXT)
1188   UNSUPPORTED_MSG(EM_GETLINE)
1189   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1190   UNSUPPORTED_MSG(EM_GETOPTIONS)
1191   UNSUPPORTED_MSG(EM_GETPASSWORDCHAR)
1192   UNSUPPORTED_MSG(EM_GETREDONAME)
1193   UNSUPPORTED_MSG(EM_GETSCROLLPOS)
1194   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1195   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1196   UNSUPPORTED_MSG(EM_GETUNDONAME)
1197   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1198   UNSUPPORTED_MSG(EM_HIDESELECTION)
1199   UNSUPPORTED_MSG(EM_LIMITTEXT) /* also known as EM_SETLIMITTEXT */
1200   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1201   UNSUPPORTED_MSG(EM_SCROLL)
1202   UNSUPPORTED_MSG(EM_SCROLLCARET)
1203   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1204   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1205   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1206   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1207   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1208   UNSUPPORTED_MSG(EM_SETOLECALLBACK)
1209   UNSUPPORTED_MSG(EM_SETOPTIONS)
1210   UNSUPPORTED_MSG(EM_SETPALETTE)
1211   UNSUPPORTED_MSG(EM_SETPASSWORDCHAR)
1212   UNSUPPORTED_MSG(EM_SETSCROLLPOS)
1213   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1214   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1215   UNSUPPORTED_MSG(EM_SETTEXTMODE)
1216   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1217   UNSUPPORTED_MSG(EM_SETUNDOLIMIT)
1218   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1219   UNSUPPORTED_MSG(EM_SHOWSCROLLBAR)
1220   UNSUPPORTED_MSG(WM_SETFONT)
1221   UNSUPPORTED_MSG(WM_STYLECHANGING)
1222   UNSUPPORTED_MSG(WM_STYLECHANGED)
1223 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1224     
1225 /* Messages specific to Richedit controls */
1226   
1227   case EM_STREAMIN:
1228    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1229   case EM_STREAMOUT:
1230    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1231   case WM_GETDLGCODE:
1232   {
1233     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1234     if (GetWindowLongW(hWnd, GWL_STYLE)&ES_WANTRETURN)
1235       code |= 0; /* FIXME what can we do here ? ask for messages and censor them ? */
1236     return code;
1237   }
1238   case WM_NCCREATE:
1239   {
1240     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1241     TRACE("WM_NCCREATE: style 0x%08lx\n", pcs->style);
1242     editor = ME_MakeEditor(hWnd);
1243     SetWindowLongW(hWnd, 0, (long)editor);
1244     pcs = 0; /* ignore */
1245     return TRUE;
1246   }
1247   case EM_EMPTYUNDOBUFFER:
1248     ME_EmptyUndoStack(editor);
1249     return 0;
1250   case EM_GETSEL:
1251   {
1252     /* Note: wParam/lParam can be NULL */
1253     UINT from, to;
1254     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1255     PUINT pto = lParam ? (PUINT)lParam : &to;
1256     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1257     if ((*pfrom|*pto) & 0xFFFF0000)
1258       return -1;
1259     return MAKELONG(*pfrom,*pto);
1260   }
1261   case EM_EXGETSEL:
1262   {
1263     CHARRANGE *pRange = (CHARRANGE *)lParam;
1264     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1265     TRACE("EM_EXGETSEL = (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1266     return 0;
1267   }
1268   case EM_CANUNDO:
1269     return editor->pUndoStack != NULL;
1270   case EM_CANREDO:
1271     return editor->pRedoStack != NULL;
1272   case WM_UNDO: /* FIXME: actually not the same */
1273   case EM_UNDO:
1274     ME_Undo(editor);
1275     return 0;
1276   case EM_REDO:
1277     ME_Redo(editor);
1278     return 0;
1279   case EM_SETSEL:
1280   {
1281     ME_SetSelection(editor, wParam, lParam);
1282     ME_Repaint(editor);
1283     ME_SendSelChange(editor);
1284     return 0;
1285   }
1286   case EM_EXSETSEL:
1287   {
1288     CHARRANGE *pRange = (CHARRANGE *)lParam;
1289     TRACE("EM_EXSETSEL (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1290     ME_SetSelection(editor, pRange->cpMin, pRange->cpMax);
1291     /* FIXME optimize */
1292     ME_Repaint(editor);
1293     ME_SendSelChange(editor);
1294     return 0;
1295   }
1296   case EM_SETTEXTEX:
1297   {
1298     LPWSTR wszText = (LPWSTR)lParam;
1299     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1300     size_t len = lstrlenW(wszText);
1301     int from, to;
1302     ME_Style *style;
1303     TRACE("EM_SETTEXEX - %s, flags %d, cp %d\n", debugstr_w(wszText), (int)pStruct->flags, pStruct->codepage);
1304     if (pStruct->codepage != 1200) {
1305       FIXME("EM_SETTEXTEX only supports unicode right now!\n"); 
1306       return 0;
1307     }
1308     /* FIXME: this should support RTF strings too, according to MSDN */
1309     if (pStruct->flags & ST_SELECTION) {
1310       ME_GetSelection(editor, &from, &to);
1311       style = ME_GetSelectionInsertStyle(editor);
1312       ME_InternalDeleteText(editor, from, to - from);
1313       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1314       ME_ReleaseStyle(style);
1315     }
1316     else {
1317       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1318       ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1319       len = 1;
1320     }
1321     ME_CommitUndo(editor);
1322     if (!(pStruct->flags & ST_KEEPUNDO))
1323       ME_EmptyUndoStack(editor);
1324     ME_UpdateRepaint(editor);
1325     return len;
1326   }
1327   case EM_SETBKGNDCOLOR:
1328   {
1329     LRESULT lColor = ME_GetBackColor(editor);
1330     if (editor->rgbBackColor != -1)
1331       DeleteObject(editor->hbrBackground);
1332     if (wParam)
1333     {
1334       editor->rgbBackColor = -1;
1335       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1336     }
1337     else
1338     {
1339       editor->rgbBackColor = lParam;
1340       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
1341     }
1342     if (editor->bRedraw)
1343     {
1344       InvalidateRect(hWnd, NULL, TRUE);
1345       UpdateWindow(hWnd);
1346     }
1347     return lColor;
1348   }
1349   case EM_GETMODIFY:
1350     return editor->nModifyStep == 0 ? 0 : 1;
1351   case EM_SETMODIFY:
1352   {
1353     if (wParam)
1354       editor->nModifyStep = 0x80000000;
1355     else
1356       editor->nModifyStep = 0;
1357     
1358     return 0;
1359   }
1360   case EM_SETREADONLY:
1361   {
1362     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1363     if (wParam)
1364       nStyle |= ES_READONLY;
1365     else
1366       nStyle &= ~ES_READONLY;
1367     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1368     ME_Repaint(editor);
1369     return 0;
1370   }
1371   case EM_SETEVENTMASK:
1372   {
1373     DWORD nOldMask = editor->nEventMask;
1374     
1375     editor->nEventMask = lParam;
1376     return nOldMask;
1377   }
1378   case EM_GETEVENTMASK:
1379     return editor->nEventMask;
1380   case EM_SETCHARFORMAT:
1381   {
1382     CHARFORMAT2W buf, *p;
1383     BOOL bRepaint = TRUE;
1384     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1385     if (!wParam)
1386       ME_SetDefaultCharFormat(editor, p);
1387     else if (wParam == (SCF_WORD | SCF_SELECTION))
1388       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1389     else if (wParam == SCF_ALL)
1390       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1391     else {
1392       int from, to;
1393       ME_GetSelection(editor, &from, &to);
1394       bRepaint = (from != to);
1395       ME_SetSelectionCharFormat(editor, p);
1396     }
1397     ME_CommitUndo(editor);
1398     if (bRepaint)
1399       ME_UpdateRepaint(editor);
1400     return 0;
1401   }
1402   case EM_GETCHARFORMAT:
1403   {
1404     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1405     if (dst->cbSize != sizeof(CHARFORMATA) &&
1406         dst->cbSize != sizeof(CHARFORMATW) &&
1407         dst->cbSize != sizeof(CHARFORMAT2A) &&
1408         dst->cbSize != sizeof(CHARFORMAT2W))
1409       return 0;
1410     tmp.cbSize = sizeof(tmp);
1411     if (!wParam)
1412       ME_GetDefaultCharFormat(editor, &tmp);
1413     else
1414       ME_GetSelectionCharFormat(editor, &tmp);
1415     ME_CopyToCFAny(dst, &tmp);
1416     return tmp.dwMask;
1417   }
1418   case EM_SETPARAFORMAT:
1419     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1420     ME_UpdateRepaint(editor);
1421     ME_CommitUndo(editor);
1422     return 0;
1423   case EM_GETPARAFORMAT:
1424     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1425     return 0;
1426   case EM_GETFIRSTVISIBLELINE:
1427   {
1428     ME_DisplayItem *p = editor->pBuffer->pFirst;
1429     int y = editor->nScrollPosY;
1430     int ypara = 0;
1431     int count = 0;
1432     int ystart, yend;
1433     while(p) {
1434       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
1435       if (p->type == diTextEnd)
1436         break;
1437       if (p->type == diParagraph) {
1438         ypara = p->member.para.nYPos;
1439         continue;
1440       }
1441       ystart = ypara + p->member.row.nYPos;
1442       yend = ystart + p->member.row.nHeight;
1443       if (y < yend) {
1444         break;
1445       }
1446       count++;
1447     }
1448     return count;
1449   }
1450   case EM_LINESCROLL:
1451   {
1452     int nPos = editor->nScrollPosY, nEnd= editor->nTotalLength - editor->sizeWindow.cy;
1453     nPos += 8 * lParam; /* FIXME follow the original */
1454     if (nPos>=nEnd)
1455       nPos = nEnd;
1456     if (nPos<0)
1457       nPos = 0;
1458     if (nPos != editor->nScrollPosY) {
1459       int dy = editor->nScrollPosY - nPos;
1460       editor->nScrollPosY = nPos;
1461       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1462       if (editor->bRedraw)
1463       {
1464         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1465         UpdateWindow(hWnd);
1466       }
1467     }
1468     return TRUE; /* Should return false if a single line richedit control */
1469   }
1470   case WM_CLEAR:
1471   {
1472     int from, to;
1473     ME_GetSelection(editor, &from, &to);
1474     ME_InternalDeleteText(editor, from, to-from);
1475     ME_CommitUndo(editor);
1476     ME_UpdateRepaint(editor);
1477     return 0;
1478   }
1479   case EM_REPLACESEL:
1480   {
1481     int from, to;
1482     ME_Style *style;
1483     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1484     size_t len = lstrlenW(wszText);
1485     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1486     
1487     ME_GetSelection(editor, &from, &to);
1488     style = ME_GetSelectionInsertStyle(editor);
1489     ME_InternalDeleteText(editor, from, to-from);
1490     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1491     ME_ReleaseStyle(style);
1492     ME_EndToUnicode(hWnd, wszText);
1493     /* drop temporary style if line end */
1494     /* FIXME question: does abc\n mean: put abc, clear temp style, put \n? (would require a change) */  
1495     if (len>0 && wszText[len-1] == '\n')
1496       ME_ClearTempStyle(editor);
1497       
1498     ME_CommitUndo(editor);
1499     if (!wParam)
1500       ME_EmptyUndoStack(editor);
1501     ME_UpdateRepaint(editor);
1502     return 0;
1503   }
1504   case WM_SETTEXT:
1505   {
1506     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1507     if (lParam)
1508     {
1509       LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1510       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1511       TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1512       if (lstrlenW(wszText) > 0)
1513       {
1514         /* uses default style! */
1515         ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1516       }
1517       ME_EndToUnicode(hWnd, wszText);
1518     }
1519     else
1520       TRACE("WM_SETTEXT - NULL\n");
1521     ME_CommitUndo(editor);
1522     ME_EmptyUndoStack(editor);
1523     ME_SetSelection(editor, 0, 0);
1524     ME_UpdateRepaint(editor);
1525     return 0;
1526   }
1527   case EM_CANPASTE:
1528   {
1529     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1530     if (IsClipboardFormatAvailable(nRTFFormat))
1531       return TRUE;
1532     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1533       return TRUE;
1534     return FALSE;
1535   }
1536   case WM_PASTE:
1537   {    
1538     DWORD dwFormat = 0;
1539     EDITSTREAM es;
1540     ME_GlobalDestStruct gds;
1541     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1542     UINT cf = 0;
1543
1544     if (IsClipboardFormatAvailable(nRTFFormat))
1545       cf = nRTFFormat, dwFormat = SF_RTF;
1546     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1547       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1548     else
1549       return 0;
1550
1551     if (!OpenClipboard(hWnd))
1552       return 0;
1553     gds.hData = GetClipboardData(cf);
1554     gds.nLength = 0;
1555     es.dwCookie = (DWORD)&gds;
1556     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1557     SendMessageW(hWnd, EM_STREAMIN, dwFormat|SFF_SELECTION, (LPARAM)&es);
1558     
1559     CloseClipboard();
1560     return 0;
1561   }
1562   case WM_CUT:
1563   case WM_COPY:
1564   {
1565     int from, to, pars;
1566     WCHAR *data;
1567     HANDLE hData;
1568     EDITSTREAM es;
1569     ME_GlobalDestStruct gds;
1570     
1571     if (!OpenClipboard(hWnd))
1572       return 0;
1573       
1574     EmptyClipboard();
1575     ME_GetSelection(editor, &from, &to);
1576     pars = ME_CountParagraphsBetween(editor, from, to);
1577     hData = GlobalAlloc(GMEM_MOVEABLE, sizeof(WCHAR)*(to-from+pars+1));
1578     data = (WCHAR *)GlobalLock(hData);
1579     ME_GetTextW(editor, data, from, to-from, TRUE);
1580     GlobalUnlock(hData);
1581
1582     gds.hData = GlobalAlloc(GMEM_MOVEABLE, 0);
1583     gds.nLength = 0;
1584     es.dwCookie = (DWORD)&gds;
1585     es.pfnCallback = ME_AppendToHGLOBAL;
1586     SendMessageW(hWnd, EM_STREAMOUT, SFF_SELECTION|SF_RTF, (LPARAM)&es);
1587     GlobalReAlloc(gds.hData, gds.nLength+1, 0);
1588     
1589     SetClipboardData(CF_UNICODETEXT, hData);    
1590     SetClipboardData(RegisterClipboardFormatA("Rich Text Format"), gds.hData);
1591     
1592     CloseClipboard();
1593     if (msg == WM_CUT)
1594     {
1595       ME_InternalDeleteText(editor, from, to-from);
1596       ME_CommitUndo(editor);
1597       ME_UpdateRepaint(editor);
1598     }
1599     return 0;
1600   }
1601   case WM_GETTEXTLENGTH:
1602     return ME_GetTextLength(editor);
1603   case EM_GETTEXTLENGTHEX:
1604     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
1605   case WM_GETTEXT:
1606   {
1607     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1608     tr.chrg.cpMin = 0;
1609     tr.chrg.cpMax = wParam-1;
1610     tr.lpstrText = (WCHAR *)lParam;
1611     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1612   }
1613   case EM_GETTEXTEX:
1614   {
1615     GETTEXTEX *ex = (GETTEXTEX*)wParam;
1616     int nStart, nCount;
1617
1618     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1619       FIXME("GETTEXTEX flags 0x%08lx not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1620
1621     if (ex->flags & GT_SELECTION)
1622     {
1623       ME_GetSelection(editor, &nStart, &nCount);
1624       nCount -= nStart;
1625       nCount = min(nCount, ex->cb - 1);
1626     }
1627     else
1628     {
1629       nStart = 0;
1630       nCount = ex->cb - 1;
1631     }
1632     if (ex->codepage == 1200 || IsWindowUnicode(hWnd))
1633     {
1634       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
1635       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
1636     }
1637     else
1638     {
1639       /* potentially each char may be a CR, why calculate the exact value with O(N) when
1640         we can just take a bigger buffer? :) */
1641       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1642       LPWSTR buffer = HeapAlloc(GetProcessHeap(), 0, (crlfmul*nCount + 1) * sizeof(WCHAR));
1643       DWORD buflen = ex->cb;
1644       LRESULT rc;
1645       DWORD flags = 0;
1646
1647       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
1648       rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
1649
1650       HeapFree(GetProcessHeap(),0,buffer);
1651       return rc;
1652     }
1653   }
1654   case EM_GETSELTEXT:
1655   {
1656     int from, to;
1657     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1658     ME_GetSelection(editor, &from, &to);
1659     tr.chrg.cpMin = from;
1660     tr.chrg.cpMax = to;
1661     tr.lpstrText = (WCHAR *)lParam;
1662     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1663   }
1664   case EM_GETTEXTRANGE:
1665   {
1666     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
1667     TRACE("EM_GETTEXTRANGE min=%ld max=%ld unicode=%d emul1.0=%d length=%d\n",
1668       rng->chrg.cpMin, rng->chrg.cpMax, IsWindowUnicode(hWnd), 
1669       editor->bEmulateVersion10, ME_GetTextLength(editor));
1670     if (IsWindowUnicode(hWnd))
1671       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
1672     else
1673     {
1674       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
1675       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1676       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
1677       /* FIXME this is a potential security hole (buffer overrun) 
1678          if you know more about wchar->mbyte conversion please explain
1679       */
1680       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
1681       FREE_OBJ(p);
1682       return nChars;
1683     }
1684   }
1685   case EM_GETLINECOUNT:
1686   {
1687     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
1688     int nRows = 0;
1689
1690     while (item != editor->pBuffer->pLast)
1691     {
1692       assert(item->type == diParagraph);
1693       nRows += item->member.para.nRows;
1694       item = item->member.para.next_para;
1695     }
1696     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
1697     return max(1, nRows);
1698   }
1699   case EM_LINEFROMCHAR:
1700   {
1701     if (wParam == -1)
1702       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
1703     else
1704       return ME_RowNumberFromCharOfs(editor, wParam);
1705   }
1706   case EM_EXLINEFROMCHAR:
1707   {
1708     return ME_RowNumberFromCharOfs(editor, lParam);
1709   }
1710   case EM_LINEINDEX:
1711   {
1712     ME_DisplayItem *item, *para;
1713     int nCharOfs;
1714     
1715     if (wParam == -1)
1716       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
1717     else
1718       item = ME_FindRowWithNumber(editor, wParam);
1719     if (!item)
1720       return -1;
1721     para = ME_GetParagraph(item);
1722     item = ME_FindItemFwd(item, diRun);
1723     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
1724     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
1725     return nCharOfs;
1726   }
1727   case EM_LINELENGTH:
1728   {
1729     ME_DisplayItem *item, *item_end;
1730     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
1731     
1732     if (wParam > ME_GetTextLength(editor))
1733       return 0;
1734     if (wParam == -1)
1735     {
1736       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
1737       return 0;
1738     }
1739     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
1740     item = ME_RowStart(item);
1741     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
1742     item_end = ME_FindItemFwd(item, diStartRow);
1743     if (item_end)
1744       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
1745     else
1746       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs
1747        - (editor->bEmulateVersion10?2:1);
1748     nChars = nNextLineOfs - nThisLineOfs;
1749     TRACE("EM_LINELENGTH(%d)==%d\n",wParam, nChars);
1750     return nChars;
1751   }
1752   case EM_FINDTEXT:
1753   {
1754     FINDTEXTA *ft = (FINDTEXTA *)lParam;
1755     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
1756     WCHAR *tmp;
1757     
1758     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1759       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
1760     return ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
1761   }
1762   case EM_FINDTEXTEX:
1763   {
1764     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
1765     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
1766     WCHAR *tmp;
1767     
1768     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1769       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
1770     return ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
1771   }
1772   case EM_FINDTEXTW:
1773   {
1774     FINDTEXTW *ft = (FINDTEXTW *)lParam;
1775     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
1776   }
1777   case EM_FINDTEXTEXW:
1778   {
1779     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
1780     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
1781   }
1782   case EM_GETZOOM:
1783     if (!wParam || !lParam)
1784       return FALSE;
1785     *(int *)wParam = editor->nZoomNumerator;
1786     *(int *)lParam = editor->nZoomDenominator;
1787     return TRUE;
1788   case EM_SETZOOM:
1789     return ME_SetZoom(editor, wParam, lParam);
1790   case EM_CHARFROMPOS:
1791     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
1792   case EM_POSFROMCHAR:
1793   {
1794     ME_DisplayItem *pRun;
1795     int nCharOfs, nOffset, nLength;
1796     POINTL pt = {0,0};
1797     
1798     nCharOfs = wParam; 
1799     /* detect which API version we're dealing with */
1800     if (wParam >= 0x40000)
1801         nCharOfs = lParam;
1802     nLength = ME_GetTextLength(editor);
1803     
1804     if (nCharOfs < nLength) { 
1805         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
1806         assert(pRun->type == diRun);
1807         pt.y = pRun->member.run.pt.y;
1808         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
1809         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
1810     } else {
1811         pt.x = 0;
1812         pt.y = editor->pBuffer->pLast->member.para.nYPos;
1813     }
1814     if (wParam >= 0x40000) {
1815         *(POINTL *)wParam = pt;
1816     }
1817     return MAKELONG( pt.x, pt.y );
1818   }
1819   case WM_CREATE:
1820     ME_CommitUndo(editor);
1821     ME_WrapMarkedParagraphs(editor);
1822     ME_MoveCaret(editor);
1823     return 0;
1824   case WM_DESTROY:
1825     ME_DestroyEditor(editor);
1826     SetWindowLongW(hWnd, 0, 0);
1827     return 0;
1828   case WM_LBUTTONDOWN:
1829     SetFocus(hWnd);
1830     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1831     SetCapture(hWnd);
1832     break;
1833   case WM_MOUSEMOVE:
1834     if (GetCapture() == hWnd)
1835       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1836     break;
1837   case WM_LBUTTONUP:
1838     if (GetCapture() == hWnd)
1839       ReleaseCapture();
1840     break;
1841   case WM_LBUTTONDBLCLK:
1842     ME_SelectWord(editor);
1843     break;
1844   case WM_PAINT:
1845     if (editor->bRedraw)
1846     {
1847       HDC hDC;
1848       PAINTSTRUCT ps;
1849
1850       hDC = BeginPaint(hWnd, &ps);
1851       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
1852       EndPaint(hWnd, &ps);
1853     }
1854     break;
1855   case WM_SETFOCUS:
1856     ME_ShowCaret(editor);
1857     ME_SendOldNotify(editor, EN_SETFOCUS);
1858     return 0;
1859   case WM_KILLFOCUS:
1860     ME_HideCaret(editor);
1861     ME_SendOldNotify(editor, EN_KILLFOCUS);
1862     return 0;
1863   case WM_ERASEBKGND:
1864   {
1865     if (editor->bRedraw)
1866     {
1867       HDC hDC = (HDC)wParam;
1868       RECT rc;
1869       if (GetUpdateRect(hWnd,&rc,TRUE))
1870       {
1871         FillRect(hDC, &rc, editor->hbrBackground);
1872       }
1873     }
1874     return 1;
1875   }
1876   case WM_COMMAND:
1877     TRACE("editor wnd command = %d\n", LOWORD(wParam));
1878     return 0;
1879   case WM_KEYDOWN:
1880     if (ME_KeyDown(editor, LOWORD(wParam)))
1881       return 0;
1882     goto do_default;
1883   case WM_CHAR: 
1884   {
1885     WCHAR wstr = LOWORD(wParam);
1886
1887     switch (wstr)
1888     {
1889     case 3: /* Ctrl-C */
1890       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
1891       return 0;
1892     }
1893     
1894     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
1895       MessageBeep(MB_ICONERROR);
1896       return 0; /* FIXME really 0 ? */
1897     }
1898
1899     switch (wstr)
1900     {
1901     case 1: /* Ctrl-A */
1902       ME_SetSelection(editor, 0, -1);
1903       return 0;
1904     case 22: /* Ctrl-V */
1905       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
1906       return 0;
1907     case 24: /* Ctrl-X */
1908       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
1909       return 0;
1910     case 25: /* Ctrl-Y */
1911       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
1912       return 0;
1913     case 26: /* Ctrl-Z */
1914       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
1915       return 0;
1916     }
1917     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
1918       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
1919       ME_Style *style = ME_GetInsertStyle(editor, 0);
1920       ME_SaveTempStyle(editor);
1921       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
1922       ME_ReleaseStyle(style);
1923       ME_CommitUndo(editor);
1924       ME_UpdateRepaint(editor);
1925     }
1926     return 0;
1927   }
1928   case WM_VSCROLL: 
1929   {
1930     int nPos = editor->nScrollPosY;
1931     si.cbSize = sizeof(SCROLLINFO);
1932     si.fMask = SIF_PAGE|SIF_POS|SIF_RANGE|SIF_TRACKPOS;
1933     GetScrollInfo(hWnd, SB_VERT, &si);
1934     switch(LOWORD(wParam)) {
1935     case SB_LINEUP:
1936       nPos -= 24; /* FIXME follow the original */
1937       if (nPos<0) nPos = 0;
1938       break;
1939     case SB_LINEDOWN:
1940     {
1941       int nEnd = editor->nTotalLength - editor->sizeWindow.cy;
1942       nPos += 24; /* FIXME follow the original */
1943       if (nPos>=nEnd) nPos = nEnd;
1944       break;
1945     }
1946     case SB_PAGEUP:
1947       nPos -= editor->sizeWindow.cy;
1948       if (nPos<0) nPos = 0;
1949       break;
1950     case SB_PAGEDOWN:
1951       nPos += editor->sizeWindow.cy;
1952       if (nPos>=editor->nTotalLength) nPos = editor->nTotalLength-1;
1953       break;
1954     case SB_THUMBTRACK:
1955     case SB_THUMBPOSITION:
1956       nPos = si.nTrackPos;
1957       break;
1958     }
1959     if (nPos != editor->nScrollPosY) {
1960       int dy = editor->nScrollPosY - nPos;
1961       editor->nScrollPosY = nPos;
1962       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1963       if (editor->bRedraw)
1964       {
1965         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1966         UpdateWindow(hWnd);
1967       }
1968     }
1969     break;
1970   }
1971   case WM_MOUSEWHEEL:
1972   {
1973     int gcWheelDelta = 0, nPos = editor->nScrollPosY, nEnd = editor->nTotalLength - editor->sizeWindow.cy; 
1974     UINT pulScrollLines;
1975     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
1976     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
1977     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
1978       nPos += pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8; /* FIXME follow the original */
1979     if (nPos>=nEnd)
1980       nPos = nEnd;
1981     if (nPos<0)
1982       nPos = 0;
1983     if (nPos != editor->nScrollPosY) {
1984       int dy = editor->nScrollPosY - nPos;
1985       editor->nScrollPosY = nPos;
1986       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1987       if (editor->bRedraw)
1988       {
1989         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1990         UpdateWindow(hWnd);
1991       }
1992     }
1993     break;
1994   }
1995   case EM_GETRECT:
1996   {
1997     *((RECT *)lParam) = editor->rcFormat;
1998     return 0;
1999   }
2000   case EM_SETRECT:
2001   case EM_SETRECTNP:
2002   {
2003     if (lParam)
2004     {
2005       RECT *rc = (RECT *)lParam;
2006       
2007       if (wParam)
2008       {
2009         editor->rcFormat.left += rc->left;
2010         editor->rcFormat.top += rc->top;
2011         editor->rcFormat.right += rc->right;
2012         editor->rcFormat.bottom += rc->bottom;
2013       }
2014       else
2015       {
2016         editor->rcFormat = *rc;
2017       }
2018     }
2019     else
2020     {
2021       GetClientRect(hWnd, &editor->rcFormat);
2022     }
2023     if (msg != EM_SETRECTNP)
2024       ME_RewrapRepaint(editor);
2025     return 0;
2026   }
2027   case EM_REQUESTRESIZE:
2028     ME_SendRequestResize(editor, TRUE);
2029     return 0;
2030   case WM_SETREDRAW:
2031     editor->bRedraw = wParam;
2032     return 0;
2033   case WM_SIZE:
2034   {
2035     GetClientRect(hWnd, &editor->rcFormat);
2036     ME_RewrapRepaint(editor);
2037     return DefWindowProcW(hWnd, msg, wParam, lParam);
2038   }
2039   case EM_GETOLEINTERFACE:
2040   {
2041     LPVOID *ppvObj = (LPVOID*) lParam;
2042     FIXME("EM_GETOLEINTERFACE %p: stub\n", ppvObj);
2043     return CreateIRichEditOle(ppvObj);
2044   }
2045   case EM_GETWORDBREAKPROC:
2046     return (LRESULT)editor->pfnWordBreak;
2047   case EM_SETWORDBREAKPROC:
2048   {
2049     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
2050
2051     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
2052     return (LRESULT)pfnOld;
2053   }
2054   default:
2055   do_default:
2056     return DefWindowProcW(hWnd, msg, wParam, lParam);
2057   }
2058   return 0L;
2059 }
2060
2061
2062 /******************************************************************
2063  *        RichEdit10ANSIWndProc (RICHED20.9)
2064  */
2065 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2066 {
2067   LRESULT result;
2068   
2069   /* FIXME: this is NOT the same as 2.0 version */
2070   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
2071   if (msg == WM_NCCREATE)
2072   {
2073     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
2074     
2075     editor->bEmulateVersion10 = TRUE;
2076     editor->pBuffer->pLast->member.para.nCharOfs = 2;
2077   }
2078   return result;
2079 }
2080
2081 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
2082 {
2083   HWND hWnd = editor->hWnd;
2084   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
2085 }
2086
2087 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
2088 {
2089   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
2090   int i = 0;
2091   
2092   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
2093     item = item->member.para.next_para;
2094   if (!item)
2095     return 0;
2096   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
2097     item = item->member.para.next_para;
2098     i++;
2099   }
2100   return i;
2101 }
2102
2103
2104 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
2105 {
2106   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
2107   int nWritten = 0;
2108   WCHAR *pStart = buffer;
2109   
2110   if (!item) {
2111     *buffer = L'\0';
2112     return 0;
2113   }
2114   
2115   if (nStart)
2116   {
2117     int nLen = ME_StrLen(item->member.run.strText) - nStart;
2118     if (nLen > nChars)
2119       nLen = nChars;
2120     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
2121     nChars -= nLen;
2122     nWritten += nLen;
2123     if (!nChars)
2124       return nWritten;
2125     buffer += nLen;
2126     nStart = 0;
2127     item = ME_FindItemFwd(item, diRun);
2128   }
2129   
2130   while(nChars && item)
2131   {
2132     int nLen = ME_StrLen(item->member.run.strText);
2133     if (nLen > nChars)
2134       nLen = nChars;
2135       
2136     if (item->member.run.nFlags & MERF_ENDPARA)
2137     {
2138       *buffer = '\r';
2139       if (bCRLF)
2140       {
2141         *(++buffer) = '\n';
2142         nWritten++;
2143       }
2144       assert(nLen == 1);
2145       /* our end paragraph consists of 2 characters now */
2146       if (editor->bEmulateVersion10)
2147         nChars--;
2148     }
2149     else      
2150       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2151     nChars -= nLen;
2152     nWritten += nLen;
2153     buffer += nLen;    
2154       
2155     if (!nChars)
2156     {
2157       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2158       *buffer = L'\0';
2159       return nWritten;
2160     }
2161     item = ME_FindItemFwd(item, diRun);
2162   }
2163   *buffer = L'\0';
2164   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2165   return nWritten;  
2166 }
2167
2168 void ME_RegisterEditorClass(HINSTANCE hInstance)
2169 {
2170   BOOL bResult;
2171   WNDCLASSW wcW;
2172   WNDCLASSA wcA;
2173   
2174   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2175   wcW.lpfnWndProc = RichEditANSIWndProc;
2176   wcW.cbClsExtra = 0;
2177   wcW.cbWndExtra = 4;
2178   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2179   wcW.hIcon = NULL;
2180   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2181   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2182   wcW.lpszMenuName = NULL;
2183   wcW.lpszClassName = wszClassName;
2184   bResult = RegisterClassW(&wcW);  
2185   assert(bResult);
2186   wcW.lpszClassName = wszClassName50;
2187   bResult = RegisterClassW(&wcW);  
2188   assert(bResult);
2189
2190   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2191   wcA.lpfnWndProc = RichEditANSIWndProc;
2192   wcA.cbClsExtra = 0;
2193   wcA.cbWndExtra = 4;
2194   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
2195   wcA.hIcon = NULL;
2196   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2197   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2198   wcA.lpszMenuName = NULL;
2199   wcA.lpszClassName = "RichEdit20A";
2200   bResult = RegisterClassA(&wcA);  
2201   assert(bResult);
2202   wcA.lpszClassName = "RichEdit50A";
2203   bResult = RegisterClassA(&wcA);  
2204   assert(bResult);
2205 }
2206 /******************************************************************
2207  *        CreateTextServices (RICHED20.4)
2208  *
2209  * FIXME should be ITextHost instead of void*
2210  */
2211 HRESULT WINAPI CreateTextServices(IUnknown *punkOuter, void *pITextHost,
2212     IUnknown **ppUnk)
2213 {
2214   FIXME("stub\n");
2215   /* FIXME should support aggregation */
2216   if (punkOuter)
2217     return CLASS_E_NOAGGREGATION;
2218     
2219   return E_FAIL; /* E_NOTIMPL isn't allowed by MSDN */
2220 }
2221
2222 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2223   /* FIXME: Not implemented */
2224   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2225         hWnd, msg, get_msg_name(msg), wParam, lParam);
2226   return DefWindowProcW(hWnd, msg, wParam, lParam);
2227 }
2228
2229 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2230   /* FIXME: Not implemented */
2231   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2232         hWnd, msg, get_msg_name(msg), wParam, lParam);
2233   return DefWindowProcW(hWnd, msg, wParam, lParam);
2234 }
2235
2236 /******************************************************************
2237  *        REExtendedRegisterClass (RICHED20.8)
2238  *
2239  * FIXME undocumented
2240  * Need to check for errors and implement controls and callbacks 
2241  */
2242 LRESULT WINAPI REExtendedRegisterClass(void)
2243 {
2244   WNDCLASSW wcW;
2245   UINT result;
2246
2247   FIXME("semi stub\n");
2248
2249   wcW.cbClsExtra = 0;
2250   wcW.cbWndExtra = 4;
2251   wcW.hInstance = NULL;
2252   wcW.hIcon = NULL;
2253   wcW.hCursor = NULL;
2254   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
2255   wcW.lpszMenuName = NULL;
2256
2257   if (!ME_ListBoxRegistered)
2258   {
2259       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
2260       wcW.lpfnWndProc = REListWndProc;
2261       wcW.lpszClassName = wszClassNameListBox;
2262       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
2263   }
2264
2265   if (!ME_ComboBoxRegistered)
2266   {
2267       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
2268       wcW.lpfnWndProc = REComboWndProc;
2269       wcW.lpszClassName = wszClassNameComboBox;
2270       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
2271   }
2272
2273   result = 0;
2274   if (ME_ListBoxRegistered)
2275       result += 1;
2276   if (ME_ComboBoxRegistered)
2277       result += 2;
2278
2279   return result;
2280 }