riched20: Include selection bar size in POSFROMCHAR.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 (only Y value valid)
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 (Also called EM_SETLIMITTEXT)
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 (partially implemented)
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 (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 "rtf.h"
230 #include "imm.h"
231 #include "res.h"
232
233 #define STACK_SIZE_DEFAULT  100
234 #define STACK_SIZE_MAX     1000
235
236 #define TEXT_LIMIT_DEFAULT 32767
237  
238 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
239
240 static BOOL ME_RegisterEditorClass(HINSTANCE);
241
242 static const WCHAR RichEdit20W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
243 static const WCHAR RichEdit50W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
244 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
245 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
246 static HCURSOR hLeft;
247 static HCURSOR hBeam;
248
249 int me_debug = 0;
250 HANDLE me_heap = NULL;
251
252 static BOOL ME_ListBoxRegistered = FALSE;
253 static BOOL ME_ComboBoxRegistered = FALSE;
254
255 static inline int is_version_nt(void)
256 {
257     return !(GetVersion() & 0x80000000);
258 }
259
260 static ME_TextBuffer *ME_MakeText(void) {
261   
262   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
263
264   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
265   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
266   
267   p1->prev = NULL;
268   p1->next = p2;
269   p2->prev = p1;
270   p2->next = NULL;
271   p1->member.para.next_para = p2;
272   p2->member.para.prev_para = p1;
273   p2->member.para.nCharOfs = 0;  
274   
275   buf->pFirst = p1;
276   buf->pLast = p2;
277   buf->pCharStyle = NULL;
278   
279   return buf;
280 }
281
282
283 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
284 {
285   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
286   WCHAR *pText;
287   
288   TRACE("%08x %p\n", dwFormat, stream);
289   
290   do {
291     long nWideChars = 0;
292
293     if (!stream->dwSize)
294     {
295       ME_StreamInFill(stream);
296       if (stream->editstream->dwError)
297         break;
298       if (!stream->dwSize)
299         break;
300     }
301       
302     if (!(dwFormat & SF_UNICODE))
303     {
304       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
305       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
306       pText = wszText;
307     }
308     else
309     {
310       nWideChars = stream->dwSize >> 1;
311       pText = (WCHAR *)stream->buffer;
312     }
313     
314     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
315     if (stream->dwSize == 0)
316       break;
317     stream->dwSize = 0;
318   } while(1);
319   ME_CommitUndo(editor);
320   ME_UpdateRepaint(editor);
321   return 0;
322 }
323
324 static void ME_RTFCharAttrHook(RTF_Info *info)
325 {
326   CHARFORMAT2W fmt;
327   fmt.cbSize = sizeof(fmt);
328   fmt.dwMask = 0;
329   fmt.dwEffects = 0;
330
331   switch(info->rtfMinor)
332   {
333     case rtfPlain:
334       /* FIXME add more flags once they're implemented */
335       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
336       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
337       fmt.yHeight = 12*20; /* 12pt */
338       fmt.wWeight = 400;
339       fmt.bUnderlineType = CFU_UNDERLINENONE;
340       break;
341     case rtfBold:
342       fmt.dwMask = CFM_BOLD;
343       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
344       break;
345     case rtfItalic:
346       fmt.dwMask = CFM_ITALIC;
347       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
348       break;
349     case rtfUnderline:
350       fmt.dwMask = CFM_UNDERLINETYPE;
351       fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
352       break;
353     case rtfDotUnderline:
354       fmt.dwMask = CFM_UNDERLINETYPE;
355       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
356       break;
357     case rtfDbUnderline:
358       fmt.dwMask = CFM_UNDERLINETYPE;
359       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
360       break;
361     case rtfWordUnderline:
362       fmt.dwMask = CFM_UNDERLINETYPE;
363       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
364       break;
365     case rtfNoUnderline:
366       fmt.dwMask = CFM_UNDERLINETYPE;
367       fmt.bUnderlineType = CFU_UNDERLINENONE;
368       break;
369     case rtfStrikeThru:
370       fmt.dwMask = CFM_STRIKEOUT;
371       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
372       break;
373     case rtfSubScript:
374     case rtfSuperScript:
375     case rtfSubScrShrink:
376     case rtfSuperScrShrink:
377     case rtfNoSuperSub:
378       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
379       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
380       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
381       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
382       break;
383     case rtfInvisible:
384       fmt.dwMask = CFM_HIDDEN;
385       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
386       break;
387     case rtfBackColor:
388       fmt.dwMask = CFM_BACKCOLOR;
389       fmt.dwEffects = 0;
390       if (info->rtfParam == 0)
391         fmt.dwEffects = CFE_AUTOBACKCOLOR;
392       else if (info->rtfParam != rtfNoParam)
393       {
394         RTFColor *c = RTFGetColor(info, info->rtfParam);
395         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
396       }
397       break;
398     case rtfForeColor:
399       fmt.dwMask = CFM_COLOR;
400       fmt.dwEffects = 0;
401       if (info->rtfParam == 0)
402         fmt.dwEffects = CFE_AUTOCOLOR;
403       else if (info->rtfParam != rtfNoParam)
404       {
405         RTFColor *c = RTFGetColor(info, info->rtfParam);
406         if (c)
407           fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
408         else
409           fmt.crTextColor = 0;
410       }
411       break;
412     case rtfFontNum:
413       if (info->rtfParam != rtfNoParam)
414       {
415         RTFFont *f = RTFGetFont(info, info->rtfParam);
416         if (f)
417         {
418           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
419           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
420           fmt.bCharSet = f->rtfFCharSet;
421           fmt.dwMask = CFM_FACE | CFM_CHARSET;
422           fmt.bPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
423         }
424       }
425       break;
426     case rtfFontSize:
427       fmt.dwMask = CFM_SIZE;
428       if (info->rtfParam != rtfNoParam)
429         fmt.yHeight = info->rtfParam*10;
430       break;
431   }
432   if (fmt.dwMask) {
433     ME_Style *style2;
434     RTFFlushOutputBuffer(info);
435     /* FIXME too slow ? how come ? */
436     style2 = ME_ApplyStyle(info->style, &fmt);
437     ME_ReleaseStyle(info->style);
438     info->style = style2;
439     info->styleChanged = TRUE;
440   }
441 }
442
443 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
444    the same tags mean different things in different contexts */
445 static void ME_RTFParAttrHook(RTF_Info *info)
446 {
447   PARAFORMAT2 fmt;
448   fmt.cbSize = sizeof(fmt);
449   fmt.dwMask = 0;
450   
451   switch(info->rtfMinor)
452   {
453   case rtfParDef: /* restores default paragraph attributes */
454     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
455     fmt.wAlignment = PFA_LEFT;
456     fmt.cTabCount = 0;
457     fmt.dxOffset = fmt.dxStartIndent = 0;
458     RTFFlushOutputBuffer(info);
459     ME_GetParagraph(info->editor->pCursors[0].pRun)->member.para.bTable = FALSE;
460     break;
461   case rtfInTable:
462   {
463     ME_DisplayItem *para;
464     
465     RTFFlushOutputBuffer(info);
466     para = ME_GetParagraph(info->editor->pCursors[0].pRun);
467     assert(para->member.para.pCells);
468     para->member.para.bTable = TRUE;
469     return;
470   }
471   case rtfFirstIndent:
472     ME_GetSelectionParaFormat(info->editor, &fmt);
473     fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
474     fmt.dxStartIndent += info->rtfParam + fmt.dxOffset;
475     fmt.dxOffset = -info->rtfParam;
476     break;
477   case rtfLeftIndent:
478     ME_GetSelectionParaFormat(info->editor, &fmt);
479     fmt.dwMask = PFM_STARTINDENT;
480     fmt.dxStartIndent = -fmt.dxOffset + info->rtfParam;
481     break;
482   case rtfRightIndent:
483     fmt.dwMask = PFM_RIGHTINDENT;
484     fmt.dxRightIndent = info->rtfParam;
485     break;
486   case rtfQuadLeft:
487   case rtfQuadJust:
488     fmt.dwMask = PFM_ALIGNMENT;
489     fmt.wAlignment = PFA_LEFT;
490     break;
491   case rtfQuadRight:
492     fmt.dwMask = PFM_ALIGNMENT;
493     fmt.wAlignment = PFA_RIGHT;
494     break;
495   case rtfQuadCenter:
496     fmt.dwMask = PFM_ALIGNMENT;
497     fmt.wAlignment = PFA_CENTER;
498     break;
499   case rtfTabPos:
500     ME_GetSelectionParaFormat(info->editor, &fmt);
501     if (!(fmt.dwMask & PFM_TABSTOPS))
502     {
503       fmt.dwMask |= PFM_TABSTOPS;
504       fmt.cTabCount = 0;
505     }
506     if (fmt.cTabCount < MAX_TAB_STOPS)
507       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
508     break;
509   }  
510   if (fmt.dwMask) {
511     RTFFlushOutputBuffer(info);
512     /* FIXME too slow ? how come ?*/
513     ME_SetSelectionParaFormat(info->editor, &fmt);
514   }
515 }
516
517 static void ME_RTFTblAttrHook(RTF_Info *info)
518 {
519   ME_DisplayItem *para;
520   
521   switch (info->rtfMinor)
522   {
523     case rtfRowDef:
524       RTFFlushOutputBuffer(info);
525       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
526       
527       /* Release possibly inherited cell definitions */
528       ME_DestroyTableCellList(para);
529       
530       para->member.para.pCells = ALLOC_OBJ(ME_TableCell);
531       para->member.para.pCells->nRightBoundary = 0;
532       para->member.para.pCells->next = NULL;
533       para->member.para.pLastCell = para->member.para.pCells;
534       break;
535     case rtfCellPos:
536       RTFFlushOutputBuffer(info);
537       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
538       
539       if (para->member.para.pLastCell->nRightBoundary)
540       {
541         ME_TableCell *pCell = ALLOC_OBJ(ME_TableCell);
542         
543         pCell->next = NULL;
544         para->member.para.pLastCell->next = pCell;
545         para->member.para.pLastCell = pCell;
546       }
547       para->member.para.pLastCell->nRightBoundary = info->rtfParam;
548       break;
549   }
550 }
551
552 static void ME_RTFReadHook(RTF_Info *info) {
553   switch(info->rtfClass)
554   {
555     case rtfGroup:
556       switch(info->rtfMajor)
557       {
558         case rtfBeginGroup:
559           if (info->stackTop < maxStack) {
560             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
561             info->stack[info->stackTop].codePage = info->codePage;
562             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
563           }
564           info->stackTop++;
565           info->styleChanged = FALSE;
566           break;
567         case rtfEndGroup:
568         {
569           ME_Style *s;
570           RTFFlushOutputBuffer(info);
571           if (info->stackTop<=1) {
572             info->rtfClass = rtfEOF;
573             return;
574           }
575           info->stackTop--;
576           assert(info->stackTop >= 0);
577           if (info->styleChanged)
578           {
579             /* FIXME too slow ? how come ? */
580             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
581             ME_ReleaseStyle(info->style);
582             info->style = s;
583             info->codePage = info->stack[info->stackTop].codePage;
584             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
585           }
586           break;
587         }
588       }
589       break;
590     case rtfControl:
591       switch(info->rtfMajor)
592       {
593         case rtfCharAttr:
594           ME_RTFCharAttrHook(info);
595           break;
596         case rtfParAttr:
597           ME_RTFParAttrHook(info);
598           break;
599         case rtfTblAttr:
600           ME_RTFTblAttrHook(info);
601           break;
602         case rtfSpecialChar:
603           if (info->rtfMinor == rtfCell)
604           {
605             RTFFlushOutputBuffer(info);
606             ME_InsertTableCellFromCursor(info->editor, 0);
607           }
608       }
609       break;
610   }
611 }
612
613 void
614 ME_StreamInFill(ME_InStream *stream)
615 {
616   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
617                                                                 (BYTE *)stream->buffer,
618                                                                 sizeof(stream->buffer),
619                                                                 (LONG *)&stream->dwSize);
620   stream->dwUsed = 0;
621 }
622
623 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
624 {
625   RTF_Info parser;
626   ME_Style *style;
627   int from, to, to2, nUndoMode;
628   int nEventMask = editor->nEventMask;
629   ME_InStream inStream;
630
631   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
632   editor->nEventMask = 0;
633   
634   ME_GetSelection(editor, &from, &to);
635   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
636     style = ME_GetSelectionInsertStyle(editor);
637
638     ME_InternalDeleteText(editor, from, to-from);
639   }
640   else {
641     style = editor->pBuffer->pDefaultStyle;
642     ME_AddRefStyle(style);
643     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
644     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
645     from = to = 0;
646     ME_ClearTempStyle(editor);
647     /* FIXME restore default paragraph formatting ! */
648   }
649
650
651   /* Back up undo mode to a local variable */
652   nUndoMode = editor->nUndoMode;
653
654   /* Only create an undo if SFF_SELECTION is set */
655   if (!(format & SFF_SELECTION))
656     editor->nUndoMode = umIgnore;
657
658   inStream.editstream = stream;
659   inStream.editstream->dwError = 0;
660   inStream.dwSize = 0;
661   inStream.dwUsed = 0;
662
663   if (format & SF_RTF)
664   {
665     /* Check if it's really RTF, and if it is not, use plain text */
666     ME_StreamInFill(&inStream);
667     if (!inStream.editstream->dwError)
668     {
669       if (strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
670       {
671         format &= ~SF_RTF;
672         format |= SF_TEXT;
673       }
674     }
675   }
676
677   if (!inStream.editstream->dwError)
678   {
679     if (format & SF_RTF) {
680       /* setup the RTF parser */
681       memset(&parser, 0, sizeof parser);
682       RTFSetEditStream(&parser, &inStream);
683       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
684       parser.hwndEdit = editor->hWnd;
685       parser.editor = editor;
686       parser.style = style;
687       WriterInit(&parser);
688       RTFInit(&parser);
689       RTFSetReadHook(&parser, ME_RTFReadHook);
690       BeginFile(&parser);
691   
692       /* do the parsing */
693       RTFRead(&parser);
694       RTFFlushOutputBuffer(&parser);
695       RTFDestroy(&parser);
696
697       style = parser.style;
698     }
699     else if (format & SF_TEXT)
700       ME_StreamInText(editor, format, &inStream, style);
701     else
702       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
703     ME_GetSelection(editor, &to, &to2);
704     /* put the cursor at the top */
705     if (!(format & SFF_SELECTION))
706       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
707   }
708
709   /* Restore saved undo mode */
710   editor->nUndoMode = nUndoMode;
711
712   /* even if we didn't add an undo, we need to commit anything on the stack */
713   ME_CommitUndo(editor);
714
715   /* If SFF_SELECTION isn't set, delete any undos from before we started too */
716   if (!(format & SFF_SELECTION))
717     ME_EmptyUndoStack(editor);
718
719   ME_ReleaseStyle(style);
720   editor->nEventMask = nEventMask;
721   if (editor->bRedraw)
722   {
723     ME_UpdateRepaint(editor);
724   }
725   if (!(format & SFF_SELECTION)) {
726     ME_ClearTempStyle(editor);
727   }
728   ME_MoveCaret(editor);
729   ME_SendSelChange(editor);
730   ME_SendRequestResize(editor, FALSE);
731
732   return 0;
733 }
734
735
736 typedef struct tagME_RTFStringStreamStruct
737 {
738   char *string;
739   int pos;
740   int length;
741 } ME_RTFStringStreamStruct;
742
743 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
744 {
745   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
746   int count;
747
748   count = min(cb, pStruct->length - pStruct->pos);
749   memmove(lpBuff, pStruct->string + pStruct->pos, count);
750   pStruct->pos += count;
751   *pcb = count;
752   return 0;
753 }
754
755 static void
756 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
757 {
758   EDITSTREAM es;
759   ME_RTFStringStreamStruct data;
760
761   data.string = string;
762   data.length = strlen(string);
763   data.pos = 0;
764   es.dwCookie = (DWORD)&data;
765   es.pfnCallback = ME_ReadFromRTFString;
766   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es);
767 }
768
769
770 ME_DisplayItem *
771 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
772 {
773   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
774   
775   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
776     item = ME_FindItemFwd(item, diParagraph);
777
778   if (!item)
779     return item;
780
781   nOffset -= item->member.para.nCharOfs;
782   if (nItemType == diParagraph) {
783     if (nItemOffset)
784       *nItemOffset = nOffset;
785     return item;
786   }
787   
788   do {
789     item = ME_FindItemFwd(item, diRun);
790   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
791   if (item) {
792     nOffset -= item->member.run.nCharOfs;
793     if (nItemOffset)
794       *nItemOffset = nOffset;
795   }
796   return item;
797 }
798
799
800 static int
801 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
802 {
803   const int nLen = lstrlenW(text);
804   const int nTextLen = ME_GetTextLength(editor);
805   int nStart, nEnd;
806   int nMin, nMax;
807   ME_DisplayItem *item;
808   ME_DisplayItem *para;
809   WCHAR wLastChar = ' ';
810
811   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
812         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
813   
814   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
815     FIXME("Flags 0x%08x not implemented\n",
816         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
817
818   nMin = chrg->cpMin;
819   if (chrg->cpMax == -1)
820     nMax = nTextLen;
821   else
822     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
823   
824   /* when searching up, if cpMin < cpMax, then instead of searching
825    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
826    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
827    * case, it is always bigger than cpMin.
828    */
829   if (!(flags & FR_DOWN))
830   {
831     int nSwap = nMax;
832
833     nMax = nMin > nTextLen ? nTextLen : nMin;
834     if (nMin < nSwap || chrg->cpMax == -1)
835       nMin = 0;
836     else
837       nMin = nSwap;
838   }
839
840   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
841   {
842     if (chrgText)
843       chrgText->cpMin = chrgText->cpMax = -1;
844     return -1;
845   }
846  
847   if (flags & FR_DOWN) /* Forward search */
848   {
849     /* If possible, find the character before where the search starts */
850     if ((flags & FR_WHOLEWORD) && nMin)
851     {
852       nStart = nMin - 1;
853       item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
854       if (!item)
855       {
856         if (chrgText)
857           chrgText->cpMin = chrgText->cpMax = -1;
858         return -1;
859       }
860       wLastChar = item->member.run.strText->szData[nStart];
861     }
862
863     nStart = nMin;
864     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
865     if (!item)
866     {
867       if (chrgText)
868         chrgText->cpMin = chrgText->cpMax = -1;
869       return -1;
870     }
871
872     para = ME_GetParagraph(item);
873     while (item
874            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
875     {
876       ME_DisplayItem *pCurItem = item;
877       int nCurStart = nStart;
878       int nMatched = 0;
879     
880       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
881       {
882         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
883           break;
884
885         nMatched++;
886         if (nMatched == nLen)
887         {
888           ME_DisplayItem *pNextItem = pCurItem;
889           int nNextStart = nCurStart;
890           WCHAR wNextChar;
891
892           /* Check to see if next character is a whitespace */
893           if (flags & FR_WHOLEWORD)
894           {
895             if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
896             {
897               pNextItem = ME_FindItemFwd(pCurItem, diRun);
898               nNextStart = -nMatched;
899             }
900
901             if (pNextItem)
902               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
903             else
904               wNextChar = ' ';
905
906             if (isalnumW(wNextChar))
907               break;
908           }
909
910           nStart += para->member.para.nCharOfs + pCurItem->member.run.nCharOfs;
911           if (chrgText)
912           {
913             chrgText->cpMin = nStart;
914             chrgText->cpMax = nStart + nLen;
915           }
916           TRACE("found at %d-%d\n", nStart, nStart + nLen);
917           return nStart;
918         }
919         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
920         {
921           pCurItem = ME_FindItemFwd(pCurItem, diRun);
922           para = ME_GetParagraph(pCurItem);
923           nCurStart = -nMatched;
924         }
925       }
926       if (pCurItem)
927         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
928       else
929         wLastChar = ' ';
930
931       nStart++;
932       if (nStart == ME_StrLen(item->member.run.strText))
933       {
934         item = ME_FindItemFwd(item, diRun);
935         para = ME_GetParagraph(item);
936         nStart = 0;
937       }
938     }
939   }
940   else /* Backward search */
941   {
942     /* If possible, find the character after where the search ends */
943     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
944     {
945       nEnd = nMax + 1;
946       item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
947       if (!item)
948       {
949         if (chrgText)
950           chrgText->cpMin = chrgText->cpMax = -1;
951         return -1;
952       }
953       wLastChar = item->member.run.strText->szData[nEnd];
954     }
955
956     nEnd = nMax;
957     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
958     if (!item)
959     {
960       if (chrgText)
961         chrgText->cpMin = chrgText->cpMax = -1;
962       return -1;
963     }
964     
965     para = ME_GetParagraph(item);
966     
967     while (item
968            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
969     {
970       ME_DisplayItem *pCurItem = item;
971       int nCurEnd = nEnd;
972       int nMatched = 0;
973       
974       if (nCurEnd - nMatched == 0)
975       {
976         pCurItem = ME_FindItemBack(pCurItem, diRun);
977         para = ME_GetParagraph(pCurItem);
978         nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
979       }
980       
981       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
982       {
983         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
984           break;
985
986         nMatched++;
987         if (nMatched == nLen)
988         {
989           ME_DisplayItem *pPrevItem = pCurItem;
990           int nPrevEnd = nCurEnd;
991           WCHAR wPrevChar;
992
993           /* Check to see if previous character is a whitespace */
994           if (flags & FR_WHOLEWORD)
995           {
996             if (nPrevEnd - nMatched == 0)
997             {
998               pPrevItem = ME_FindItemBack(pCurItem, diRun);
999               if (pPrevItem)
1000                 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1001             }
1002
1003             if (pPrevItem)
1004               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1005             else
1006               wPrevChar = ' ';
1007
1008             if (isalnumW(wPrevChar))
1009               break;
1010           }
1011
1012           nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1013           if (chrgText)
1014           {
1015             chrgText->cpMin = nStart;
1016             chrgText->cpMax = nStart + nLen;
1017           }
1018           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1019           return nStart;
1020         }
1021         if (nCurEnd - nMatched == 0)
1022         {
1023           pCurItem = ME_FindItemBack(pCurItem, diRun);
1024           /* Don't care about pCurItem becoming NULL here; it's already taken
1025            * care of in the exterior loop condition */
1026           para = ME_GetParagraph(pCurItem);
1027           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1028         }
1029       }
1030       if (pCurItem)
1031         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1032       else
1033         wLastChar = ' ';
1034
1035       nEnd--;
1036       if (nEnd < 0)
1037       {
1038         item = ME_FindItemBack(item, diRun);
1039         para = ME_GetParagraph(item);
1040         nEnd = ME_StrLen(item->member.run.strText);
1041       }
1042     }
1043   }
1044   TRACE("not found\n");
1045   if (chrgText)
1046     chrgText->cpMin = chrgText->cpMax = -1;
1047   return -1;
1048 }
1049
1050 /* helper to send a msg filter notification */
1051 static BOOL
1052 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1053 {
1054     MSGFILTER msgf;
1055
1056     msgf.nmhdr.hwndFrom = editor->hWnd;
1057     msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1058     msgf.nmhdr.code = EN_MSGFILTER;
1059     msgf.msg = msg;
1060
1061     msgf.wParam = *wParam;
1062     msgf.lParam = *lParam;
1063     if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1064         return FALSE;
1065     *wParam = msgf.wParam;
1066     *lParam = msgf.lParam;
1067     msgf.wParam = *wParam;
1068
1069     return TRUE;
1070 }
1071
1072 static BOOL
1073 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1074 {
1075   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1076   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1077   
1078   switch (nKey)
1079   {
1080     case VK_LEFT:
1081     case VK_RIGHT:
1082     case VK_UP:
1083     case VK_DOWN:
1084     case VK_HOME:
1085     case VK_END:
1086     case VK_PRIOR:
1087     case VK_NEXT:
1088       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1089       return TRUE;
1090     case VK_BACK:
1091     case VK_DELETE:
1092       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1093       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1094         return FALSE;
1095       if (ME_IsSelection(editor))
1096         ME_DeleteSelection(editor);
1097       else if (nKey == VK_DELETE || ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1098         ME_DeleteTextAtCursor(editor, 1, 1);
1099       else
1100         return TRUE;
1101       ME_CommitUndo(editor);
1102       ME_UpdateRepaint(editor);
1103       ME_SendRequestResize(editor, FALSE);
1104       return TRUE;
1105
1106     default:
1107       if (ctrl_is_down)
1108       {
1109         if (nKey == 'W')
1110         {
1111           CHARFORMAT2W chf;
1112           char buf[2048];
1113           chf.cbSize = sizeof(chf);
1114           
1115           ME_GetSelectionCharFormat(editor, &chf);
1116           ME_DumpStyleToBuf(&chf, buf);
1117           MessageBoxA(NULL, buf, "Style dump", MB_OK);
1118         }
1119         if (nKey == 'Q')
1120         {
1121           ME_CheckCharOffsets(editor);
1122         }
1123       }
1124   }
1125   return FALSE;
1126 }
1127
1128 static void ME_SetCursor(ME_TextEditor *editor, int x)
1129 {
1130     if (x < editor->selofs || editor->linesel)
1131       SetCursor(hLeft);
1132     else
1133       SetCursor(hBeam);
1134 }
1135
1136 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1137 {
1138   CHARRANGE selrange;
1139   HMENU menu;
1140   int seltype = 0;
1141   if(!editor->lpOleCallback)
1142     return FALSE;
1143   ME_GetSelection(editor, (int *)&selrange.cpMin, (int *)&selrange.cpMax);
1144   if(selrange.cpMin == selrange.cpMax)
1145     seltype |= SEL_EMPTY;
1146   else
1147   {
1148     /* FIXME: Handle objects */
1149     seltype |= SEL_TEXT;
1150     if(selrange.cpMax-selrange.cpMin > 1)
1151       seltype |= SEL_MULTICHAR;
1152   }
1153   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1154   {
1155     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1156     DestroyMenu(menu);
1157   }
1158   return TRUE;
1159 }
1160
1161 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1162   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1163   int i;
1164   ed->hWnd = hWnd;
1165   ed->bEmulateVersion10 = FALSE;
1166   ed->pBuffer = ME_MakeText();
1167   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1168   ME_MakeFirstParagraph(ed);
1169   ed->bCaretShown = FALSE;
1170   ed->nCursors = 4;
1171   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1172   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1173   ed->pCursors[0].nOffset = 0;
1174   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1175   ed->pCursors[1].nOffset = 0;
1176   ed->pCursors[2] = ed->pCursors[0];
1177   ed->pCursors[3] = ed->pCursors[1];
1178   ed->nLastTotalLength = ed->nTotalLength = 0;
1179   ed->nHeight = 0;
1180   ed->nUDArrowX = -1;
1181   ed->nSequence = 0;
1182   ed->rgbBackColor = -1;
1183   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1184   ed->bCaretAtEnd = FALSE;
1185   ed->nEventMask = 0;
1186   ed->nModifyStep = 0;
1187   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1188   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1189   ed->nUndoStackSize = 0;
1190   ed->nUndoLimit = STACK_SIZE_DEFAULT;
1191   ed->nUndoMode = umAddToUndo;
1192   ed->nParagraphs = 1;
1193   ed->nLastSelStart = ed->nLastSelEnd = 0;
1194   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1195   ed->bRedraw = TRUE;
1196   ed->bHideSelection = FALSE;
1197   ed->nInvalidOfs = -1;
1198   ed->pfnWordBreak = NULL;
1199   ed->lpOleCallback = NULL;
1200   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1201   ed->AutoURLDetect_bEnable = FALSE;
1202   ed->bHaveFocus = FALSE;
1203   GetClientRect(hWnd, &ed->rcFormat);
1204   for (i=0; i<HFONT_CACHE_SIZE; i++)
1205   {
1206     ed->pFontCache[i].nRefs = 0;
1207     ed->pFontCache[i].nAge = 0;
1208     ed->pFontCache[i].hFont = NULL;
1209   }
1210   
1211   ME_CheckCharOffsets(ed);
1212   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
1213     ed->selofs = 16;
1214   else
1215     ed->selofs = 0;
1216   ed->linesel = 0;
1217
1218   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1219     ed->cPasswordMask = '*';
1220   else
1221     ed->cPasswordMask = 0;
1222   
1223   return ed;
1224 }
1225
1226 typedef struct tagME_GlobalDestStruct
1227 {
1228   HGLOBAL hData;
1229   int nLength;
1230 } ME_GlobalDestStruct;
1231
1232 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1233 {
1234   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1235   int i;
1236   WORD *pSrc, *pDest;
1237   
1238   cb = cb >> 1;
1239   pDest = (WORD *)lpBuff;
1240   pSrc = (WORD *)GlobalLock(pData->hData);
1241   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1242     pDest[i] = pSrc[pData->nLength+i];
1243   }    
1244   pData->nLength += i;
1245   *pcb = 2*i;
1246   GlobalUnlock(pData->hData);
1247   return 0;
1248 }
1249
1250 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1251 {
1252   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1253   int i;
1254   BYTE *pSrc, *pDest;
1255   
1256   pDest = lpBuff;
1257   pSrc = (BYTE *)GlobalLock(pData->hData);
1258   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1259     pDest[i] = pSrc[pData->nLength+i];
1260   }    
1261   pData->nLength += i;
1262   *pcb = i;
1263   GlobalUnlock(pData->hData);
1264   return 0;
1265 }
1266
1267
1268 void ME_DestroyEditor(ME_TextEditor *editor)
1269 {
1270   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1271   ME_DisplayItem *p = pFirst, *pNext = NULL;
1272   int i;
1273
1274   ME_ClearTempStyle(editor);
1275   ME_EmptyUndoStack(editor);
1276   while(p) {
1277     pNext = p->next;
1278     ME_DestroyDisplayItem(p);
1279     p = pNext;
1280   }
1281   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1282   for (i=0; i<HFONT_CACHE_SIZE; i++)
1283   {
1284     if (editor->pFontCache[i].hFont)
1285       DeleteObject(editor->pFontCache[i].hFont);
1286   }
1287   if (editor->rgbBackColor != -1)
1288     DeleteObject(editor->hbrBackground);
1289   if(editor->lpOleCallback)
1290     IUnknown_Release(editor->lpOleCallback);
1291
1292   FREE_OBJ(editor->pBuffer);
1293   FREE_OBJ(editor->pCursors);
1294
1295   FREE_OBJ(editor);
1296 }
1297
1298 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1299 {
1300     TRACE("\n");
1301     switch (fdwReason)
1302     {
1303     case DLL_PROCESS_ATTACH:
1304       DisableThreadLibraryCalls(hinstDLL);
1305       me_heap = HeapCreate (0, 0x10000, 0);
1306       if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
1307       hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
1308       hBeam = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
1309       LookupInit();
1310       break;
1311
1312     case DLL_PROCESS_DETACH:
1313       UnregisterClassW(RichEdit20W, 0);
1314       UnregisterClassW(RichEdit50W, 0);
1315       UnregisterClassA("RichEdit20A", 0);
1316       UnregisterClassA("RichEdit50A", 0);
1317       if (ME_ListBoxRegistered)
1318           UnregisterClassW(REListBox20W, 0);
1319       if (ME_ComboBoxRegistered)
1320           UnregisterClassW(REComboBox20W, 0);
1321       LookupCleanup();
1322       HeapDestroy (me_heap);
1323       me_heap = NULL;
1324       break;
1325     }
1326     return TRUE;
1327 }
1328
1329
1330 #define UNSUPPORTED_MSG(e) \
1331   case e: \
1332     FIXME(#e ": stub\n"); \
1333     return DefWindowProcW(hWnd, msg, wParam, lParam);
1334
1335 static const char * const edit_messages[] = {
1336   "EM_GETSEL",
1337   "EM_SETSEL",
1338   "EM_GETRECT",
1339   "EM_SETRECT",
1340   "EM_SETRECTNP",
1341   "EM_SCROLL",
1342   "EM_LINESCROLL",
1343   "EM_SCROLLCARET",
1344   "EM_GETMODIFY",
1345   "EM_SETMODIFY",
1346   "EM_GETLINECOUNT",
1347   "EM_LINEINDEX",
1348   "EM_SETHANDLE",
1349   "EM_GETHANDLE",
1350   "EM_GETTHUMB",
1351   "EM_UNKNOWN_BF",
1352   "EM_UNKNOWN_C0",
1353   "EM_LINELENGTH",
1354   "EM_REPLACESEL",
1355   "EM_UNKNOWN_C3",
1356   "EM_GETLINE",
1357   "EM_LIMITTEXT",
1358   "EM_CANUNDO",
1359   "EM_UNDO",
1360   "EM_FMTLINES",
1361   "EM_LINEFROMCHAR",
1362   "EM_UNKNOWN_CA",
1363   "EM_SETTABSTOPS",
1364   "EM_SETPASSWORDCHAR",
1365   "EM_EMPTYUNDOBUFFER",
1366   "EM_GETFIRSTVISIBLELINE",
1367   "EM_SETREADONLY",
1368   "EM_SETWORDBREAKPROC",
1369   "EM_GETWORDBREAKPROC",
1370   "EM_GETPASSWORDCHAR",
1371   "EM_SETMARGINS",
1372   "EM_GETMARGINS",
1373   "EM_GETLIMITTEXT",
1374   "EM_POSFROMCHAR",
1375   "EM_CHARFROMPOS"
1376 };
1377
1378 static const char * const richedit_messages[] = {
1379   "EM_CANPASTE",
1380   "EM_DISPLAYBAND",
1381   "EM_EXGETSEL",
1382   "EM_EXLIMITTEXT",
1383   "EM_EXLINEFROMCHAR",
1384   "EM_EXSETSEL",
1385   "EM_FINDTEXT",
1386   "EM_FORMATRANGE",
1387   "EM_GETCHARFORMAT",
1388   "EM_GETEVENTMASK",
1389   "EM_GETOLEINTERFACE",
1390   "EM_GETPARAFORMAT",
1391   "EM_GETSELTEXT",
1392   "EM_HIDESELECTION", 
1393   "EM_PASTESPECIAL",
1394   "EM_REQUESTRESIZE",
1395   "EM_SELECTIONTYPE",
1396   "EM_SETBKGNDCOLOR",
1397   "EM_SETCHARFORMAT",
1398   "EM_SETEVENTMASK",
1399   "EM_SETOLECALLBACK",
1400   "EM_SETPARAFORMAT",
1401   "EM_SETTARGETDEVICE",
1402   "EM_STREAMIN",
1403   "EM_STREAMOUT",
1404   "EM_GETTEXTRANGE",
1405   "EM_FINDWORDBREAK",
1406   "EM_SETOPTIONS",
1407   "EM_GETOPTIONS",
1408   "EM_FINDTEXTEX",
1409   "EM_GETWORDBREAKPROCEX",
1410   "EM_SETWORDBREAKPROCEX",
1411   "EM_SETUNDOLIMIT",
1412   "EM_UNKNOWN_USER_83",
1413   "EM_REDO",
1414   "EM_CANREDO",
1415   "EM_GETUNDONAME",
1416   "EM_GETREDONAME",
1417   "EM_STOPGROUPTYPING",
1418   "EM_SETTEXTMODE",
1419   "EM_GETTEXTMODE",
1420   "EM_AUTOURLDETECT",
1421   "EM_GETAUTOURLDETECT",
1422   "EM_SETPALETTE",
1423   "EM_GETTEXTEX",
1424   "EM_GETTEXTLENGTHEX",
1425   "EM_SHOWSCROLLBAR",
1426   "EM_SETTEXTEX",
1427   "EM_UNKNOWN_USER_98",
1428   "EM_UNKNOWN_USER_99",
1429   "EM_SETPUNCTUATION",
1430   "EM_GETPUNCTUATION",
1431   "EM_SETWORDWRAPMODE",
1432   "EM_GETWORDWRAPMODE",
1433   "EM_SETIMECOLOR",
1434   "EM_GETIMECOLOR",
1435   "EM_SETIMEOPTIONS",
1436   "EM_GETIMEOPTIONS",
1437   "EM_CONVPOSITION",
1438   "EM_UNKNOWN_USER_109",
1439   "EM_UNKNOWN_USER_110",
1440   "EM_UNKNOWN_USER_111",
1441   "EM_UNKNOWN_USER_112",
1442   "EM_UNKNOWN_USER_113",
1443   "EM_UNKNOWN_USER_114",
1444   "EM_UNKNOWN_USER_115",
1445   "EM_UNKNOWN_USER_116",
1446   "EM_UNKNOWN_USER_117",
1447   "EM_UNKNOWN_USER_118",
1448   "EM_UNKNOWN_USER_119",
1449   "EM_SETLANGOPTIONS",
1450   "EM_GETLANGOPTIONS",
1451   "EM_GETIMECOMPMODE",
1452   "EM_FINDTEXTW",
1453   "EM_FINDTEXTEXW",
1454   "EM_RECONVERSION",
1455   "EM_SETIMEMODEBIAS",
1456   "EM_GETIMEMODEBIAS"
1457 };
1458
1459 static const char *
1460 get_msg_name(UINT msg)
1461 {
1462   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
1463     return edit_messages[msg - EM_GETSEL];
1464   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1465     return richedit_messages[msg - EM_CANPASTE];
1466   return "";
1467 }
1468
1469 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
1470                                       LPARAM lParam, BOOL unicode)
1471 {
1472   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
1473   
1474   TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
1475         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
1476   
1477   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
1478     ERR("called with invalid hWnd %p - application bug?\n", hWnd);
1479     return 0; 
1480   }
1481
1482   switch(msg) {
1483   
1484   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1485   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1486   UNSUPPORTED_MSG(EM_FMTLINES)
1487   UNSUPPORTED_MSG(EM_FORMATRANGE)
1488   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1489   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1490   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1491   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1492   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1493   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1494   UNSUPPORTED_MSG(EM_GETREDONAME)
1495   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1496   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1497   UNSUPPORTED_MSG(EM_GETUNDONAME)
1498   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1499   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1500   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1501   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1502   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1503   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1504   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1505   UNSUPPORTED_MSG(EM_SETPALETTE)
1506   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1507   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1508   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1509   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1510   UNSUPPORTED_MSG(WM_STYLECHANGING)
1511   UNSUPPORTED_MSG(WM_STYLECHANGED)
1512 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1513     
1514 /* Messages specific to Richedit controls */
1515   
1516   case EM_STREAMIN:
1517    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1518   case EM_STREAMOUT:
1519    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1520   case WM_GETDLGCODE:
1521   {
1522     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1523     if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
1524     {
1525       int vk = (int)((LPMSG)lParam)->wParam;
1526       /* if style says we want return key */
1527       if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
1528       {
1529         code |= DLGC_WANTMESSAGE;
1530       }
1531       /* we always handle ctrl-tab */
1532       if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
1533       {
1534         code |= DLGC_WANTMESSAGE;
1535       }
1536     }
1537     return code;
1538   }
1539   case WM_NCCREATE:
1540   {
1541     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1542     TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
1543     editor = ME_MakeEditor(hWnd);
1544     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
1545     return TRUE;
1546   }
1547   case EM_EMPTYUNDOBUFFER:
1548     ME_EmptyUndoStack(editor);
1549     return 0;
1550   case EM_GETSEL:
1551   {
1552     /* Note: wParam/lParam can be NULL */
1553     UINT from, to;
1554     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1555     PUINT pto = lParam ? (PUINT)lParam : &to;
1556     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1557     if ((*pfrom|*pto) & 0xFFFF0000)
1558       return -1;
1559     return MAKELONG(*pfrom,*pto);
1560   }
1561   case EM_EXGETSEL:
1562   {
1563     CHARRANGE *pRange = (CHARRANGE *)lParam;
1564     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1565     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
1566     return 0;
1567   }
1568   case EM_SETUNDOLIMIT:
1569   {
1570     if ((int)wParam < 0)
1571       editor->nUndoLimit = STACK_SIZE_DEFAULT;
1572     else
1573       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
1574     /* Setting a max stack size keeps wine from getting killed 
1575       for hogging memory. Windows allocates all this memory at once, so
1576       no program would realistically set a value above our maximum. */
1577     return editor->nUndoLimit;
1578   }
1579   case EM_CANUNDO:
1580     return editor->pUndoStack != NULL;
1581   case EM_CANREDO:
1582     return editor->pRedoStack != NULL;
1583   case WM_UNDO: /* FIXME: actually not the same */
1584   case EM_UNDO:
1585     ME_Undo(editor);
1586     return 0;
1587   case EM_REDO:
1588     ME_Redo(editor);
1589     return 0;
1590   case EM_GETOPTIONS:
1591   {
1592     /* these flags are equivalent to the ES_* counterparts */
1593     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1594                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1595     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
1596
1597     return settings;
1598   }
1599   case EM_SETOPTIONS:
1600   {
1601     /* these flags are equivalent to ES_* counterparts                      
1602      * ECO_READONLY is already implemented in the code, only requires 
1603      * setting the bit to work                                        
1604      */
1605     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1606                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
1607     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
1608     DWORD settings = mask & raw;
1609
1610     switch(wParam)
1611     {
1612       case ECOOP_SET:
1613         settings = lParam;
1614         break;
1615       case ECOOP_OR:
1616         settings |= lParam;
1617         break;
1618       case ECOOP_AND:
1619         settings &= lParam;
1620         break;
1621       case ECOOP_XOR:
1622         settings ^= lParam;
1623     }
1624     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
1625
1626     if (settings & ECO_AUTOWORDSELECTION)
1627       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
1628     if (settings & ECO_SELECTIONBAR)
1629         editor->selofs = 16;
1630     else
1631         editor->selofs = 0;
1632     ME_WrapMarkedParagraphs(editor);
1633
1634     if (settings & ECO_VERTICAL)
1635       FIXME("ECO_VERTICAL not implemented yet!\n");
1636     if (settings & ECO_AUTOHSCROLL)
1637       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
1638     if (settings & ECO_AUTOVSCROLL)
1639       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
1640     if (settings & ECO_NOHIDESEL)
1641       FIXME("ECO_NOHIDESEL not implemented yet!\n");
1642     if (settings & ECO_WANTRETURN)
1643       FIXME("ECO_WANTRETURN not implemented yet!\n");
1644
1645     return settings;
1646   }
1647   case EM_SETSEL:
1648   {
1649     ME_InvalidateSelection(editor);
1650     ME_SetSelection(editor, wParam, lParam);
1651     ME_InvalidateSelection(editor);
1652     ME_SendSelChange(editor);
1653     return 0;
1654   }
1655   case EM_SETSCROLLPOS:
1656   {
1657     POINT *point = (POINT *)lParam;
1658     ME_ScrollAbs(editor, point->y);
1659     return 0;
1660   }
1661   case EM_AUTOURLDETECT:
1662   {
1663     if (wParam==1 || wParam ==0) 
1664     {
1665         editor->AutoURLDetect_bEnable = (BOOL)wParam;
1666         return 0;
1667     }
1668     return E_INVALIDARG;
1669   }
1670   case EM_GETAUTOURLDETECT:
1671   {
1672     return editor->AutoURLDetect_bEnable;
1673   }
1674   case EM_EXSETSEL:
1675   {
1676     int end;
1677     CHARRANGE range = *(CHARRANGE *)lParam;
1678
1679     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
1680
1681     ME_InvalidateSelection(editor);
1682     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
1683     ME_InvalidateSelection(editor);
1684     ME_SendSelChange(editor);
1685
1686     return end;
1687   }
1688   case EM_SHOWSCROLLBAR:
1689   {
1690     ShowScrollBar(editor->hWnd, wParam, lParam);
1691     return 0;
1692   }
1693   case EM_SETTEXTEX:
1694   {
1695     LPWSTR wszText;
1696     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1697     size_t len;
1698     int from, to;
1699     ME_Style *style;
1700     int oldModify = editor->nModifyStep;
1701
1702     if (!pStruct) return 0;
1703
1704     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
1705           pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
1706           pStruct->flags, pStruct->codepage);
1707
1708     /* FIXME: make use of pStruct->codepage in the to unicode translation */
1709     wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
1710     len = wszText ? lstrlenW(wszText) : 0;
1711
1712     /* FIXME: this should support RTF strings too, according to MSDN */
1713     if (pStruct->flags & ST_SELECTION) {
1714       ME_GetSelection(editor, &from, &to);
1715       style = ME_GetSelectionInsertStyle(editor);
1716       ME_InternalDeleteText(editor, from, to - from);
1717       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1718       ME_ReleaseStyle(style);
1719     }
1720     else {
1721       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1722       ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1723       len = 1;
1724     }
1725     ME_CommitUndo(editor);
1726     if (!(pStruct->flags & ST_KEEPUNDO))
1727     {
1728       editor->nModifyStep = oldModify;
1729       ME_EmptyUndoStack(editor);
1730     }
1731     ME_UpdateRepaint(editor);
1732     return len;
1733   }
1734   case EM_SETBKGNDCOLOR:
1735   {
1736     LRESULT lColor;
1737     if (editor->rgbBackColor != -1) {
1738       DeleteObject(editor->hbrBackground);
1739       lColor = editor->rgbBackColor;
1740     }
1741     else lColor = GetSysColor(COLOR_WINDOW);
1742
1743     if (wParam)
1744     {
1745       editor->rgbBackColor = -1;
1746       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1747     }
1748     else
1749     {
1750       editor->rgbBackColor = lParam;
1751       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
1752     }
1753     if (editor->bRedraw)
1754     {
1755       InvalidateRect(hWnd, NULL, TRUE);
1756       UpdateWindow(hWnd);
1757     }
1758     return lColor;
1759   }
1760   case EM_GETMODIFY:
1761     return editor->nModifyStep == 0 ? 0 : 1;
1762   case EM_SETMODIFY:
1763   {
1764     if (wParam)
1765       editor->nModifyStep = 1;
1766     else
1767       editor->nModifyStep = 0;
1768     
1769     return 0;
1770   }
1771   case EM_SETREADONLY:
1772   {
1773     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1774     if (wParam)
1775       nStyle |= ES_READONLY;
1776     else
1777       nStyle &= ~ES_READONLY;
1778     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1779     return 0;
1780   }
1781   case EM_SETEVENTMASK:
1782   {
1783     DWORD nOldMask = editor->nEventMask;
1784     
1785     editor->nEventMask = lParam;
1786     return nOldMask;
1787   }
1788   case EM_GETEVENTMASK:
1789     return editor->nEventMask;
1790   case EM_SETCHARFORMAT:
1791   {
1792     CHARFORMAT2W buf, *p;
1793     BOOL bRepaint = TRUE;
1794     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1795     if (p == NULL) return 0;
1796     if (!wParam)
1797       ME_SetDefaultCharFormat(editor, p);
1798     else if (wParam == (SCF_WORD | SCF_SELECTION)) {
1799       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1800       return 0;
1801     } else if (wParam == SCF_ALL) {
1802       if (editor->mode & TM_PLAINTEXT)
1803         ME_SetDefaultCharFormat(editor, p);
1804       else
1805         ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1806     } else if (editor->mode & TM_PLAINTEXT) {
1807       return 0;
1808     } else {
1809       int from, to;
1810       ME_GetSelection(editor, &from, &to);
1811       bRepaint = (from != to);
1812       ME_SetSelectionCharFormat(editor, p);
1813     }
1814     editor->nModifyStep = 1;
1815     ME_CommitUndo(editor);
1816     if (bRepaint)
1817       ME_RewrapRepaint(editor);
1818     return 1;
1819   }
1820   case EM_GETCHARFORMAT:
1821   {
1822     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1823     if (dst->cbSize != sizeof(CHARFORMATA) &&
1824         dst->cbSize != sizeof(CHARFORMATW) &&
1825         dst->cbSize != sizeof(CHARFORMAT2A) &&
1826         dst->cbSize != sizeof(CHARFORMAT2W))
1827       return 0;
1828     tmp.cbSize = sizeof(tmp);
1829     if (!wParam)
1830       ME_GetDefaultCharFormat(editor, &tmp);
1831     else
1832       ME_GetSelectionCharFormat(editor, &tmp);
1833     ME_CopyToCFAny(dst, &tmp);
1834     return tmp.dwMask;
1835   }
1836   case EM_SETPARAFORMAT:
1837     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1838     ME_RewrapRepaint(editor);
1839     ME_CommitUndo(editor);
1840     return 0;
1841   case EM_GETPARAFORMAT:
1842     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1843     return 0;
1844   case EM_GETFIRSTVISIBLELINE:
1845   {
1846     ME_DisplayItem *p = editor->pBuffer->pFirst;
1847     int y = ME_GetYScrollPos(editor);
1848     int ypara = 0;
1849     int count = 0;
1850     int ystart, yend;
1851     while(p) {
1852       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
1853       if (p->type == diTextEnd)
1854         break;
1855       if (p->type == diParagraph) {
1856         ypara = p->member.para.nYPos;
1857         continue;
1858       }
1859       ystart = ypara + p->member.row.nYPos;
1860       yend = ystart + p->member.row.nHeight;
1861       if (y < yend) {
1862         break;
1863       }
1864       count++;
1865     }
1866     return count;
1867   }
1868   case EM_HIDESELECTION:
1869   {
1870      editor->bHideSelection = (wParam != 0);
1871      ME_InvalidateSelection(editor);
1872      return 0;
1873   }
1874   case EM_LINESCROLL:
1875   {
1876     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
1877     return TRUE; /* Should return false if a single line richedit control */
1878   }
1879   case WM_CLEAR:
1880   {
1881     int from, to;
1882     ME_GetSelection(editor, &from, &to);
1883     ME_InternalDeleteText(editor, from, to-from);
1884     ME_CommitUndo(editor);
1885     ME_UpdateRepaint(editor);
1886     return 0;
1887   }
1888   case EM_REPLACESEL:
1889   {
1890     int from, to;
1891     ME_Style *style;
1892     LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
1893     size_t len = wszText ? lstrlenW(wszText) : 0;
1894     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1895
1896     ME_GetSelection(editor, &from, &to);
1897     style = ME_GetSelectionInsertStyle(editor);
1898     ME_InternalDeleteText(editor, from, to-from);
1899     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1900     ME_ReleaseStyle(style);
1901     /* drop temporary style if line end */
1902     /*
1903      * FIXME question: does abc\n mean: put abc,
1904      * clear temp style, put \n? (would require a change)
1905      */
1906     if (len>0 && wszText[len-1] == '\n')
1907       ME_ClearTempStyle(editor);
1908     ME_EndToUnicode(unicode, wszText);
1909     ME_CommitUndo(editor);
1910     if (!wParam)
1911       ME_EmptyUndoStack(editor);
1912     ME_UpdateRepaint(editor);
1913     return len;
1914   }
1915   case EM_SCROLLCARET:
1916   {
1917     int top, bottom; /* row's edges relative to document top */
1918     int nPos;
1919     ME_DisplayItem *para, *row;
1920     
1921     nPos = ME_GetYScrollPos(editor);
1922     row = ME_RowStart(editor->pCursors[0].pRun);
1923     para = ME_GetParagraph(row);
1924     top = para->member.para.nYPos + row->member.row.nYPos;
1925     bottom = top + row->member.row.nHeight;
1926     
1927     if (top < nPos) /* caret above window */
1928       ME_ScrollAbs(editor,  top);
1929     else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
1930       ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
1931     return 0;
1932   }
1933   case WM_SETFONT:
1934   {
1935     LOGFONTW lf;
1936     CHARFORMAT2W fmt;
1937     HDC hDC;
1938     BOOL bRepaint = LOWORD(lParam);
1939     
1940     if (!wParam)
1941       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
1942     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
1943     hDC = GetDC(hWnd);
1944     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
1945     ReleaseDC(hWnd, hDC);   
1946     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
1947     ME_SetDefaultCharFormat(editor, &fmt);
1948
1949     ME_CommitUndo(editor);
1950     if (bRepaint)
1951       ME_RewrapRepaint(editor);
1952     return 0;
1953   }
1954   case WM_SETTEXT:
1955   {
1956     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1957     if (lParam)
1958     {
1959       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1960       if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
1961       {
1962         /* Undocumented: WM_SETTEXT supports RTF text */
1963         ME_StreamInRTFString(editor, 0, (char *)lParam);
1964       }
1965       else
1966       {
1967         LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
1968         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1969         if (lstrlenW(wszText) > 0)
1970         {
1971           int len = -1;
1972
1973           /* uses default style! */
1974           if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
1975           {
1976             WCHAR * p;
1977
1978             p = wszText;
1979             while (*p != '\0' && *p != '\r' && *p != '\n') p++;
1980             len = p - wszText;
1981           }
1982           ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1983         }
1984         ME_EndToUnicode(unicode, wszText);
1985       }
1986     }
1987     else
1988       TRACE("WM_SETTEXT - NULL\n");
1989     ME_CommitUndo(editor);
1990     ME_EmptyUndoStack(editor);
1991     ME_SetSelection(editor, 0, 0);
1992     editor->nModifyStep = 0;
1993     ME_UpdateRepaint(editor);
1994     return 1;
1995   }
1996   case EM_CANPASTE:
1997   {
1998     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1999     if (IsClipboardFormatAvailable(nRTFFormat))
2000       return TRUE;
2001     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2002       return TRUE;
2003     return FALSE;
2004   }
2005   case WM_PASTE:
2006   {    
2007     DWORD dwFormat = 0;
2008     EDITSTREAM es;
2009     ME_GlobalDestStruct gds;
2010     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2011     UINT cf = 0;
2012
2013     if (IsClipboardFormatAvailable(nRTFFormat))
2014       cf = nRTFFormat, dwFormat = SF_RTF;
2015     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2016       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2017     else
2018       return 0;
2019
2020     if (!OpenClipboard(hWnd))
2021       return 0;
2022     gds.hData = GetClipboardData(cf);
2023     gds.nLength = 0;
2024     es.dwCookie = (DWORD)&gds;
2025     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2026     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es);
2027
2028     CloseClipboard();
2029     return 0;
2030   }
2031   case WM_CUT:
2032   case WM_COPY:
2033   {
2034     LPDATAOBJECT dataObj = NULL;
2035     CHARRANGE range;
2036     HRESULT hr = S_OK;
2037     
2038     if (editor->cPasswordMask)
2039       return 0; /* Copying or Cutting masked text isn't allowed */
2040     
2041     ME_GetSelection(editor, (int*)&range.cpMin, (int*)&range.cpMax);
2042     if(editor->lpOleCallback)
2043         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2044     if(FAILED(hr) || !dataObj)
2045         hr = ME_GetDataObject(editor, &range, &dataObj);
2046     if(SUCCEEDED(hr)) {
2047         hr = OleSetClipboard(dataObj);
2048         IDataObject_Release(dataObj);
2049     }
2050     if (SUCCEEDED(hr) && msg == WM_CUT)
2051     {
2052       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
2053       ME_CommitUndo(editor);
2054       ME_UpdateRepaint(editor);
2055     }
2056     return 0;
2057   }
2058   case WM_GETTEXTLENGTH:
2059   {
2060     GETTEXTLENGTHEX how;
2061
2062     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2063     how.codepage = unicode ? 1200 : CP_ACP;
2064     return ME_GetTextLengthEx(editor, &how);
2065   }
2066   case EM_GETTEXTLENGTHEX:
2067     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2068   case WM_GETTEXT:
2069   {
2070     GETTEXTEX ex;
2071     LRESULT rc;
2072     LPSTR bufferA = NULL;
2073     LPWSTR bufferW = NULL;
2074
2075     if (unicode)
2076         bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2077     else
2078         bufferA = heap_alloc(wParam + 2);
2079
2080     ex.cb = wParam + (unicode ? 2*sizeof(WCHAR) : 2);
2081     ex.flags = GT_USECRLF;
2082     ex.codepage = unicode ? 1200 : CP_ACP;
2083     ex.lpDefaultChar = NULL;
2084     ex.lpUsedDefaultChar = NULL;
2085     rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
2086
2087     if (unicode)
2088     {
2089         memcpy((LPWSTR)lParam, bufferW, wParam);
2090         if (lstrlenW(bufferW) >= wParam / sizeof(WCHAR)) rc = 0;
2091     }
2092     else
2093     {
2094         memcpy((LPSTR)lParam, bufferA, wParam);
2095         if (strlen(bufferA) >= wParam) rc = 0;
2096     }
2097     heap_free(bufferA);
2098     heap_free(bufferW);
2099     return rc;
2100   }
2101   case EM_GETTEXTEX:
2102   {
2103     GETTEXTEX *ex = (GETTEXTEX*)wParam;
2104     int nStart, nCount;
2105
2106     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2107       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2108
2109     if (ex->flags & GT_SELECTION)
2110     {
2111       ME_GetSelection(editor, &nStart, &nCount);
2112       nCount -= nStart;
2113       nCount = min(nCount, ex->cb - 1);
2114     }
2115     else
2116     {
2117       nStart = 0;
2118       nCount = ex->cb - 1;
2119     }
2120     if (ex->codepage == 1200)
2121     {
2122       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2123       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2124     }
2125     else
2126     {
2127       /* potentially each char may be a CR, why calculate the exact value with O(N) when
2128         we can just take a bigger buffer? :) */
2129       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2130       LPWSTR buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
2131       DWORD buflen = ex->cb;
2132       LRESULT rc;
2133       DWORD flags = 0;
2134
2135       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2136       rc = WideCharToMultiByte(ex->codepage, flags, buffer, -1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
2137       if (rc) rc--; /* do not count 0 terminator */
2138
2139       heap_free(buffer);
2140       return rc;
2141     }
2142   }
2143   case EM_GETSELTEXT:
2144   {
2145     int from, to;
2146     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2147     ME_GetSelection(editor, &from, &to);
2148     tr.chrg.cpMin = from;
2149     tr.chrg.cpMax = to;
2150     tr.lpstrText = (WCHAR *)lParam;
2151     return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
2152   }
2153   case EM_GETSCROLLPOS:
2154   {
2155       POINT *point = (POINT *)lParam;
2156       point->x = 0; /* FIXME side scrolling not implemented */
2157       point->y = ME_GetYScrollPos(editor);
2158       return 1;
2159   }
2160   case EM_GETTEXTRANGE:
2161   {
2162     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2163     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2164       rng->chrg.cpMin, rng->chrg.cpMax, unicode,
2165       editor->bEmulateVersion10, ME_GetTextLength(editor));
2166     if (unicode)
2167       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
2168     else
2169     {
2170       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2171       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2172       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
2173       /* FIXME this is a potential security hole (buffer overrun) 
2174          if you know more about wchar->mbyte conversion please explain
2175       */
2176       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2177       FREE_OBJ(p);
2178       return nChars;
2179     }
2180   }
2181   case EM_GETLINE:
2182   {
2183     ME_DisplayItem *run;
2184     const unsigned int nMaxChars = *(WORD *) lParam;
2185     unsigned int nEndChars, nCharsLeft = nMaxChars;
2186     char *dest = (char *) lParam;
2187     /* rich text editor 1.0 uses \r\n for line end, 2.0 uses just \r; 
2188     we need to know how if we have the extra \n or not */
2189     int nLF = editor->bEmulateVersion10;
2190
2191     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2192           unicode ? "Unicode" : "Ansi");
2193
2194     run = ME_FindRowWithNumber(editor, wParam);
2195     if (run == NULL)
2196       return 0;
2197
2198     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2199            && !(run->member.run.nFlags & MERF_ENDPARA))
2200     {
2201       unsigned int nCopy;
2202       ME_String *strText;
2203       if (run->type != diRun)
2204         break;
2205       strText = run->member.run.strText;
2206       nCopy = min(nCharsLeft, strText->nLen);
2207
2208       if (unicode)
2209         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2210       else
2211         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2212                                     nCharsLeft, NULL, NULL);
2213       dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
2214       nCharsLeft -= nCopy;
2215     }
2216
2217     /* append \r\0 (or \r\n\0 in 1.0), space allowing */
2218     nEndChars = min(nCharsLeft, 2 + nLF);
2219     nCharsLeft -= nEndChars;
2220     if (unicode)
2221     {
2222       const WCHAR src[] = {'\r', '\0'};
2223       const WCHAR src10[] = {'\r', '\n', '\0'};
2224       lstrcpynW((LPWSTR) dest, nLF ? src10 : src, nEndChars);
2225     }
2226     else
2227       lstrcpynA(dest, nLF ? "\r\n" : "\r", nEndChars);
2228
2229     TRACE("EM_GETLINE: got %u bytes\n", nMaxChars - nCharsLeft);
2230
2231     if (nEndChars == 2 + nLF)
2232       return nMaxChars - nCharsLeft - 1; /* don't count \0 */
2233     else
2234       return nMaxChars - nCharsLeft;
2235   }
2236   case EM_GETLINECOUNT:
2237   {
2238     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2239     int nRows = 0;
2240
2241     while (item != editor->pBuffer->pLast)
2242     {
2243       assert(item->type == diParagraph);
2244       nRows += item->member.para.nRows;
2245       item = item->member.para.next_para;
2246     }
2247     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2248     return max(1, nRows);
2249   }
2250   case EM_LINEFROMCHAR:
2251   {
2252     if (wParam == -1)
2253       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2254     else
2255       return ME_RowNumberFromCharOfs(editor, wParam);
2256   }
2257   case EM_EXLINEFROMCHAR:
2258   {
2259     if (lParam == -1)
2260       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2261     else    
2262       return ME_RowNumberFromCharOfs(editor, lParam);
2263   }
2264   case EM_LINEINDEX:
2265   {
2266     ME_DisplayItem *item, *para;
2267     int nCharOfs;
2268     
2269     if (wParam == -1)
2270       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2271     else
2272       item = ME_FindRowWithNumber(editor, wParam);
2273     if (!item)
2274       return -1;
2275     para = ME_GetParagraph(item);
2276     item = ME_FindItemFwd(item, diRun);
2277     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2278     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2279     return nCharOfs;
2280   }
2281   case EM_LINELENGTH:
2282   {
2283     ME_DisplayItem *item, *item_end;
2284     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2285     
2286     if (wParam > ME_GetTextLength(editor))
2287       return 0;
2288     if (wParam == -1)
2289     {
2290       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2291       return 0;
2292     }
2293     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2294     item = ME_RowStart(item);
2295     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2296     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2297     if (item_end->type == diStartRow)
2298       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2299     else
2300       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs
2301        - (editor->bEmulateVersion10?2:1);
2302     nChars = nNextLineOfs - nThisLineOfs;
2303     TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
2304     return nChars;
2305   }
2306   case EM_EXLIMITTEXT:
2307   {
2308     if ((int)lParam < 0)
2309      return 0;
2310     if (lParam == 0)
2311       editor->nTextLimit = 65536;
2312     else
2313       editor->nTextLimit = (int) lParam;
2314     return 0;
2315   }
2316   case EM_LIMITTEXT:
2317   {
2318     if (wParam == 0)
2319       editor->nTextLimit = 65536;
2320     else
2321       editor->nTextLimit = (int) wParam;
2322     return 0;
2323   }
2324   case EM_GETLIMITTEXT:
2325   {
2326     return editor->nTextLimit;
2327   }
2328   case EM_FINDTEXT:
2329   {
2330     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2331     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2332     WCHAR *tmp;
2333     LRESULT r;
2334
2335     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2336       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2337     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2338     FREE_OBJ( tmp );
2339     return r;
2340   }
2341   case EM_FINDTEXTEX:
2342   {
2343     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2344     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2345     WCHAR *tmp;
2346     LRESULT r;
2347
2348     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2349       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2350     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2351     FREE_OBJ( tmp );
2352     return r;
2353   }
2354   case EM_FINDTEXTW:
2355   {
2356     FINDTEXTW *ft = (FINDTEXTW *)lParam;
2357     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2358   }
2359   case EM_FINDTEXTEXW:
2360   {
2361     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2362     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2363   }
2364   case EM_GETZOOM:
2365     if (!wParam || !lParam)
2366       return FALSE;
2367     *(int *)wParam = editor->nZoomNumerator;
2368     *(int *)lParam = editor->nZoomDenominator;
2369     return TRUE;
2370   case EM_SETZOOM:
2371     return ME_SetZoom(editor, wParam, lParam);
2372   case EM_CHARFROMPOS:
2373     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2374   case EM_POSFROMCHAR:
2375   {
2376     ME_DisplayItem *pRun;
2377     int nCharOfs, nOffset, nLength;
2378     POINTL pt = {0,0};
2379     
2380     nCharOfs = wParam; 
2381     /* detect which API version we're dealing with */
2382     if (wParam >= 0x40000)
2383         nCharOfs = lParam;
2384     nLength = ME_GetTextLength(editor);
2385     
2386     if (nCharOfs < nLength) { 
2387         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2388         assert(pRun->type == diRun);
2389         pt.y = pRun->member.run.pt.y;
2390         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
2391         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
2392     } else {
2393         pt.x = 0;
2394         pt.y = editor->pBuffer->pLast->member.para.nYPos;
2395     }
2396     pt.x += editor->selofs;
2397     if (wParam >= 0x40000) {
2398         *(POINTL *)wParam = pt;
2399     }
2400     return MAKELONG( pt.x, pt.y );
2401   }
2402   case WM_CREATE:
2403     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
2404     { /* Squelch the default horizontal scrollbar it would make */
2405       ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
2406     }
2407     ME_CommitUndo(editor);
2408     ME_WrapMarkedParagraphs(editor);
2409     ME_MoveCaret(editor);
2410     return 0;
2411   case WM_DESTROY:
2412     ME_DestroyEditor(editor);
2413     SetWindowLongPtrW(hWnd, 0, 0);
2414     return 0;
2415   case WM_LBUTTONDOWN:
2416     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2417         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2418       return 0;
2419     SetFocus(hWnd);
2420     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2421     SetCapture(hWnd);
2422     ME_LinkNotify(editor,msg,wParam,lParam);
2423     ME_SetCursor(editor, LOWORD(lParam));
2424     break;
2425   case WM_MOUSEMOVE:
2426     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2427         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2428       return 0;
2429     if (GetCapture() == hWnd)
2430       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2431     ME_LinkNotify(editor,msg,wParam,lParam);
2432     ME_SetCursor(editor, LOWORD(lParam));
2433     break;
2434   case WM_LBUTTONUP:
2435     if (GetCapture() == hWnd)
2436       ReleaseCapture();
2437     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2438         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2439       return 0;
2440     editor->linesel = 0;
2441     ME_SetCursor(editor, LOWORD(lParam));
2442     ME_LinkNotify(editor,msg,wParam,lParam);
2443     break;
2444   case WM_LBUTTONDBLCLK:
2445     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2446         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2447       return 0;
2448     ME_LinkNotify(editor,msg,wParam,lParam);
2449     ME_SelectWord(editor);
2450     break;
2451   case WM_RBUTTONUP:
2452   case WM_RBUTTONDOWN:
2453     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2454         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2455       return 0;
2456     goto do_default;
2457   case WM_CONTEXTMENU:
2458     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
2459       goto do_default;
2460     break;
2461   case WM_PAINT:
2462     if (editor->bRedraw)
2463     {
2464       HDC hDC;
2465       PAINTSTRUCT ps;
2466
2467       hDC = BeginPaint(hWnd, &ps);
2468       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
2469       EndPaint(hWnd, &ps);
2470     }
2471     break;
2472   case WM_SETFOCUS:
2473     editor->bHaveFocus = TRUE;
2474     ME_ShowCaret(editor);
2475     ME_SendOldNotify(editor, EN_SETFOCUS);
2476     return 0;
2477   case WM_KILLFOCUS:
2478     ME_HideCaret(editor);
2479     editor->bHaveFocus = FALSE;
2480     ME_SendOldNotify(editor, EN_KILLFOCUS);
2481     return 0;
2482   case WM_ERASEBKGND:
2483   {
2484     if (editor->bRedraw)
2485     {
2486       HDC hDC = (HDC)wParam;
2487       RECT rc;
2488       if (GetUpdateRect(hWnd,&rc,TRUE))
2489       {
2490         FillRect(hDC, &rc, editor->hbrBackground);
2491       }
2492     }
2493     return 1;
2494   }
2495   case WM_COMMAND:
2496     TRACE("editor wnd command = %d\n", LOWORD(wParam));
2497     return 0;
2498   case WM_KEYUP:
2499     if ((editor->nEventMask & ENM_KEYEVENTS) &&
2500         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2501       return 0;
2502     goto do_default;
2503   case WM_KEYDOWN:
2504     if ((editor->nEventMask & ENM_KEYEVENTS) &&
2505         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2506       return 0;
2507     if (ME_KeyDown(editor, LOWORD(wParam)))
2508       return 0;
2509     goto do_default;
2510   case WM_CHAR: 
2511   {
2512     WCHAR wstr;
2513
2514     if (unicode)
2515         wstr = (WCHAR)wParam;
2516     else
2517     {
2518         CHAR charA = wParam;
2519         MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2520     }
2521     if (editor->AutoURLDetect_bEnable)
2522       ME_AutoURLDetect(editor, wstr);
2523         
2524     switch (wstr)
2525     {
2526     case 1: /* Ctrl-A */
2527       ME_SetSelection(editor, 0, -1);
2528       return 0;
2529     case 3: /* Ctrl-C */
2530       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
2531       return 0;
2532     }
2533     
2534     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
2535       MessageBeep(MB_ICONERROR);
2536       return 0; /* FIXME really 0 ? */
2537     }
2538
2539     switch (wstr)
2540     {
2541     case 22: /* Ctrl-V */
2542       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
2543       return 0;
2544     case 24: /* Ctrl-X */
2545       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
2546       return 0;
2547     case 25: /* Ctrl-Y */
2548       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
2549       return 0;
2550     case 26: /* Ctrl-Z */
2551       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
2552       return 0;
2553     }
2554     if (((unsigned)wstr)>=' '
2555         || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2556         || wstr=='\t') {
2557       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2558       /* WM_CHAR is restricted to nTextLimit */
2559       int from, to;
2560       ME_GetSelection(editor, &from, &to);
2561       if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2562       {
2563         ME_Style *style = ME_GetInsertStyle(editor, 0);
2564         ME_SaveTempStyle(editor);
2565         ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2566         ME_ReleaseStyle(style);
2567         ME_CommitUndo(editor);
2568       }
2569       ME_UpdateRepaint(editor);
2570     }
2571     return 0;
2572   }
2573   case EM_SCROLL: /* fall through */
2574   case WM_VSCROLL: 
2575   {
2576     int origNPos;
2577     int lineHeight;
2578     
2579     origNPos = ME_GetYScrollPos(editor);
2580     lineHeight = 24;
2581     
2582     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
2583       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2584     if (lineHeight <= 0) lineHeight = 24;
2585     
2586     switch(LOWORD(wParam)) 
2587     {
2588       case SB_LINEUP:
2589         ME_ScrollUp(editor,lineHeight);
2590         break;
2591       case SB_LINEDOWN:
2592         ME_ScrollDown(editor,lineHeight);
2593         break;
2594       case SB_PAGEUP:
2595         ME_ScrollUp(editor,editor->sizeWindow.cy);
2596         break;
2597       case SB_PAGEDOWN:
2598         ME_ScrollDown(editor,editor->sizeWindow.cy);
2599         break;
2600       case SB_THUMBTRACK:
2601       case SB_THUMBPOSITION:
2602         ME_ScrollAbs(editor,HIWORD(wParam));
2603         break;
2604     }
2605     if (msg == EM_SCROLL)
2606       return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
2607     break;
2608   }
2609   case WM_MOUSEWHEEL:
2610   {
2611     int gcWheelDelta;
2612     UINT pulScrollLines;
2613
2614     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2615         !ME_FilterEvent(editor, msg, &wParam, &lParam))
2616       return 0;
2617
2618     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
2619     gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
2620     
2621     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
2622     {
2623       /* FIXME follow the original */
2624       ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8); 
2625     }
2626     break;
2627   }
2628   case EM_GETRECT:
2629   {
2630     *((RECT *)lParam) = editor->rcFormat;
2631     return 0;
2632   }
2633   case EM_SETRECT:
2634   case EM_SETRECTNP:
2635   {
2636     if (lParam)
2637     {
2638       RECT *rc = (RECT *)lParam;
2639       
2640       if (wParam)
2641       {
2642         editor->rcFormat.left += rc->left;
2643         editor->rcFormat.top += rc->top;
2644         editor->rcFormat.right += rc->right;
2645         editor->rcFormat.bottom += rc->bottom;
2646       }
2647       else
2648       {
2649         editor->rcFormat = *rc;
2650       }
2651     }
2652     else
2653     {
2654       GetClientRect(hWnd, &editor->rcFormat);
2655     }
2656     if (msg != EM_SETRECTNP)
2657       ME_RewrapRepaint(editor);
2658     return 0;
2659   }
2660   case EM_REQUESTRESIZE:
2661     ME_SendRequestResize(editor, TRUE);
2662     return 0;
2663   case WM_SETREDRAW:
2664     if ((editor->bRedraw = wParam))
2665       ME_RewrapRepaint(editor);
2666     return 0;
2667   case WM_SIZE:
2668   {
2669     GetClientRect(hWnd, &editor->rcFormat);
2670     ME_RewrapRepaint(editor);
2671     return DefWindowProcW(hWnd, msg, wParam, lParam);
2672   }
2673   /* IME messages to make richedit controls IME aware */
2674   case WM_IME_SETCONTEXT:
2675   case WM_IME_CONTROL:
2676   case WM_IME_SELECT:
2677   case WM_IME_COMPOSITIONFULL:
2678     return 0;
2679   case WM_IME_STARTCOMPOSITION:
2680   {
2681     editor->imeStartIndex=ME_GetCursorOfs(editor,0);
2682     ME_DeleteSelection(editor);
2683     ME_CommitUndo(editor);
2684     ME_UpdateRepaint(editor);
2685     return 0;
2686   }
2687   case WM_IME_COMPOSITION:
2688   {
2689     HIMC hIMC;
2690
2691     ME_Style *style = ME_GetInsertStyle(editor, 0);
2692     hIMC = ImmGetContext(hWnd);
2693     ME_DeleteSelection(editor);
2694     ME_CommitUndo(editor);
2695     ME_SaveTempStyle(editor);
2696     if (lParam & GCS_RESULTSTR)
2697     {
2698         LPWSTR lpCompStr = NULL;
2699         DWORD dwBufLen;
2700
2701         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2702         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
2703         ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
2704         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
2705         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
2706     }
2707     else if (lParam & GCS_COMPSTR)
2708     {
2709         LPWSTR lpCompStr = NULL;
2710         DWORD dwBufLen;
2711
2712         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
2713         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
2714         ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
2715         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
2716
2717         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
2718         ME_SetSelection(editor,editor->imeStartIndex,
2719                         editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
2720     }
2721     ME_ReleaseStyle(style);
2722     ME_UpdateRepaint(editor);
2723     return 0;
2724   }
2725   case WM_IME_ENDCOMPOSITION:
2726   {
2727     ME_DeleteSelection(editor);
2728     editor->imeStartIndex=-1;
2729     return 0;
2730   }
2731   case EM_GETOLEINTERFACE:
2732   {
2733     LPVOID *ppvObj = (LPVOID*) lParam;
2734     return CreateIRichEditOle(editor, ppvObj);
2735   }
2736   case EM_GETPASSWORDCHAR:
2737   {
2738     return editor->cPasswordMask;
2739   }
2740   case EM_SETOLECALLBACK:
2741     if(editor->lpOleCallback)
2742       IUnknown_Release(editor->lpOleCallback);
2743     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
2744     if(editor->lpOleCallback)
2745       IUnknown_AddRef(editor->lpOleCallback);
2746     return TRUE;
2747   case EM_GETWORDBREAKPROC:
2748     return (LRESULT)editor->pfnWordBreak;
2749   case EM_SETWORDBREAKPROC:
2750   {
2751     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
2752
2753     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
2754     return (LRESULT)pfnOld;
2755   }
2756   case EM_SETTEXTMODE:
2757   {
2758     LRESULT ret;
2759     int mask = 0;
2760     int changes = 0;
2761     ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
2762     if (!ret)
2763     {
2764       /*Check for valid wParam*/
2765       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
2766           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
2767           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
2768         return 1;
2769       else
2770       {
2771         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
2772         {
2773           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
2774           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
2775         }
2776         /*FIXME: Currently no support for undo level and code page options*/ 
2777         editor->mode = (editor->mode & (~mask)) | changes;
2778         return 0;
2779       }
2780     }
2781     return ret;
2782   }
2783   case EM_SETPASSWORDCHAR:
2784   {
2785     editor->cPasswordMask = wParam;
2786     ME_RewrapRepaint(editor);
2787     return 0;
2788   }
2789   default:
2790   do_default:
2791     return DefWindowProcW(hWnd, msg, wParam, lParam);
2792   }
2793   return 0L;
2794 }
2795
2796 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2797 {
2798     BOOL unicode = TRUE;
2799
2800     /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
2801     if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
2802         unicode = FALSE;
2803
2804     return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
2805 }
2806
2807 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2808 {
2809     return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
2810 }
2811
2812 /******************************************************************
2813  *        RichEditANSIWndProc (RICHED20.10)
2814  */
2815 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2816 {
2817     return RichEditWndProcA(hWnd, msg, wParam, lParam);
2818 }
2819
2820 /******************************************************************
2821  *        RichEdit10ANSIWndProc (RICHED20.9)
2822  */
2823 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2824 {
2825   LRESULT result;
2826   
2827   /* FIXME: this is NOT the same as 2.0 version */
2828   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
2829   if (msg == WM_NCCREATE)
2830   {
2831     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2832     
2833     editor->bEmulateVersion10 = TRUE;
2834     editor->pBuffer->pLast->member.para.nCharOfs = 2;
2835   }
2836   return result;
2837 }
2838
2839 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
2840 {
2841   HWND hWnd = editor->hWnd;
2842   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
2843 }
2844
2845 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2846 {
2847   int x,y;
2848   ME_Cursor tmpCursor;
2849   int nCharOfs; /* The start of the clicked text. Absolute character offset */
2850
2851   ME_Run *tmpRun;
2852
2853   ENLINK info;
2854   x = (short)LOWORD(lParam);
2855   y = (short)HIWORD(lParam);
2856   nCharOfs = ME_CharFromPos(editor, x, y);
2857   if (nCharOfs < 0) return;
2858
2859   ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
2860   tmpRun = &tmpCursor.pRun->member.run;
2861
2862   if ((tmpRun->style->fmt.dwMask & CFM_LINK)
2863     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
2864   { /* The clicked run has CFE_LINK set */
2865     info.nmhdr.hwndFrom = editor->hWnd;
2866     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2867     info.nmhdr.code = EN_LINK;
2868     info.msg = msg;
2869     info.wParam = wParam;
2870     info.lParam = lParam;
2871     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
2872     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
2873     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
2874   }  
2875 }
2876
2877 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
2878 {
2879   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
2880   int i = 0;
2881   
2882   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
2883     item = item->member.para.next_para;
2884   if (!item)
2885     return 0;
2886   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
2887     item = item->member.para.next_para;
2888     i++;
2889   }
2890   return i;
2891 }
2892
2893
2894 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
2895 {
2896   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
2897   int nWritten = 0;
2898   WCHAR *pStart = buffer;
2899   
2900   if (!item) {
2901     *buffer = 0;
2902     return 0;
2903   }
2904   
2905   if (nStart)
2906   {
2907     int nLen = ME_StrLen(item->member.run.strText) - nStart;
2908     if (nLen > nChars)
2909       nLen = nChars;
2910     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
2911     nChars -= nLen;
2912     nWritten += nLen;
2913     if (!nChars)
2914       return nWritten;
2915     buffer += nLen;
2916     nStart = 0;
2917     item = ME_FindItemFwd(item, diRun);
2918   }
2919   
2920   while(nChars && item)
2921   {
2922     int nLen = ME_StrLen(item->member.run.strText);
2923     if (nLen > nChars)
2924       nLen = nChars;
2925
2926     if (item->member.run.nFlags & MERF_ENDPARA)
2927     {
2928       if (!ME_FindItemFwd(item, diRun))
2929         /* No '\r' is appended to the last paragraph. */
2930         nLen = 0;
2931       else if (bCRLF && nChars == 1) {
2932         nLen = 0;
2933         nChars = 0;
2934       } else {
2935         *buffer = '\r';
2936         if (bCRLF)
2937         {
2938           *(++buffer) = '\n';
2939           nWritten++;
2940         }
2941         assert(nLen == 1);
2942         /* our end paragraph consists of 2 characters now */
2943         if (editor->bEmulateVersion10)
2944           nChars--;
2945       }
2946     }
2947     else
2948       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2949     nChars -= nLen;
2950     nWritten += nLen;
2951     buffer += nLen;    
2952       
2953     if (!nChars)
2954     {
2955       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2956       *buffer = 0;
2957       return nWritten;
2958     }
2959     item = ME_FindItemFwd(item, diRun);
2960   }
2961   *buffer = 0;
2962   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2963   return nWritten;  
2964 }
2965
2966 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
2967 {
2968   WNDCLASSW wcW;
2969   WNDCLASSA wcA;
2970   
2971   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2972   wcW.lpfnWndProc = RichEditWndProcW;
2973   wcW.cbClsExtra = 0;
2974   wcW.cbWndExtra = sizeof(ME_TextEditor *);
2975   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2976   wcW.hIcon = NULL;
2977   wcW.hCursor = hBeam;
2978   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2979   wcW.lpszMenuName = NULL;
2980
2981   if (is_version_nt())
2982   {
2983     wcW.lpszClassName = RichEdit20W;
2984     if (!RegisterClassW(&wcW)) return FALSE;
2985     wcW.lpszClassName = RichEdit50W;
2986     if (!RegisterClassW(&wcW)) return FALSE;
2987   }
2988   else
2989   {
2990     /* WNDCLASSA/W have the same layout */
2991     wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
2992     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
2993     wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
2994     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
2995   }
2996
2997   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2998   wcA.lpfnWndProc = RichEditWndProcA;
2999   wcA.cbClsExtra = 0;
3000   wcA.cbWndExtra = sizeof(ME_TextEditor *);
3001   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
3002   wcA.hIcon = NULL;
3003   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
3004   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
3005   wcA.lpszMenuName = NULL;
3006   wcA.lpszClassName = "RichEdit20A";
3007   if (!RegisterClassA(&wcA)) return FALSE;
3008   wcA.lpszClassName = "RichEdit50A";
3009   if (!RegisterClassA(&wcA)) return FALSE;
3010
3011   return TRUE;
3012 }
3013
3014 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3015   /* FIXME: Not implemented */
3016   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3017         hWnd, msg, get_msg_name(msg), wParam, lParam);
3018   return DefWindowProcW(hWnd, msg, wParam, lParam);
3019 }
3020
3021 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3022   /* FIXME: Not implemented */
3023   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3024         hWnd, msg, get_msg_name(msg), wParam, lParam);
3025   return DefWindowProcW(hWnd, msg, wParam, lParam);
3026 }
3027
3028 /******************************************************************
3029  *        REExtendedRegisterClass (RICHED20.8)
3030  *
3031  * FIXME undocumented
3032  * Need to check for errors and implement controls and callbacks 
3033  */
3034 LRESULT WINAPI REExtendedRegisterClass(void)
3035 {
3036   WNDCLASSW wcW;
3037   UINT result;
3038
3039   FIXME("semi stub\n");
3040
3041   wcW.cbClsExtra = 0;
3042   wcW.cbWndExtra = 4;
3043   wcW.hInstance = NULL;
3044   wcW.hIcon = NULL;
3045   wcW.hCursor = NULL;
3046   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
3047   wcW.lpszMenuName = NULL;
3048
3049   if (!ME_ListBoxRegistered)
3050   {
3051       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
3052       wcW.lpfnWndProc = REListWndProc;
3053       wcW.lpszClassName = REListBox20W;
3054       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
3055   }
3056
3057   if (!ME_ComboBoxRegistered)
3058   {
3059       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
3060       wcW.lpfnWndProc = REComboWndProc;
3061       wcW.lpszClassName = REComboBox20W;
3062       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
3063   }
3064
3065   result = 0;
3066   if (ME_ListBoxRegistered)
3067       result += 1;
3068   if (ME_ComboBoxRegistered)
3069       result += 2;
3070
3071   return result;
3072 }
3073
3074 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar) 
3075 {
3076   struct prefix_s {
3077     const char *text;
3078     int length;
3079   } prefixes[12] = {
3080     {"http:", 5},
3081     {"file:", 6},
3082     {"mailto:", 8},
3083     {"ftp:", 5},
3084     {"https:", 7},
3085     {"gopher:", 8},
3086     {"nntp:", 6},
3087     {"prospero:", 10},
3088     {"telnet:", 8},
3089     {"news:", 6},
3090     {"wais:", 6},
3091     {"www.", 5}
3092   };
3093   CHARRANGE ins_pt;
3094   int curf_ef, link_ef, def_ef;
3095   int cur_prefx, prefx_cnt;
3096   int sel_min, sel_max;
3097   int car_pos = 0;
3098   int text_pos=-1;
3099   int URLmin, URLmax = 0;
3100   CHARRANGE url;
3101   FINDTEXTA ft;
3102   CHARFORMAT2W cur_format;
3103   CHARFORMAT2W default_format;
3104   CHARFORMAT2W link;
3105   RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
3106   sel_min = ins_pt.cpMin;
3107   sel_max = ins_pt.cpMax;
3108   if (sel_min==sel_max) 
3109     car_pos = sel_min;
3110   if (sel_min!=sel_max)
3111     car_pos = ME_GetTextLength(editor)+1;   
3112   cur_format.cbSize = sizeof(cur_format);
3113   default_format.cbSize = sizeof(default_format);
3114   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
3115   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
3116   link.cbSize = sizeof(link);
3117   link.dwMask = CFM_LINK;
3118   link.dwEffects = CFE_LINK;
3119   curf_ef = cur_format.dwEffects & link.dwEffects;
3120   def_ef = default_format.dwEffects & link.dwEffects;
3121   link_ef = link.dwEffects & link.dwEffects;
3122   if (curf_ef == link_ef) 
3123   {
3124     if( curChar == '\n' || curChar=='\r' || curChar==' ') 
3125     {
3126       ME_SetSelection(editor, car_pos, car_pos);
3127       RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
3128       text_pos=-1;
3129       return 0;
3130     }
3131   }
3132   if (curf_ef == def_ef)
3133   {
3134     cur_prefx = 0;
3135     prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
3136     while (cur_prefx<=prefx_cnt) 
3137     {
3138       if (text_pos == -1) 
3139       {
3140         ft.lpstrText = prefixes[cur_prefx].text;
3141         URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
3142         URLmax=max(0, car_pos);
3143         if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
3144         {
3145         URLmax = ME_GetTextLength(editor)+1;
3146         }
3147         ft.chrg.cpMin = URLmin;
3148         ft.chrg.cpMax = URLmax;
3149         text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);   
3150         cur_prefx++;
3151       }
3152       if (text_pos != -1) 
3153       {
3154         url.cpMin=text_pos;
3155         url.cpMax=car_pos-1;
3156         ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
3157         ME_RewrapRepaint(editor);
3158         break;
3159       }
3160     }
3161   }
3162   return 0;
3163 }