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