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